<?php
session_start();

require_once __DIR__ . '/../../DataBase/koneksi.php';
require_once __DIR__ . '/../../vendor/autoload.php';

// ✅ IMPORT STATEMENTS DI PALING ATAS
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Alignment;

// Cek login dan role
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    header("Location: ../../index.html?error=session");
    exit;
}

if (!function_exists('checkRole')) {
    function checkRole($allowedRoles) {
        $userRole = $_SESSION['role'] ?? $_SESSION['user_type'] ?? '';
        if (!in_array($userRole, $allowedRoles)) {
            header("Location: ../../index.html?error=unauthorized");
            exit;
        }
    }
}
checkRole(['admin']); // Hanya Admin

/* =========================
   AJAX HANDLER
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    // EXPORT HANDLER
    if ($action === 'export') {
        $exportFormat = $_POST['export_format'] ?? '';
        $exportScope = $_POST['export_scope'] ?? 'all';
        $includePasswords = isset($_POST['include_passwords']);
        $includePasswordHash = isset($_POST['include_password_hash']);

        if (empty($exportFormat)) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Format export harus dipilih!']);
            exit;
        }

        // Build WHERE clause for filtered export
        $whereConditions = [];
        $params = [];
        $types = '';

        if ($exportScope === 'filtered') {
            if (!empty($_POST['filter_search'])) {
                $whereConditions[] = "(username LIKE ? OR full_name LIKE ? OR email LIKE ?)";
                $searchParam = "%{$_POST['filter_search']}%";
                $params[] = $searchParam;
                $params[] = $searchParam;
                $params[] = $searchParam;
                $types .= 'sss';
            }
            if (!empty($_POST['filter_role'])) {
                $whereConditions[] = "role = ?";
                $params[] = $_POST['filter_role'];
                $types .= 's';
            }
            if (!empty($_POST['filter_department'])) {
                $whereConditions[] = "department = ?";
                $params[] = $_POST['filter_department'];
                $types .= 's';
            }
            if (isset($_POST['filter_status']) && $_POST['filter_status'] !== '') {
                $whereConditions[] = "is_active = ?";
                $params[] = (int)$_POST['filter_status'];
                $types .= 'i';
            }
        }

        $whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';
        $sql = "SELECT * FROM users $whereClause ORDER BY department ASC, created_at DESC";

        $stmt = $conn->prepare($sql);
        if (!empty($params)) {
            $stmt->bind_param($types, ...$params);
        }
        $stmt->execute();
        $result = $stmt->get_result();

        $exportData = [];
        while($row = $result->fetch_assoc()) {
            $exportData[] = $row;
        }
        $stmt->close();

        // Generate filename
        $timestamp = date('Y-m-d_His');
        $filename = "ACF_EDU_HUB_Users_{$timestamp}";

        if ($exportFormat === 'excel') {
            // Excel Export
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            $sheet->setTitle('User Data');

            // Header styling
            $headerStyle = [
                'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF'], 'size' => 12],
                'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '4D869C']],
                'borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN]],
                'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER]
            ];

            // Set headers
            $headers = ['No', 'Username', 'Nama Lengkap', 'Email', 'Role', 'Department', 'Status', 'Created At', 'Last Login'];
            if ($includePasswords) $headers[] = 'Password (Plain Text)';
            if ($includePasswordHash) $headers[] = 'Password Hash';

            $col = 'A';
            foreach ($headers as $header) {
                $sheet->setCellValue($col . '1', $header);
                $sheet->getStyle($col . '1')->applyFromArray($headerStyle);
                $sheet->getColumnDimension($col)->setAutoSize(true);
                $col++;
            }

            // Data rows
            $row = 2;
            foreach ($exportData as $index => $user) {
                $col = 'A';
                $sheet->setCellValue($col++ . $row, $index + 1);
                $sheet->setCellValue($col++ . $row, $user['username']);
                $sheet->setCellValue($col++ . $row, $user['full_name']);
                $sheet->setCellValue($col++ . $row, $user['email'] ?? '-');
                $sheet->setCellValue($col++ . $row, strtoupper($user['role']));
                $sheet->setCellValue($col++ . $row, $user['department'] ?? '-');
                $sheet->setCellValue($col++ . $row, $user['is_active'] ? 'Active' : 'Inactive');
                $sheet->setCellValue($col++ . $row, $user['created_at']);
                $sheet->setCellValue($col++ . $row, $user['last_login'] ?? '-');
                
                if ($includePasswords) {
                    // ✅ METODE 1: DENGAN ENKRIPSI (SUDAH DIAKTIFKAN)
                    if (!empty($user['password_encrypted']) && !empty($user['encryption_key'])) {
                        $decrypted = openssl_decrypt($user['password_encrypted'], 'AES-128-CBC', $user['encryption_key'], 0, substr(md5($user['encryption_key']), 0, 16));
                        $sheet->setCellValue($col++ . $row, $decrypted ?: '[Decryption Failed]');
                    } else {
                        $sheet->setCellValue($col++ . $row, '[Not Available - User created before encryption]');
                    }
                }
                if ($includePasswordHash) {
                    $sheet->setCellValue($col++ . $row, $user['password']);
                }
                
                $row++;
            }

            // Auto-size all columns
            foreach(range('A', $col) as $columnID) {
                $sheet->getColumnDimension($columnID)->setAutoSize(true);
            }

            // Output
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
            header('Cache-Control: max-age=0');

            $writer = new Xlsx($spreadsheet);
            $writer->save('php://output');
            exit;

        } elseif ($exportFormat === 'csv') {
            // CSV Export
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment;filename="' . $filename . '.csv"');
            header('Cache-Control: max-age=0');

            $output = fopen('php://output', 'w');
            
            // UTF-8 BOM for Excel compatibility
            fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));

            // Headers
            $headers = ['No', 'Username', 'Nama Lengkap', 'Email', 'Role', 'Department', 'Status', 'Created At', 'Last Login'];
            if ($includePasswords) $headers[] = 'Password (Plain Text)';
            if ($includePasswordHash) $headers[] = 'Password Hash';
            fputcsv($output, $headers);

            // Data
            foreach ($exportData as $index => $user) {
                $csvRow = [
                    $index + 1,
                    $user['username'],
                    $user['full_name'],
                    $user['email'] ?? '-',
                    strtoupper($user['role']),
                    $user['department'] ?? '-',
                    $user['is_active'] ? 'Active' : 'Inactive',
                    $user['created_at'],
                    $user['last_login'] ?? '-'
                ];
                
                if ($includePasswords) {
                    // ✅ METODE 1: DENGAN ENKRIPSI (SUDAH DIAKTIFKAN)
                    if (!empty($user['password_encrypted']) && !empty($user['encryption_key'])) {
                        $decrypted = openssl_decrypt($user['password_encrypted'], 'AES-128-CBC', $user['encryption_key'], 0, substr(md5($user['encryption_key']), 0, 16));
                        $csvRow[] = $decrypted ?: '[Decryption Failed]';
                    } else {
                        $csvRow[] = '[Not Available - User created before encryption]';
                    }
                }
                if ($includePasswordHash) {
                    $csvRow[] = $user['password'];
                }
                
                fputcsv($output, $csvRow);
            }

            fclose($output);
            exit;
        }

        exit;
    }

    // Continue with other actions...
    header('Content-Type: application/json');

    try {
        $action = $_POST['action'];

        if ($action === 'add') {
            $username = trim($_POST['username']);
            $password = $_POST['password'] ?? '';
            $fullName = trim($_POST['full_name']);
            $email = trim($_POST['email']);
            $role = $_POST['role'];
            $department = $_POST['department'] ?? null;

            if (empty($password)) {
                echo json_encode(['success' => false, 'message' => 'Password harus diisi!']);
                exit;
            }

            // Cek username duplikat
            $checkStmt = $conn->prepare("SELECT id FROM users WHERE username = ?");
            $checkStmt->bind_param("s", $username);
            $checkStmt->execute();
            if ($checkStmt->get_result()->num_rows > 0) {
                echo json_encode(['success' => false, 'message' => 'Username sudah digunakan!']);
                exit;
            }
            $checkStmt->close();

            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            
            // ✅ METODE 1: DENGAN ENKRIPSI (SUDAH DIAKTIFKAN)
            $encryptionKey = bin2hex(random_bytes(16));
            $passwordEncrypted = openssl_encrypt($password, 'AES-128-CBC', $encryptionKey, 0, substr(md5($encryptionKey), 0, 16));
            
            $stmt = $conn->prepare("INSERT INTO users (username, password, password_encrypted, encryption_key, full_name, email, role, department, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)");
            $stmt->bind_param("ssssssss", $username, $hashedPassword, $passwordEncrypted, $encryptionKey, $fullName, $email, $role, $department);
            
            $stmt->execute();
            $stmt->close();

            echo json_encode(['success' => true, 'message' => 'User berhasil ditambahkan!']);
        }

        elseif ($action === 'edit') {
            $userId = intval($_POST['user_id']);
            $username = trim($_POST['username']);
            $fullName = trim($_POST['full_name']);
            $email = trim($_POST['email']);
            $role = $_POST['role'];
            $department = $_POST['department'] ?? null;

            $stmt = $conn->prepare("UPDATE users SET username=?, full_name=?, email=?, role=?, department=? WHERE id=?");
            $stmt->bind_param("sssssi", $username, $fullName, $email, $role, $department, $userId);
            $stmt->execute();
            $stmt->close();

            echo json_encode(['success' => true, 'message' => 'Data user berhasil diupdate!']);
        }

        elseif ($action === 'change_password') {
            $userId = intval($_POST['user_id']);
            $newPassword = $_POST['new_password'] ?? '';
            $confirmPassword = $_POST['confirm_password'] ?? '';

            if (empty($newPassword)) {
                echo json_encode(['success' => false, 'message' => 'Password baru harus diisi!']);
                exit;
            }

            if (strlen($newPassword) < 6) {
                echo json_encode(['success' => false, 'message' => 'Password minimal 6 karakter!']);
                exit;
            }

            if ($newPassword !== $confirmPassword) {
                echo json_encode(['success' => false, 'message' => 'Konfirmasi password tidak cocok!']);
                exit;
            }

            $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
            
            // ✅ METODE 1: DENGAN ENKRIPSI (SUDAH DIAKTIFKAN)
            $encryptionKey = bin2hex(random_bytes(16));
            $passwordEncrypted = openssl_encrypt($newPassword, 'AES-128-CBC', $encryptionKey, 0, substr(md5($encryptionKey), 0, 16));
            
            $stmt = $conn->prepare("UPDATE users SET password=?, password_encrypted=?, encryption_key=? WHERE id=?");
            $stmt->bind_param("sssi", $hashedPassword, $passwordEncrypted, $encryptionKey, $userId);
            
            $stmt->execute();
            $stmt->close();

            echo json_encode(['success' => true, 'message' => 'Password berhasil diubah!']);
        }

        elseif ($action === 'delete') {
            $userId = intval($_POST['user_id']);

            if ($userId == $_SESSION['user_id']) {
                echo json_encode(['success' => false, 'message' => 'Anda tidak dapat menghapus akun Anda sendiri!']);
                exit;
            }

            $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
            $stmt->bind_param("i", $userId);
            $stmt->execute();
            $stmt->close();

            echo json_encode(['success' => true, 'message' => 'User berhasil dihapus!']);
        }

    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Terjadi kesalahan: ' . $e->getMessage()]);
    }
    exit;
}

// Get filter parameters
$searchTerm = isset($_GET['search']) ? trim($_GET['search']) : '';
$filterRole = isset($_GET['role']) ? $_GET['role'] : '';
$filterDepartment = isset($_GET['department']) ? $_GET['department'] : '';
$filterStatus = isset($_GET['status']) ? $_GET['status'] : '';

// Build WHERE clause
$whereConditions = [];
$params = [];
$types = '';

if (!empty($searchTerm)) {
    $whereConditions[] = "(username LIKE ? OR full_name LIKE ? OR email LIKE ?)";
    $searchParam = "%{$searchTerm}%";
    $params[] = $searchParam;
    $params[] = $searchParam;
    $params[] = $searchParam;
    $types .= 'sss';
}

if (!empty($filterRole)) {
    $whereConditions[] = "role = ?";
    $params[] = $filterRole;
    $types .= 's';
}

if (!empty($filterDepartment)) {
    $whereConditions[] = "department = ?";
    $params[] = $filterDepartment;
    $types .= 's';
}

if ($filterStatus !== '') {
    $whereConditions[] = "is_active = ?";
    $params[] = (int)$filterStatus;
    $types .= 'i';
}

$whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';

// Main query - Get ALL users (without pagination limit for proper grouping)
$sql = "SELECT * FROM users $whereClause ORDER BY 
        CASE 
            WHEN department IS NULL OR department = '' THEN 1 
            ELSE 0 
        END,
        department ASC, 
        created_at DESC";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();

$allUsers = [];
while($row = $result->fetch_assoc()) {
    // Set default department for users without department
    if (empty($row['department'])) {
        $row['department'] = 'Tidak Ada Department';
    }
    $allUsers[] = $row;
}
$stmt->close();

// Count total users after filtering (not after pagination)
$totalRecords = count($allUsers);

// Pagination
$itemsPerPage = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 10;
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$currentPage = max(1, $currentPage);
$totalPages = ceil($totalRecords / $itemsPerPage);
$offset = ($currentPage - 1) * $itemsPerPage;

// Apply pagination AFTER grouping
$paginatedUsers = array_slice($allUsers, $offset, $itemsPerPage);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola User - ACF EDU HUB</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f8fafc;
            padding: 25px;
            color: #1e293b;
        }

        /* HEADER */
        .header {
            background: linear-gradient(135deg, #7AB2B2 0%, #4D869C 100%);
            color: white;
            padding: 40px;
            border-radius: 20px;
            margin-bottom: 30px;
            box-shadow: 0 8px 25px rgba(122, 178, 178, 0.25);
        }

        .header h1 {
            font-size: 32px;
            font-weight: 800;
            margin-bottom: 8px;
        }

        .header p {
            font-size: 16px;
            opacity: 0.95;
        }

        /* CARD */
        .card {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            margin-bottom: 30px;
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 20px;
            border-bottom: 2px solid #f1f5f9;
        }

        .card-title {
            font-size: 20px;
            font-weight: 700;
            color: #1e293b;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .card-title i {
            color: #7AB2B2;
            font-size: 24px;
        }

        /* BUTTON */
        .btn {
            padding: 12px 24px;
            border-radius: 10px;
            border: none;
            cursor: pointer;
            font-weight: 600;
            font-size: 14px;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            font-family: 'Inter', sans-serif;
        }

        .btn-add {
            background: linear-gradient(135deg, #7AB2B2 0%, #4D869C 100%);
            color: white;
            box-shadow: 0 4px 15px rgba(122, 178, 178, 0.3);
        }

        .btn-add:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(122, 178, 178, 0.4);
        }

        .btn-export {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3);
        }

        .btn-export:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4);
        }

        /* TABLE */
        .table-container {
            overflow-x: auto;
            border-radius: 10px;
        }

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

        table thead {
            background: linear-gradient(135deg, #7AB2B2 0%, #4D869C 100%);
        }

        table th {
            color: white;
            padding: 16px;
            text-align: left;
            font-weight: 600;
            font-size: 14px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        table th:first-child {
            border-radius: 10px 0 0 0;
        }

        table th:last-child {
            border-radius: 0 10px 0 0;
        }

        table td {
            padding: 16px;
            border-bottom: 1px solid #f1f5f9;
            font-size: 14px;
            color: #334155;
        }

        table tbody tr {
            transition: all 0.3s ease;
        }

        table tbody tr:hover {
            background: #f8fafc;
        }

        table tbody tr:last-child td {
            border-bottom: none;
        }

        /* DEPARTMENT SEPARATOR */
        tr.dept-separator {
            background: linear-gradient(135deg, #5a9a9a 0%, #3d6b7d 100%) !important;
            border-top: 3px solid #2c5468;
            border-bottom: 3px solid #2c5468;
        }

        tr.dept-separator td {
            padding: 15px 20px;
            font-weight: 800;
            font-size: 14px;
            letter-spacing: 0.8px;
            color: white !important;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }

        tr.dept-separator:hover {
            background: linear-gradient(135deg, #4d8585 0%, #355e6f 100%) !important;
        }

        tr.dept-separator i {
            margin-right: 10px;
            font-size: 16px;
        }

        /* BADGE */
        .badge {
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            display: inline-block;
            border: 1px solid transparent;
        }

        .badge-admin {
            background: linear-gradient(135deg, rgba(239, 68, 68, 0.15), rgba(220, 38, 38, 0.1));
            color: #b91c1c;
            border-color: rgba(239, 68, 68, 0.3);
        }

        .badge-director {
            background: linear-gradient(135deg, rgba(139, 92, 246, 0.15), rgba(124, 58, 237, 0.1));
            color: #6d28d9;
            border-color: rgba(139, 92, 246, 0.3);
        }

        .badge-dept_head {
            background: linear-gradient(135deg, rgba(59, 130, 246, 0.15), rgba(37, 99, 235, 0.1));
            color: #1e40af;
            border-color: rgba(59, 130, 246, 0.3);
        }

        .badge-staff {
            background: linear-gradient(135deg, rgba(245, 158, 11, 0.15), rgba(217, 119, 6, 0.1));
            color: #c2410c;
            border-color: rgba(245, 158, 11, 0.3);
        }

        .badge-intern {
            background: linear-gradient(135deg, rgba(16, 185, 129, 0.15), rgba(5, 150, 105, 0.1));
            color: #047857;
            border-color: rgba(16, 185, 129, 0.3);
        }

        /* Status Active/Inactive Badge */
        .badge-active {
            background: linear-gradient(135deg, rgba(34, 197, 94, 0.15), rgba(22, 163, 74, 0.1));
            color: #15803d;
            border-color: rgba(34, 197, 94, 0.3);
        }

        .badge-inactive {
            background: linear-gradient(135deg, rgba(107, 114, 128, 0.15), rgba(75, 85, 99, 0.1));
            color: #374151;
            border-color: rgba(107, 114, 128, 0.3);
        }

        /* DROPDOWN */
        .dropdown {
            position: relative;
            display: inline-block;
        }

        .dropdown-toggle {
            background: #7AB2B2;
            color: white;
            width: 36px;
            height: 36px;
            border-radius: 8px;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }

        .dropdown-toggle:hover {
            background: #4D869C;
            transform: scale(1.05);
        }

        .dropdown-menu {
            position: absolute;
            right: 0;
            top: 100%;
            margin-top: 8px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.15);
            min-width: 180px;
            opacity: 0;
            visibility: hidden;
            transform: translateY(-10px);
            transition: all 0.3s ease;
            z-index: 1000;
        }

        .dropdown.active .dropdown-menu {
            opacity: 1;
            visibility: visible;
            transform: translateY(0);
        }

        .dropdown-item {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 12px 16px;
            color: #334155;
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s ease;
            cursor: pointer;
            border: none;
            background: none;
            width: 100%;
            text-align: left;
        }

        .dropdown-item:first-child {
            border-radius: 10px 10px 0 0;
        }

        .dropdown-item:last-child {
            border-radius: 0 0 10px 10px;
        }

        .dropdown-item i {
            width: 18px;
            font-size: 14px;
        }

        .dropdown-item:hover {
            background: #f8fafc;
        }

        .dropdown-item.edit:hover {
            background: rgba(59, 130, 246, 0.1);
            color: #3b82f6;
        }

        .dropdown-item.password:hover {
            background: rgba(245, 158, 11, 0.1);
            color: #f59e0b;
        }

        .dropdown-item.delete:hover {
            background: rgba(239, 68, 68, 0.1);
            color: #ef4444;
        }

        .dropdown-divider {
            height: 1px;
            background: #f1f5f9;
            margin: 4px 0;
        }

        /* MODAL */
        .modal {
            display: none;
            position: fixed;
            z-index: 10000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .modal-wrapper {
            width: 100%;
            height: 100%;
            overflow-y: auto;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .modal-content {
            background-color: #fff;
            margin: auto;
            padding: 0;
            border-radius: 20px;
            width: 90%;
            max-width: 600px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            animation: slideDown 0.3s ease;
        }

        @keyframes slideDown {
            from {
                transform: translateY(-50px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .modal-header {
            background: linear-gradient(135deg, #7AB2B2 0%, #4D869C 100%);
            color: white;
            padding: 25px 30px;
            border-radius: 20px 20px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h2 {
            font-size: 22px;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .close {
            color: white;
            font-size: 32px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 35px;
            height: 35px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
        }

        .close:hover {
            background: rgba(255,255,255,0.2);
            transform: rotate(90deg);
        }

        .modal-body {
            padding: 30px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #1e293b;
            font-weight: 600;
            font-size: 14px;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            font-size: 14px;
            font-family: 'Inter', sans-serif;
            transition: all 0.3s ease;
        }

        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #7AB2B2;
            box-shadow: 0 0 0 3px rgba(122, 178, 178, 0.1);
        }

        .form-group small {
            font-size: 12px;
            color: #64748b;
            margin-top: 4px;
            display: block;
        }

        .form-actions {
            margin-top: 30px;
            display: flex;
            gap: 12px;
            justify-content: flex-end;
            padding-top: 20px;
            border-top: 1px solid #f1f5f9;
        }

        .btn-submit {
            background: linear-gradient(135deg, #7AB2B2 0%, #4D869C 100%);
            color: white;
            padding: 12px 32px;
        }

        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(122, 178, 178, 0.4);
        }

        .btn-cancel {
            background: #64748b;
            color: white;
            padding: 12px 32px;
        }

        .btn-cancel:hover {
            background: #475569;
        }

        /* PASSWORD FEATURES */
        .password-info {
            background: rgba(245, 158, 11, 0.1);
            border-left: 4px solid #f59e0b;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 13px;
            color: #92400e;
        }

        .password-strength {
            height: 5px;
            border-radius: 3px;
            margin-top: 8px;
            transition: all 0.3s;
            background: #e5e7eb;
        }

        .password-strength-bar {
            height: 100%;
            border-radius: 3px;
            transition: all 0.3s;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #94a3b8;
        }

        .empty-state i {
            font-size: 64px;
            margin-bottom: 20px;
            opacity: 0.3;
        }

        /* FILTER SECTION */
        .filter-section {
            background: #f8fafc;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 25px;
            border: 2px solid #e2e8f0;
        }

        .filter-form {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .filter-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
        }

        .filter-item label {
            display: block;
            margin-bottom: 8px;
            color: #1e293b;
            font-weight: 600;
            font-size: 13px;
        }

        .filter-item label i {
            color: #7AB2B2;
            margin-right: 5px;
        }

        .filter-input {
            width: 100%;
            padding: 10px 14px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            font-family: 'Inter', sans-serif;
            transition: all 0.3s ease;
            background: white;
        }

        .filter-input:focus {
            outline: none;
            border-color: #7AB2B2;
            box-shadow: 0 0 0 3px rgba(122, 178, 178, 0.1);
        }

        /* CUSTOM DROPDOWN */
        .custom-dropdown {
            position: relative;
            width: 100%;
        }

        .dropdown-trigger {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 14px;
            background: white;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            color: #1e293b;
            font-family: 'Inter', sans-serif;
            user-select: none;
        }

        .dropdown-trigger:hover {
            border-color: #7AB2B2;
        }

        .dropdown-trigger.active {
            border-color: #7AB2B2;
            box-shadow: 0 0 0 3px rgba(122, 178, 178, 0.1);
        }

        .dropdown-icon {
            font-size: 10px;
            transition: transform 0.3s ease;
            color: #64748b;
        }

        .dropdown-trigger.active .dropdown-icon {
            transform: rotate(180deg);
        }

        .dropdown-options {
            position: absolute;
            top: calc(100% + 8px);
            left: 0;
            right: 0;
            background: white;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            z-index: 1000;
            opacity: 0;
            visibility: hidden;
            transform: translateY(-10px);
            transition: all 0.3s ease;
            max-height: 0;
            overflow: hidden;
        }

        .dropdown-options.show {
            opacity: 1;
            visibility: visible;
            transform: translateY(0);
            max-height: 300px;
        }

        .dropdown-options-inner {
            max-height: 300px;
            overflow-y: auto;
            padding: 4px;
        }

        .dropdown-options-inner::-webkit-scrollbar {
            width: 6px;
        }

        .dropdown-options-inner::-webkit-scrollbar-track {
            background: #f1f5f9;
            border-radius: 3px;
        }

        .dropdown-options-inner::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 3px;
        }

        .dropdown-options-inner::-webkit-scrollbar-thumb:hover {
            background: #94a3b8;
        }

        .dropdown-option {
            padding: 10px 12px;
            cursor: pointer;
            transition: all 0.2s ease;
            border-radius: 6px;
            font-size: 14px;
            color: #334155;
            font-family: 'Inter', sans-serif;
        }

        .dropdown-option:hover {
            background: #f8fafc;
            color: #7AB2B2;
        }

        .dropdown-option.selected {
            background: rgba(122, 178, 178, 0.1);
            color: #7AB2B2;
            font-weight: 600;
        }

        .dropdown-option.selected::before {
            content: '✓ ';
            margin-right: 6px;
        }

        /* PAGINATION */
        .pagination {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 25px;
            background: #f8fafc;
            margin-top: 20px;
            border-radius: 0 0 10px 10px;
            border-top: 2px solid #e2e8f0;
        }

        .pagination-info {
            font-size: 14px;
            color: #64748b;
            font-weight: 600;
        }

        .pagination-info span {
            color: #1e293b;
            font-weight: 700;
        }

        .pagination-buttons {
            display: flex;
            gap: 8px;
        }

        .page-btn {
            padding: 8px 16px;
            border: 2px solid #e2e8f0;
            background: white;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            color: #64748b;
            transition: all 0.2s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .page-btn:hover {
            border-color: #7AB2B2;
            color: #7AB2B2;
        }

        .page-btn.active {
            background: linear-gradient(135deg, #7AB2B2, #4D869C);
            border-color: #7AB2B2;
            color: white;
        }

        .page-btn i {
            font-size: 12px;
        }

        /* RESPONSIVE */
        @media (max-width: 768px) {
            body {
                padding: 15px;
            }

            .header {
                padding: 25px;
            }

            .header h1 {
                font-size: 24px;
            }

            .card {
                padding: 20px;
            }

            .card-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }

            .filter-grid {
                grid-template-columns: 1fr;
            }

            .pagination {
                flex-direction: column;
                gap: 15px;
                text-align: center;
            }

            .pagination-info {
                display: flex;
                flex-direction: column;
                gap: 10px;
            }

            .pagination-buttons {
                flex-wrap: wrap;
                justify-content: center;
            }

            table th,
            table td {
                padding: 12px 8px;
                font-size: 13px;
            }

            .modal-wrapper {
                padding: 10px;
            }

            .modal-content {
                width: 95%;
            }

            .modal-body {
                padding: 20px;
            }

            .form-actions {
                flex-direction: column;
            }

            .form-actions .btn {
                width: 100%;
            }
        }
    </style>
</head>
<body>

    <!-- HEADER -->
    <div class="header">
        <h1><i class="fas fa-user-shield"></i> Kelola User</h1>
        <p>Manajemen Akses Pengguna Sistem ACF EDU HUB</p>
    </div>

    <!-- CARD CONTENT -->
    <div class="card">
        <div class="card-header">
            <div class="card-title">
                <i class="fas fa-users"></i>
                Daftar Pengguna Sistem
            </div>
            <div style="display: flex; gap: 12px;">
                <button class="btn btn-export" onclick="openExportModal()">
                    <i class="fas fa-file-excel"></i>
                    Export Data
                </button>
                <button class="btn btn-add" onclick="openModal('add')">
                    <i class="fas fa-plus"></i>
                    Tambah User
                </button>
            </div>
        </div>

        <!-- FILTER SECTION -->
        <div class="filter-section">
            <form method="GET" id="filterForm" class="filter-form">
                <div class="filter-grid">
                    <div class="filter-item">
                        <label><i class="fas fa-search"></i> Cari</label>
                        <input type="text" name="search" placeholder="Username, nama, atau email..." 
                               value="<?= htmlspecialchars($searchTerm) ?>" class="filter-input" 
                               onkeyup="autoSubmitSearch(event)">
                    </div>
                    
                    <div class="filter-item">
                        <label><i class="fas fa-user-tag"></i> Role</label>
                        <div class="custom-dropdown" id="roleDropdown">
                            <div class="dropdown-trigger" onclick="toggleDropdown('roleDropdown')">
                                <span id="selectedRole">
                                    <?php 
                                    $roleLabels = [
                                        'admin' => 'Administrator',
                                        'director' => 'Director',
                                        'dept_head' => 'Department Head',
                                        'staff' => 'Staff',
                                        'intern' => 'Intern'
                                    ];
                                    echo !empty($filterRole) ? $roleLabels[$filterRole] : 'Semua Role';
                                    ?>
                                </span>
                                <span class="dropdown-icon">▼</span>
                            </div>
                            <div class="dropdown-options">
                                <div class="dropdown-options-inner">
                                    <div class="dropdown-option <?= empty($filterRole) ? 'selected' : '' ?>" 
                                         onclick="selectOption('role', '', 'Semua Role')">
                                        Semua Role
                                    </div>
                                    <div class="dropdown-option <?= $filterRole === 'admin' ? 'selected' : '' ?>" 
                                         onclick="selectOption('role', 'admin', 'Administrator')">
                                        Administrator
                                    </div>
                                    <div class="dropdown-option <?= $filterRole === 'director' ? 'selected' : '' ?>" 
                                         onclick="selectOption('role', 'director', 'Director')">
                                        Director
                                    </div>
                                    <div class="dropdown-option <?= $filterRole === 'dept_head' ? 'selected' : '' ?>" 
                                         onclick="selectOption('role', 'dept_head', 'Department Head')">
                                        Department Head
                                    </div>
                                    <div class="dropdown-option <?= $filterRole === 'staff' ? 'selected' : '' ?>" 
                                         onclick="selectOption('role', 'staff', 'Staff')">
                                        Staff
                                    </div>
                                    <div class="dropdown-option <?= $filterRole === 'intern' ? 'selected' : '' ?>" 
                                         onclick="selectOption('role', 'intern', 'Intern')">
                                        Intern
                                    </div>
                                </div>
                            </div>
                        </div>
                        <input type="hidden" name="role" id="roleValue" value="<?= htmlspecialchars($filterRole) ?>">
                    </div>
                    
                    <div class="filter-item">
                        <label><i class="fas fa-building"></i> Department</label>
                        <div class="custom-dropdown" id="departmentDropdown">
                            <div class="dropdown-trigger" onclick="toggleDropdown('departmentDropdown')">
                                <span id="selectedDepartment">
                                    <?= !empty($filterDepartment) ? htmlspecialchars($filterDepartment) : 'Semua Department' ?>
                                </span>
                                <span class="dropdown-icon">▼</span>
                            </div>
                            <div class="dropdown-options">
                                <div class="dropdown-options-inner">
                                    <div class="dropdown-option <?= empty($filterDepartment) ? 'selected' : '' ?>" 
                                         onclick="selectOption('department', '', 'Semua Department')">
                                        Semua Department
                                    </div>
                                    <div class="dropdown-option <?= $filterDepartment === 'Formal Education' ? 'selected' : '' ?>" 
                                         onclick="selectOption('department', 'Formal Education', 'Formal Education')">
                                        Formal Education
                                    </div>
                                    <div class="dropdown-option <?= $filterDepartment === 'Non Formal Education' ? 'selected' : '' ?>" 
                                         onclick="selectOption('department', 'Non Formal Education', 'Non Formal Education')">
                                        Non Formal Education
                                    </div>
                                    <div class="dropdown-option <?= $filterDepartment === 'Operational' ? 'selected' : '' ?>" 
                                         onclick="selectOption('department', 'Operational', 'Operational')">
                                        Operational
                                    </div>
                                    <div class="dropdown-option <?= $filterDepartment === 'Marketing Communication' ? 'selected' : '' ?>" 
                                         onclick="selectOption('department', 'Marketing Communication', 'Marketing Communication')">
                                        Marketing Communication
                                    </div>
                                    <div class="dropdown-option <?= $filterDepartment === 'Finance' ? 'selected' : '' ?>" 
                                         onclick="selectOption('department', 'Finance', 'Finance')">
                                        Finance
                                    </div>
                                    <div class="dropdown-option <?= $filterDepartment === 'Human Resources' ? 'selected' : '' ?>" 
                                         onclick="selectOption('department', 'Human Resources', 'Human Resources')">
                                        Human Resources
                                    </div>
                                    <div class="dropdown-option <?= $filterDepartment === 'IT' ? 'selected' : '' ?>" 
                                         onclick="selectOption('department', 'IT', 'IT')">
                                        IT
                                    </div>
                                    <div class="dropdown-option <?= $filterDepartment === 'Creative Design and Brand' ? 'selected' : '' ?>" 
                                         onclick="selectOption('department', 'Creative Design and Brand', 'Creative Design and Brand')">
                                        Creative Design and Brand
                                    </div>
                                </div>
                            </div>
                        </div>
                        <input type="hidden" name="department" id="departmentValue" value="<?= htmlspecialchars($filterDepartment) ?>">
                    </div>

                    <div class="filter-item">
                        <label><i class="fas fa-toggle-on"></i> Status</label>
                        <div class="custom-dropdown" id="statusDropdown">
                            <div class="dropdown-trigger" onclick="toggleDropdown('statusDropdown')">
                                <span id="selectedStatus">
                                    <?php 
                                    if ($filterStatus === '1') echo 'Active';
                                    elseif ($filterStatus === '0') echo 'Inactive';
                                    else echo 'Semua Status';
                                    ?>
                                </span>
                                <span class="dropdown-icon">▼</span>
                            </div>
                            <div class="dropdown-options">
                                <div class="dropdown-options-inner">
                                    <div class="dropdown-option <?= $filterStatus === '' ? 'selected' : '' ?>" 
                                         onclick="selectOption('status', '', 'Semua Status')">
                                        Semua Status
                                    </div>
                                    <div class="dropdown-option <?= $filterStatus === '1' ? 'selected' : '' ?>" 
                                         onclick="selectOption('status', '1', 'Active')">
                                        Active
                                    </div>
                                    <div class="dropdown-option <?= $filterStatus === '0' ? 'selected' : '' ?>" 
                                         onclick="selectOption('status', '0', 'Inactive')">
                                        Inactive
                                    </div>
                                </div>
                            </div>
                        </div>
                        <input type="hidden" name="status" id="statusValue" value="<?= htmlspecialchars($filterStatus) ?>">
                    </div>
                </div>
            </form>
        </div>

        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th style="width: 60px;">No</th>
                        <th>Username</th>
                        <th>Nama Lengkap</th>
                        <th>Email</th>
                        <th style="width: 140px;">Role</th>
                        <th style="width: 100px;">Status</th>
                        <th style="width: 80px; text-align: center;">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($paginatedUsers)): ?>
                        <tr>
                            <td colspan="7">
                                <div class="empty-state">
                                    <i class="fas fa-users"></i>
                                    <p>Belum ada data user</p>
                                </div>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php 
                        $currentDept = null;
                        $globalIndex = $offset;
                        foreach ($paginatedUsers as $user): 
                            // Show department separator when department changes
                            if ($currentDept !== $user['department']):
                                $currentDept = $user['department'];
                        ?>
                        <tr class="dept-separator">
                            <td colspan="7">
                                <i class="fas fa-building"></i>
                                <?= htmlspecialchars($currentDept) ?>
                            </td>
                        </tr>
                        <?php endif; ?>
                        <tr>
                            <td><strong><?= ++$globalIndex ?></strong></td>
                            <td><strong><?= htmlspecialchars($user['username']) ?></strong></td>
                            <td><?= htmlspecialchars($user['full_name']) ?></td>
                            <td><?= htmlspecialchars($user['email'] ?? '-') ?></td>
                            <td>
                                <span class="badge badge-<?= $user['role'] ?>">
                                    <i class="fas fa-circle" style="font-size: 8px;"></i>
                                    <?php
                                    $roleLabels = [
                                        'admin' => 'ADMIN',
                                        'director' => 'DIRECTOR',
                                        'dept_head' => 'DEPT HEAD',
                                        'staff' => 'STAFF',
                                        'intern' => 'INTERN'
                                    ];
                                    echo $roleLabels[$user['role']] ?? strtoupper($user['role']);
                                    ?>
                                </span>
                            </td>
                            <td>
                                <?php 
                                $isActive = isset($user['is_active']) ? (int)$user['is_active'] : 1;
                                $statusText = $isActive ? 'Active' : 'Inactive';
                                $statusClass = $isActive ? 'active' : 'inactive';
                                ?>
                                <span class="badge badge-<?= $statusClass ?>">
                                    <i class="fas fa-circle" style="font-size: 8px;"></i>
                                    <?= $statusText ?>
                                </span>
                            </td>
                            <td style="text-align: center;">
                                <div class="dropdown" id="dropdown-<?= $user['id'] ?>">
                                    <button class="dropdown-toggle" onclick="toggleActionDropdown(<?= $user['id'] ?>)">
                                        <i class="fas fa-ellipsis-vertical"></i>
                                    </button>
                                    <div class="dropdown-menu">
                                        <button class="dropdown-item edit" onclick='editUser(<?= json_encode($user) ?>)'>
                                            <i class="fas fa-edit"></i>
                                            Edit Data
                                        </button>
                                        <button class="dropdown-item password" onclick='changePassword(<?= $user['id'] ?>, "<?= htmlspecialchars($user['username']) ?>")'>
                                            <i class="fas fa-key"></i>
                                            Ganti Password
                                        </button>
                                        <?php if($user['id'] != $_SESSION['user_id']): ?>
                                        <div class="dropdown-divider"></div>
                                        <button class="dropdown-item delete" onclick="deleteUser(<?= $user['id'] ?>, '<?= htmlspecialchars($user['username']) ?>')">
                                            <i class="fas fa-trash"></i>
                                            Hapus User
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- PAGINATION -->
        <?php if ($totalPages > 1 || $totalRecords > 10): ?>
        <div class="pagination">
            <div class="pagination-info">
                Menampilkan <span><?= $offset + 1 ?>-<?= min($offset + $itemsPerPage, $totalRecords) ?></span> 
                dari <span><?= $totalRecords ?></span> user
                
                <span style="margin-left: 20px; display: inline-flex; align-items: center; gap: 8px;">
                    <i class="fas fa-list-ol" style="color: #7AB2B2;"></i>
                    <div class="custom-dropdown" id="perPageDropdown" style="min-width: 140px;">
                        <div class="dropdown-trigger" onclick="toggleDropdown('perPageDropdown')" style="padding: 8px 12px; font-size: 13px;">
                            <span id="selectedPerPage"><?= $itemsPerPage ?> / halaman</span>
                            <span class="dropdown-icon">▼</span>
                        </div>
                        <div class="dropdown-options">
                            <div class="dropdown-options-inner">
                                <div class="dropdown-option <?= $itemsPerPage === 10 ? 'selected' : '' ?>" onclick="changePerPage(10)">
                                    10 / halaman
                                </div>
                                <div class="dropdown-option <?= $itemsPerPage === 25 ? 'selected' : '' ?>" onclick="changePerPage(25)">
                                    25 / halaman
                                </div>
                                <div class="dropdown-option <?= $itemsPerPage === 50 ? 'selected' : '' ?>" onclick="changePerPage(50)">
                                    50 / halaman
                                </div>
                                <div class="dropdown-option <?= $itemsPerPage === 100 ? 'selected' : '' ?>" onclick="changePerPage(100)">
                                    100 / halaman
                                </div>
                            </div>
                        </div>
                    </div>
                </span>
            </div>
            <div class="pagination-buttons">
                <?php 
                $urlParams = '';
                if ($searchTerm) $urlParams .= '&search='.urlencode($searchTerm);
                if ($filterRole) $urlParams .= '&role='.$filterRole;
                if ($filterDepartment) $urlParams .= '&department='.urlencode($filterDepartment);
                if ($filterStatus !== '') $urlParams .= '&status='.$filterStatus;
                ?>
                
                <?php if ($currentPage > 1): ?>
                    <a href="?page=<?= $currentPage - 1 ?>&per_page=<?= $itemsPerPage ?><?= $urlParams ?>" 
                       class="page-btn">
                        <i class="fas fa-chevron-left"></i> Previous
                    </a>
                <?php endif; ?>

                <?php
                $startPage = max(1, $currentPage - 2);
                $endPage = min($totalPages, $currentPage + 2);
                for ($i = $startPage; $i <= $endPage; $i++):
                ?>
                    <a href="?page=<?= $i ?>&per_page=<?= $itemsPerPage ?><?= $urlParams ?>" 
                       class="page-btn <?= $i === $currentPage ? 'active' : '' ?>">
                        <?= $i ?>
                    </a>
                <?php endfor; ?>

                <?php if ($currentPage < $totalPages): ?>
                    <a href="?page=<?= $currentPage + 1 ?>&per_page=<?= $itemsPerPage ?><?= $urlParams ?>" 
                       class="page-btn">
                        Next <i class="fas fa-chevron-right"></i>
                    </a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- MODAL FORM USER -->
    <div id="userModal" class="modal">
        <div class="modal-wrapper">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 id="modalTitle">
                        <i class="fas fa-user-plus"></i>
                        Tambah User
                    </h2>
                    <span class="close" onclick="closeModal()">&times;</span>
                </div>
                <div class="modal-body">
                    <form id="userForm">
                        <input type="hidden" id="formAction" name="action" value="add">
                        <input type="hidden" id="userId" name="user_id">

                        <div class="form-group">
                            <label for="username">
                                <i class="fas fa-user"></i> Username *
                            </label>
                            <input type="text" id="username" name="username" placeholder="Masukkan username" required>
                        </div>

                        <div class="form-group">
                            <label for="fullName">
                                <i class="fas fa-id-card"></i> Nama Lengkap *
                            </label>
                            <input type="text" id="fullName" name="full_name" placeholder="Masukkan nama lengkap" required>
                        </div>

                        <div class="form-group">
                            <label for="email">
                                <i class="fas fa-envelope"></i> Email *
                            </label>
                            <input type="email" id="email" name="email" placeholder="Masukkan email" required>
                        </div>

                        <div class="form-group">
                            <label for="role">
                                <i class="fas fa-user-tag"></i> Role *
                            </label>
                            <select id="role" name="role" required>
                                <option value="admin">Administrator</option>
                                <option value="director">Director</option>
                                <option value="dept_head">Department Head</option>
                                <option value="staff">Staff</option>
                                <option value="intern">Intern</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="department">
                                <i class="fas fa-building"></i> Department
                            </label>
                            <select id="department" name="department">
                                <option value="">- Pilih Department -</option>
                                <option value="Formal Education">Formal Education</option>
                                <option value="Non Formal Education">Non Formal Education</option>
                                <option value="Operational">Operational</option>
                                <option value="Marketing Communication">Marketing Communication</option>
                                <option value="Finance">Finance</option>
                                <option value="Human Resources">Human Resources</option>
                                <option value="IT">IT</option>
                                <option value="Creative Design and Brand">Creative Design and Brand</option>
                            </select>
                            <small>*Opsional, bisa dikosongkan</small>
                        </div>

                        <div class="form-group" id="passwordGroup">
                            <label for="password">
                                <i class="fas fa-lock"></i> Password *
                            </label>
                            <input type="password" id="password" name="password" placeholder="Minimal 6 karakter" minlength="6">
                            <small>*Minimal 6 karakter</small>
                        </div>

                        <div class="form-actions">
                            <button type="button" class="btn btn-cancel" onclick="closeModal()">
                                <i class="fas fa-times"></i>
                                Batal
                            </button>
                            <button type="submit" class="btn btn-submit">
                                <i class="fas fa-save"></i>
                                Simpan
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- MODAL GANTI PASSWORD -->
    <div id="passwordModal" class="modal">
        <div class="modal-wrapper">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>
                        <i class="fas fa-key"></i>
                        Ganti Password
                    </h2>
                    <span class="close" onclick="closePasswordModal()">&times;</span>
                </div>
                <div class="modal-body">
                    <form id="passwordForm">
                        <input type="hidden" name="action" value="change_password">
                        <input type="hidden" id="passUserId" name="user_id">

                        <div class="password-info">
                            <i class="fas fa-info-circle"></i> 
                            <strong>Mengubah password untuk:</strong> 
                            <span id="passUsername"></span>
                        </div>

                        <div class="form-group">
                            <label for="newPassword">
                                <i class="fas fa-lock"></i> Password Baru *
                            </label>
                            <input type="password" id="newPassword" name="new_password" placeholder="Minimal 6 karakter" required minlength="6" oninput="checkPasswordStrength()">
                            <div class="password-strength">
                                <div class="password-strength-bar" id="strengthBar"></div>
                            </div>
                            <small>*Minimal 6 karakter, gunakan kombinasi huruf, angka, dan simbol</small>
                        </div>

                        <div class="form-group">
                            <label for="confirmPassword">
                                <i class="fas fa-lock"></i> Konfirmasi Password *
                            </label>
                            <input type="password" id="confirmPassword" name="confirm_password" placeholder="Ulangi password baru" required minlength="6" oninput="checkPasswordMatch()">
                            <small id="matchMessage"></small>
                        </div>

                        <div class="form-actions">
                            <button type="button" class="btn btn-cancel" onclick="closePasswordModal()">
                                <i class="fas fa-times"></i>
                                Batal
                            </button>
                            <button type="submit" class="btn btn-submit" id="submitPasswordBtn">
                                <i class="fas fa-save"></i>
                                Simpan Password
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- MODAL EXPORT -->
    <div id="exportModal" class="modal">
        <div class="modal-wrapper">
            <div class="modal-content">
                <div class="modal-header" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                    <h2>
                        <i class="fas fa-file-export"></i>
                        Export Data User
                    </h2>
                    <span class="close" onclick="closeExportModal()">&times;</span>
                </div>
                <div class="modal-body">
                    <div style="background: rgba(16, 185, 129, 0.1); border-left: 4px solid #10b981; padding: 16px; border-radius: 8px; margin-bottom: 24px;">
                        <div style="display: flex; align-items: start; gap: 12px;">
                            <i class="fas fa-info-circle" style="color: #059669; font-size: 20px; margin-top: 2px;"></i>
                            <div>
                                <strong style="color: #065f46; display: block; margin-bottom: 6px;">Informasi Export</strong>
                                <p style="color: #047857; font-size: 13px; line-height: 1.6; margin: 0;">
                                    Data yang akan di-export mencakup semua informasi user termasuk <strong>password dalam bentuk text (plain text)</strong>. 
                                    Pastikan file export disimpan dengan aman dan tidak dibagikan sembarangan.
                                </p>
                            </div>
                        </div>
                    </div>

                    <form id="exportForm" method="POST" action="">
                        <input type="hidden" name="action" value="export">

                        <div class="form-group">
                            <label for="exportFormat">
                                <i class="fas fa-file-alt"></i> Format Export *
                            </label>
                            <select id="exportFormat" name="export_format" required onchange="updateExportDescription()">
                                <option value="">- Pilih Format -</option>
                                <option value="excel">Excel (.xlsx) - Microsoft Excel</option>
                                <option value="csv">CSV (.csv) - Comma Separated Values</option>
                            </select>
                            <small id="formatDescription"></small>
                        </div>

                        <div class="form-group">
                            <label>
                                <i class="fas fa-filter"></i> Data yang Di-export
                            </label>
                            <div style="background: #f8fafc; padding: 16px; border-radius: 8px; border: 2px solid #e2e8f0;">
                                <label style="display: flex; align-items: center; gap: 10px; cursor: pointer; margin-bottom: 12px;">
                                    <input type="radio" name="export_scope" value="all" checked onchange="toggleFilterExport()">
                                    <span><strong>Semua User</strong> - Export seluruh data user</span>
                                </label>
                                <label style="display: flex; align-items: center; gap: 10px; cursor: pointer;">
                                    <input type="radio" name="export_scope" value="filtered" onchange="toggleFilterExport()">
                                    <span><strong>Data Terfilter</strong> - Sesuai filter yang sedang aktif</span>
                                </label>
                            </div>
                            <div id="filterInfo" style="display: none; margin-top: 12px; padding: 12px; background: rgba(59, 130, 246, 0.1); border-radius: 8px; font-size: 13px; color: #1e40af;">
                                <i class="fas fa-info-circle"></i> 
                                <span id="filterInfoText">Filter aktif akan diterapkan pada export</span>
                            </div>
                        </div>

                        <div class="form-group">
                            <label>
                                <i class="fas fa-shield-alt"></i> Keamanan Password
                            </label>
                            <div style="background: #fef3c7; padding: 16px; border-radius: 8px; border: 2px solid #fbbf24;">
                                <label style="display: flex; align-items: start; gap: 10px; cursor: pointer; margin-bottom: 12px;">
                                    <input type="checkbox" name="include_passwords" value="1" checked style="margin-top: 4px;">
                                    <div>
                                        <strong style="color: #92400e;">Sertakan Password Plain Text</strong>
                                        <p style="margin: 4px 0 0 0; font-size: 13px; color: #78350f;">
                                            Password akan ditampilkan dalam bentuk text biasa. <strong>Sangat tidak disarankan!</strong>
                                        </p>
                                    </div>
                                </label>
                                <label style="display: flex; align-items: start; gap: 10px; cursor: pointer;">
                                    <input type="checkbox" name="include_password_hash" value="1" style="margin-top: 4px;">
                                    <div>
                                        <strong style="color: #92400e;">Sertakan Password Hash</strong>
                                        <p style="margin: 4px 0 0 0; font-size: 13px; color: #78350f;">
                                            Password dalam bentuk hash (encrypted). Lebih aman untuk backup.
                                        </p>
                                    </div>
                                </label>
                            </div>
                        </div>

                        <div class="form-actions">
                            <button type="button" class="btn btn-cancel" onclick="closeExportModal()">
                                <i class="fas fa-times"></i>
                                Batal
                            </button>
                            <button type="submit" class="btn btn-submit" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                                <i class="fas fa-download"></i>
                                Download Export
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Custom dropdown filter functions
        function toggleDropdown(dropdownId) {
            const dropdown = document.getElementById(dropdownId);
            if (!dropdown) return;
            
            const trigger = dropdown.querySelector('.dropdown-trigger');
            const options = dropdown.querySelector('.dropdown-options');
            
            document.querySelectorAll('.custom-dropdown').forEach(dd => {
                if (dd.id !== dropdownId) {
                    const otherTrigger = dd.querySelector('.dropdown-trigger');
                    const otherOptions = dd.querySelector('.dropdown-options');
                    if (otherTrigger) otherTrigger.classList.remove('active');
                    if (otherOptions) otherOptions.classList.remove('show');
                }
            });
            
            if (trigger) trigger.classList.toggle('active');
            if (options) options.classList.toggle('show');
        }

        function selectOption(filterType, value, text) {
            const selectedSpan = document.getElementById('selected' + filterType.charAt(0).toUpperCase() + filterType.slice(1));
            if (selectedSpan) selectedSpan.textContent = text;
            
            const hiddenInput = document.getElementById(filterType + 'Value');
            if (hiddenInput) hiddenInput.value = value;
            
            const dropdown = document.getElementById(filterType + 'Dropdown');
            if (dropdown) {
                dropdown.querySelectorAll('.dropdown-option').forEach(opt => {
                    opt.classList.remove('selected');
                });
                if (window.event && window.event.target) {
                    window.event.target.classList.add('selected');
                }
            }
            
            toggleDropdown(filterType + 'Dropdown');
            
            const form = document.getElementById('filterForm');
            if (form) form.submit();
        }

        function toggleActionDropdown(id) {
            const dropdown = document.getElementById('dropdown-' + id);
            const allDropdowns = document.querySelectorAll('.dropdown');
            
            allDropdowns.forEach(d => {
                if (d.id !== 'dropdown-' + id) {
                    d.classList.remove('active');
                }
            });
            
            if (dropdown) {
                dropdown.classList.toggle('active');
            }
        }

        document.addEventListener('click', function(event) {
            if (!event.target.closest('.custom-dropdown')) {
                document.querySelectorAll('.dropdown-options').forEach(opt => {
                    opt.classList.remove('show');
                });
                document.querySelectorAll('.custom-dropdown .dropdown-trigger').forEach(trigger => {
                    trigger.classList.remove('active');
                });
            }

            if (!event.target.closest('.dropdown')) {
                document.querySelectorAll('.dropdown').forEach(d => {
                    d.classList.remove('active');
                });
            }
        });

        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.dropdown-options').forEach(dropdown => {
                dropdown.addEventListener('click', function(e) {
                    e.stopPropagation();
                });
            });
        });

        function changePerPage(perPage) {
            const selectedSpan = document.getElementById('selectedPerPage');
            if (selectedSpan) selectedSpan.textContent = perPage + ' / halaman';
            
            const dropdown = document.getElementById('perPageDropdown');
            if (dropdown) {
                dropdown.querySelectorAll('.dropdown-option').forEach(opt => {
                    opt.classList.remove('selected');
                });
                if (window.event && window.event.target) {
                    window.event.target.classList.add('selected');
                }
            }
            
            toggleDropdown('perPageDropdown');
            
            const urlParams = new URLSearchParams(window.location.search);
            urlParams.set('per_page', perPage);
            urlParams.set('page', '1');
            window.location.search = urlParams.toString();
        }

        let searchTimeout;
        function autoSubmitSearch(event) {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(function() {
                document.getElementById('filterForm').submit();
            }, 800);
        }

        function openModal(action) {
            document.querySelectorAll('.dropdown').forEach(d => {
                d.classList.remove('active');
            });

            document.getElementById('userModal').style.display = 'block';
            document.body.style.overflow = 'hidden';
            document.getElementById('formAction').value = action;
            document.getElementById('userForm').reset();

            if (action === 'add') {
                document.getElementById('modalTitle').innerHTML = '<i class="fas fa-user-plus"></i> Tambah User Baru';
                document.getElementById('passwordGroup').style.display = 'block';
                document.getElementById('password').required = true;
            } else {
                document.getElementById('modalTitle').innerHTML = '<i class="fas fa-user-edit"></i> Edit Data User';
                document.getElementById('passwordGroup').style.display = 'none';
                document.getElementById('password').required = false;
            }
        }

        function closeModal() {
            document.getElementById('userModal').style.display = 'none';
            document.getElementById('userForm').reset();
            document.body.style.overflow = '';
        }

        function editUser(user) {
            document.querySelectorAll('.dropdown').forEach(d => {
                d.classList.remove('active');
            });

            openModal('edit');
            document.getElementById('userId').value = user.id;
            document.getElementById('username').value = user.username;
            document.getElementById('fullName').value = user.full_name;
            document.getElementById('email').value = user.email || '';
            document.getElementById('role').value = user.role;
            document.getElementById('department').value = user.department || '';
        }

        function changePassword(userId, username) {
            document.querySelectorAll('.dropdown').forEach(d => {
                d.classList.remove('active');
            });

            document.getElementById('passwordModal').style.display = 'block';
            document.body.style.overflow = 'hidden';
            document.getElementById('passUserId').value = userId;
            document.getElementById('passUsername').textContent = username;
            document.getElementById('passwordForm').reset();
            document.getElementById('strengthBar').style.width = '0%';
            document.getElementById('matchMessage').textContent = '';
        }

        function closePasswordModal() {
            document.getElementById('passwordModal').style.display = 'none';
            document.getElementById('passwordForm').reset();
            document.body.style.overflow = '';
        }

        function deleteUser(id, username) {
            document.getElementById('dropdown-' + id).classList.remove('active');

            if (confirm('Yakin ingin menghapus user "' + username + '"?\n\nData yang terhapus tidak dapat dikembalikan!')) {
                const formData = new FormData();
                formData.append('action', 'delete');
                formData.append('user_id', id);

                fetch('', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert(data.message);
                        location.reload();
                    } else {
                        alert(data.message);
                    }
                });
            }
        }

        document.getElementById('userForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    location.reload();
                } else {
                    alert(data.message);
                }
            })
            .catch(error => {
                alert('Terjadi kesalahan: ' + error);
            });
        });

        document.getElementById('passwordForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    closePasswordModal();
                    location.reload();
                } else {
                    alert(data.message);
                }
            })
            .catch(error => {
                alert('Terjadi kesalahan: ' + error);
            });
        });

        function checkPasswordStrength() {
            const password = document.getElementById('newPassword').value;
            const strengthBar = document.getElementById('strengthBar');
            let strength = 0;
            
            if (password.length >= 6) strength++;
            if (password.length >= 10) strength++;
            if (/[a-z]/.test(password) && /[A-Z]/.test(password)) strength++;
            if (/[0-9]/.test(password)) strength++;
            if (/[^a-zA-Z0-9]/.test(password)) strength++;
            
            const colors = ['#ef4444', '#f59e0b', '#eab308', '#84cc16', '#10b981'];
            const widths = ['20%', '40%', '60%', '80%', '100%'];
            
            strengthBar.style.width = widths[strength - 1] || '0%';
            strengthBar.style.backgroundColor = colors[strength - 1] || '#e5e7eb';
        }

        function checkPasswordMatch() {
            const password = document.getElementById('newPassword').value;
            const confirm = document.getElementById('confirmPassword').value;
            const message = document.getElementById('matchMessage');
            const submitBtn = document.getElementById('submitPasswordBtn');
            
            if (confirm.length > 0) {
                if (password === confirm) {
                    message.textContent = '✓ Password cocok';
                    message.style.color = '#10b981';
                    submitBtn.disabled = false;
                } else {
                    message.textContent = '✗ Password tidak cocok';
                    message.style.color = '#ef4444';
                    submitBtn.disabled = true;
                }
            } else {
                message.textContent = '';
                submitBtn.disabled = false;
            }
        }

        document.getElementById('userModal').addEventListener('click', function(event) {
            if (event.target === this) {
                closeModal();
            }
        });

        document.getElementById('passwordModal').addEventListener('click', function(event) {
            if (event.target === this) {
                closePasswordModal();
            }
        });

        document.getElementById('exportModal').addEventListener('click', function(event) {
            if (event.target === this) {
                closeExportModal();
            }
        });

        function openExportModal() {
            document.getElementById('exportModal').style.display = 'block';
            document.body.style.overflow = 'hidden';
            updateFilterInfo();
        }

        function closeExportModal() {
            document.getElementById('exportModal').style.display = 'none';
            document.getElementById('exportForm').reset();
            document.body.style.overflow = '';
        }

        function updateExportDescription() {
            const format = document.getElementById('exportFormat').value;
            const description = document.getElementById('formatDescription');
            
            if (format === 'excel') {
                description.textContent = 'File Excel dengan formatting dan dapat dibuka di Microsoft Excel, Google Sheets, atau LibreOffice';
                description.style.color = '#059669';
            } else if (format === 'csv') {
                description.textContent = 'File CSV yang kompatibel dengan semua aplikasi spreadsheet dan database';
                description.style.color = '#059669';
            } else {
                description.textContent = '';
            }
        }

        function toggleFilterExport() {
            const filtered = document.querySelector('input[name="export_scope"]:checked').value === 'filtered';
            const filterInfo = document.getElementById('filterInfo');
            
            if (filtered) {
                filterInfo.style.display = 'block';
                updateFilterInfo();
            } else {
                filterInfo.style.display = 'none';
            }
        }

        function updateFilterInfo() {
            const urlParams = new URLSearchParams(window.location.search);
            const activeFilters = [];
            
            if (urlParams.get('search')) activeFilters.push('Search: "' + urlParams.get('search') + '"');
            if (urlParams.get('role')) activeFilters.push('Role: ' + urlParams.get('role'));
            if (urlParams.get('department')) activeFilters.push('Department: ' + urlParams.get('department'));
            if (urlParams.get('status')) activeFilters.push('Status: ' + (urlParams.get('status') === '1' ? 'Active' : 'Inactive'));
            
            const filterInfoText = document.getElementById('filterInfoText');
            if (activeFilters.length > 0) {
                filterInfoText.innerHTML = '<strong>Filter aktif:</strong> ' + activeFilters.join(', ');
            } else {
                filterInfoText.textContent = 'Tidak ada filter aktif (akan export semua data)';
            }
        }

        document.getElementById('exportForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const format = document.getElementById('exportFormat').value;
            if (!format) {
                alert('Silakan pilih format export terlebih dahulu!');
                return;
            }

            const formData = new FormData(this);
            
            if (document.querySelector('input[name="export_scope"]:checked').value === 'filtered') {
                const urlParams = new URLSearchParams(window.location.search);
                if (urlParams.get('search')) formData.append('filter_search', urlParams.get('search'));
                if (urlParams.get('role')) formData.append('filter_role', urlParams.get('role'));
                if (urlParams.get('department')) formData.append('filter_department', urlParams.get('department'));
                if (urlParams.get('status')) formData.append('filter_status', urlParams.get('status'));
            }

            const downloadForm = document.createElement('form');
            downloadForm.method = 'POST';
            downloadForm.action = '';
            
            for (let [key, value] of formData.entries()) {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = key;
                input.value = value;
                downloadForm.appendChild(input);
            }
            
            document.body.appendChild(downloadForm);
            downloadForm.submit();
            document.body.removeChild(downloadForm);
            
            setTimeout(() => {
                closeExportModal();
            }, 500);
        });
    </script>

</body>
</html>