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

// Senarai superadmin yang dilindungi - role mereka tidak boleh diubah
$protected_superadmin_emails = ['syarafana@mainpp.gov.my', 'fikri@mainpp.gov.my'];

// DAPATKAN ROLE UNTUK SIDEBAR CONSISTENCY
$role = $_SESSION['role'] ?? 'superadmin';
$departments_list = getDepartmentList();
$user_status_sort_columns = [
    'fullname' => ['label' => 'Nama', 'type' => 'text'],
    'short_name' => ['label' => 'Nama Pendek', 'type' => 'text'],
    'ic_number' => ['label' => 'No. IC', 'type' => 'text'],
    'email' => ['label' => 'Emel', 'type' => 'text'],
    'department' => ['label' => 'Bahagian', 'type' => 'text'],
    'position' => ['label' => 'Jawatan', 'type' => 'text'],
    'role' => ['label' => 'Role', 'type' => 'text'],
    'registered_at' => ['label' => 'Tarikh Daftar', 'type' => 'date'],
];
$user_role_sort_columns = [
    'fullname' => ['label' => 'Nama', 'type' => 'text'],
    'short_name' => ['label' => 'Nama Pendek', 'type' => 'text'],
    'email' => ['label' => 'Emel', 'type' => 'text'],
    'department' => ['label' => 'Bahagian', 'type' => 'text'],
    'position' => ['label' => 'Jawatan', 'type' => 'text'],
    'status' => ['label' => 'Status', 'type' => 'text'],
    'role' => ['label' => 'Role Semasa', 'type' => 'text'],
    'registered_at' => ['label' => 'Tarikh', 'type' => 'date'],
];
$user_table_sort_state = [
    'status' => [
        'sort' => trim((string) ($_GET['status_sort'] ?? '')),
        'dir' => strtolower(trim((string) ($_GET['status_dir'] ?? ''))),
        'columns' => $user_status_sort_columns,
    ],
    'role' => [
        'sort' => trim((string) ($_GET['role_sort'] ?? '')),
        'dir' => strtolower(trim((string) ($_GET['role_dir'] ?? ''))),
        'columns' => $user_role_sort_columns,
    ],
];
foreach ($user_table_sort_state as $table_key => $state) {
    if (!isset($state['columns'][$state['sort']])) {
        $user_table_sort_state[$table_key]['sort'] = '';
    }
    if (!in_array($state['dir'], ['asc', 'desc'], true)) {
        $user_table_sort_state[$table_key]['dir'] = 'asc';
    }
}

// PROSES TOGGLE STATUS (dalam page sama)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_status'], $_POST['user_id'])) {
    $uid = intval($_POST['user_id']);
    $new_status = $_POST['new_status'] ?? ''; // 'approved' atau 'rejected'

    if (!in_array($new_status, ['approved', 'rejected'], true)) {
        header("Location: user_list.php?error=invalid_status");
        exit();
    }
    
    // Elak edit superadmin lain
    $check = mysqli_prepare($conn, "SELECT email, role FROM users WHERE id = ?");
    mysqli_stmt_bind_param($check, "i", $uid);
    mysqli_stmt_execute($check);
    $target = mysqli_fetch_assoc(mysqli_stmt_get_result($check));
    
    if ($target && !in_array($target['email'], $protected_superadmin_emails, true)) {
        $update = mysqli_prepare($conn, "UPDATE users SET status = ? WHERE id = ?");
        mysqli_stmt_bind_param($update, "si", $new_status, $uid);
        if (mysqli_stmt_execute($update)) {
            logActivity(
                $conn,
                (int) ($_SESSION['user_id'] ?? 0),
                'update_user_status',
                'Kemaskini status user: ' . ($target['email'] ?? '') . ' kepada ' . $new_status . ' (User ID: ' . $uid . ')'
            );
        }
    }
    // Redirect ke diri sendiri untuk refresh data (POST-Redirect-GET pattern)
    header("Location: user_list.php?success=status_updated");
    exit();
}

// PROSES TUKAR ROLE (dalam page sama)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_role'], $_POST['user_id'], $_POST['new_role'])) {
    $uid = intval($_POST['user_id']);
    $new_role = $_POST['new_role'] ?? '';

    if (!in_array($new_role, ['user', 'admin', 'superadmin'], true)) {
        header("Location: user_list.php?error=invalid_role");
        exit();
    }
    
    // Elak edit superadmin lain
    $check = mysqli_prepare($conn, "SELECT email, role FROM users WHERE id = ?");
    mysqli_stmt_bind_param($check, "i", $uid);
    mysqli_stmt_execute($check);
    $target = mysqli_fetch_assoc(mysqli_stmt_get_result($check));
    
    if ($target && !in_array($target['email'], $protected_superadmin_emails, true)) {
        $update = mysqli_prepare($conn, "UPDATE users SET role = ? WHERE id = ?");
        mysqli_stmt_bind_param($update, "si", $new_role, $uid);
        if (mysqli_stmt_execute($update)) {
            logActivity(
                $conn,
                (int) ($_SESSION['user_id'] ?? 0),
                'update_user_role',
                'Kemaskini role user: ' . ($target['email'] ?? '') . ' kepada ' . $new_role . ' (User ID: ' . $uid . ')'
            );
        }
    }
    // Redirect ke diri sendiri untuk refresh data
    header("Location: user_list.php?success=role_updated");
    exit();
}

// CARIAN ADVANCE UNTUK TABLE 1: SENARAI PENGGUNA
$where1 = ["1=1"];
$params1 = [];
$types1 = "";

if (!empty($_GET['search1_ic'])) { $where1[] = "ic_number LIKE ?"; $params1[] = "%{$_GET['search1_ic']}%"; $types1 .= "s"; }
if (!empty($_GET['search1_email'])) { $where1[] = "email LIKE ?"; $params1[] = "%{$_GET['search1_email']}%"; $types1 .= "s"; }
if (!empty($_GET['search1_name'])) { $where1[] = "fullname LIKE ?"; $params1[] = "%{$_GET['search1_name']}%"; $types1 .= "s"; }
if (!empty($_GET['search1_role']) && $_GET['search1_role'] !== 'all') { $where1[] = "role = ?"; $params1[] = $_GET['search1_role']; $types1 .= "s"; }
if (!empty($_GET['search1_dept']) && $_GET['search1_dept'] !== 'all') { $where1[] = "department = ?"; $params1[] = $_GET['search1_dept']; $types1 .= "s"; }
if (!empty($_GET['search1_status']) && $_GET['search1_status'] !== 'all') { $where1[] = "status = ?"; $params1[] = $_GET['search1_status']; $types1 .= "s"; }

// TAMBAHAN: EKSKLUSKAN USER PENDING DARI TABLE 1
$where1[] = "status != 'pending'";

$sql1 = "SELECT id, fullname, short_name, ic_number, email, department, position, role, status, registered_at FROM users WHERE " . implode(' AND ', $where1) . " ORDER BY FIELD(status, 'approved', 'rejected'), registered_at DESC";

if (!empty($params1)) {
    $stmt1 = mysqli_prepare($conn, $sql1);
    mysqli_stmt_bind_param($stmt1, $types1, ...$params1);
    mysqli_stmt_execute($stmt1);
    $result1 = mysqli_stmt_get_result($stmt1);
} else {
    $result1 = mysqli_query($conn, $sql1);
}
$users = mysqli_fetch_all($result1, MYSQLI_ASSOC);
foreach ($users as $index => &$user_row) {
    $user_row['_default_order'] = $index;
}
unset($user_row);
sortUserTableRows($users, $user_table_sort_state['status']['sort'], $user_table_sort_state['status']['dir'], $user_table_sort_state['status']['columns']);
$users_pagination = paginateArrayItems($users, 'users_page', 15);
$display_users = $users_pagination['items'];

// CARIAN ADVANCE UNTUK TABLE 2: URUS ROLE PENGGUNA
$where2 = ["1=1"];
$params2 = [];
$types2 = "";

if (!empty($_GET['search2_ic'])) { $where2[] = "ic_number LIKE ?"; $params2[] = "%{$_GET['search2_ic']}%"; $types2 .= "s"; }
if (!empty($_GET['search2_email'])) { $where2[] = "email LIKE ?"; $params2[] = "%{$_GET['search2_email']}%"; $types2 .= "s"; }
if (!empty($_GET['search2_name'])) { $where2[] = "fullname LIKE ?"; $params2[] = "%{$_GET['search2_name']}%"; $types2 .= "s"; }
if (!empty($_GET['search2_role']) && $_GET['search2_role'] !== 'all') { $where2[] = "role = ?"; $params2[] = $_GET['search2_role']; $types2 .= "s"; }
if (!empty($_GET['search2_dept']) && $_GET['search2_dept'] !== 'all') { $where2[] = "department = ?"; $params2[] = $_GET['search2_dept']; $types2 .= "s"; }
if (!empty($_GET['search2_status']) && $_GET['search2_status'] !== 'all') { $where2[] = "status = ?"; $params2[] = $_GET['search2_status']; $types2 .= "s"; }

// TABLE 2: PAPAR SEMUA USER (termasuk pending)
$sql2 = "SELECT id, fullname, short_name, email, department, position, status, role, registered_at FROM users WHERE " . implode(' AND ', $where2) . " ORDER BY registered_at DESC";

if (!empty($params2)) {
    $stmt2 = mysqli_prepare($conn, $sql2);
    mysqli_stmt_bind_param($stmt2, $types2, ...$params2);
    mysqli_stmt_execute($stmt2);
    $result2 = mysqli_stmt_get_result($stmt2);
} else {
    $result2 = mysqli_query($conn, $sql2);
}
$all_users = mysqli_fetch_all($result2, MYSQLI_ASSOC);
foreach ($all_users as $index => &$user_row) {
    $user_row['_default_order'] = $index;
}
unset($user_row);
sortUserTableRows($all_users, $user_table_sort_state['role']['sort'], $user_table_sort_state['role']['dir'], $user_table_sort_state['role']['columns']);
$all_users_pagination = paginateArrayItems($all_users, 'roles_page', 15);
$display_all_users = $all_users_pagination['items'];

function getUserTableSortValue($user, $column) {
    switch ($column) {
        case 'registered_at':
            return strtotime((string) ($user['registered_at'] ?? '')) ?: 0;
        case 'fullname':
        case 'short_name':
        case 'ic_number':
        case 'email':
        case 'department':
        case 'position':
        case 'role':
        case 'status':
            return $user[$column] ?? '';
        default:
            return '';
    }
}

function sortUserTableRows(&$users, $sort_column, $sort_dir, $sort_columns) {
    if ($sort_column === '' || !isset($sort_columns[$sort_column])) {
        return;
    }

    usort($users, function ($user_a, $user_b) use ($sort_column, $sort_dir, $sort_columns) {
        $sort_type = $sort_columns[$sort_column]['type'] ?? 'text';
        $value_a = getUserTableSortValue($user_a, $sort_column);
        $value_b = getUserTableSortValue($user_b, $sort_column);

        if ($sort_type === 'date' || $sort_type === 'number') {
            $compare = ((float) $value_a) <=> ((float) $value_b);
        } else {
            $compare = strnatcasecmp((string) $value_a, (string) $value_b);
        }

        if ($compare === 0) {
            return ((int) ($user_a['_default_order'] ?? 0)) <=> ((int) ($user_b['_default_order'] ?? 0));
        }

        return $sort_dir === 'desc' ? -$compare : $compare;
    });
}

function buildUserTableSortUrl($table_key, $column, $current_sort, $current_dir) {
    $query = $_GET;
    unset($query[$table_key === 'status' ? 'users_page' : 'roles_page']);
    $sort_param = $table_key . '_sort';
    $dir_param = $table_key . '_dir';

    if ($current_sort !== $column) {
        $query[$sort_param] = $column;
        $query[$dir_param] = 'asc';
    } elseif ($current_dir === 'asc') {
        $query[$sort_param] = $column;
        $query[$dir_param] = 'desc';
    } else {
        unset($query[$sort_param], $query[$dir_param]);
    }

    $base_path = basename((string) ($_SERVER['PHP_SELF'] ?? 'user_list.php'));
    $query_string = http_build_query($query);
    return htmlspecialchars($base_path . ($query_string !== '' ? '?' . $query_string : ''));
}

function renderUserSortableHeader($label, $table_key, $column, $current_sort, $current_dir) {
    $is_active = $current_sort === $column;
    $indicator = $is_active ? ($current_dir === 'desc' ? '&darr;' : '&uarr;') : '&#8597;';
    $aria_sort = $is_active ? ($current_dir === 'desc' ? 'descending' : 'ascending') : 'none';

    echo '<th aria-sort="' . htmlspecialchars($aria_sort) . '">';
    echo '<a class="sort-link' . ($is_active ? ' active' : '') . '" href="' . buildUserTableSortUrl($table_key, $column, $current_sort, $current_dir) . '">';
    echo '<span>' . htmlspecialchars($label) . '</span><span class="sort-indicator">' . $indicator . '</span>';
    echo '</a>';
    echo '</th>';
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Senarai 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; --text-main: #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: '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 - SAMA PERSIS DENGAN DASHBOARD.PHP */

        .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); font-size: 1.3rem; font-weight: 600; display: flex; align-items: center; gap: 8px; }
        .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; }
        
        /* Filter Box */
        .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); margin-bottom: 14px; font-size: 1rem; font-weight: 600; display: flex; align-items: center; gap: 8px; }
        .filter-form { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; }
        .filter-field { display: flex; flex-direction: column; gap: 6px; }
        .filter-field label { color: var(--text-main); font-size: 0.82rem; font-weight: 800; }
        .filter-form input, .filter-form select { padding: 10px 14px; border: 1px solid var(--border); border-radius: 8px; font-size: 0.9rem; background: #fff; }
        .filter-form input:focus, .filter-form select:focus { border-color: var(--primary); outline: none; box-shadow: 0 0 0 3px rgba(0,119,182,0.15); }
        .filter-form button { padding: 10px 18px; background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; 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; }
        .filter-form button:hover { opacity: 0.95; }
        .filter-form a { padding: 10px 18px; background: #526b79; color: #fff; border-radius: 999px; text-decoration: none; display: inline-flex; align-items: center; gap: 7px; }
        
        .search-actions { display: flex; gap: 10px; margin-top: 20px; flex-wrap: wrap; }
        .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; transition: transform 0.2s ease, filter 0.2s ease, box-shadow 0.2s ease; }
        .btn:hover { transform: translateY(-1px); filter: brightness(1.04); }
        .btn-primary { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; }
        .btn-secondary { background: #526b79; color: #fff; }
        .search-actions .btn { width: 40px; min-height: 38px; height: 38px; min-width: 40px; padding: 0; border-radius: 999px; justify-content: center; gap: 0; }
        .search-actions .btn i { margin: 0; }
        .search-actions .btn-secondary { background: rgba(255,255,255,0.70); color: var(--primary); border: 1px solid rgba(0,119,182,0.18); box-shadow: 0 10px 22px rgba(2,62,95,0.08); }
        
        /* Card & Table */
        .card { background: var(--bg-card); border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.04); padding: 22px; margin-bottom: 25px; border: 1px solid var(--border); }
        .card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 18px; padding-bottom: 14px; border-bottom: 1px solid var(--border); }
        .card-title { color: var(--primary); font-size: 1.15rem; font-weight: 600; }
        table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
        table th { background: #f8fafc; color: var(--primary); font-weight: 600; text-align: center; padding: 14px 16px; border-bottom: 2px solid var(--border); }
        table td { padding: 14px 16px; border-bottom: 1px solid var(--border); vertical-align: middle; text-align: left; }
        table td.empty-state { text-align: center; }
        table tr:hover { background: #f8fbfd; }
        
        /* STATUS DROPDOWN STYLES */
        .status-dropdown {
            padding: 6px 12px;
            border: 1px solid var(--border);
            border-radius: 6px;
            font-size: 0.85rem;
            background: #fff;
            cursor: pointer;
            min-width: 110px;
            transition: border-color 0.2s ease;
        }
        .status-dropdown:focus {
            border-color: var(--primary);
            outline: none;
            box-shadow: 0 0 0 3px rgba(0,119,182,0.15);
        }
        .status-dropdown option[value="approved"] { color: var(--success); font-weight: 500; }
        .status-dropdown option[value="rejected"] { color: var(--danger); font-weight: 500; }
        
        /* ROLE SELECT STYLES */
        .role-select {
            padding: 6px 12px;
            border: 1px solid var(--border);
            border-radius: 6px;
            font-size: 0.85rem;
            background: #fff;
            cursor: pointer;
            min-width: 100px;
        }
        .role-select:focus {
            border-color: var(--primary);
            outline: none;
            box-shadow: 0 0 0 3px rgba(0,119,182,0.15);
        }
        
        /* Badges */
        .badge { padding: 5px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: 500; display: inline-block; }
        .badge-purple { background: #f0e6ff; color: var(--superadmin); }
        .badge-green { background: #e6fff0; color: var(--success); }
        .badge-yellow { background: #fff3cd; color: #856404; }
        .badge-red { background: #f8d7da; color: #721c24; }
        
        /* Footer */
        .page-footer { text-align: center; padding: 20px; color: var(--text-muted); font-size: 0.8rem; margin-top: 30px; }

        :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);
            --text-main: #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,
        .filter-box,
        .card {
            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 {
            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); }
        .filter-box h4,
        .card-title {
            color: var(--deep-blue);
            font-weight: 800;
        }
        .filter-box,
        .card {
            border-radius: 22px;
        }
        .filter-form input,
        .filter-form select,
        .status-dropdown,
        .role-select {
            background: rgba(255,255,255,0.76);
            border-color: rgba(255,255,255,0.62);
            border-radius: 12px;
            color: var(--text-main);
        }
        .filter-form input:focus,
        .filter-form select:focus,
        .status-dropdown:focus,
        .role-select:focus {
            border-color: rgba(0,180,216,0.82);
            box-shadow: 0 0 0 4px rgba(0,180,216,0.16);
        }
        .filter-form button,
        .btn-primary {
            background: linear-gradient(90deg, var(--primary), var(--secondary));
            box-shadow: 0 14px 28px rgba(0,119,182,0.18);
        }
        .filter-form a,
        .btn-secondary {
            background: #526b79;
            color: #fff;
            border: none;
        }
        .btn,
        .filter-form button,
        .filter-form a {
            padding: 10px 18px;
            border-radius: 999px;
            font-weight: 850;
            gap: 7px;
            transition: transform 0.2s ease, filter 0.2s ease, box-shadow 0.2s ease;
        }
        .btn:hover,
        .filter-form button:hover,
        .filter-form a:hover {
            transform: translateY(-1px);
            filter: brightness(1.04);
        }
        .search-actions .btn,
        .filter-form .search-actions button,
        .filter-form .search-actions a {
            width: 40px;
            min-height: 38px;
            height: 38px;
            min-width: 40px;
            padding: 0;
            border-radius: 999px;
            justify-content: center;
            gap: 0;
        }
        .filter-form .search-actions .btn-secondary {
            background: rgba(255,255,255,0.70);
            color: var(--primary);
            border: 1px solid rgba(0,119,182,0.18);
            box-shadow: 0 10px 22px rgba(2,62,95,0.08);
        }
        table {
            border-collapse: separate;
            border-spacing: 0;
        }
        table th {
            background: rgba(255,255,255,0.70);
            color: var(--deep-blue);
            border-bottom: 1px solid rgba(0,119,182,0.16);
        }
        .sort-link { color: inherit; display: inline-flex; align-items: center; justify-content: center; gap: 6px; text-decoration: none; width: 100%; }
        .sort-link:hover, .sort-link.active { color: var(--primary); }
        .sort-indicator { font-size: 0.78rem; line-height: 1; opacity: 0.78; }
        table td {
            border-bottom: 1px solid rgba(0,119,182,0.10);
        }
        table tr:hover {
            background: rgba(255,255,255,0.42);
        }
        .badge {
            font-weight: 700;
            border: 1px solid rgba(255,255,255,0.48);
        }
        .page-footer { color: var(--text-muted); }

        @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; }
        }
    
        /* 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);
        }
        .main .pagination-wrap {
            padding-right: 24px;
        }
        .main .pagination {
            margin-right: 8px;
        }
        @media (max-width: 640px) {
            .main .pagination-wrap {
                justify-content: center !important;
                padding-right: 0;
            }
            .main .pagination-info {
                width: 100%;
                text-align: center;
            }
            .main .pagination {
                width: 100%;
                justify-content: center;
                margin-right: 0;
            }
        }</style>
</head>
<body class="role-<?= htmlspecialchars($role) ?>">

    <!-- SIDEBAR - SAMA PERSIS DENGAN DASHBOARD.PHP -->
    <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, 'user_list.php'); ?>
        </ul>
    </aside>

    <!-- MAIN CONTENT -->
    <main class="main">
        <div class="top-bar">
            <h2><i class="fas fa-list"></i> Senarai Pengguna</h2>
            <?php renderTopBarUserMenu($conn, $role, 'user_list.php'); ?>
        </div>

        <?php
        renderBreadcrumb([
            ['label' => 'Dashboard', 'url' => 'dashboard.php'],
            ['label' => 'Pengurusan Pengguna', 'url' => 'user_management.php'],
            ['label' => 'Senarai Pengguna', 'url' => 'user_list.php', 'current' => true]
        ]);
        ?>

        <!-- SUCCESS MESSAGES -->
        <?php if (isset($_GET['success'])): 
            if ($_GET['success'] === 'status_updated'): ?>
        <div style="background:#d4edda;color:#155724;padding:12px 20px;border-radius:8px;margin-bottom:20px;border-left:4px solid var(--success);"> Status pengguna berjaya dikemaskini!
        </div>
            <?php elseif ($_GET['success'] === 'role_updated'): ?>
        <div style="background:#d4edda;color:#155724;padding:12px 20px;border-radius:8px;margin-bottom:20px;border-left:4px solid var(--success);"> Role pengguna berjaya dikemaskini!
        </div>
            <?php endif; ?>
        <?php endif; ?>

        <!-- FILTER BOX UNTUK TABLE 1: SENARAI PENGGUNA -->
        <div class="filter-box">
            <h4><i></i> Carian - Senarai Pengguna</h4>
            <form method="GET" class="filter-form">
                <?php if (($user_table_sort_state['status']['sort'] ?? '') !== ''): ?>
                <input type="hidden" name="status_sort" value="<?= htmlspecialchars($user_table_sort_state['status']['sort']) ?>">
                <input type="hidden" name="status_dir" value="<?= htmlspecialchars($user_table_sort_state['status']['dir']) ?>">
                <?php endif; ?>
                <div class="filter-field">
                    <label>No. IC</label>
                    <input type="text" name="search1_ic" placeholder="Cari No. IC..." value="<?= htmlspecialchars($_GET['search1_ic']??'') ?>">
                </div>
                <div class="filter-field">
                    <label>Emel</label>
                    <input type="email" name="search1_email" placeholder="Cari Emel..." value="<?= htmlspecialchars($_GET['search1_email']??'') ?>">
                </div>
                <div class="filter-field">
                    <label>Nama</label>
                    <input type="text" name="search1_name" placeholder="Cari Nama..." value="<?= htmlspecialchars($_GET['search1_name']??'') ?>">
                </div>
                <div class="filter-field">
                    <label>Role</label>
                    <select name="search1_role">
                        <option value="all">Semua Role</option>
                        <option value="user" <?= (($_GET['search1_role']??'')==='user')?'selected':'' ?>>User</option>
                        <option value="admin" <?= (($_GET['search1_role']??'')==='admin')?'selected':'' ?>>Admin</option>
                        <option value="superadmin" <?= (($_GET['search1_role']??'')==='superadmin')?'selected':'' ?>>Superadmin</option>
                    </select>
                </div>
                <div class="filter-field">
                    <label>Bahagian</label>
                    <select name="search1_dept">
                        <option value="all">Semua Bahagian</option>
                        <?php foreach ($departments_list as $dept): ?>
                        <option value="<?= htmlspecialchars($dept) ?>" <?= (($_GET['search1_dept']??'')===$dept)?'selected':'' ?>><?= htmlspecialchars($dept) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-field">
                    <label>Status</label>
                    <select name="search1_status">
                        <option value="all">Semua Status</option>
                        <option value="approved" <?= (($_GET['search1_status']??'')==='approved')?'selected':'' ?>>Active</option>
                        <option value="rejected" <?= (($_GET['search1_status']??'')==='rejected')?'selected':'' ?>>Deactive</option>
                    </select>
                </div>
                <div class="search-actions">
                    <button type="submit" class="btn btn-primary" title="Cari" aria-label="Cari"><i class="fas fa-search"></i></button>
                    <a href="user_list.php" class="btn btn-secondary" title="Reset" aria-label="Reset"><i class="fas fa-rotate-left"></i></a>
                </div>
            </form>
        </div>

        <!-- TABLE 1: SENARAI PENGGUNA (Dengan Toggle Status) -->
        <div class="card">
            <div class="card-header">
                <div class="card-title"> Status Senarai Pengguna</div>
            </div>
            <div class="table-responsive" style="overflow-x:auto;">
                <table>
                    <thead>
                        <tr>
                            <th>Bil</th>
                            <?php renderUserSortableHeader('Nama', 'status', 'fullname', $user_table_sort_state['status']['sort'], $user_table_sort_state['status']['dir']); ?>
                            <?php renderUserSortableHeader('Nama Pendek', 'status', 'short_name', $user_table_sort_state['status']['sort'], $user_table_sort_state['status']['dir']); ?>
                            <?php renderUserSortableHeader('No. IC', 'status', 'ic_number', $user_table_sort_state['status']['sort'], $user_table_sort_state['status']['dir']); ?>
                            <?php renderUserSortableHeader('Emel', 'status', 'email', $user_table_sort_state['status']['sort'], $user_table_sort_state['status']['dir']); ?>
                            <?php renderUserSortableHeader('Bahagian', 'status', 'department', $user_table_sort_state['status']['sort'], $user_table_sort_state['status']['dir']); ?>
                            <?php renderUserSortableHeader('Jawatan', 'status', 'position', $user_table_sort_state['status']['sort'], $user_table_sort_state['status']['dir']); ?>
                            <?php renderUserSortableHeader('Role', 'status', 'role', $user_table_sort_state['status']['sort'], $user_table_sort_state['status']['dir']); ?>
                            <th>Status</th>
                            <?php renderUserSortableHeader('Tarikh Daftar', 'status', 'registered_at', $user_table_sort_state['status']['sort'], $user_table_sort_state['status']['dir']); ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($display_users)): ?>
                        <tr><td colspan="10" style="text-align:center;padding:30px;color:var(--text-muted);">Tiada rekod dijumpai.</td></tr>
                        <?php else: ?>
                        <?php foreach ($display_users as $index => $u): 
                            $is_locked_superadmin = in_array($u['email'], $protected_superadmin_emails, true);
                        ?>
                        <tr>
                            <td><?= $users_pagination['offset'] + $index + 1 ?></td>
                            <td><?= htmlspecialchars($u['fullname']) ?></td>
                            <td><?= htmlspecialchars($u['short_name'] ?: '-') ?></td>
                            <td><?= htmlspecialchars($u['ic_number']) ?></td>
                            <td><?= htmlspecialchars($u['email']) ?></td>
                            <td><?= htmlspecialchars($u['department']) ?></td>
                            <td><?= htmlspecialchars($u['position'] ?: '-') ?></td>
                            <td><span class="badge badge-purple"><?= ucfirst($u['role']) ?></span></td>
                            
                            <!-- STATUS DROPDOWN -->
                            <td>
                                <?php if (!$is_locked_superadmin): ?>
                                <form method="POST" style="display:inline;" id="statusForm_<?= $u['id'] ?>">
                                    <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                                    <input type="hidden" name="toggle_status" value="1">
                                    <input type="hidden" name="original_status" value="<?= $u['status'] ?>">
                                    <select name="new_status" class="status-dropdown" onchange="confirmStatusChange(this, <?= $u['id'] ?>)">
                                        <option value="approved" <?= $u['status']==='approved'?'selected':'' ?>> Active</option>
                                        <option value="rejected" <?= $u['status']==='rejected'?'selected':'' ?>> Deactive</option>
                                    </select>
                                </form>
                                <?php else: ?>
                                    <span class="badge badge-green">Active</span>
                                <?php endif; ?>
                            </td>
                            
                            <td><?= date('d/m/Y', strtotime($u['registered_at'])) ?></td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
                <?php renderPaginationControls($users_pagination, 'pengguna'); ?>
            </div>
        </div>

        <!-- FILTER BOX UNTUK TABLE 2: URUS ROLE PENGGUNA -->
        <div class="filter-box">
            <h4><i class="fas fa-filter"></i> Carian - Role Pengguna</h4>
            <form method="GET" class="filter-form">
                <?php if (($user_table_sort_state['role']['sort'] ?? '') !== ''): ?>
                <input type="hidden" name="role_sort" value="<?= htmlspecialchars($user_table_sort_state['role']['sort']) ?>">
                <input type="hidden" name="role_dir" value="<?= htmlspecialchars($user_table_sort_state['role']['dir']) ?>">
                <?php endif; ?>
                <div class="filter-field">
                    <label>No. IC</label>
                    <input type="text" name="search2_ic" placeholder="Cari No. IC..." value="<?= htmlspecialchars($_GET['search2_ic']??'') ?>">
                </div>
                <div class="filter-field">
                    <label>Emel</label>
                    <input type="email" name="search2_email" placeholder="Cari Emel..." value="<?= htmlspecialchars($_GET['search2_email']??'') ?>">
                </div>
                <div class="filter-field">
                    <label>Nama</label>
                    <input type="text" name="search2_name" placeholder="Cari Nama..." value="<?= htmlspecialchars($_GET['search2_name']??'') ?>">
                </div>
                <div class="filter-field">
                    <label>Role</label>
                    <select name="search2_role">
                        <option value="all">Semua Role</option>
                        <option value="user" <?= (($_GET['search2_role']??'')==='user')?'selected':'' ?>>User</option>
                        <option value="admin" <?= (($_GET['search2_role']??'')==='admin')?'selected':'' ?>>Admin</option>
                        <option value="superadmin" <?= (($_GET['search2_role']??'')==='superadmin')?'selected':'' ?>>Superadmin</option>
                    </select>
                </div>
                <div class="filter-field">
                    <label>Bahagian</label>
                    <select name="search2_dept">
                        <option value="all">Semua Bahagian</option>
                        <?php foreach ($departments_list as $dept): ?>
                        <option value="<?= htmlspecialchars($dept) ?>" <?= (($_GET['search2_dept']??'')===$dept)?'selected':'' ?>><?= htmlspecialchars($dept) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-field">
                    <label>Status</label>
                    <select name="search2_status">
                        <option value="all">Semua Status</option>
                        <option value="approved" <?= (($_GET['search2_status']??'')==='approved')?'selected':'' ?>>Active</option>
                        <option value="rejected" <?= (($_GET['search2_status']??'')==='rejected')?'selected':'' ?>>Deactive</option>
                    </select>
                </div>
                <div class="search-actions">
                    <button type="submit" class="btn btn-primary" title="Cari" aria-label="Cari"><i class="fas fa-search"></i></button>
                    <a href="user_list.php" class="btn btn-secondary" title="Reset" aria-label="Reset"><i class="fas fa-rotate-left"></i></a>
                </div>
            </form>
        </div>

        <!-- TABLE 2: URUS ROLE PENGGUNA (Dengan Dropdown Tukar Role) -->
        <div class="card">
            <div class="card-header">
                <div class="card-title"> Urus Role Pengguna</div>
            </div>
            <div class="table-responsive" style="overflow-x:auto;">
                <table>
                    <thead>
                        <tr>
                            <th>Bil</th>
                            <?php renderUserSortableHeader('Nama', 'role', 'fullname', $user_table_sort_state['role']['sort'], $user_table_sort_state['role']['dir']); ?>
                            <?php renderUserSortableHeader('Nama Pendek', 'role', 'short_name', $user_table_sort_state['role']['sort'], $user_table_sort_state['role']['dir']); ?>
                            <?php renderUserSortableHeader('Emel', 'role', 'email', $user_table_sort_state['role']['sort'], $user_table_sort_state['role']['dir']); ?>
                            <?php renderUserSortableHeader('Bahagian', 'role', 'department', $user_table_sort_state['role']['sort'], $user_table_sort_state['role']['dir']); ?>
                            <?php renderUserSortableHeader('Jawatan', 'role', 'position', $user_table_sort_state['role']['sort'], $user_table_sort_state['role']['dir']); ?>
                            <?php renderUserSortableHeader('Status', 'role', 'status', $user_table_sort_state['role']['sort'], $user_table_sort_state['role']['dir']); ?>
                            <?php renderUserSortableHeader('Role Semasa', 'role', 'role', $user_table_sort_state['role']['sort'], $user_table_sort_state['role']['dir']); ?>
                            <th>Tukar Role</th>
                            <?php renderUserSortableHeader('Tarikh', 'role', 'registered_at', $user_table_sort_state['role']['sort'], $user_table_sort_state['role']['dir']); ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($display_all_users)): ?>
                        <tr><td colspan="10" style="text-align:center;padding:30px;color:var(--text-muted);">Tiada rekod dijumpai.</td></tr>
                        <?php else: ?>
                        <?php foreach ($display_all_users as $index => $u): 
                            $is_locked_superadmin = in_array($u['email'], $protected_superadmin_emails, true);
                        ?>
                        <tr>
                            <td><?= $all_users_pagination['offset'] + $index + 1 ?></td>
                            <td><?= htmlspecialchars($u['fullname']) ?></td>
                            <td><?= htmlspecialchars($u['short_name'] ?: '-') ?></td>
                            <td><?= htmlspecialchars($u['email']) ?></td>
                            <td><?= htmlspecialchars($u['department']) ?></td>
                            <td><?= htmlspecialchars($u['position'] ?: '-') ?></td>
                            <td><span class="badge <?= $u['status']==='approved'?'badge-green':($u['status']==='pending'?'badge-yellow':'badge-red') ?>"><?= ucfirst($u['status']) ?></span></td>
                            <td><span class="badge badge-purple"><?= ucfirst($u['role']) ?></span></td>
                            <td>
                                <?php if ($is_locked_superadmin): ?>
                                    <span class="badge badge-purple">Superadmin</span>
                                <?php else: ?>
                                    <form method="POST" style="display:inline;">
                                        <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                                        <input type="hidden" name="change_role" value="1">
                                        <input type="hidden" name="original_role" value="<?= $u['role'] ?>">
                                        <select name="new_role" class="role-select" onchange="confirmRoleChange(this, <?= $u['id'] ?>)">
                                            <option value="user" <?= $u['role']==='user'?'selected':'' ?>>User</option>
                                            <option value="admin" <?= $u['role']==='admin'?'selected':'' ?>>Admin</option>
                                        </select>
                                    </form>
                                <?php endif; ?>
                            </td>
                            <td><?= date('d/m/Y', strtotime($u['registered_at'])) ?></td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
                <?php renderPaginationControls($all_users_pagination, 'pengguna'); ?>
            </div>
        </div>

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

    <script>
                const sidebar = document.getElementById('sidebar');
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', () => sidebar.classList.toggle('collapsed'));
        }
        if (window.innerWidth < 992) sidebar.classList.add('collapsed');

        document.querySelectorAll('.sidebar-menu .dropdown-toggle, .dropdown-toggle').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                const dropdown = this.parentElement;
                const isActive = dropdown.classList.contains('active');
                document.querySelectorAll('.sidebar-menu .dropdown, .dropdown').forEach(item => {
                    if (item !== dropdown) item.classList.remove('active');
                });
                dropdown.classList.toggle('active', !isActive);
            });
        });
        function confirmStatusChange(select, userId) {
            const form = select.closest('form');
            const newStatus = select.value;
            const originalStatus = form.querySelector('input[name="original_status"]')?.value;
            
            if (newStatus === originalStatus) {
                return;
            }
            
            const actionText = newStatus === 'approved' ? 'AKTIFKAN' : 'NYAHAKTIFKAN';
            
            if (confirm(`Adakah anda pasti mahu ${actionText} akaun pengguna ini?`)) {
                form.submit();
            } else {
                select.value = originalStatus;
            }
        }

        function confirmRoleChange(select, userId) {
            const form = select.closest('form');
            const newRole = select.value;
            const originalRole = form.querySelector('input[name="original_role"]')?.value;

            if (newRole === originalRole) {
                return;
            }

            if (confirm(`Adakah anda pasti mahu tukar role pengguna ini kepada ${newRole.toUpperCase()}?`)) {
                form.submit();
            } else {
                select.value = originalRole;
            }
        }
        
        // Confirm Logout
        function confirmLogout() { return confirm("Adakah anda pasti ingin log keluar?"); }
    </script>
    <?php renderSessionTimeoutScript(); ?>
</body>
</html>


