<?php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/db.php';

if (empty($_SESSION['user_id'])) {
    header("Location: index.html?e=1");
    exit;
}

$pdo = db();
if (!$pdo instanceof PDO) {
    http_response_code(500);
    exit('DB not ready');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

/* ========= Helpers ========= */
function h($s): string
{
    return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
}

function csrf_token(): string
{
    if (empty($_SESSION['csrf'])) {
        $_SESSION['csrf'] = bin2hex(random_bytes(32));
    }
    return (string)$_SESSION['csrf'];
}

function csrf_check(): void
{
    $t = (string)($_POST['csrf'] ?? '');
    if ($t === '' || empty($_SESSION['csrf']) || !hash_equals((string)($_SESSION['csrf']), $t)) {
        http_response_code(419);
        exit('CSRF');
    }
}

function page_is_active(string $file): string
{
    return basename((string)($_SERVER['PHP_SELF'] ?? '')) === $file ? 'active' : '';
}

function table_cols(PDO $pdo, string $table): array
{
    try {
        $st = $pdo->query("SHOW COLUMNS FROM `$table`");
        return $st->fetchAll(PDO::FETCH_COLUMN, 0);
    } catch (Throwable $e) {
        return [];
    }
}

/* ========= Access ========= */
$role = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
if ($role !== 'OWNER') {
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>إدارة الصلاحيات</title>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800&display=swap" rel="stylesheet">
<style>
  body{
    margin:0;
    font-family:"Tajawal",system-ui,sans-serif;
    background:#081820;
    color:#fff;
    display:grid;
    place-items:center;
    min-height:100vh;
    padding:24px;
  }
  .box{
    width:min(520px,100%);
    background:rgba(255,255,255,.06);
    border:1px solid rgba(255,255,255,.08);
    border-radius:20px;
    padding:28px;
    text-align:center;
  }
  .icon{font-size:42px;margin-bottom:10px}
  .title{font-size:24px;font-weight:800;margin-bottom:8px}
  .desc{color:rgba(255,255,255,.72);margin-bottom:18px}
  .btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    height:44px;
    padding:0 16px;
    border-radius:14px;
    background:#d4af37;
    color:#1d1600;
    text-decoration:none;
    font-weight:800;
  }
</style>
</head>
<body>
  <div class="box">
    <div class="icon">🔒</div>
    <div class="title">إدارة الصلاحيات</div>
    <div class="desc">هذه الصفحة مخصصة لمالك النظام فقط</div>
    <a href="dashboard.php" class="btn">العودة إلى لوحة التحكم</a>
  </div>
</body>
</html>
<?php
    exit;
}

$logo = "https://hamdanlegalgroup.ae/wp-content/uploads/2026/02/logomail.png";
$name = (string)($_SESSION['name'] ?? $_SESSION['username'] ?? 'Admin');

$msg = '';
$err = '';

/* ========= صفحات النظام ========= */
$allPages = [
    'finance_access'             => 'الوصول إلى القسم المالي',
    'payroll_page'               => 'صفحة الرواتب',
    'advances_page'              => 'صفحة السلف',
    'bonuses_page'               => 'صفحة المكافآت',
    'deductions_page'            => 'صفحة الخصومات',

    'financial_access'           => 'الوصول إلى الإدارة المالية',
    'financial_dashboard_page'   => 'لوحة الإدارة المالية',
    'financial_income_page'      => 'صفحة الإيرادات',
    'financial_expenses_page'    => 'صفحة المصروفات',
    'financial_reports_page'     => 'صفحة التقارير المالية',
    'financial_half_yearly_page' => 'صفحة النصف سنوي',
    'financial_yearly_page'      => 'صفحة السنوي',

    'hr_access'                  => 'الوصول إلى قسم الموارد البشرية',
    'attendance_page'            => 'الوصول إلى صفحة الحضور والانصراف',
    'attendance_admin'           => 'إدارة صفحة الحضور والانصراف',
    'leaves_page'                => 'صفحة الإجازات',
    'employee_form_page'         => 'صفحة إضافة / تعديل موظف',
    'employees_page'             => 'صفحة الموظفين',

    'cases_access'               => 'الوصول إلى قسم القضايا',
    'cases_page'                 => 'صفحة القضايا',
    'case_details_page'          => 'صفحة تفاصيل القضية',
    'case_documents_page'        => 'صفحة مستندات القضية',

    'clients_access'             => 'الوصول إلى العملاء',
    'clients_page'               => 'صفحة العملاء',

    'ai_access'                  => 'الوصول إلى الذكاء القانوني',
    'ai_page'                    => 'صفحة الذكاء القانوني',
    'ai_chat_page'               => 'صفحة محادثة الذكاء',

    'library_access'             => 'الوصول إلى المكتبة القانونية',
    'library_page'               => 'صفحة المكتبة القانونية',

    'settings_access'            => 'الوصول إلى الإعدادات',
    'settings_page'              => 'صفحة الإعدادات',

    'permissions_access'         => 'الوصول إلى إدارة الصلاحيات',
    'permissions_page'           => 'صفحة إدارة الصلاحيات',
];

/* ========= تأكد من جدول employee_permissions ========= */
try {
    $permCols = table_cols($pdo, 'employee_permissions');

    if (!$permCols) {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS employee_permissions (
                id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                employee_id INT UNSIGNED NOT NULL,
                permission_key VARCHAR(150) NOT NULL,
                created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
                UNIQUE KEY uniq_emp_perm (employee_id, permission_key),
                KEY idx_employee (employee_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    }
} catch (Throwable $e) {
    $err = 'تعذر تجهيز جدول الصلاحيات الخاصة: ' . $e->getMessage();
}

try {
    $userIdSession = (int)($_SESSION['user_id'] ?? 0);
    $branchId      = (int)($_SESSION['branch_id'] ?? 1);

    /* اسم الفرع الحالي */
    $currentBranchName = 'أبوظبي';
    try {
        $st = $pdo->prepare("SELECT name_ar FROM branches WHERE id=? LIMIT 1");
        $st->execute([$branchId]);
        $currentBranchName = (string)($st->fetchColumn() ?: 'أبوظبي');
    } catch (Throwable $e) {
        $currentBranchName = 'أبوظبي';
    }

    /* جلب الفروع */
    $branches = [];
    try {
        $branches = $pdo->query("SELECT id, name_ar FROM branches ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        $branches = [];
    }

    /* ========= جدول employees ========= */
    $empCols = table_cols($pdo, 'employees');
    $empHasUserId   = in_array('user_id', $empCols, true);
    $empHasFullName = in_array('full_name', $empCols, true);
    $empHasName     = in_array('name', $empCols, true);
    $empHasBranch   = in_array('branch_id', $empCols, true);
    $empHasStatus   = in_array('status', $empCols, true);
    $empHasRole     = in_array('role', $empCols, true);
    $empHasIsActive = in_array('is_active', $empCols, true);

    /* ========= دالة تحويل user_id إلى employee_id ========= */
    $resolveEmployeeId = function (int $userId) use ($pdo, $empCols, $empHasUserId, $empHasStatus): int {
        if (!$empCols) {
            return 0;
        }

        if ($empHasUserId) {
            $sql = "SELECT e.id FROM employees e WHERE e.user_id = ?";
            $args = [$userId];

            if ($empHasStatus) {
                $sql .= " AND (e.status = 'ACTIVE' OR e.status = 'active' OR e.status IS NULL)";
            }

            $sql .= " ORDER BY e.id ASC LIMIT 1";

            $st = $pdo->prepare($sql);
            $st->execute($args);
            $id = (int)($st->fetchColumn() ?: 0);
            if ($id > 0) {
                return $id;
            }
        }

        $sql = "SELECT e.id FROM employees e WHERE e.id = ?";
        $args = [$userId];

        if ($empHasStatus) {
            $sql .= " AND (e.status = 'ACTIVE' OR e.status = 'active' OR e.status IS NULL)";
        }

        $sql .= " ORDER BY e.id ASC LIMIT 1";

        $st = $pdo->prepare($sql);
        $st->execute($args);
        return (int)($st->fetchColumn() ?: 0);
    };

    /* ========= حفظ التعديلات ========= */
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        csrf_check();

        $userId       = (int)($_POST['user_id'] ?? 0);
        $newRole      = strtoupper(trim((string)($_POST['role'] ?? 'STAFF')));
        $branchIdPost = trim((string)($_POST['branch_id'] ?? ''));
        $status       = strtolower(trim((string)($_POST['status'] ?? 'active')));

        $selectedPages = $_POST['page_permissions'] ?? [];
        if (!is_array($selectedPages)) {
            $selectedPages = [];
        }

        $selectedPages = array_values(array_unique(array_filter(array_map('strval', $selectedPages))));
        $allowedPageCodes = array_keys($allPages);
        $selectedPages = array_values(array_intersect($selectedPages, $allowedPageCodes));

        if ($userId <= 0) {
            $err = 'رقم المستخدم غير صحيح';
        } else {
            $allowedRoles = ['OWNER', 'ADMIN', 'STAFF', 'CLIENT'];
            if (!in_array($newRole, $allowedRoles, true)) {
                $newRole = 'STAFF';
            }

            $allowedStatus = ['active', 'inactive', '1', '0'];
            if (!in_array($status, $allowedStatus, true)) {
                $status = 'active';
            }
            if ($status === '1') $status = 'active';
            if ($status === '0') $status = 'inactive';

            $branchIdValue = null;
            if ($branchIdPost !== '' && strtoupper($branchIdPost) !== 'NULL') {
                $branchIdValue = (int)$branchIdPost;
            }

            if ($userId === $userIdSession && $newRole !== 'OWNER') {
                $err = 'لا يمكنك إزالة صلاحية المالك من حسابك';
            } else {
                $pdo->beginTransaction();

                try {
                    /* 1) تحديث users */
                    $st = $pdo->prepare("
                        UPDATE users
                        SET role = ?, branch_id = ?, status = ?
                        WHERE id = ?
                        LIMIT 1
                    ");
                    $ok = $st->execute([$newRole, $branchIdValue, $status, $userId]);

                    if (!$ok) {
                        throw new RuntimeException('تعذر تحديث بيانات المستخدم');
                    }

                    /* 2) تحديد employee_id */
                    $employeeId = $resolveEmployeeId($userId);

                    /* 3) تحديث employees */
                    if ($employeeId > 0) {
                        $empUpdateFields = [];
                        $empUpdateVals   = [];

                        if ($empHasBranch) {
                            $empUpdateFields[] = "branch_id = ?";
                            $empUpdateVals[]   = $branchIdValue;
                        }

                        if ($empHasRole) {
                            $empUpdateFields[] = "role = ?";
                            $empUpdateVals[]   = $newRole;
                        }

                        if ($empHasStatus) {
                            $empUpdateFields[] = "status = ?";
                            $empUpdateVals[]   = ($status === 'active' ? 'ACTIVE' : 'INACTIVE');
                        }

                        if ($empHasIsActive) {
                            $empUpdateFields[] = "is_active = ?";
                            $empUpdateVals[]   = ($status === 'active' ? 1 : 0);
                        }

                        if (!empty($empUpdateFields)) {
                            $empUpdateVals[] = $employeeId;

                            $sqlEmpUpdate = "
                                UPDATE employees
                                SET " . implode(', ', $empUpdateFields) . "
                                WHERE id = ?
                                LIMIT 1
                            ";

                            $stEmpUp = $pdo->prepare($sqlEmpUpdate);
                            $stEmpUp->execute($empUpdateVals);
                        }

                        /* 4) تحديث صلاحيات الصفحات */
                        $del = $pdo->prepare("DELETE FROM employee_permissions WHERE employee_id = ?");
                        $del->execute([$employeeId]);

                        if (!empty($selectedPages)) {
                            $ins = $pdo->prepare("
                                INSERT INTO employee_permissions (employee_id, permission_key)
                                VALUES (?, ?)
                            ");
                            foreach ($selectedPages as $pageCode) {
                                $ins->execute([$employeeId, $pageCode]);
                            }
                        }
                    }

                    $pdo->commit();
                    $msg = 'تم حفظ الصلاحيات وتحديث بيانات الموظف بنجاح';
                } catch (Throwable $e) {
                    if ($pdo->inTransaction()) {
                        $pdo->rollBack();
                    }
                    $err = 'تعذر الحفظ: ' . $e->getMessage();
                }
            }
        }
    }

    /* ========= البحث ========= */
    $q = trim((string)($_GET['q'] ?? ''));

    $params = [];
    $where = "1=1";

    if ($q !== '') {
        $where .= " AND (username LIKE ? OR name LIKE ?)";
        $like = "%{$q}%";
        $params[] = $like;
        $params[] = $like;
    }

    $sql = "
        SELECT id, username, name, role, status, branch_id
        FROM users
        WHERE {$where}
        ORDER BY id DESC
        LIMIT 200
    ";
    $st = $pdo->prepare($sql);
    $st->execute($params);
    $users = $st->fetchAll(PDO::FETCH_ASSOC);

    /* ========= خريطة user => employee ========= */
    $userToEmployeeMap = [];
    if ($empCols) {
        if ($empHasUserId) {
            $sqlMap = "SELECT id, user_id FROM employees WHERE user_id IS NOT NULL";
            if ($empHasStatus) {
                $sqlMap .= " AND (status = 'ACTIVE' OR status = 'active' OR status IS NULL)";
            }
            $rowsMap = $pdo->query($sqlMap)->fetchAll(PDO::FETCH_ASSOC);
            foreach ($rowsMap as $r) {
                $userToEmployeeMap[(int)$r['user_id']] = (int)$r['id'];
            }
        }

        foreach ($users as $u) {
            $uid = (int)$u['id'];
            if (!isset($userToEmployeeMap[$uid])) {
                $userToEmployeeMap[$uid] = $resolveEmployeeId($uid);
            }
        }
    }

    /* ========= خريطة صلاحيات المستخدمين ========= */
    $userPermissionsMap = [];
    try {
        $permRows = $pdo->query("SELECT employee_id, permission_key FROM employee_permissions")->fetchAll(PDO::FETCH_ASSOC);

        $employeeToUserMap = array_flip(array_filter($userToEmployeeMap));

        foreach ($permRows as $pr) {
            $empId = (int)$pr['employee_id'];
            $code  = (string)$pr['permission_key'];

            if (!isset($employeeToUserMap[$empId])) {
                continue;
            }

            $uid = (int)$employeeToUserMap[$empId];

            if (!isset($userPermissionsMap[$uid])) {
                $userPermissionsMap[$uid] = [];
            }

            $userPermissionsMap[$uid][] = $code;
        }
    } catch (Throwable $e) {
        $userPermissionsMap = [];
    }

} catch (Throwable $ex) {
    http_response_code(500);
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>خطأ</title>
  <style>
    body{font-family:system-ui;background:#f6f7f8;margin:0;padding:24px;color:#111}
    .box{max-width:900px;margin:0 auto;background:#fff;border:1px solid #e5e7eb;border-radius:14px;padding:18px}
    .muted{color:#6b7280;font-size:14px;line-height:1.6}
    pre{white-space:pre-wrap;background:#0b1020;color:#e5e7eb;border-radius:12px;padding:12px;overflow:auto}
  </style>
</head>
<body>
  <div class="box">
    <div style="font-size:18px;font-weight:700;margin-bottom:8px">تعذر تحميل صفحة الصلاحيات</div>
    <div class="muted">تفاصيل الخطأ:</div>
    <pre><?= h($ex->getMessage() . "\n\n" . $ex->getTraceAsString()) ?></pre>
  </div>
</body>
</html>
<?php
    exit;
}
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>إدارة الصلاحيات</title>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800&display=swap" rel="stylesheet">
<style>
  :root{
    --hlg-dark:#0f2a33;
    --hlg-teal:#006a7a;
    --hlg-gold:#d4af37;
    --bg:#f4f7f8;
    --card:#fff;
    --border:#e6edef;
    --muted:#6b7a7f;
    --radius:18px;
    --sidebar-w:280px;
    --ring:0 0 0 4px rgba(0,106,122,.12);
  }

  *{box-sizing:border-box}
  body{
    margin:0;
    font-family:"Tajawal",system-ui;
    background:linear-gradient(180deg,#fff,var(--bg));
    color:#0b1b1f;
  }
  a{color:inherit;text-decoration:none}

  .app{
    min-height:100vh;
    display:grid;
    grid-template-columns:var(--sidebar-w) 1fr;
  }

  .sidebar{
    background:linear-gradient(180deg,#0b2230,#0a1d28);
    color:#eaf5f7;
    padding:18px 16px;
    position:sticky;
    top:0;
    height:100vh;
    overflow:auto;
  }

  .brand{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    padding:10px 10px 16px;
    border-bottom:1px solid rgba(255,255,255,.08);
    margin-bottom:14px;
  }

  .brand-left{
    display:flex;
    align-items:center;
    gap:12px;
    min-width:0;
  }

  .brand-logo{
    width:46px;
    height:46px;
    border-radius:14px;
    background:rgba(255,255,255,.10);
    border:1px solid rgba(255,255,255,.14);
    display:flex;
    align-items:center;
    justify-content:center;
    overflow:hidden;
  }

  .brand-logo img{
    width:100%;
    height:100%;
    object-fit:contain;
    padding:8px;
  }

  .brand-title{
    display:flex;
    flex-direction:column;
    gap:2px;
    min-width:0;
  }

  .brand-title .name{
    font-weight:700;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
  }

  .brand-title .sub{
    font-size:12.5px;
    opacity:.85;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
  }

  .nav{
    margin-top:10px;
    display:grid;
    gap:6px;
  }

  .nav a{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:10px;
    padding:11px 12px;
    border-radius:14px;
    color:#eaf5f7;
    border:1px solid transparent;
    transition:.15s ease;
  }

  .nav a:hover{
    background:rgba(255,255,255,.06);
    border-color:rgba(255,255,255,.08);
  }

  .nav a.active{
    background:rgba(255,255,255,.08);
    border-color:rgba(255,255,255,.10);
  }

  .nav .label{
    font-weight:700;
    opacity:.95;
  }

  .pill{
    font-size:12px;
    color:#d7f3f7;
    background:rgba(255,255,255,.08);
    border:1px solid rgba(255,255,255,.10);
    padding:4px 10px;
    border-radius:999px;
    opacity:.9;
  }

  .logout{
    margin-top:16px;
    padding-top:14px;
    border-top:1px solid rgba(255,255,255,.08);
    display:flex;
    gap:10px;
    align-items:center;
    justify-content:space-between;
    opacity:.95;
  }

  .logout a{
    display:inline-flex;
    align-items:center;
    gap:8px;
    padding:10px 12px;
    border-radius:14px;
    background:rgba(255,255,255,.06);
    border:1px solid rgba(255,255,255,.10);
  }

  .main{
    min-width:0;
    padding:18px 22px 26px;
  }

  .wrap{
    max-width:1300px;
    margin:0 auto;
    padding:0 8px;
  }

  .menuBtn{
    display:none;
    width:44px;
    height:44px;
    border-radius:14px;
    border:1px solid var(--border);
    background:#fff;
    cursor:pointer;
    font-weight:900;
    font-size:18px;
    line-height:1;
  }

  .overlay{
    display:none;
    position:fixed;
    inset:0;
    background:rgba(0,0,0,.35);
    z-index:998;
  }

  .topbar{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    padding:10px 12px;
    background:#fff;
    border:1px solid var(--border);
    border-radius:var(--radius);
    box-shadow:0 10px 25px rgba(0,0,0,.05);
    position:sticky;
    top:12px;
    z-index:10;
    margin-bottom:14px;
  }

  .branchPill{
    display:inline-flex;
    align-items:center;
    gap:8px;
    background:#fff;
    border:1px solid var(--border);
    border-radius:999px;
    padding:10px 12px;
    font-weight:900;
  }

  .dot{
    width:8px;
    height:8px;
    border-radius:50%;
    background:var(--hlg-teal);
    box-shadow:0 0 0 4px rgba(0,106,122,.12);
  }

  .head{
    display:flex;
    justify-content:space-between;
    align-items:flex-end;
    gap:12px;
    flex-wrap:wrap;
    margin-bottom:12px;
  }

  h1{
    margin:0;
    font-size:28px;
  }

  .sub{
    color:var(--muted);
    font-size:14px;
  }

  .btnAdd{
    display:inline-flex;
    align-items:center;
    gap:10px;
    height:44px;
    padding:0 14px;
    border-radius:14px;
    border:0;
    cursor:pointer;
    background:linear-gradient(90deg,var(--hlg-gold),#caa52f);
    color:#1d1600;
    font-weight:900;
    box-shadow:0 12px 25px rgba(212,175,55,.22);
    transition:.15s ease;
  }

  .btnAdd:hover{
    transform:translateY(-1px);
  }

  .btnAdd .plus{
    width:28px;
    height:28px;
    border-radius:10px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    background:rgba(29,22,0,.10);
    border:1px solid rgba(29,22,0,.12);
    font-weight:900;
  }

  .card{
    background:var(--card);
    border:1px solid var(--border);
    border-radius:var(--radius);
    box-shadow:0 10px 25px rgba(0,0,0,.05);
    overflow:hidden;
  }

  .toolbar{
    display:flex;
    gap:10px;
    align-items:center;
    justify-content:space-between;
    flex-wrap:wrap;
    padding:12px 14px;
    border-bottom:1px solid var(--border);
  }

  .search{
    display:flex;
    gap:10px;
    align-items:center;
    flex-wrap:wrap;
  }

  .search input{
    height:40px;
    border-radius:999px;
    border:1px solid var(--border);
    padding:0 14px;
    min-width:260px;
    background:#fbfeff;
    outline:none;
  }

  .search input:focus{
    border-color:rgba(0,106,122,.45);
    box-shadow:var(--ring);
    background:#fff;
  }

  .search button{
    height:40px;
    border-radius:999px;
    border:1px solid var(--border);
    padding:0 14px;
    background:#fff;
    cursor:pointer;
    font-weight:800;
  }

  .msg{
    padding:10px 14px;
    border-bottom:1px solid var(--border);
  }

  .ok{
    background:#ecfdf5;
    color:#065f46;
  }

  .bad{
    background:#fef2f2;
    color:#991b1b;
  }

  table{
    width:100%;
    border-collapse:collapse;
  }

  th,td{
    padding:12px 10px;
    border-bottom:1px solid var(--border);
    text-align:right;
    vertical-align:top;
  }

  th{
    background:#f8fafb;
    color:#51666c;
    font-size:13px;
    font-weight:900;
  }

  td{
    font-size:14px;
  }

  .muted2{
    color:var(--muted);
    font-size:13px;
  }

  .rowForm{
    display:flex;
    gap:8px;
    align-items:center;
    justify-content:flex-start;
    flex-wrap:wrap;
  }

  .rowForm select{
    height:36px;
    border-radius:12px;
    border:1px solid var(--border);
    padding:0 10px;
    background:#fff;
    outline:none;
  }

  .save{
    height:36px;
    border-radius:12px;
    border:0;
    padding:0 12px;
    cursor:pointer;
    font-weight:900;
    background:linear-gradient(90deg,var(--hlg-gold),#caa52f);
    color:#1d1600;
  }

  .pillRole{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:6px 10px;
    border-radius:999px;
    border:1px solid var(--border);
    font-weight:900;
    font-size:12px;
    background:#fbfeff;
  }

  .pillRole.admin{
    background:rgba(212,175,55,.12);
    border-color:rgba(212,175,55,.22);
    color:#7a5a00;
  }

  .pillRole.staff{
    background:rgba(0,106,122,.10);
    border-color:rgba(0,106,122,.18);
    color:#055b66;
  }

  .pillRole.client{
    background:rgba(59,130,246,.10);
    border-color:rgba(59,130,246,.18);
    color:#1d4ed8;
  }

  .pillRole.owner{
    background:rgba(17,24,39,.10);
    border-color:rgba(17,24,39,.18);
    color:#111827;
  }

  .permBox{
    background:#fbfeff;
    border:1px dashed rgba(0,106,122,.25);
    border-radius:16px;
    padding:10px;
    min-width:340px;
  }

  .permSelect{
    width:100%;
    min-width:340px;
    height:auto;
    min-height:180px;
    padding:10px;
    border-radius:12px;
    border:1px solid var(--border);
    background:#fff;
    outline:none;
    font-family:inherit;
  }

  .permSelect:focus{
    border-color:rgba(0,106,122,.45);
    box-shadow:var(--ring);
  }

  .permHint{
    margin-top:8px;
    color:var(--muted);
    font-size:12px;
  }

  .selectedWrap{
    display:flex;
    gap:6px;
    flex-wrap:wrap;
    margin-bottom:8px;
  }

  .selectedChip{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:6px 10px;
    border-radius:999px;
    border:1px solid rgba(0,106,122,.18);
    background:rgba(0,106,122,.08);
    color:#055b66;
    font-size:12px;
    font-weight:900;
  }

  .linkWarn{
    margin-top:4px;
    color:#dc2626;
    font-size:12px;
    font-weight:700;
  }

  @media (max-width: 980px){
    .app{grid-template-columns:1fr;}
    .sidebar{
      position:fixed;
      top:0;
      right:0;
      height:100vh;
      width:280px;
      transform:translateX(110%);
      transition:transform .2s ease;
      z-index:999;
      box-shadow:0 18px 50px rgba(0,0,0,.25);
    }
    body.nav-open .sidebar{transform:translateX(0);}
    body.nav-open .overlay{display:block;}
    .menuBtn{display:inline-flex;align-items:center;justify-content:center;}
    .search input{min-width:180px;}
    .card{overflow:auto;}
    th,td{white-space:nowrap;}
    .permBox,.permSelect{min-width:280px;}
  }
</style>
</head>
<body>
<div class="overlay" id="overlay" aria-hidden="true"></div>

<div class="app">
  <aside class="sidebar">
    <div class="brand">
      <div class="brand-left">
        <div class="brand-logo"><img src="<?= h($logo) ?>" alt="HLG"></div>
        <div class="brand-title">
          <div class="name">مجموعة حمدان القانونية</div>
          <div class="sub">بوابة إدارة الأعمال القانونية</div>
        </div>
      </div>
    </div>

    <nav class="nav">
      <a class="<?= page_is_active('dashboard.php') ?>" href="dashboard.php">
        <span class="left"><span class="label">الرئيسية</span></span>
        <span class="pill">لوحة</span>
      </a>

      <a class="<?= page_is_active('cases.php') ?>" href="cases.php">
        <span class="left"><span class="label">القضايا</span></span>
        <span class="pill">إدارة</span>
      </a>

      <a class="<?= page_is_active('tasks.php') ?>" href="tasks.php">
        <span class="left"><span class="label">المهام</span></span>
        <span class="pill">متابعة</span>
      </a>

      <a class="<?= page_is_active('hr_employee_form.php') ?>" href="hr_employee_form.php">
        <span class="left"><span class="label">شؤون الموظفين</span></span>
        <span class="pill">HR</span>
      </a>

      <a class="<?= page_is_active('permissions_manage.php') ?>" href="permissions_manage.php">
        <span class="left"><span class="label">الصلاحيات</span></span>
        <span class="pill">تحكم</span>
      </a>
    </nav>

    <div class="logout">
      <div style="min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?= h($name) ?></div>
      <a href="logout.php" title="تسجيل الخروج"><span>خروج</span></a>
    </div>
  </aside>

  <main class="main">
    <div class="topbar">
      <button class="menuBtn" type="button" id="menuBtn" aria-label="فتح القائمة" aria-expanded="false">☰</button>
      <span class="branchPill"><span class="dot"></span><span><?= h($currentBranchName ?? '') ?></span></span>
    </div>

    <div class="wrap">
      <div class="head">
        <div>
          <h1>إدارة الصلاحيات</h1>
          <div class="sub">هذه الصفحة متاحة لمالك النظام فقط، ويمكنك منح صلاحية صفحة معيّنة لأي موظف مع إبقائه موظفًا في باقي النظام.</div>
        </div>

        <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;justify-content:flex-end">
          <a href="users_add.php" class="btnAdd">
            <span class="plus">+</span>
            <span>إضافة موظف</span>
          </a>
          <div class="sub">المستخدم الحالي: <?= h($_SESSION['name'] ?? $_SESSION['username'] ?? '') ?></div>
        </div>
      </div>

      <div class="card">
        <div class="toolbar">
          <form class="search" method="get" action="permissions_manage.php">
            <input type="text" name="q" value="<?= h($q ?? '') ?>" placeholder="بحث بالاسم أو اليوزر..." />
            <button type="submit">بحث</button>
            <a href="permissions_manage.php" class="muted2">مسح</a>
          </form>
          <div class="muted2">النتائج: <?= (int)count($users) ?></div>
        </div>

        <?php if ($msg !== ''): ?>
          <div class="msg ok"><?= h($msg) ?></div>
        <?php endif; ?>

        <?php if ($err !== ''): ?>
          <div class="msg bad"><?= h($err) ?></div>
        <?php endif; ?>

        <table>
          <thead>
            <tr>
              <th style="width:70px">ID</th>
              <th>المستخدم</th>
              <th style="width:140px">الدور</th>
              <th style="width:170px">الفرع</th>
              <th style="width:120px">الحالة</th>
              <th style="width:460px">صلاحيات الصفحات</th>
              <th style="width:290px">تعديل</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($users as $u): ?>
            <?php
              $r = strtoupper((string)($u['role'] ?? 'STAFF'));
              $pillClass = ($r === 'ADMIN') ? 'admin' : (($r === 'CLIENT') ? 'client' : (($r === 'OWNER') ? 'owner' : 'staff'));

              $branchLabel = '—';
              if (($u['branch_id'] ?? null) !== null) {
                  $bid = (int)$u['branch_id'];
                  foreach ($branches as $b) {
                      if ((int)$b['id'] === $bid) {
                          $branchLabel = (string)$b['name_ar'];
                          break;
                      }
                  }
                  if ($branchLabel === '—') {
                      $branchLabel = (string)$bid;
                  }
              }

              $userPerms = $userPermissionsMap[(int)$u['id']] ?? [];
              $linkedEmployeeId = (int)($userToEmployeeMap[(int)$u['id']] ?? 0);
            ?>
            <tr>
              <td><?= (int)$u['id'] ?></td>

              <td>
                <div style="font-weight:900"><?= h(($u['name'] ?? '') ?: ($u['username'] ?? '')) ?></div>
                <div class="muted2">@<?= h((string)($u['username'] ?? '')) ?></div>
                <?php if ($linkedEmployeeId <= 0): ?>
                  <div class="linkWarn">غير مرتبط بجدول employees</div>
                <?php endif; ?>
              </td>

              <td>
                <span class="pillRole <?= h($pillClass) ?>"><?= h($r) ?></span>
              </td>

              <td class="muted2"><?= h($branchLabel) ?></td>
              <td><?= h((string)($u['status'] ?? '')) ?></td>

              <td>
                <div class="permBox">
                  <?php if (!empty($userPerms)): ?>
                    <div class="selectedWrap">
                      <?php foreach ($userPerms as $permCode): ?>
                        <span class="selectedChip">
                          <?= h($allPages[$permCode] ?? $permCode) ?>
                        </span>
                      <?php endforeach; ?>
                    </div>
                  <?php endif; ?>

                  <select
                    name="page_permissions[]"
                    form="f<?= (int)$u['id'] ?>"
                    class="permSelect"
                    multiple
                    size="8"
                  >
                    <?php foreach ($allPages as $pageCode => $pageLabel): ?>
                      <option value="<?= h($pageCode) ?>" <?= in_array($pageCode, $userPerms, true) ? 'selected' : '' ?>>
                        <?= h($pageLabel) ?> — <?= h($pageCode) ?>
                      </option>
                    <?php endforeach; ?>
                  </select>

                  <div class="permHint">
                    اختر صفحة واحدة أو أكثر. استخدم Ctrl من الكيبورد لتحديد عدة صفحات.
                  </div>
                </div>
              </td>

              <td>
                <form class="rowForm" id="f<?= (int)$u['id'] ?>" method="post" action="permissions_manage.php">
                  <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                  <input type="hidden" name="user_id" value="<?= (int)$u['id'] ?>">

                  <select name="role">
                    <option value="OWNER" <?= $r === 'OWNER' ? 'selected' : '' ?>>OWNER</option>
                    <option value="ADMIN" <?= $r === 'ADMIN' ? 'selected' : '' ?>>ADMIN</option>
                    <option value="STAFF" <?= $r === 'STAFF' ? 'selected' : '' ?>>STAFF</option>
                    <option value="CLIENT" <?= $r === 'CLIENT' ? 'selected' : '' ?>>CLIENT</option>
                  </select>

                  <select name="branch_id">
                    <option value="NULL" <?= (($u['branch_id'] ?? null) === null) ? 'selected' : '' ?>>بدون فرع</option>
                    <?php foreach ($branches as $b): ?>
                      <option value="<?= (int)$b['id'] ?>" <?= ((int)($u['branch_id'] ?? 0) === (int)$b['id']) ? 'selected' : '' ?>>
                        <?= h($b['name_ar']) ?> (<?= (int)$b['id'] ?>)
                      </option>
                    <?php endforeach; ?>
                  </select>

                  <select name="status">
                    <option value="active" <?= (($u['status'] ?? '') === 'active') ? 'selected' : '' ?>>active</option>
                    <option value="inactive" <?= (($u['status'] ?? '') === 'inactive') ? 'selected' : '' ?>>inactive</option>
                  </select>

                  <button class="save" type="submit">حفظ</button>
                </form>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <div class="muted2" style="margin-top:10px">
        ملاحظة: الموظف يمكن أن يبقى STAFF، ومع ذلك تعطيه صلاحية إدارة صفحة محددة فقط من خلال القائمة أعلاه.
      </div>
    </div>
  </main>
</div>

<script>
(function(){
  const menuBtn = document.getElementById('menuBtn');
  const overlay = document.getElementById('overlay');

  function openNav(){
    document.body.classList.add('nav-open');
    if(menuBtn) menuBtn.setAttribute('aria-expanded','true');
    if(overlay) overlay.setAttribute('aria-hidden','false');
  }

  function closeNav(){
    document.body.classList.remove('nav-open');
    if(menuBtn) menuBtn.setAttribute('aria-expanded','false');
    if(overlay) overlay.setAttribute('aria-hidden','true');
  }

  function toggleNav(){
    if(document.body.classList.contains('nav-open')) closeNav();
    else openNav();
  }

  if(menuBtn){
    menuBtn.addEventListener('click', function(e){
      e.stopPropagation();
      toggleNav();
    });
  }

  if(overlay){
    overlay.addEventListener('click', closeNav);
  }

  document.addEventListener('keydown', function(e){
    if(e.key === 'Escape') closeNav();
  });
})();
</script>
</body>
</html>