<?php
// ============================================================
// includes/rbac.php — نظام التحكم في الوصول بناءً على الدور
// ============================================================

// Permission map: role => [allowed_modules]
const PERMISSIONS = [
    'admin' => [
        'dashboard', 'users', 'users_create', 'users_edit', 'users_delete',
        'lawyers_review', 'lawyers_approve', 'lawyers_reject',
        'cases_view', 'reports', 'audit_log', 'settings',
    ],
    'clerk' => [
        'dashboard', 'cases_view', 'cases_create', 'cases_edit',
        'sessions_view', 'sessions_create', 'sessions_edit',
        'minutes_create', 'minutes_edit',
        'judgments_view', 'judgments_create',
        'appeals_view', 'appeals_create',
        'documents_view', 'documents_upload',
        'notifications',
    ],
    'lawyer' => [
        'dashboard', 'my_cases', 'documents_upload', 'profile_edit',
        'notifications', 'appeals_view',
    ],
];

function hasPermission(string $permission): bool {
    $role = $_SESSION['user_role'] ?? '';
    return in_array($permission, PERMISSIONS[$role] ?? [], true);
}

function requirePermission(string $permission): void {
    if (!hasPermission($permission)) {
        http_response_code(403);
        include __DIR__ . '/../public/403.php';
        exit;
    }
}

function requireRole(string ...$roles): void {
    $current = $_SESSION['user_role'] ?? '';
    if (!in_array($current, $roles, true)) {
        http_response_code(403);
        include __DIR__ . '/../public/403.php';
        exit;
    }
}

function requireActiveLawyer(): void {
    // إذا كان المحامي معلقاً أو مرفوضاً، يُعاد توجيهه لصفحة الوثائق فقط
    $status = $_SESSION['user_status'] ?? 'active';
    $role   = $_SESSION['user_role']   ?? '';
    if ($role === 'lawyer' && in_array($status, ['pending','rejected'], true)) {
        $currentPage = basename($_SERVER['PHP_SELF']);
        if ($currentPage !== 'documents.php') {
            header('Location: ' . BASE_URL . '/modules/lawyer/documents.php');
            exit;
        }
    }
}

function redirectByRole(): void {
    $role = $_SESSION['user_role'] ?? '';
    $map  = [
        'admin'  => BASE_URL . '/modules/admin/dashboard.php',
        'clerk'  => BASE_URL . '/modules/clerk/dashboard.php',
        'lawyer' => BASE_URL . '/modules/lawyer/dashboard.php',
    ];
    $url = $map[$role] ?? BASE_URL . '/public/index.php';
    header('Location: ' . $url);
    exit;
}