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

// DAPATKAN ROLE UNTUK SIDEBAR CONSISTENCY
$role = $_SESSION['role'] ?? 'user';

// PROSES BULK APPROVE/REJECT
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['bulk_action'], $_POST['user_ids']) && is_array($_POST['user_ids'])) {
        $action = $_POST['bulk_action'];
        $new_status = ($action === 'approve') ? 'approved' : 'rejected';
        $user_ids = array_map('intval', $_POST['user_ids']);
        
        if (!empty($user_ids)) {
            $placeholders = implode(',', array_fill(0, count($user_ids), '?'));
            $stmt = mysqli_prepare($conn, "UPDATE users SET status = ? WHERE id IN ($placeholders)");
            $types = 's' . str_repeat('i', count($user_ids));
            mysqli_stmt_bind_param($stmt, $types, $new_status, ...$user_ids);
            if (mysqli_stmt_execute($stmt)) {
                logActivity(
                    $conn,
                    (int) ($_SESSION['user_id'] ?? 0),
                    'update_user_status_bulk',
                    'Kelulusan user pukal: ' . $action . ' kepada ' . count($user_ids) . ' user (ID: ' . implode(', ', $user_ids) . ')'
                );
            }
        }
        header("Location: user_approval.php?success=bulk_" . $action);
        exit();
    }
    
    // PROSES INDIVIDUAL ACTION VIA DROPDOWN
    if (isset($_POST['individual_action'], $_POST['user_id'], $_POST['action_type'])) {
        $uid = intval($_POST['user_id']);
        $action_type = $_POST['action_type']; // 'approve' atau 'reject'
        $new_status = ($action_type === 'approve') ? 'approved' : 'rejected';
        
        $stmt = mysqli_prepare($conn, "UPDATE users SET status = ? WHERE id = ?");
        mysqli_stmt_bind_param($stmt, "si", $new_status, $uid);
        if (mysqli_stmt_execute($stmt)) {
            logActivity(
                $conn,
                (int) ($_SESSION['user_id'] ?? 0),
                'update_user_status',
                'Kelulusan user: ' . $action_type . ' (User ID: ' . $uid . ', Status: ' . $new_status . ')'
            );
        }
        
        header("Location: user_approval.php?success=" . $action_type);
        exit();
    }
}

// Dapatkan senarai pengguna pending
$sql = "SELECT id, fullname, ic_number, email, department, registered_at FROM users WHERE status = 'pending' ORDER BY registered_at DESC";
$result = mysqli_query($conn, $sql);
$pending_users = mysqli_fetch_all($result, MYSQLI_ASSOC);
$pending_pagination = paginateArrayItems($pending_users, 'page', 15);
$display_pending_users = $pending_pagination['items'];
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelulusan 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; }
        
        /* Stats & Table */
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px; margin-bottom: 25px; }
        .stat-card { background: var(--bg-card); padding: 18px; border-radius: 12px; text-align: center; border-top: 4px solid var(--warning); box-shadow: 0 2px 8px rgba(0,0,0,0.04); }
        .stat-card h3 { font-size: 1.8rem; margin: 8px 0; color: var(--text-main); }
        .stat-card p { font-size: 0.85rem; color: var(--text-muted); }
        .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; }
        
        /* Bulk Action Bar */
        .bulk-actions {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
            padding: 12px 15px;
            background: #f8fafc;
            border-radius: 8px;
            border: 1px solid var(--border);
            align-items: center;
            flex-wrap: wrap;
        }
        .bulk-actions .btn-bulk {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.85rem;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            color: #fff;
        }
        .btn-approve-bulk { background: var(--success); }
        .btn-reject-bulk { background: var(--danger); }
        .btn-bulk:hover { opacity: 0.95; }
        .bulk-actions .selected-count {
            font-size: 0.85rem;
            color: var(--text-muted);
            margin-left: auto;
        }
        
        /* Table */
        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; }
        .badge { padding: 5px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: 500; }
        .badge-yellow { background: #fff3cd; color: #856404; }
        
        /* Checkbox Styles */
        .checkbox-cell { width: 40px; text-align: center; }
        .checkbox-cell input[type="checkbox"] {
            width: 18px;
            height: 18px;
            cursor: pointer;
            accent-color: var(--primary);
        }
        
        /* ACTION DROPDOWN STYLES - SAMA SEPERTI user_list.php */
        .action-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;
        }
        .action-dropdown:focus {
            border-color: var(--primary);
            outline: none;
            box-shadow: 0 0 0 3px rgba(0,119,182,0.15);
        }
        .action-dropdown option[value="approve"] { color: var(--success); font-weight: 500; }
        .action-dropdown option[value="reject"] { color: var(--danger); font-weight: 500; }
        
        .empty-state { text-align: center; padding: 40px 20px; color: var(--text-muted); }
        .empty-state i { font-size: 2.5rem; margin-bottom: 12px; opacity: 0.6; }
        .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,
        .stat-card,
        .card,
        .bulk-actions {
            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); }
        .card-title {
            color: var(--deep-blue);
            font-weight: 800;
        }
        .stat-card,
        .card,
        .bulk-actions {
            border-radius: 22px;
        }
        .stat-card {
            border-top: 4px solid var(--secondary);
        }
        .stat-card h3 {
            color: var(--deep-blue);
            font-weight: 800;
        }
        .action-dropdown {
            background: rgba(255,255,255,0.76);
            border-color: rgba(255,255,255,0.62);
            border-radius: 12px;
            color: var(--text-main);
        }
        .action-dropdown:focus {
            border-color: rgba(0,180,216,0.82);
            box-shadow: 0 0 0 4px rgba(0,180,216,0.16);
        }
        .bulk-actions .btn-bulk {
            border-radius: 12px;
            font-weight: 700;
            transition: opacity 0.2s, transform 0.2s, box-shadow 0.2s;
        }
        .btn-approve-bulk { background: linear-gradient(135deg, #1a9955, #34c77b); }
        .btn-reject-bulk { background: linear-gradient(135deg, #dc3545, #f06472); }
        .btn-bulk:hover {
            opacity: 0.96;
            transform: translateY(-1px);
        }
        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);
        }
        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);
        }
        .empty-state {
            background: rgba(255,255,255,0.42);
            border-radius: 18px;
        }
        .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);
        }</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_approval.php'); ?>
        </ul>
    </aside>

    <!-- MAIN CONTENT -->
    <main class="main">
        <div class="top-bar">
            <h2><i class="fas fa-user-check"></i> Kelulusan Pengguna Baru</h2>
            <?php renderTopBarUserMenu($conn, $role, 'user_approval.php'); ?>
        </div>

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

        <!-- SUCCESS MESSAGE -->
        <?php if (isset($_GET['success'])): 
            $success_msg = '';
            if ($_GET['success'] === 'bulk_approve') $success_msg = 'Pengguna terpilih berjaya DILULUSKAN!';
            elseif ($_GET['success'] === 'bulk_reject') $success_msg = 'Pengguna terpilih berjaya DITOLAK!';
            elseif ($_GET['success'] === 'approve') $success_msg = 'Pengguna berjaya DILULUSKAN!';
            elseif ($_GET['success'] === 'reject') $success_msg = 'Pengguna berjaya DITOLAK!';
        ?>
        <div style="background:<?= in_array($_GET['success'], ['approve','bulk_approve'])?'#d4edda':'#f8d7da' ?>;color:<?= in_array($_GET['success'], ['approve','bulk_approve'])?'#155724':'#721c24' ?>;padding:12px 20px;border-radius:8px;margin-bottom:20px;border-left:4px solid <?= in_array($_GET['success'], ['approve','bulk_approve'])?'#1a9955':'#dc3545' ?>;">
            <?= $success_msg ?>
        </div>
        <?php endif; ?>

        <!-- STATS -->
        <div class="stats-grid">
            <div class="stat-card">
                <i class="fas fa-hourglass-half" style="font-size:1.5rem;color:var(--warning);"></i>
                <h3><?= count($pending_users) ?></h3>
                <p>Menunggu Kelulusan</p>
            </div>
        </div>

        <!-- PENDING USERS TABLE -->
        <div class="card">
            <div class="card-header">
                <div class="card-title">Senarai Permohonan Baru</div>
            </div>
            
            <?php if (empty($display_pending_users)): ?>
                <div class="empty-state">
                    <i class="fas fa-check-circle"></i><br>
                    Tiada permohonan baru.<br>
                </div>
            <?php else: ?>
            
            <!-- BULK ACTION BAR -->
            <form method="POST" id="bulkForm">
                <div class="bulk-actions">
                    <button type="submit" name="bulk_action" value="approve" class="btn-bulk btn-approve-bulk" onclick="return confirmBulk('approve')">
                        <i class="fas fa-check"></i> Lulus 
                    </button>
                    <button type="submit" name="bulk_action" value="reject" class="btn-bulk btn-reject-bulk" onclick="return confirmBulk('reject')">
                        <i class="fas fa-times"></i> Tolak 
                    </button>
                    <span class="selected-count" id="selectedCount">0 dipilih</span>
                </div>
                
                <div class="table-responsive" style="overflow-x:auto;">
                    <table>
                        <thead>
                            <tr>
                                <th class="checkbox-cell">
                                    <input type="checkbox" id="selectAll" title="Pilih Semua">
                                </th>
                                <th>Nama Penuh</th>
                                <th>No. IC</th>
                                <th>Emel</th>
                                <th>Bahagian</th>
                                <th>Tarikh Daftar</th>
                                <th>Tindakan</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($display_pending_users as $u): ?>
                            <tr>
                                <td class="checkbox-cell">
                                    <input type="checkbox" name="user_ids[]" value="<?= $u['id'] ?>" class="user-checkbox">
                                </td>
                                <td><?= htmlspecialchars($u['fullname']) ?></td>
                                <td><?= htmlspecialchars($u['ic_number']) ?></td>
                                <td><?= htmlspecialchars($u['email']) ?></td>
                                <td><?= htmlspecialchars($u['department']) ?></td>
                                <td><?= date('d/m/Y H:i', strtotime($u['registered_at'])) ?></td>
                                
                                <!-- ACTION DROPDOWN (Gantikan Butang Individu) -->
                                <td>
                                    <form method="POST" style="display:inline;" id="actionForm_<?= $u['id'] ?>">
                                        <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                                        <input type="hidden" name="individual_action" value="1">
                                        <select name="action_type" class="action-dropdown" onchange="confirmActionChange(this, <?= $u['id'] ?>)">
                                            <option value="">-- Pilih Tindakan --</option>
                                            <option value="approve">Lulus</option>
                                            <option value="reject">Tolak</option>
                                        </select>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <?php renderPaginationControls($pending_pagination, 'permohonan'); ?>
                </div>
            </form>
            <?php endif; ?>
        </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 confirmLogout() { return confirm("Adakah anda pasti ingin log keluar?"); }
        
        // SELECT ALL CHECKBOX
        const selectAll = document.getElementById('selectAll');
        const checkboxes = document.querySelectorAll('.user-checkbox');
        const selectedCount = document.getElementById('selectedCount');
        
        function updateSelectedCount() {
            const count = document.querySelectorAll('.user-checkbox:checked').length;
            selectedCount.textContent = count + ' dipilih';
        }
        
        if (selectAll) {
            selectAll.addEventListener('change', function() {
                checkboxes.forEach(cb => cb.checked = this.checked);
                updateSelectedCount();
            });
        }
        
        checkboxes.forEach(cb => {
            cb.addEventListener('change', updateSelectedCount);
        });
        
        // CONFIRM BULK ACTION
        function confirmBulk(action) {
            const checked = document.querySelectorAll('.user-checkbox:checked');
            if (checked.length === 0) {
                alert('Sila pilih sekurang-kurangnya satu pengguna.');
                return false;
            }
            const actionText = action === 'approve' ? 'LULUSKAN' : 'TOLAK';
            return confirm(`Adakah anda pasti mahu ${actionText} ${checked.length} pengguna terpilih?`);
        }
        
        // CONFIRM INDIVIDUAL ACTION VIA DROPDOWN
        function confirmActionChange(select, userId) {
            const actionType = select.value;
            
            // Jika tiada pilihan, jangan buat apa-apa
            if (!actionType) {
                return;
            }
            
            const actionText = actionType === 'approve' ? 'LULUSKAN' : 'TOLAK';
            
            if (confirm(`Adakah anda pasti mahu ${actionText} akaun pengguna ini?`)) {
                // Submit form jika user confirm
                document.getElementById('actionForm_' + userId).submit();
            } else {
                // Revert ke pilihan asal jika user cancel
                select.value = '';
            }
        }
    </script>
    <?php renderSessionTimeoutScript(); ?>
</body>
</html>


