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

// DAPATKAN ROLE PENGGUNA (FIX ERROR)
$user_email = $_SESSION['email'] ?? '';
$check_status = mysqli_prepare($conn, "SELECT role FROM users WHERE email = ?");
mysqli_stmt_bind_param($check_status, "s", $user_email);
mysqli_stmt_execute($check_status);
$status_result = mysqli_stmt_get_result($check_status);
$user_data = mysqli_fetch_assoc($status_result);
$role = $user_data['role'] ?? 'user';
$departments_list = getDepartmentList();
$position_map = getDepartmentPositionMap();

// Semak jika user adalah superadmin. Mode preview akses dibenarkan untuk papar halaman blur sahaja.
if ($role !== 'superadmin' && !(function_exists('isAccessPreviewRequest') && isAccessPreviewRequest())) {
    redirectToLogin('unauthorized');
}

// PROSES PENDAFTARAN USER BARU
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['register_user'])) {
    
    $fullname   = trim((string) ($_POST['fullname'] ?? ''));
    $short_name = trim((string) ($_POST['short_name'] ?? ''));
    $ic_number  = trim((string) ($_POST['ic_number'] ?? ''));
    $email      = trim((string) ($_POST['email'] ?? ''));
    $department = trim((string) ($_POST['department'] ?? ''));
    $position   = trim((string) ($_POST['position'] ?? ''));
    $password   = (string) ($_POST['password'] ?? '');
    $confirm_pass = (string) ($_POST['confirm_pass'] ?? '');
    
    // Validasi password
    if ($fullname === '' || $short_name === '') {
        $message = "<div style='background:#f8d7da;color:#721c24;padding:12px;border-radius:8px;margin-bottom:20px;'> Sila isi nama penuh dan nama pendek!</div>";
    } elseif (!preg_match('/^\d{12}$/', $ic_number)) {
        $message = "<div style='background:#f8d7da;color:#721c24;padding:12px;border-radius:8px;margin-bottom:20px;'> No. Kad Pengenalan mesti mengandungi 12 digit nombor.</div>";
    } elseif ($password !== $confirm_pass) {
        $message = "<div style='background:#f8d7da;color:#721c24;padding:12px;border-radius:8px;margin-bottom:20px;'> Kata laluan tidak sepadan!</div>";
    } elseif (!in_array($department, $departments_list, true) || !isValidDepartmentPosition($department, $position)) {
        $message = "<div style='background:#f8d7da;color:#721c24;padding:12px;border-radius:8px;margin-bottom:20px;'> Sila pilih bahagian dan jawatan yang sah!</div>";
    } else {
        // Semak jika IC sudah wujud
        $check_ic = mysqli_prepare($conn, "SELECT id FROM users WHERE ic_number = ?");
        mysqli_stmt_bind_param($check_ic, "s", $ic_number);
        mysqli_stmt_execute($check_ic);
        $result_ic = mysqli_stmt_get_result($check_ic); // Simpan result dahulu
        
        // GUNA mysqli_num_rows() untuk mysqli_result (BUKAN mysqli_stmt_num_rows)
        if (mysqli_num_rows($result_ic) > 0) {
            $message = "<div style='background:#f8d7da;color:#721c24;padding:12px;border-radius:8px;margin-bottom:20px;'> No. IC ini sudah berdaftar!</div>";
        } else {
            // Semak jika email sudah wujud
            $check_email = mysqli_prepare($conn, "SELECT id FROM users WHERE email = ?");
            mysqli_stmt_bind_param($check_email, "s", $email);
            mysqli_stmt_execute($check_email);
            $result_email = mysqli_stmt_get_result($check_email); // Simpan result dahulu
            
            // GUNA mysqli_num_rows() untuk mysqli_result
            if (mysqli_num_rows($result_email) > 0) {
                $message = "<div style='background:#f8d7da;color:#721c24;padding:12px;border-radius:8px;margin-bottom:20px;'> Emel ini sudah berdaftar!</div>";
            } else {
                // Hash password
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                
                // INSERT USER BARU DENGAN status='approved' & role='user'
                $insert = mysqli_prepare($conn, "INSERT INTO users (fullname, short_name, ic_number, email, department, position, password, status, role) VALUES (?, ?, ?, ?, ?, ?, ?, 'approved', 'user')");
                mysqli_stmt_bind_param($insert, "sssssss", $fullname, $short_name, $ic_number, $email, $department, $position, $hashed_password);
                
                if (mysqli_stmt_execute($insert)) {
                    logActivity(
                        $conn,
                        (int) ($_SESSION['user_id'] ?? 0),
                        'create_user',
                        'Daftar pengguna baharu: ' . $fullname . ' (' . $email . ') - ' . $department . ', ' . $position
                    );
                    $message = "<div style='background:#d4edda;color:#155724;padding:12px;border-radius:8px;margin-bottom:20px;'> Pengguna baru berjaya didaftarkan! Boleh login serta-merta.</div>";
                    // Reset form
                    $_POST = array();
                } else {
                    $message = "<div style='background:#f8d7da;color:#721c24;padding:12px;border-radius:8px;margin-bottom:20px;'> Ralat sistem: " . mysqli_error($conn) . "</div>";
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Daftar 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; }
        
        /* Form Styles */
        .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); }
        .register-card { max-width: 590px; margin-left: auto; margin-right: auto; padding: 24px 28px; }
        .register-card .form-header { text-align: center; margin-bottom: 28px; }
        .register-card .form-header img { width: 74px; margin-bottom: 12px; filter: drop-shadow(0 12px 18px rgba(2,62,95,0.18)); }
        .register-card .form-header h1 { color: var(--primary-dark); font-size: 1.45rem; line-height: 1.12; font-weight: 850; margin: 0 0 6px; letter-spacing: 0; }
        .form-heading { text-align: center; margin-bottom: 18px; }
        .form-heading h1 { color: #005f99; font-size: clamp(1.75rem, 3vw, 2.2rem); line-height: 1.12; font-weight: 800; margin-bottom: 7px; }
        .form-heading p { color: #355f73; font-size: 0.94rem; font-weight: 500; line-height: 1.5; }
        .form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px 14px; }
        .form-group { position: relative; margin-bottom: 0; }
        .form-group.full { grid-column: 1 / -1; }
        .form-group label { display: block; margin-bottom: 6px; font-weight: 700; color: var(--text-main); font-size: 0.86rem; }
        .form-group input, .form-group select { width: 100%; height: 42px; padding: 9px 13px; border: 1px solid #dce5e4; border-radius: 7px; font-size: 0.9rem; background: #fff; color: #12313e; transition: border-color 0.2s ease, box-shadow 0.2s ease, background 0.2s ease; box-shadow: 0 1px 0 rgba(16, 50, 47, 0.03); }
        .form-group input::placeholder { color: #526b79; }
        .form-group input:focus, .form-group select:focus { border-color: rgba(0, 180, 216, 0.95); outline: none; box-shadow: 0 0 0 4px rgba(0, 180, 216, 0.15); background: #fff; }
        .pass-wrapper { position: relative; }
        .pass-wrapper input[type="password"] { padding-right: 46px; }
        .toggle-pass { position: absolute; right: 13px; top: 50%; transform: translateY(-50%); cursor: pointer; background: none; border: none; padding: 3px; display: inline-flex; align-items: center; justify-content: center; }
        .toggle-pass svg { width: 20px; height: 20px; fill: #627781; transition: fill 0.2s ease; }
        .toggle-pass:hover svg { fill: var(--primary); }
        .btn-submit { width: 100%; height: 46px; margin-top: 16px; padding: 0 18px; background: linear-gradient(90deg, #0077b6, #00b4d8); color: #fff; border: 1px solid rgba(0, 119, 182, 0.28); border-radius: 999px; font-size: 0.95rem; font-weight: 850; letter-spacing: 0.04em; cursor: pointer; box-shadow: 0 14px 28px rgba(0, 119, 182, 0.26); transition: transform 0.2s ease, box-shadow 0.2s ease, filter 0.2s ease; }
        .btn-submit:hover { transform: translateY(-1px); filter: brightness(1.03); box-shadow: 0 18px 34px rgba(0, 119, 182, 0.34); }
        .error-msg { color: #dc3545; font-size: 0.8rem; margin-top: 4px; display: none; }
        .info-box { background: #e6f4ff; border-left: 4px solid var(--primary); padding: 12px 15px; border-radius: 0 8px 8px 0; margin-bottom: 20px; font-size: 0.9rem; color: var(--text-main); }
        .info-box i { margin-right: 8px; }
        .page-footer { text-align: center; padding: 20px; color: var(--text-muted); font-size: 0.8rem; margin-top: 30px; }

        @media (max-width: 980px) {
            .form-grid { grid-template-columns: 1fr; }
        }

        :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,
        .card,
        .info-box {
            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 {
            border-radius: 22px;
            padding: 26px;
        }
        .register-card {
            max-width: 590px;
            margin-left: auto;
            margin-right: auto;
            padding: 24px 28px;
        }
        .info-box {
            border-left: 4px solid var(--secondary);
            border-radius: 16px;
            color: var(--text-main);
            padding: 14px 16px;
        }
        .form-group label {
            color: var(--deep-blue);
            font-weight: 700;
        }
        .form-group input,
        .form-group select {
            background: rgba(255,255,255,0.76);
            border-color: rgba(255,255,255,0.62);
            color: var(--text-main);
        }
        .toggle-pass svg { fill: var(--text-muted); }
        .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 user_list.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_register.php'); ?>
        </ul>
    </aside>

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

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

        <!-- INFO BOX -->
        <div class="info-box">
            <i class="fas fa-info-circle"></i>
            <strong>Nota:</strong> Pengguna yang didaftarkan oleh Superadmin akan mempunyai status <b>Active</b> dan boleh log masuk serta-merta tanpa kelulusan.
        </div>

        <!-- FORM PENDAFTARAN -->
        <div class="card register-card">
            <div class="form-header">
                <img src="mainpp.png" alt="Logo MAINPP">
                <h1>DAFTAR PENGGUNA</h1>
            </div>
            <?= $message ?>
            <form method="POST" id="regForm">
                <div class="form-grid">
                    <div class="form-group full">
                        <label for="fullname">Nama Penuh</label>
                        <input type="text" name="fullname" id="fullname" value="<?= htmlspecialchars($_POST['fullname']??'') ?>" required>
                    </div>

                    <div class="form-group">
                        <label for="short_name">Nama Panggilan</label>
                        <input type="text" name="short_name" id="short_name" value="<?= htmlspecialchars($_POST['short_name']??'') ?>" maxlength="100" required>
                    </div>

                    <div class="form-group">
                        <label for="ic_number">No. Kad Pengenalan</label>
                        <input type="text" name="ic_number" id="ic_number" value="<?= htmlspecialchars($_POST['ic_number']??'') ?>" inputmode="numeric" pattern="\d{12}" minlength="12" maxlength="12" title="No. Kad Pengenalan mesti mengandungi 12 digit nombor." required>
                    </div>

                    <div class="form-group full">
                        <label for="email">Emel Rasmi</label>
                        <input type="email" name="email" id="email" value="<?= htmlspecialchars($_POST['email']??'') ?>" title="Gunakan emel rasmi MAINPP yang berakhir dengan @mainpp.gov.my" required>
                    </div>

                    <div class="form-group">
                        <label for="department">Bahagian / Unit</label>
                        <select name="department" id="department" required>
                            <option value="" disabled selected>-- Sila Pilih Bahagian --</option>
                            <?php foreach ($departments_list as $department_option): ?>
                            <option value="<?= htmlspecialchars($department_option) ?>" <?= (($_POST['department']??'') === $department_option) ? 'selected' : '' ?>><?= htmlspecialchars($department_option) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="position">Jawatan</label>
                        <select name="position" id="position" data-selected="<?= htmlspecialchars($_POST['position'] ?? '') ?>" required>
                            <option value="" disabled selected>-- Pilih Bahagian Dahulu --</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="regPass">Kata Laluan</label>
                        <div class="pass-wrapper">
                            <input type="password" name="password" id="regPass" required>
                            <button type="button" class="toggle-pass" onclick="togglePass('regPass', this)" aria-label="Papar atau sembunyi kata laluan">
                                <svg viewBox="0 0 24 24"><path d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z"/></svg>
                            </button>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="regConfirmPass">Sahkan Kata Laluan</label>
                        <div class="pass-wrapper">
                            <input type="password" name="confirm_pass" id="regConfirmPass" required>
                            <button type="button" class="toggle-pass" onclick="togglePass('regConfirmPass', this)" aria-label="Papar atau sembunyi kata laluan">
                                <svg viewBox="0 0 24 24"><path d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z"/></svg>
                            </button>
                        </div>
                        <div class="error-msg" id="passError">Kata laluan tidak sepadan.</div>
                    </div>
                </div>

                <button type="submit" name="register_user" class="btn-submit">DAFTAR PENGGUNA</button>
            </form>
        </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);
            });
        });
        const positionMap = <?= json_encode($position_map, JSON_UNESCAPED_UNICODE) ?>;
        const departmentSelect = document.getElementById('department');
        const positionSelect = document.getElementById('position');
        function syncPositionOptions() {
            if (!departmentSelect || !positionSelect) return;
            const selected = positionSelect.dataset.selected || '';
            const positions = positionMap[departmentSelect.value] || [];
            positionSelect.innerHTML = '<option value="">-- Sila Pilih Jawatan --</option>';
            positions.forEach(position => {
                const option = document.createElement('option');
                option.value = position;
                option.textContent = position;
                option.selected = selected === position;
                positionSelect.appendChild(option);
            });
            positionSelect.disabled = positions.length === 0;
        }
        if (departmentSelect) {
            departmentSelect.addEventListener('change', function () {
                if (positionSelect) positionSelect.dataset.selected = '';
                syncPositionOptions();
            });
            syncPositionOptions();
        }
        function togglePass(inputId, btn) {
            const input = document.getElementById(inputId);
            const isPass = input.type === 'password';
            input.type = isPass ? 'text' : 'password';
            const openIcon = '<svg viewBox="0 0 24 24"><path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/></svg>';
            const closedIcon = '<svg viewBox="0 0 24 24"><path d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z"/></svg>';
            btn.innerHTML = isPass ? openIcon : closedIcon;
        }
        
        // Password Match Validation
        document.getElementById('regForm').addEventListener('submit', function(e) {
            const p1 = document.getElementById('regPass').value;
            const p2 = document.getElementById('regConfirmPass').value;
            const err = document.getElementById('passError');
            if (p1 !== p2) {
                e.preventDefault();
                err.style.display = 'block';
                document.getElementById('regConfirmPass').style.borderColor = '#dc3545';
            } else {
                err.style.display = 'none';
                document.getElementById('regConfirmPass').style.borderColor = '#e0e8f0';
            }
        });
        
        // Confirm Logout
        function confirmLogout() { return confirm("Adakah anda pasti ingin log keluar?"); }
    </script>
    <?php renderSessionTimeoutScript(); ?>
</body>
</html>
