<?php
require_once 'auth.php';
include 'db.php';
requireLogin($conn, ['superadmin']);

$role = $_SESSION['role'] ?? 'superadmin';
$message = '';
$request_method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$permission_definition = getPermissionDefinition();
unset($permission_definition['document']);
$all_actions = [];
$preferred_action_order = ['create', 'read', 'update', 'delete', 'close', 'download', 'restore'];
$access_scope = strtolower(trim((string) ($_POST['access_scope'] ?? ($_GET['scope'] ?? 'department'))));

if (!in_array($access_scope, ['department', 'user'], true)) {
    $access_scope = 'department';
}

foreach ($permission_definition as $module_config) {
    foreach ($module_config['actions'] as $action => $action_label) {
        $all_actions[$action] = $action_label;
    }
}

uksort($all_actions, static function ($a, $b) use ($preferred_action_order) {
    $a_index = array_search($a, $preferred_action_order, true);
    $b_index = array_search($b, $preferred_action_order, true);
    $a_index = $a_index === false ? 999 : $a_index;
    $b_index = $b_index === false ? 999 : $b_index;
    return $a_index <=> $b_index ?: strcmp((string) $a, (string) $b);
});

$departments = array_values(array_filter(array_map('normalizeDepartmentValue', getDepartmentList())));
$selected_department = normalizeDepartmentValue($_POST['selected_department'] ?? ($_GET['department'] ?? ($departments[0] ?? '')));

if (!in_array($selected_department, $departments, true) && !empty($departments)) {
    $selected_department = $departments[0];
}

$department_users = getDepartmentUsers($conn, $selected_department);
$department_user_ids = array_map('intval', array_column($department_users, 'id'));
$selected_user_id = (int) ($_POST['selected_user_id'] ?? ($_GET['user_id'] ?? ($department_user_ids[0] ?? 0)));

if ($selected_user_id > 0 && !in_array($selected_user_id, $department_user_ids, true)) {
    $selected_user_id = (int) ($department_user_ids[0] ?? 0);
}

if ($request_method === 'POST' && isset($_POST['save_department_permissions'])) {
    $submitted = $_POST['permissions'] ?? [];
    $current_user_id = (int) ($_SESSION['user_id'] ?? 0);
    $selected_department = normalizeDepartmentValue($selected_department);

    if ($selected_department === '') {
        $message = "<div class='alert error'>Sila pilih bahagian sebelum menyimpan capaian.</div>";
    } else {
        $upsert = mysqli_prepare($conn, "INSERT INTO department_permissions (department, module, action, is_allowed, updated_by)
            VALUES (?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE is_allowed = VALUES(is_allowed), updated_by = VALUES(updated_by), updated_at = CURRENT_TIMESTAMP");

        if ($upsert) {
            foreach ($permission_definition as $module => $module_config) {
                foreach ($module_config['actions'] as $action => $action_label) {
                    $allowed = !empty($submitted[$module][$action]) ? 1 : 0;
                    mysqli_stmt_bind_param($upsert, "sssii", $selected_department, $module, $action, $allowed, $current_user_id);
                    mysqli_stmt_execute($upsert);
                }
            }

            if (!empty($department_user_ids)) {
                $user_id_list = implode(',', array_map('intval', $department_user_ids));
                mysqli_query($conn, "DELETE FROM user_permissions WHERE user_id IN ({$user_id_list})");
            }

            logActivity($conn, $current_user_id, 'update_department_permissions', 'Kemaskini capaian bahagian: ' . $selected_department);
            $message = "<div class='alert success'>Tetapan capaian bahagian berjaya dikemaskini.</div>";
        } else {
            $message = "<div class='alert error'>Gagal menyimpan tetapan capaian bahagian. Sila cuba semula.</div>";
        }
    }
}

if ($request_method === 'POST' && isset($_POST['save_user_permissions'])) {
    $submitted = $_POST['user_permissions'] ?? [];
    $current_user_id = (int) ($_SESSION['user_id'] ?? 0);
    $selected_department = normalizeDepartmentValue($selected_department);

    if ($selected_user_id <= 0) {
        $message = "<div class='alert error'>Sila pilih user sebelum menyimpan capaian individu.</div>";
    } else {
        $department_permission_matrix = getDepartmentPermissions($conn, $selected_department);
        $department_base_permissions = $department_permission_matrix[$selected_department] ?? [];
        $upsert = mysqli_prepare($conn, "INSERT INTO user_permissions (user_id, module, action, is_allowed, updated_by)
            VALUES (?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE is_allowed = VALUES(is_allowed), updated_by = VALUES(updated_by), updated_at = CURRENT_TIMESTAMP");
        $delete_matching = mysqli_prepare($conn, "DELETE FROM user_permissions WHERE user_id = ? AND module = ? AND action = ?");

        if ($upsert && $delete_matching) {
            foreach ($permission_definition as $module => $module_config) {
                foreach ($module_config['actions'] as $action => $action_label) {
                    $allowed = !empty($submitted[$module][$action]) ? 1 : 0;
                    $department_allowed = !empty($department_base_permissions[$module][$action]) ? 1 : 0;

                    if ($allowed === $department_allowed) {
                        mysqli_stmt_bind_param($delete_matching, "iss", $selected_user_id, $module, $action);
                        mysqli_stmt_execute($delete_matching);
                    } else {
                        mysqli_stmt_bind_param($upsert, "issii", $selected_user_id, $module, $action, $allowed, $current_user_id);
                        mysqli_stmt_execute($upsert);
                    }
                }
            }

            logActivity($conn, $current_user_id, 'update_user_permissions', 'Kemaskini capaian individu user ID: ' . $selected_user_id);
            $message = "<div class='alert success'>Tetapan capaian individu berjaya dikemaskini untuk user dipilih.</div>";
        } else {
            $message = "<div class='alert error'>Gagal menyimpan tetapan capaian individu. Sila cuba semula.</div>";
        }
    }
}

if ($request_method === 'POST' && isset($_POST['reset_user_permissions'])) {
    if ($selected_user_id <= 0) {
        $message = "<div class='alert error'>Sila pilih user sebelum reset capaian individu.</div>";
    } else {
        $delete_stmt = mysqli_prepare($conn, "DELETE FROM user_permissions WHERE user_id = ?");
        if ($delete_stmt) {
            mysqli_stmt_bind_param($delete_stmt, "i", $selected_user_id);
            mysqli_stmt_execute($delete_stmt);
            logActivity($conn, (int) ($_SESSION['user_id'] ?? 0), 'reset_user_permissions', 'Reset capaian individu user ID: ' . $selected_user_id);
            $message = "<div class='alert success'>Capaian individu telah dikosongkan untuk user dipilih. User ini kini ikut capaian bahagian.</div>";
        } else {
            $message = "<div class='alert error'>Gagal reset capaian individu. Sila cuba semula.</div>";
        }
    }
}

$permission_matrix_all = getDepartmentPermissions($conn);
$selected_permissions = $permission_matrix_all[$selected_department] ?? [];
$user_permission_matrix = getUserPermissions($conn, $selected_user_id);
$selected_user_permissions = $user_permission_matrix[$selected_user_id] ?? [];
$selected_user = null;

foreach ($department_users as $user_row) {
    if ((int) ($user_row['id'] ?? 0) === $selected_user_id) {
        $selected_user = $user_row;
    }
}

$total_modules = count($permission_definition);
$modules_with_access = 0;
$active_permissions = 0;
$user_override_count = 0;

foreach ($permission_definition as $module => $module_config) {
    $module_has_access = false;
    foreach ($module_config['actions'] as $action => $action_label) {
        if (!empty($selected_permissions[$module][$action])) {
            $module_has_access = true;
            $active_permissions++;
        }
        if (array_key_exists($action, $module_config['actions']) && isset($selected_user_permissions[$module][$action])) {
            $user_override_count++;
        }
    }
    if ($module_has_access) {
        $modules_with_access++;
    }
}

$last_updated_display = 'Belum ada rekod';
$rollback_stmt = mysqli_prepare($conn, "SELECT MAX(updated_at) AS last_updated FROM department_permissions WHERE department = ?");
if ($rollback_stmt && $selected_department !== '') {
    mysqli_stmt_bind_param($rollback_stmt, "s", $selected_department);
    mysqli_stmt_execute($rollback_stmt);
    $rollback_row = mysqli_fetch_assoc(mysqli_stmt_get_result($rollback_stmt));
    if (!empty($rollback_row['last_updated'])) {
        $last_updated_display = date('d/m/Y H:i', strtotime($rollback_row['last_updated']));
    }
}

function permissionModuleIcon($module) {
    switch ($module) {
        case 'folder':
            return 'fa-folder-open';
        case 'document':
            return 'fa-file-alt';
        case 'draft_letter':
            return 'fa-file-signature';
        case 'deleted_item':
            return 'fa-trash-restore';
        default:
            return 'fa-shield-alt';
    }
}

function getEffectiveUserPermissionValue($department_permissions, $user_permissions, $module, $action) {
    if (isset($user_permissions[$module]) && array_key_exists($action, $user_permissions[$module])) {
        return (int) $user_permissions[$module][$action] === 1;
    }

    return !empty($department_permissions[$module][$action]);
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Capaian Pengguna | MAINPP WORKSPACE</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <?php renderAppShellAssets(); ?>
    <style>
        :root {
            --primary: #0077b6; --primary-dark: #005f99; --secondary: #00b4d8;
            --superadmin: #6c5ce7; --superadmin-dark: #5b4cdb;
            --bg-light: #f8fbfd; --bg-card: #ffffff; --card: #ffffff; --text-main: #1a3a5c; --text: #1a3a5c;
            --text-muted: #6c757d; --border: #e0e8f0; --sidebar-width: 240px;
            --success: #1a9955; --danger: #dc3545; --warning: #ffc107;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: var(--app-font, 'Segoe UI', 'Inter', Tahoma, Geneva, Verdana, sans-serif); }
        button, input, select, textarea, table { font-family: var(--app-font, 'Segoe UI', 'Inter', Tahoma, Geneva, Verdana, sans-serif); }
        body { background: linear-gradient(135deg, #e0f7fa 0%, #f1f8e9 100%); min-height: 100vh; display: flex; color: var(--text-main); }

        .sidebar { width: var(--sidebar-width); background: linear-gradient(180deg, #fff 0%, #f8fbfd 100%); border-right: 1px solid var(--border); position: fixed; height: 100vh; padding: 20px 0; overflow-y: auto; overflow-x: hidden; z-index: 1000; box-shadow: 2px 0 10px rgba(0,0,0,0.03); transition: width 0.3s ease; display:flex; flex-direction:column; }
        .sidebar.collapsed { width: 70px; }
        .sidebar-header { text-align: center; padding: 0 20px 20px; border-bottom: 1px solid var(--border); margin-bottom: 20px; white-space: nowrap; overflow: hidden; }
        .sidebar.collapsed .sidebar-header h3, .sidebar.collapsed .sidebar-header p, .sidebar.collapsed .menu-text { display: none; }
        .sidebar-header img { width: 50px; margin-bottom: 10px; transition: margin 0.3s ease; }
        .sidebar.collapsed .sidebar-header img { margin: 0 auto 10px; }
        .sidebar-header h3 { font-size: 1rem; font-weight: 700; color: var(--primary); margin-bottom: 4px; }
        .sidebar-header p { font-size: 0.75rem; color: var(--text-muted); }
        .role-badge { display: inline-block; padding: 3px 10px; border-radius: 12px; font-size: 0.7rem; font-weight: 600; margin-left: 8px; }
        .role-badge.user { background: #e6f4ff; color: var(--primary); }
        .role-badge.admin { background: #d4edda; color: var(--success); }
        .role-badge.superadmin { background: linear-gradient(90deg, var(--superadmin), var(--superadmin-dark)); color: #fff; }
        .sidebar-menu { list-style: none; padding: 0 10px; display:flex; flex-direction:column; flex:1; }
        .sidebar-section { padding: 10px 18px 6px; color: var(--text-muted); font-size: 0.72rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; }
        .sidebar-spacer { margin-top: auto; }
        .sidebar-menu li a { display: flex; align-items: center; gap: 12px; padding: 12px 18px; color: var(--text-main); text-decoration: none; border-radius: 8px; margin-bottom: 4px; transition: all 0.2s ease; font-size: 0.9rem; white-space: nowrap; }
        .sidebar-menu li a:hover, .sidebar-menu li a.active { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; }
        .sidebar-menu li a i { width: 20px; text-align: center; font-size: 1.1rem; }
        .sidebar-menu .dropdown { position: relative; }
        .sidebar-menu .dropdown-toggle { display: flex; align-items: center; justify-content: space-between; width: 100%; padding: 12px 18px; color: var(--text-main); background: none; border: none; border-radius: 8px; cursor: pointer; font-size: 0.9rem; text-align: left; transition: all 0.2s ease; }
        .sidebar-menu .dropdown-toggle:hover, .sidebar-menu .dropdown-toggle.active { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; }
        .sidebar-menu .dropdown-toggle i.chevron { transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); font-size: 0.8rem; }
        .sidebar-menu .dropdown.active .dropdown-toggle i.chevron { transform: rotate(180deg); }
        .sidebar-menu .dropdown-menu { display: flex; flex-direction: column; padding-left: 42px; margin-top: 4px; max-height: 0; opacity: 0; overflow: hidden; transition: max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.25s ease; }
        .sidebar-menu .dropdown.active .dropdown-menu { max-height: 260px; opacity: 1; }
        .sidebar-menu .dropdown-menu a { padding: 8px 18px; color: var(--text-main); text-decoration: none; border-radius: 6px; font-size: 0.85rem; display: flex; align-items: center; gap: 8px; opacity: 0; transform: translateY(-5px); transition: opacity 0.2s ease, transform 0.2s ease; }
        .sidebar-menu .dropdown.active .dropdown-menu a { opacity: 1; transform: translateY(0); }
        .sidebar-menu .dropdown-menu a:hover, .sidebar-menu .dropdown-menu a.active { background: #e6f4ff; color: var(--primary); }
        .sidebar.collapsed + .main { margin-left: 70px; }
        .sidebar-toggle { position: absolute; right: -12px; top: 20px; width: 24px; height: 24px; background: var(--primary); color: #fff; border: none; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 0.7rem; box-shadow: 0 2px 6px rgba(0,0,0,0.15); transition: transform 0.3s ease; z-index: 1001; }
        .sidebar.collapsed .sidebar-toggle { transform: rotate(180deg); }
        .main { margin-left: var(--sidebar-width); flex: 1; padding: 25px 30px; transition: margin-left 0.3s ease; }
        .top-bar { background: var(--bg-card); padding: 15px 25px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.04); margin-bottom: 25px; display: flex; justify-content: space-between; align-items: center; border: 1px solid var(--border); }
        .top-bar h2 { color: var(--primary-dark); font-size: 1.35rem; font-weight: 850; display: flex; align-items: center; gap: 10px; }
        .top-bar h2 i { color: var(--secondary); }
        .user-info { display: flex; align-items: center; gap: 15px; font-size: 0.9rem; color: var(--text-muted); }
        .user-info span { color: var(--primary); font-weight: 600; }
        .user-info a { color: var(--danger); text-decoration: none; font-weight: 500; display: flex; align-items: center; gap: 5px; }
        .user-info a:hover { text-decoration: underline; }

        .access-tabs { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 16px; }
        .access-tab { display: inline-flex; align-items: center; gap: 8px; padding: 10px 16px; border-radius: 999px; border: 1px solid var(--border); background: var(--bg-card); color: var(--text-main); text-decoration: none; font-weight: 800; box-shadow: 0 2px 10px rgba(0,0,0,0.04); }
        .access-tab.active { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; border-color: transparent; }
        .filter-box { background: var(--bg-card); padding: 18px 22px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.04); margin-bottom: 22px; border: 1px solid var(--border); }
        .filter-box h4 { color: var(--primary-dark); margin-bottom: 14px; font-size: 1rem; font-weight: 700; display: flex; align-items: center; gap: 8px; }
        .filter-form { display: grid; grid-template-columns: minmax(260px, 1fr) minmax(260px, 1fr) auto; gap: 12px; align-items: end; }
        .filter-field label { display: block; color: var(--text-muted); font-size: 0.78rem; font-weight: 700; margin-bottom: 6px; }
        .filter-field select { width: 100%; padding: 10px 14px; border: 1px solid var(--border); border-radius: 8px; font-size: 0.9rem; background: #fff; color: var(--text-main); }
        .filter-field select:focus { border-color: var(--primary); outline: none; box-shadow: 0 0 0 3px rgba(0,119,182,0.15); }
        .filter-form .save-btn { padding: 10px 18px; border: none; border-radius: 999px; cursor: pointer; font-size: 0.95rem; font-weight: 850; display: inline-flex; align-items: center; gap: 7px; text-decoration: none; background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; transition: transform 0.2s ease, filter 0.2s ease, box-shadow 0.2s ease; }
        .filter-form .save-btn { width: 40px; min-height: 38px; height: 38px; min-width: 40px; padding: 0; border-radius: 999px; justify-content: center; gap: 0; box-shadow: 0 10px 22px rgba(0,119,182,0.18); }
        .filter-form .save-btn i { margin: 0; }
        .filter-form .save-btn:hover { transform: translateY(-1px); filter: brightness(1.04); }
        .alert { padding: 12px 16px; border-radius: 10px; margin-bottom: 18px; border-left: 4px solid transparent; font-size: 0.9rem; }
        .alert.success { background: #d4edda; color: #155724; border-left-color: var(--success); }
        .alert.error { background: #f8d7da; color: #721c24; border-left-color: var(--danger); }
        .matrix-card, .users-card { background: var(--bg-card); border: 1px solid var(--border); border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.04); }
        .content-grid { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 18px; align-items: start; margin-bottom: 18px; }
        .content-grid-single { grid-template-columns: minmax(0, 1fr); }
        .stack { display: flex; flex-direction: column; gap: 18px; min-width: 0; }
        .card-head { padding: 17px 18px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; gap: 16px; align-items: flex-start; }
        .card-head h3 { color: var(--primary-dark); font-size: 1rem; font-weight: 700; display: flex; align-items: center; gap: 8px; margin-bottom: 5px; }
        .card-head p { color: var(--text-muted); font-size: 0.84rem; line-height: 1.5; }
        .matrix-wrap { padding: 14px 18px 18px; overflow-x: auto; }
        .permission-table { width: 100%; min-width: 780px; border-collapse: collapse; font-size: 0.84rem; }
        .permission-table th { color: var(--text-muted); font-size: 0.72rem; text-transform: uppercase; text-align: center; padding: 10px 8px; border-bottom: 1px solid var(--border); }
        .permission-table th:first-child, .permission-table td:first-child { text-align: left; width: 280px; }
        .permission-table td { padding: 13px 8px; border-bottom: 1px solid var(--border); text-align: center; vertical-align: middle; }
        .module-title { display: flex; align-items: flex-start; gap: 10px; }
        .module-title i { width: 34px; height: 34px; border-radius: 9px; display: inline-flex; align-items: center; justify-content: center; background: #e8f4ff; color: var(--primary); flex: 0 0 auto; }
        .module-title strong { display: block; color: var(--text-main); margin-bottom: 4px; }
        .module-title span { color: var(--text-muted); font-size: 0.76rem; line-height: 1.4; }
        .switch { position: relative; display: inline-block; width: 42px; height: 23px; }
        .switch input { opacity: 0; width: 0; height: 0; }
        .slider { position: absolute; cursor: pointer; inset: 0; background: #cbd5df; transition: 0.2s; border-radius: 999px; }
        .slider:before {
            position: absolute;
            content: "\f00d";
            height: 17px;
            width: 17px;
            left: 3px;
            top: 3px;
            background: #fff;
            transition: 0.2s;
            border-radius: 50%;
            box-shadow: 0 1px 3px rgba(0,0,0,0.18);
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: "Font Awesome 6 Free";
            font-weight: 900;
            font-size: 10px;
            line-height: 1;
            color: #111827;
        }
        .switch input:checked + .slider { background: var(--success); }
        .switch input:checked + .slider:before { content: "\f00c"; transform: translateX(19px); }
        .save-panel { display: flex; justify-content: space-between; align-items: center; gap: 14px; padding: 15px 18px; border-top: 1px solid var(--border); background: #f8fbfd; }
        .save-panel p { color: var(--text-muted); font-size: 0.83rem; line-height: 1.45; }
        .button-row { display: flex; gap: 10px; flex-wrap: wrap; justify-content: flex-end; }
        .save-btn, .ghost-btn { border: 0; border-radius: 8px; padding: 11px 18px; font-weight: 800; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; white-space: nowrap; text-decoration: none; }
        .save-btn { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; }
        .ghost-btn { background: #fff; color: var(--text-main); border: 1px solid var(--border); }
        .user-permission-actions .save-btn,
        .user-permission-actions .ghost-btn {
            min-width: 242px;
            min-height: 49px;
            border-radius: 999px;
            justify-content: center;
            gap: 0;
        }
        .save-btn[name="save_department_permissions"] {
            min-width: 242px;
            min-height: 49px;
            border-radius: 999px;
            justify-content: center;
            gap: 0;
        }
        .users-card { overflow: hidden; }
        .user-list { display: flex; flex-direction: column; }
        .user-row { padding: 12px 14px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 10px; text-decoration: none; color: inherit; }
        .user-row:hover, .user-row.active { background: #f0f8ff; }
        .user-select-all { background: rgba(255,255,255,0.36); font-weight: 800; }
        .user-row input[type="checkbox"] { width: 17px; height: 17px; accent-color: var(--primary); flex: 0 0 auto; }
        .user-avatar { width: 34px; height: 34px; border-radius: 50%; background: linear-gradient(135deg, var(--primary), var(--secondary)); color: #fff; display: inline-flex; align-items: center; justify-content: center; font-weight: 800; font-size: 0.78rem; flex: 0 0 auto; }
        .user-meta { min-width: 0; flex: 1; }
        .user-meta strong { display: block; color: var(--text-main); font-size: 0.88rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .user-meta span { display: block; color: var(--text-muted); font-size: 0.76rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .status-pill { border-radius: 999px; padding: 4px 8px; font-size: 0.68rem; font-weight: 800; background: #eef4f8; color: var(--text-muted); text-transform: uppercase; }
        .status-pill.approved, .status-pill.active { background: #dff6e8; color: #12653a; }
        .status-pill.pending { background: #fff3cd; color: #856404; }
        .status-pill.rejected, .status-pill.inactive { background: #f8d7da; color: #721c24; }
        .empty-state { color: var(--text-muted); padding: 18px; text-align: center; font-size: 0.86rem; }
        .user-toolbar { padding: 14px 18px; border-bottom: 1px solid var(--border); background: #f8fbfd; }
        .selected-user-card { display: flex; gap: 10px; align-items: center; min-width: 0; }
        .selected-user-card .user-meta { flex: 1; text-align: left; }
        .inherit-note { display: inline-flex; align-items: center; gap: 6px; font-size: 0.75rem; color: var(--text-muted); font-weight: 700; margin-top: 4px; }
        .override-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--success); }
        .page-footer { text-align: center; padding: 20px; color: var(--text-muted); font-size: 0.8rem; margin-top: 12px; }

        :root {
            --primary: #0077b6;
            --primary-dark: #005f99;
            --secondary: #00b4d8;
            --deep-blue: #023e5f;
            --bg-light: rgba(245, 250, 253, 0.72);
            --bg-card: rgba(255,255,255,0.68);
            --card: rgba(255,255,255,0.68);
            --text-main: #163447;
            --text: #163447;
            --text-muted: #2d5367;
            --border: rgba(255,255,255,0.48);
            --sidebar-width: 280px;
            --glass: rgba(255,255,255,0.58);
            --glass-strong: rgba(255,255,255,0.76);
            --shadow-soft: 0 24px 70px rgba(2,62,95,0.16);
        }
        body {
            background:
                linear-gradient(135deg, rgba(245,250,253,0.90), rgba(222,246,252,0.76)),
                url('assets/auth-bg.png') center/cover no-repeat fixed;
            color: var(--text-main);
            overflow-x: hidden;
        }
        body::before {
            content: '';
            position: fixed;
            inset: 0;
            background:
                radial-gradient(circle at 18% 18%, rgba(0,180,216,0.22), transparent 28%),
                radial-gradient(circle at 86% 12%, rgba(0,119,182,0.18), transparent 28%),
                linear-gradient(120deg, rgba(255,255,255,0.28), rgba(255,255,255,0.08));
            pointer-events: none;
            z-index: 0;
        }
        body::after {
            content: '';
            position: fixed;
            width: 520px;
            height: 520px;
            right: -180px;
            bottom: -220px;
            background: rgba(0,180,216,0.18);
            filter: blur(8px);
            transform: rotate(18deg);
            border-radius: 42px;
            pointer-events: none;
            z-index: 0;
        }
        .sidebar {
            background: linear-gradient(180deg, rgba(2,62,95,0.94), rgba(0,119,182,0.84));
            border-right: 1px solid rgba(255,255,255,0.22);
            box-shadow: 18px 0 44px rgba(2,38,60,0.20);
            backdrop-filter: blur(18px) saturate(1.25);
            overflow: hidden;
        }
        .sidebar-header {
            flex: 0 0 auto;
            background: transparent !important;
            border-bottom: 1px solid rgba(255,255,255,0.16);
        }
        .sidebar-header img {
            width: 58px;
            filter: drop-shadow(0 8px 14px rgba(0,0,0,0.22));
        }
        .sidebar-header h3 { color: #fff; font-weight: 800; }
        .sidebar-header p { color: rgba(255,255,255,0.72); }
        .sidebar-menu {
            flex: 1 1 auto;
            min-height: 0;
            overflow-y: auto;
            overflow-x: hidden;
            padding-bottom: 0;
            overscroll-behavior: contain;
            scrollbar-width: thin;
            scrollbar-color: #8f8f8f transparent;
        }
        .sidebar-menu::-webkit-scrollbar {
            width: 10px;
        }
        .sidebar-menu::-webkit-scrollbar-track {
            background: transparent;
        }
        .sidebar-menu::-webkit-scrollbar-thumb {
            background: #8f8f8f;
            border-radius: 999px;
            border: 2px solid transparent;
            background-clip: content-box;
        }
        .sidebar-menu::-webkit-scrollbar-button {
            display: none;
            width: 0;
            height: 0;
        }
        .sidebar-section { color: rgba(255,255,255,0.56); }
        .sidebar-menu li a,
        .sidebar-menu .dropdown-toggle {
            color: rgba(255,255,255,0.88);
        }
        .sidebar-menu li a:hover,
        .sidebar-menu li a.active,
        .sidebar-menu .dropdown-toggle:hover,
        .sidebar-menu .dropdown-toggle.active {
            background: rgba(255,255,255,0.18);
            color: #fff;
            box-shadow: inset 0 0 0 1px rgba(255,255,255,0.18);
        }
        .sidebar-menu .dropdown-menu a { color: rgba(255,255,255,0.78); }
        .sidebar-menu .dropdown-menu a:hover,
        .sidebar-menu .dropdown-menu a.active {
            background: rgba(255,255,255,0.16);
            color: #fff;
        }
        .sidebar-toggle {
            right: 10px;
            top: 28px;
            width: 28px;
            height: 28px;
            background: rgba(255,255,255,0.18);
            border: 1px solid rgba(255,255,255,0.22);
            box-shadow: 0 8px 20px rgba(0,0,0,0.15);
        }
        .main {
            padding: 28px 32px;
            position: relative;
            z-index: 1;
        }
        .top-bar,
        .access-tab,
        .filter-box,
        .matrix-card,
        .users-card,
        .save-panel {
            background: var(--glass);
            border: 1px solid var(--border);
            box-shadow: var(--shadow-soft);
            backdrop-filter: blur(24px) saturate(1.35);
        }
        .top-bar {
            border-radius: 18px;
            padding: 16px 24px;
        }
        .top-bar h2,
        .filter-box h4,
        .card-head h3 {
            color: var(--primary-dark);
            font-weight: 800;
        }
        .filter-box,
        .access-tab,
        .matrix-card,
        .users-card,
        .save-panel {
            border-radius: 22px;
        }
        .filter-field select,
        .ghost-btn {
            background: rgba(255,255,255,0.76);
            border-color: rgba(255,255,255,0.62);
            border-radius: 12px;
            color: var(--text-main);
        }
        .filter-field select:focus {
            border-color: rgba(0,180,216,0.82);
            box-shadow: 0 0 0 4px rgba(0,180,216,0.16);
        }
        .card-head,
        .user-toolbar {
            background: rgba(255,255,255,0.24);
            border-bottom-color: rgba(0,119,182,0.12);
        }
        .matrix-wrap {
            background: rgba(255,255,255,0.18);
        }
        .permission-table th {
            color: var(--deep-blue);
            border-bottom-color: rgba(0,119,182,0.16);
        }
        .permission-table td {
            border-bottom-color: rgba(0,119,182,0.10);
        }
        .module-title i {
            background: rgba(0,180,216,0.16);
            color: var(--primary);
        }
        .save-panel {
            border-top: 1px solid rgba(255,255,255,0.48);
            box-shadow: none;
        }
        .save-btn {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            border-radius: 12px;
            box-shadow: 0 14px 28px rgba(0,119,182,0.18);
        }
        .filter-form .save-btn {
            padding: 10px 18px;
            border-radius: 999px;
            font-size: 0.95rem;
            font-weight: 850;
            gap: 7px;
            background: linear-gradient(90deg, var(--primary), var(--secondary));
            transition: transform 0.2s ease, filter 0.2s ease, box-shadow 0.2s ease;
        }
        .filter-form .save-btn:hover {
            transform: translateY(-1px);
            filter: brightness(1.04);
        }
        .filter-form .filter-field .save-btn {
            width: 40px;
            min-height: 38px;
            height: 38px;
            min-width: 40px;
            padding: 0;
            border-radius: 999px;
            justify-content: center;
            gap: 0;
        }
        .filter-form .filter-field .save-btn i {
            margin: 0;
        }
        .ghost-btn {
            border: 1px solid rgba(0,119,182,0.18);
            font-weight: 800;
        }
        .user-row:hover,
        .user-row.active {
            background: rgba(255,255,255,0.46);
        }
        .user-avatar {
            box-shadow: 0 10px 22px rgba(0,119,182,0.18);
        }
        .alert {
            border-radius: 14px;
            border: 1px solid rgba(255,255,255,0.48);
            backdrop-filter: blur(18px);
        }
        .page-footer { color: var(--text-muted); }

        @media (max-width: 1100px) {
            .filter-form, .content-grid { grid-template-columns: 1fr; }
        }
        @media (max-width: 992px) {
            .sidebar { width: 70px; }
            .sidebar .sidebar-header h3, .sidebar .sidebar-header p, .sidebar .menu-text, .sidebar .role-badge, .sidebar .dropdown-menu, .sidebar .sidebar-section { display: none; }
            .main { margin-left: 70px; }
            .sidebar-toggle { display: none; }
        }
        @media (max-width: 640px) {
            .save-panel { flex-direction: column; align-items: stretch; }
            .button-row, .save-btn, .ghost-btn { justify-content: center; width: 100%; }
            .filter-form .filter-field .save-btn { width: 40px; min-width: 40px; }
            .card-head { flex-direction: column; }
        }
    
        /* Button hover animation */
        .main .btn,
        .main .tab-btn,
        .main .action-btn,
        .main .btn-action,
        .main .filter-btn,
        .main .button,
        .main .generate-closing-btn,
        .main .attachment-remove-btn,
        .main .page-add-btn,
        .main .page-delete-btn,
        .main .delete-current-page-btn,
        .main .form-actions a,
        .main .form-actions button,
        .main .filter-actions a,
        .main .filter-actions button,
        .main .document-command a,
        .main .document-command button,
        .main table a[class*="btn"],
        .main table button[class*="btn"],
        .main input[type="submit"],
        .main input[type="button"] {
            transition: transform 0.2s ease, filter 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease, border-color 0.2s ease !important;
            will-change: transform;
        }

        .main .btn:hover:not(:disabled),
        .main .tab-btn:hover:not(:disabled),
        .main .action-btn:hover:not(:disabled),
        .main .btn-action:hover:not(:disabled),
        .main .filter-btn:hover:not(:disabled),
        .main .button:hover:not(:disabled),
        .main .generate-closing-btn:hover:not(:disabled),
        .main .attachment-remove-btn:hover:not(:disabled),
        .main .page-add-btn:hover:not(:disabled),
        .main .page-delete-btn:hover:not(:disabled),
        .main .delete-current-page-btn:hover:not(:disabled),
        .main .form-actions a:hover,
        .main .form-actions button:hover:not(:disabled),
        .main .filter-actions a:hover,
        .main .filter-actions button:hover:not(:disabled),
        .main .document-command a:hover,
        .main .document-command button:hover:not(:disabled),
        .main table a[class*="btn"]:hover,
        .main table button[class*="btn"]:hover:not(:disabled),
        .main input[type="submit"]:hover:not(:disabled),
        .main input[type="button"]:hover:not(:disabled) {
            transform: translateY(-1px);
            filter: brightness(1.04);
            box-shadow: 0 14px 28px rgba(0, 119, 182, 0.18);
        }

        .main .btn:active:not(:disabled),
        .main .tab-btn:active:not(:disabled),
        .main .action-btn:active:not(:disabled),
        .main .btn-action:active:not(:disabled),
        .main .filter-btn:active:not(:disabled),
        .main .button:active:not(:disabled),
        .main .generate-closing-btn:active:not(:disabled),
        .main .attachment-remove-btn:active:not(:disabled),
        .main .page-add-btn:active:not(:disabled),
        .main .page-delete-btn:active:not(:disabled),
        .main .delete-current-page-btn:active:not(:disabled),
        .main .form-actions a:active,
        .main .form-actions button:active:not(:disabled),
        .main .filter-actions a:active,
        .main .filter-actions button:active:not(:disabled),
        .main .document-command a:active,
        .main .document-command button:active:not(:disabled),
        .main table a[class*="btn"]:active,
        .main table button[class*="btn"]:active:not(:disabled),
        .main input[type="submit"]:active:not(:disabled),
        .main input[type="button"]:active:not(:disabled) {
            transform: translateY(0);
            filter: brightness(0.98);
        }</style>
</head>
<body class="role-<?= htmlspecialchars($role) ?>">
    <aside class="sidebar" id="sidebar">
        <button class="sidebar-toggle" id="sidebarToggle" title="Tutup/Buka Menu"><i class="fas fa-chevron-left"></i></button>
        <div class="sidebar-header">
            <img src="mainpp.png" alt="Logo MAINPP">
            <h3>MAINPP WORKSPACE</h3>
        </div>
        <ul class="sidebar-menu">
            <?php renderUnifiedSidebarMenu($conn, $role, 'system_config.php'); ?>
        </ul>
    </aside>

    <main class="main">
        <div class="top-bar">
            <h2><i class="fas fa-shield-alt"></i> Capaian Pengguna</h2>
            <?php renderTopBarUserMenu($conn, $role, 'system_config.php'); ?>
        </div>

        <?php
        renderBreadcrumb([
            ['label' => 'Dashboard', 'url' => 'dashboard.php'],
            ['label' => 'Capaian Pengguna', 'url' => 'system_config.php', 'current' => true]
        ]);
        ?>

        <?= $message ?>

        <div class="access-tabs" aria-label="Pilihan capaian">
            <a class="access-tab <?= $access_scope === 'department' ? 'active' : '' ?>" href="system_config.php?scope=department&department=<?= urlencode($selected_department) ?>">
                 Capaian Bahagian
            </a>
            <a class="access-tab <?= $access_scope === 'user' ? 'active' : '' ?>" href="system_config.php?scope=user&department=<?= urlencode($selected_department) ?>&user_id=<?= (int) $selected_user_id ?>">
                Capaian Pengguna
            </a>
        </div>

        <div class="filter-box">
            <h4><?= $access_scope === 'user' ? 'Kawalan Capaian Pengguna' : 'Kawalan Capaian Bahagian' ?></h4>
            <form class="filter-form" method="GET" action="system_config.php">
                <input type="hidden" name="scope" value="<?= htmlspecialchars($access_scope) ?>">
                <div class="filter-field">
                    <label for="department">Bahagian / Unit</label>
                    <select name="department" id="department" onchange="this.form.submit()">
                        <?php foreach ($departments as $department): ?>
                            <option value="<?= htmlspecialchars($department) ?>" <?= $selected_department === $department ? 'selected' : '' ?>>
                                <?= htmlspecialchars($department) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php if ($access_scope === 'user'): ?>
                    <div class="filter-field">
                        <label for="user_id">User</label>
                        <select name="user_id" id="user_id" onchange="this.form.submit()" <?= empty($department_users) ? 'disabled' : '' ?>>
                            <?php if (empty($department_users)): ?>
                                <option value="">Tiada user dalam bahagian ini</option>
                            <?php else: ?>
                                <?php foreach ($department_users as $user_row): ?>
                                    <?php $user_row_id = (int) ($user_row['id'] ?? 0); ?>
                                    <option value="<?= $user_row_id ?>" <?= $selected_user_id === $user_row_id ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($user_row['fullname'] ?? '-') ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                    </div>
                    <div class="filter-field">
                        <label>&nbsp;</label>
                        <button type="submit" class="save-btn" title="Papar" aria-label="Papar"><i class="fas fa-search"></i></button>
                    </div>
                <?php else: ?>
                    <div class="filter-field">
                        <label>&nbsp;</label>
                        <button type="submit" class="save-btn" title="Papar" aria-label="Papar"><i class="fas fa-search"></i></button>
                    </div>
                <?php endif; ?>
            </form>
        </div>

        <div class="content-grid <?= $access_scope === 'department' ? 'content-grid-single' : '' ?>">
            <div class="stack">
                <?php if ($access_scope === 'department'): ?>
                <form method="POST" class="matrix-card">
                    <input type="hidden" name="access_scope" value="department">
                    <input type="hidden" name="selected_department" value="<?= htmlspecialchars($selected_department) ?>">
                    <input type="hidden" name="selected_user_id" value="<?= (int) $selected_user_id ?>">
                    <div class="card-head">
                        <div>
                            <h3> Capaian Bahagian: <?= htmlspecialchars($selected_department ?: '-') ?></h3>
                        </div>
                    </div>
                    <div class="matrix-wrap">
                        <table class="permission-table">
                            <thead>
                                <tr>
                                    <th>Modul</th>
                                    <?php foreach ($all_actions as $action => $action_label): ?>
                                        <th><?= htmlspecialchars($action_label) ?></th>
                                    <?php endforeach; ?>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($permission_definition as $module => $module_config): ?>
                                    <tr>
                                        <td>
                                            <div class="module-title">
                                                <i class="fas <?= permissionModuleIcon($module) ?>"></i>
                                                <div>
                                                    <strong><?= htmlspecialchars($module_config['label']) ?></strong>
                                                    <span>Kawalan capaian untuk modul <?= htmlspecialchars(strtolower($module_config['label'])) ?>.</span>
                                                </div>
                                            </div>
                                        </td>
                                        <?php foreach ($all_actions as $action => $action_label): ?>
                                            <td>
                                                <?php if (array_key_exists($action, $module_config['actions'])): ?>
                                                    <label class="switch" title="<?= htmlspecialchars($module_config['label'] . ' - ' . $action_label) ?>">
                                                        <input
                                                            type="checkbox"
                                                            name="permissions[<?= htmlspecialchars($module) ?>][<?= htmlspecialchars($action) ?>]"
                                                            value="1"
                                                            <?= !empty($selected_permissions[$module][$action]) ? 'checked' : '' ?>
                                                        >
                                                        <span class="slider"></span>
                                                    </label>
                                                <?php else: ?>
                                                    <span style="color:var(--text-muted);font-size:0.72rem;">Tidak digunakan</span>
                                                <?php endif; ?>
                                            </td>
                                        <?php endforeach; ?>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="save-panel">
                        <button type="submit" name="save_department_permissions" class="save-btn">
                            Simpan Capaian Bahagian
                        </button>
                    </div>
                </form>
                <?php endif; ?>

                <?php if ($access_scope === 'user'): ?>
                <form method="POST" class="matrix-card" id="userPermissionForm">
                    <input type="hidden" name="access_scope" value="user">
                    <input type="hidden" name="selected_department" value="<?= htmlspecialchars($selected_department) ?>">
                    <input type="hidden" name="selected_user_id" value="<?= (int) $selected_user_id ?>">
                    <div class="card-head">
                        <div>
                            <h3>Capaian Individu User</h3>
                        </div>
                        <span class="status-pill"><?= $selected_user_id > 0 ? '1 user dipilih' : 'Tiada user' ?></span>
                    </div>
                    <div class="user-toolbar">
                        <div class="selected-user-card">
                            <?php if ($selected_user): ?>
                                <?php
                                $parts = preg_split('/\s+/', trim((string) ($selected_user['fullname'] ?? '')), -1, PREG_SPLIT_NO_EMPTY);
                                $initials = '';
                                foreach (array_slice($parts ?: ['U'], 0, 2) as $part) {
                                    $initials .= function_exists('mb_substr') ? mb_substr($part, 0, 1, 'UTF-8') : substr($part, 0, 1);
                                }
                                ?>
                                <div class="user-meta">
                                    <strong><?= htmlspecialchars($selected_user['fullname'] ?? '-') ?></strong>
                                    <span><?= htmlspecialchars(strtoupper($selected_user['role'] ?? 'user')) ?> &middot; <?= htmlspecialchars($selected_user['status'] ?? '-') ?></span>
                                    <span class="inherit-note"><span class="override-dot"></span> <?= $user_override_count > 0 ? 'Ada capaian individu' : 'Masih ikut capaian bahagian' ?></span>
                                </div>
                                <div class="user-avatar"><?= htmlspecialchars(strtoupper($initials ?: 'U')) ?></div>
                            <?php else: ?>
                                <div class="empty-state">Pilih user untuk tetapan individu.</div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="matrix-wrap">
                        <table class="permission-table">
                            <thead>
                                <tr>
                                    <th>Modul</th>
                                    <?php foreach ($all_actions as $action => $action_label): ?>
                                        <th><?= htmlspecialchars($action_label) ?></th>
                                    <?php endforeach; ?>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($permission_definition as $module => $module_config): ?>
                                    <tr>
                                        <td>
                                            <div class="module-title">
                                                <i class="fas <?= permissionModuleIcon($module) ?>"></i>
                                                <div>
                                                    <strong><?= htmlspecialchars($module_config['label']) ?></strong>
                                                    <span>Jika belum disimpan, nilai asal ikut capaian bahagian.</span>
                                                </div>
                                            </div>
                                        </td>
                                        <?php foreach ($all_actions as $action => $action_label): ?>
                                            <td>
                                                <?php if (array_key_exists($action, $module_config['actions'])): ?>
                                                    <label class="switch" title="<?= htmlspecialchars($module_config['label'] . ' - ' . $action_label) ?>">
                                                        <input
                                                            type="checkbox"
                                                            name="user_permissions[<?= htmlspecialchars($module) ?>][<?= htmlspecialchars($action) ?>]"
                                                            value="1"
                                                            <?= getEffectiveUserPermissionValue($selected_permissions, $selected_user_permissions, $module, $action) ? 'checked' : '' ?>
                                                            <?= $selected_user_id <= 0 ? 'disabled' : '' ?>
                                                        >
                                                        <span class="slider"></span>
                                                    </label>
                                                <?php else: ?>
                                                    <span style="color:var(--text-muted);font-size:0.72rem;">Tidak digunakan</span>
                                                <?php endif; ?>
                                            </td>
                                        <?php endforeach; ?>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="save-panel">
                        <div class="button-row user-permission-actions">
                            <button type="submit" name="reset_user_permissions" class="ghost-btn" <?= $selected_user_id <= 0 ? 'disabled' : '' ?>>
                                Ikut Capaian Bahagian
                            </button>
                            <button type="submit" name="save_user_permissions" class="save-btn" <?= $selected_user_id <= 0 ? 'disabled' : '' ?>>
                                Simpan Capaian User
                            </button>
                        </div>
                    </div>
                </form>
                <?php endif; ?>
            </div>

            <?php if ($access_scope === 'user'): ?>
            <aside class="users-card">
                <div class="card-head">
                    <div>
                        <h3><i class="fas fa-user-check"></i> User Dipilih</h3>
                    </div>
                </div>
                <div class="user-list">
                    <?php if (!$selected_user): ?>
                        <div class="empty-state">Tiada pengguna dalam bahagian ini.</div>
                    <?php else: ?>
                        <?php
                        $parts = preg_split('/\s+/', trim((string) ($selected_user['fullname'] ?? '')), -1, PREG_SPLIT_NO_EMPTY);
                        $initials = '';
                        foreach (array_slice($parts ?: ['U'], 0, 2) as $part) {
                            $initials .= function_exists('mb_substr') ? mb_substr($part, 0, 1, 'UTF-8') : substr($part, 0, 1);
                        }
                        ?>
                        <div class="user-row active">
                            <div class="user-avatar"><?= htmlspecialchars(strtoupper($initials ?: 'U')) ?></div>
                            <div class="user-meta">
                                <strong><?= htmlspecialchars($selected_user['fullname'] ?? '-') ?></strong>
                                <span><?= htmlspecialchars($selected_user['email'] ?? '-') ?></span>
                                <span><?= htmlspecialchars(strtoupper($selected_user['role'] ?? 'user')) ?> &middot; <?= htmlspecialchars($selected_department ?: '-') ?></span>
                            </div>
                            <span class="status-pill <?= htmlspecialchars($selected_user['status'] ?? '') ?>">
                                <?= htmlspecialchars($selected_user['status'] ?? '-') ?>
                            </span>
                        </div>
                    <?php endif; ?>
                </div>
            </aside>
            <?php endif; ?>
        </div>

        <div class="page-footer">
            Hakcipta Terpelihara &copy; <?= date('Y') ?> Majlis Agama Islam Negeri Pulau Pinang.
        </div>
    </main>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const sidebar = document.getElementById('sidebar');
            const toggle = document.getElementById('sidebarToggle');
            if (toggle && sidebar) {
                toggle.addEventListener('click', function () {
                    sidebar.classList.toggle('collapsed');
                    localStorage.setItem('sidebarCollapsed', sidebar.classList.contains('collapsed') ? '1' : '0');
                });
                if (localStorage.getItem('sidebarCollapsed') === '1') {
                    sidebar.classList.add('collapsed');
                }
            }

            document.querySelectorAll('.dropdown-toggle').forEach(function (button) {
                button.addEventListener('click', function () {
                    const dropdown = this.closest('.dropdown');
                    if (dropdown) {
                        dropdown.classList.toggle('active');
                    }
                });
            });

        });
    </script>
    <?php renderSessionTimeoutScript(); ?>
</body>
</html>
