<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
define('BASE_URL', '');

include __DIR__ . '/config/db.php';
include __DIR__ . '/config/auth.php';

// ── NAV: each page file gets its OWN permission key = the filename ──────
// sidebar.php must check: has_page_access('submissions.php') etc.
$NAV = [
    '__group_overview' => 'Overview',
    'admin_dashboard.php' => [
        'label' => 'Dashboard',
        'icon'  => '<rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/>',
    ],
    'submissions.php' => [
        'label' => 'Submissions',
        'icon'  => '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="9" y1="13" x2="15" y2="13"/><line x1="9" y1="17" x2="12" y2="17"/>',
    ],
    'final_submissions.php' => [
        'label' => 'Final Submissions',
        'icon'  => '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="9" y1="13" x2="15" y2="13"/><line x1="9" y1="17" x2="12" y2="17"/>',
    ],
    'resubmissions.php' => [
        'label' => 'ReSubmissions',
        'icon'  => '<polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 .49-3.5"/>',
    ],
    'reviewer-due-dates.php' => [
        'label' => 'Reviewer Due Dates',
        'icon'  => '<rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>',
    ],
    'reminders.php' => [
        'label' => 'Reminders',
        'icon'  => '<path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/>',
    ],
    'live_feedback.php' => [
        'label' => 'Live Feedbacks',
        'icon'  => '<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>',
    ],
    'reviewer_tickets.php' => [
        'label' => 'Reviewer Tickets',
        'icon'  => '<path d="M20 12v6a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h6"/><circle cx="18" cy="6" r="3"/>',
    ],
    'author_tickets.php' => [
        'label' => 'Author Tickets',
        'icon'  => '<path d="M20 12v6a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h6"/><circle cx="18" cy="6" r="3"/>',
    ],
    'all_payments.php' => [
        'label' => 'All Payments',
        'icon'  => '<rect x="1" y="4" width="22" height="16" rx="2" ry="2"/><line x1="1" y1="10" x2="23" y2="10"/>',
    ],
    'stripe-payments.php' => [
        'label' => 'Stripe Payments',
        'icon'  => '<rect x="1" y="4" width="22" height="16" rx="2" ry="2"/><line x1="1" y1="10" x2="23" y2="10"/>',
    ],

    '__group_people' => 'People',
    'reviewers_applications.php' => [
        'label' => 'Reviewers Applications',
        'icon'  => '<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>',
    ],
    'suggested_reviewers.php' => [
        'label' => 'Suggested Reviewers',
        'icon'  => '<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>',
    ],
    'editorial_applications.php' => [
        'label' => 'Editorial Applications',
        'icon'  => '<path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>',
    ],
    'conference_proceedings.php' => [
        'label' => 'Conference Proceedings',
        'icon'  => '<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>',
    ],
    'subscribers.php' => [
        'label' => 'Subscribers',
        'icon'  => '<path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/>',
    ],
    'users.php' => [
        'label' => 'Users',
        'icon'  => '<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/>',
    ],
    'manage_users.php' => [
        'label' => 'Manage Admin Users',
        'icon'  => '<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><line x1="23" y1="11" x2="17" y2="11"/><line x1="20" y1="8" x2="20" y2="14"/>',
    ],

    '__group_website' => 'Website',
    'pages.php' => [
        'label' => 'Pages',
        'icon'  => '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="9" y1="13" x2="15" y2="13"/><line x1="9" y1="17" x2="12" y2="17"/>',
    ],
    'categories.php' => [
        'label' => 'Journals Category',
        'icon'  => '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="9" y1="13" x2="15" y2="13"/><line x1="9" y1="17" x2="12" y2="17"/>',
    ],
    'journals.php' => [
        'label' => 'Journals',
        'icon'  => '<path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/>',
    ],
    'website-details.php' => [
        'label' => 'Website Details',
        'icon'  => '<circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>',
    ],
    'admin_homepage.php' => [
        'label' => 'Main Website Homepage',
        'icon'  => '<circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>',
    ],
    'bfooter.php' => [
        'label' => 'Footer',
        'icon'  => '<rect x="2" y="14" width="20" height="8" rx="2"/><line x1="6" y1="18" x2="6" y2="18.01"/><line x1="10" y1="18" x2="14" y2="18"/>',
    ],
];

// ── Build NAV_GROUPS for permission UI (grouped by section, one card per page) ──
$NAV_GROUPS = [];
$currentGroup = 'General';
foreach ($NAV as $file => $val) {
    if (str_starts_with($file, '__group_')) {
        $currentGroup = $val;
        continue;
    }
    if (!is_array($val)) continue;
    $NAV_GROUPS[$currentGroup][] = [
        'perm'  => $file,           // permission key = filename e.g. submissions.php
        'label' => $val['label'],
        'icon'  => $val['icon'],
    ];
}

// ── AJAX: get single user + permissions ───────────────────────────────
if (isset($_GET['action']) && $_GET['action'] === 'get_user' && isset($_GET['id'])) {
    $id   = (int) $_GET['id'];
    $stmt = $pdo->prepare("SELECT id, email, first_name, last_name, role, is_active, last_login_at FROM admin_users WHERE id = ?");
    $stmt->execute([$id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    $perms = [];
    if ($user) {
        try {
            $ps = $pdo->prepare("SELECT permission_key FROM admin_user_permissions WHERE user_id = ?");
            $ps->execute([$id]);
            $perms = $ps->fetchAll(PDO::FETCH_COLUMN);
        } catch (\Exception $e) {
            $perms = [];
        }
    }

    header('Content-Type: application/json');
    echo json_encode(['user' => $user, 'permissions' => $perms]);
    exit;
}

// ── Handle POST ────────────────────────────────────────────────────────
$flash = ['type' => '', 'msg' => ''];

// DDL: ensure table exists
try {
    $pdo->exec("ALTER TABLE admin_users MODIFY COLUMN role
        ENUM('superadmin','admin','subadmin','editor','reviewer','author')
        NOT NULL DEFAULT 'author'");
} catch (\Exception $e) {}

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS admin_user_permissions (
        id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        user_id INT UNSIGNED NOT NULL,
        permission_key VARCHAR(100) NOT NULL,
        UNIQUE KEY uq_user_perm (user_id, permission_key),
        INDEX idx_user (user_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (\Exception $e) {}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['_action'] ?? '';

    if ($action === 'create') {
        $email    = trim($_POST['email'] ?? '');
        $first    = trim($_POST['first_name'] ?? '');
        $last     = trim($_POST['last_name'] ?? '');
        $role     = $_POST['role'] ?? 'subadmin';
        $active   = isset($_POST['is_active']) ? 1 : 0;
        $password = $_POST['password'] ?? '';
        $perms    = $_POST['permissions'] ?? [];
        $allowedRoles = ['superadmin','admin','subadmin','editor','reviewer'];
        if (!in_array($role, $allowedRoles)) $role = 'subadmin';

        if (!$email || !$password || !$first || !$last) {
            $flash = ['type' => 'error', 'msg' => 'All required fields must be filled.'];
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $flash = ['type' => 'error', 'msg' => 'Invalid email address.'];
        } elseif (strlen($password) < 8) {
            $flash = ['type' => 'error', 'msg' => 'Password must be at least 8 characters.'];
        } else {
            try {
                $check = $pdo->prepare("SELECT id FROM admin_users WHERE email = ?");
                $check->execute([$email]);
                if ($check->fetch()) {
                    $flash = ['type' => 'error', 'msg' => 'Email already exists.'];
                } else {
                    $pdo->beginTransaction();
                    $hash = password_hash($password, PASSWORD_DEFAULT);
                    $ins  = $pdo->prepare("INSERT INTO admin_users (email,password_hash,first_name,last_name,role,is_active) VALUES (?,?,?,?,?,?)");
                    $ins->execute([$email, $hash, $first, $last, $role, $active]);
                    $newId = $pdo->lastInsertId();
                    foreach ($perms as $pkey) {
                        $pi = $pdo->prepare("INSERT IGNORE INTO admin_user_permissions (user_id,permission_key) VALUES (?,?)");
                        $pi->execute([$newId, $pkey]);
                    }
                    $pdo->commit();
                    $flash = ['type' => 'success', 'msg' => "User <strong>{$first} {$last}</strong> created successfully."];
                }
            } catch (\Exception $e) {
                if ($pdo->inTransaction()) $pdo->rollBack();
                $flash = ['type' => 'error', 'msg' => 'DB error: ' . $e->getMessage()];
            }
        }
    }

    if ($action === 'update') {
        $id       = (int) ($_POST['user_id'] ?? 0);
        $email    = trim($_POST['email'] ?? '');
        $first    = trim($_POST['first_name'] ?? '');
        $last     = trim($_POST['last_name'] ?? '');
        $role     = $_POST['role'] ?? 'subadmin';
        $active   = isset($_POST['is_active']) ? 1 : 0;
        $password = trim($_POST['password'] ?? '');
        $perms    = $_POST['permissions'] ?? [];
        $allowedRoles = ['superadmin','admin','subadmin','editor','reviewer'];
        if (!in_array($role, $allowedRoles)) $role = 'subadmin';

        if (!$id || !$email || !$first || !$last) {
            $flash = ['type' => 'error', 'msg' => 'Required fields missing.'];
        } else {
            try {
                $pdo->beginTransaction();
                if ($password) {
                    $hash = password_hash($password, PASSWORD_DEFAULT);
                    $upd  = $pdo->prepare("UPDATE admin_users SET email=?,first_name=?,last_name=?,role=?,is_active=?,password_hash=?,updated_at=NOW() WHERE id=?");
                    $upd->execute([$email, $first, $last, $role, $active, $hash, $id]);
                } else {
                    $upd = $pdo->prepare("UPDATE admin_users SET email=?,first_name=?,last_name=?,role=?,is_active=?,updated_at=NOW() WHERE id=?");
                    $upd->execute([$email, $first, $last, $role, $active, $id]);
                }
                $pdo->prepare("DELETE FROM admin_user_permissions WHERE user_id=?")->execute([$id]);
                foreach ($perms as $pkey) {
                    $pi = $pdo->prepare("INSERT IGNORE INTO admin_user_permissions (user_id,permission_key) VALUES (?,?)");
                    $pi->execute([$id, $pkey]);
                }
                $pdo->commit();
                $flash = ['type' => 'success', 'msg' => "User updated successfully."];
            } catch (\Exception $e) {
                if ($pdo->inTransaction()) $pdo->rollBack();
                $flash = ['type' => 'error', 'msg' => 'DB error: ' . $e->getMessage()];
            }
        }
    }

    if ($action === 'delete') {
        $id = (int) ($_POST['user_id'] ?? 0);
        $me = $_SESSION['admin_user_id'] ?? 0;
        if ($id === 1 || $id === (int)$me) {
            $flash = ['type' => 'error', 'msg' => 'Cannot delete this account.'];
        } elseif ($id > 0) {
            try {
                $pdo->beginTransaction();
                $pdo->prepare("DELETE FROM admin_user_permissions WHERE user_id=?")->execute([$id]);
                $pdo->prepare("DELETE FROM admin_users WHERE id=?")->execute([$id]);
                $pdo->commit();
                $flash = ['type' => 'success', 'msg' => 'User deleted.'];
            } catch (\Exception $e) {
                if ($pdo->inTransaction()) $pdo->rollBack();
                $flash = ['type' => 'error', 'msg' => 'Delete failed: ' . $e->getMessage()];
            }
        }
    }
}

// ── Fetch users ────────────────────────────────────────────────────────
$search     = trim($_GET['search'] ?? '');
$roleFilter = $_GET['role_filter'] ?? '';
$sql        = "SELECT id,email,first_name,last_name,role,is_active,last_login_at,created_at FROM admin_users WHERE 1";
$params     = [];
if ($search) {
    $sql .= " AND (first_name LIKE ? OR last_name LIKE ? OR email LIKE ?)";
    $s = "%{$search}%"; $params = array_merge($params, [$s,$s,$s]);
}
if ($roleFilter) { $sql .= " AND role = ?"; $params[] = $roleFilter; }
$sql .= " ORDER BY id DESC";
$stmt = $pdo->prepare($sql); $stmt->execute($params);
$adminUsers = $stmt->fetchAll(PDO::FETCH_ASSOC);

$permsByUser = [];
try {
    $allPerms = $pdo->query("SELECT user_id,permission_key FROM admin_user_permissions")->fetchAll(PDO::FETCH_ASSOC);
    foreach ($allPerms as $row) $permsByUser[$row['user_id']][] = $row['permission_key'];
} catch (\Exception $e) {}

$totalUsers    = count($adminUsers);
$activeUsers   = count(array_filter($adminUsers, fn($u) => $u['is_active']));
$inactiveUsers = $totalUsers - $activeUsers;
$subadmins     = count(array_filter($adminUsers, fn($u) => $u['role'] === 'subadmin'));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manage Users — Admin</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<style>
body{font-family:'Roboto',sans-serif;margin:0;height:100vh;overflow:hidden;}
body.dark{background-color:#1a202c;color:#e2e8f0;}
.sidebar{width:250px;background:#2d3748;color:white;transition:all .3s;height:100%;position:fixed;top:0;left:0;z-index:10;overflow-y:auto;}
.sidebar.collapsed{width:70px;}
.sidebar.collapsed .sidebar-title{display:none;}
.content{margin-left:250px;transition:margin-left .3s;height:100vh;overflow-y:auto;}
.content.collapsed-sidebar{margin-left:70px;}
.nav-item{padding:10px 12px;cursor:pointer;transition:background .2s;display:flex;align-items:center;}
.nav-item:hover{background:#4a5568;}
.nav-item.active{background:#4a5568;border-left:4px solid #4299e1;}
body.dark .bg-white{background-color:#2d3748!important;}
body.dark .text-gray-700{color:#d1d5db;}
body.dark table{color:#e2e8f0;}
body.dark .border-gray-200{border-color:#4a5568;}
body.dark .bg-gray-50{background-color:#374151!important;}
body.dark input,body.dark select,body.dark textarea{background-color:#374151!important;color:#e5e7eb!important;border-color:#4b5563!important;}
body.dark .text-gray-800{color:#F3F4F6;}
body.dark .text-gray-600{color:#9CA3AF;}
body.dark .text-gray-500{color:#6B7280;}
body.dark .bg-gray-100{background-color:#1a202c!important;}
body.dark .border-gray-100{border-color:#4a5568;}
body.dark .modal-box{background:#2d3748!important;}
body.dark .modal-section{background:#374151!important;border-color:#4a5568!important;}
body.dark .perm-card{background:#2d3748!important;border-color:#4a5568!important;}
body.dark .perm-card:hover{border-color:#4299e1!important;}
body.dark .perm-card.checked{background:#1a365d!important;border-color:#4299e1!important;}
body.dark .perm-icon-wrap{background:#374151!important;}
body.dark .perm-card.checked .perm-icon-wrap{background:#1e3a5f!important;}
@media(max-width:768px){.sidebar{transform:translateX(-250px)}.sidebar.mobile-open{transform:translateX(0)}.content{margin-left:0}}

.rbadge{display:inline-flex;align-items:center;gap:4px;padding:2px 10px;border-radius:20px;font-size:11px;font-weight:700;letter-spacing:.4px;text-transform:uppercase;}
.rb-superadmin{background:#FEF3C7;color:#92400E;}.rb-admin{background:#DBEAFE;color:#1E40AF;}.rb-subadmin{background:#FCE7F3;color:#9D174D;}.rb-editor{background:#D1FAE5;color:#065F46;}.rb-reviewer{background:#EDE9FE;color:#5B21B6;}.rb-author{background:#F1F5F9;color:#475569;}
.sdot{width:8px;height:8px;border-radius:50%;display:inline-block;flex-shrink:0;}.sdot-on{background:#10b981;}.sdot-off{background:#ef4444;}
.stat-card{background:white;border-radius:12px;padding:16px 20px;border:1px solid #E5E7EB;display:flex;align-items:center;gap:14px;transition:box-shadow .2s;}
.stat-card:hover{box-shadow:0 4px 16px rgba(0,0,0,.08);}
.stat-icon{width:44px;height:44px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:18px;flex-shrink:0;}
.tbl{width:100%;border-collapse:collapse;}
.tbl th{padding:10px 14px;text-align:left;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.6px;color:#6B7280;border-bottom:1px solid #E5E7EB;background:#F9FAFB;}
.tbl td{padding:12px 14px;border-bottom:1px solid #F3F4F6;font-size:13px;vertical-align:middle;}
.tbl tr:hover td{background:#F8FAFC;}

/* ── Permission cards ── */
.perm-card{display:flex;align-items:flex-start;gap:10px;padding:10px 12px;border:1.5px solid #E5E7EB;border-radius:10px;cursor:pointer;transition:all .15s;background:white;}
.perm-card:hover{border-color:#93C5FD;background:#EFF6FF;}
.perm-card.checked{border-color:#2563EB;background:#EFF6FF;}
.perm-check{width:16px;height:16px;border-radius:4px;border:2px solid #D1D5DB;flex-shrink:0;margin-top:2px;display:flex;align-items:center;justify-content:center;transition:all .15s;}
.perm-card.checked .perm-check{background:#2563EB;border-color:#2563EB;}
.perm-card.checked .perm-check::after{content:'✓';color:white;font-size:10px;font-weight:700;}
.perm-icon-wrap{width:32px;height:32px;border-radius:8px;background:#F3F4F6;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:background .15s;}
.perm-card.checked .perm-icon-wrap{background:#DBEAFE;}
.perm-icon{color:#6B7280;transition:color .15s;}
.perm-card.checked .perm-icon{color:#2563EB;}

/* ── Modal ── */
.modal-overlay{position:fixed;inset:0;background:rgba(15,23,42,.55);backdrop-filter:blur(4px);z-index:200;display:none;align-items:center;justify-content:center;padding:20px;}
.modal-overlay.open{display:flex;}
.modal-box{background:white;border-radius:16px;width:100%;max-width:820px;max-height:90vh;display:flex;flex-direction:column;box-shadow:0 24px 80px rgba(0,0,0,.22);}
.modal-header{padding:20px 24px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;justify-content:space-between;flex-shrink:0;}
.modal-body{overflow-y:auto;flex:1;padding:24px;}
.modal-footer{padding:16px 24px;border-top:1px solid #E5E7EB;display:flex;justify-content:flex-end;gap:10px;flex-shrink:0;}
.modal-section{background:#F8FAFC;border:1px solid #E5E7EB;border-radius:12px;padding:18px;}
.finput{width:100%;border:1.5px solid #D1D5DB;border-radius:8px;padding:9px 12px;font-size:13px;color:#374151;transition:border-color .15s;outline:none;font-family:'Roboto',sans-serif;}
.finput:focus{border-color:#3B82F6;box-shadow:0 0 0 3px rgba(59,130,246,.1);}
.flabel{font-size:12px;font-weight:600;color:#374151;margin-bottom:4px;display:block;}
.toast{position:fixed;bottom:24px;right:24px;z-index:9999;padding:12px 20px;border-radius:10px;font-size:13px;font-weight:600;display:flex;align-items:center;gap:8px;box-shadow:0 8px 24px rgba(0,0,0,.15);transform:translateY(80px);opacity:0;transition:all .3s ease;max-width:360px;}
.toast.show{transform:translateY(0);opacity:1;}
.toast-success{background:#ECFDF5;color:#065F46;border:1px solid #A7F3D0;}
.toast-error{background:#FEF2F2;color:#991B1B;border:1px solid #FECACA;}
.confirm-overlay{position:fixed;inset:0;background:rgba(15,23,42,.55);backdrop-filter:blur(4px);z-index:300;display:none;align-items:center;justify-content:center;}
.confirm-overlay.open{display:flex;}
.pg-tab{padding:6px 14px;border-radius:8px;font-size:12px;font-weight:600;cursor:pointer;border:none;background:transparent;color:#64748b;transition:all .15s;white-space:nowrap;}
.pg-tab.active{background:#EFF6FF;color:#1d4ed8;}
.toggle-wrap{position:relative;display:inline-flex;align-items:center;gap:8px;cursor:pointer;user-select:none;}
.toggle-input{display:none;}
.toggle-track{width:44px;height:24px;background:#D1D5DB;border-radius:999px;transition:background .2s;flex-shrink:0;}
.toggle-input:checked ~ .toggle-track{background:#2563EB;}
.toggle-thumb{position:absolute;left:3px;top:50%;transform:translateY(-50%);width:18px;height:18px;background:white;border-radius:50%;box-shadow:0 1px 3px rgba(0,0,0,.2);transition:left .2s;}
.toggle-input:checked ~ .toggle-track ~ .toggle-thumb{left:23px;}
</style>
</head>
<body class="bg-gray-100">

<button onclick="toggleMobileSidebar()" class="fixed top-3 left-3 z-20 bg-gray-800 text-white px-3 py-2 rounded-md md:hidden">☰</button>

<?php include __DIR__ . '/include/sidebar.php'; ?>

<div class="content" id="content">

    <!-- Topbar -->
    <div class="bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between sticky top-0 z-10 shadow-sm" style="margin-top:50px;">
        <div class="flex items-center gap-3">

            <div class="flex items-center gap-2 text-sm text-gray-500">
                <i class="fas fa-chevron-right text-xs text-gray-300"></i>
                <span class="text-gray-800 font-bold flex items-center gap-2">
                    <i class="fas fa-users-cog text-blue-600"></i> Manage Users
                </span>
            </div>
        </div>
        <div class="flex items-center gap-3">
            <button onclick="openCreateModal()"
                    class="inline-flex items-center gap-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold px-4 py-2 rounded-lg transition-colors">
                <i class="fas fa-plus text-xs"></i> New User
            </button>
            <button id="darkModeToggle"
                    class="text-gray-500 hover:text-gray-700 w-9 h-9 rounded-lg border border-gray-200 flex items-center justify-center">
                <i class="fas fa-moon"></i>
            </button>
        </div>
    </div>

    <main class="p-6 space-y-6">

        <?php if ($flash['msg']): ?>
        <div id="flash-bar"
             class="flex items-center gap-3 px-4 py-3 rounded-lg text-sm font-medium
                    <?= $flash['type'] === 'success' ? 'bg-emerald-50 text-emerald-800 border border-emerald-200' : 'bg-red-50 text-red-800 border border-red-200' ?>">
            <i class="fas <?= $flash['type'] === 'success' ? 'fa-check-circle text-emerald-500' : 'fa-exclamation-circle text-red-500' ?>"></i>
            <span><?= $flash['msg'] ?></span>
            <button onclick="document.getElementById('flash-bar').remove()" class="ml-auto opacity-60 hover:opacity-100"><i class="fas fa-times"></i></button>
        </div>
        <?php endif; ?>

        <!-- Stats -->
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div class="stat-card"><div class="stat-icon bg-blue-50 text-blue-600"><i class="fas fa-users"></i></div><div><div class="text-2xl font-bold text-gray-800"><?= $totalUsers ?></div><div class="text-xs text-gray-500 font-medium">Total Users</div></div></div>
            <div class="stat-card"><div class="stat-icon bg-emerald-50 text-emerald-600"><i class="fas fa-check-circle"></i></div><div><div class="text-2xl font-bold text-gray-800"><?= $activeUsers ?></div><div class="text-xs text-gray-500 font-medium">Active</div></div></div>
            <div class="stat-card"><div class="stat-icon bg-red-50 text-red-500"><i class="fas fa-ban"></i></div><div><div class="text-2xl font-bold text-gray-800"><?= $inactiveUsers ?></div><div class="text-xs text-gray-500 font-medium">Inactive</div></div></div>
            <div class="stat-card"><div class="stat-icon bg-pink-50 text-pink-600"><i class="fas fa-user-tie"></i></div><div><div class="text-2xl font-bold text-gray-800"><?= $subadmins ?></div><div class="text-xs text-gray-500 font-medium">Subadmins</div></div></div>
        </div>

        <!-- Table -->
        <div class="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden">
            <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 px-5 py-4 border-b border-gray-100">
                <h2 class="font-bold text-gray-800 flex items-center gap-2">
                    <i class="fas fa-shield-alt text-blue-500 text-sm"></i> Admin Users
                    <span class="text-xs font-medium bg-blue-50 text-blue-700 px-2 py-0.5 rounded-full"><?= $totalUsers ?></span>
                </h2>
                <form method="GET" class="flex items-center gap-2 flex-wrap">
                    <div class="relative">
                        <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-xs"></i>
                        <input name="search" value="<?= htmlspecialchars($search) ?>" placeholder="Search name or email…"
                               class="pl-8 pr-3 py-2 text-sm border border-gray-200 rounded-lg outline-none focus:border-blue-400 w-52">
                    </div>
                    <select name="role_filter" class="text-sm border border-gray-200 rounded-lg px-3 py-2 outline-none focus:border-blue-400 bg-white text-gray-700">
                        <option value="">All Roles</option>
                        <option value="superadmin" <?= $roleFilter==='superadmin'?'selected':'' ?>>Superadmin</option>
                        <option value="admin"      <?= $roleFilter==='admin'     ?'selected':'' ?>>Admin</option>
                        <option value="subadmin"   <?= $roleFilter==='subadmin'  ?'selected':'' ?>>Subadmin</option>
                        <option value="editor"     <?= $roleFilter==='editor'    ?'selected':'' ?>>Editor</option>
                        <option value="reviewer"   <?= $roleFilter==='reviewer'  ?'selected':'' ?>>Reviewer</option>
                    </select>
                    <button type="submit" class="bg-blue-600 text-white text-sm px-3 py-2 rounded-lg hover:bg-blue-700"><i class="fas fa-search"></i></button>
                    <?php if ($search || $roleFilter): ?>
                    <a href="manage_users.php" class="text-sm text-gray-500 hover:text-gray-700 px-3 py-2 rounded-lg border border-gray-200 hover:bg-gray-50"><i class="fas fa-times text-xs"></i> Clear</a>
                    <?php endif; ?>
                </form>
            </div>

            <div class="overflow-x-auto">
                <table class="tbl">
                    <thead>
                        <tr>
                            <th>User</th><th>Role</th><th>Page Access</th><th>Status</th><th>Last Login</th><th>Created</th><th style="text-align:right;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if (empty($adminUsers)): ?>
                        <tr><td colspan="7" class="text-center py-14 text-gray-400"><i class="fas fa-users-slash text-3xl mb-3 block"></i><span class="text-sm">No users found</span></td></tr>
                    <?php else: ?>
                    <?php foreach ($adminUsers as $u):
                        $initials  = strtoupper(substr($u['first_name'],0,1).substr($u['last_name'],0,1));
                        $userPerms = $permsByUser[$u['id']] ?? [];
                        $permCount = count($userPerms);
                        $colors    = ['bg-blue-500','bg-indigo-500','bg-violet-500','bg-emerald-500','bg-amber-500','bg-rose-500'];
                        $color     = $colors[$u['id'] % count($colors)];
                    ?>
                    <tr>
                        <td>
                            <div class="flex items-center gap-3">
                                <div class="w-9 h-9 rounded-full <?= $color ?> flex items-center justify-center text-white font-bold text-xs flex-shrink-0"><?= $initials ?></div>
                                <div>
                                    <div class="font-semibold text-gray-800 text-sm"><?= htmlspecialchars($u['first_name'].' '.$u['last_name']) ?></div>
                                    <div class="text-xs text-gray-400"><?= htmlspecialchars($u['email']) ?></div>
                                </div>
                            </div>
                        </td>
                        <td>
                            <span class="rbadge rb-<?= $u['role'] ?>">
                                <?php $ricon=['superadmin'=>'fa-star','admin'=>'fa-crown','subadmin'=>'fa-user-tie','editor'=>'fa-pen','reviewer'=>'fa-eye','author'=>'fa-file'][$u['role']]??'fa-user'; ?>
                                <i class="fas <?= $ricon ?> text-xs"></i> <?= ucfirst($u['role']) ?>
                            </span>
                        </td>
                        <td>
                            <?php if ($u['role'] === 'superadmin'): ?>
                                <span class="text-xs text-amber-600 font-semibold"><i class="fas fa-infinity mr-1"></i>Full Access</span>
                            <?php elseif ($permCount > 0): ?>
                                <div class="flex items-center gap-2">
                                    <span class="text-xs bg-blue-50 text-blue-700 font-semibold px-2 py-0.5 rounded-full"><?= $permCount ?> page<?= $permCount!==1?'s':'' ?></span>
                                    <button onclick='showPermsPopup(<?= json_encode($userPerms) ?>)' class="text-xs text-gray-400 hover:text-blue-600" title="View"><i class="fas fa-eye"></i></button>
                                </div>
                            <?php else: ?>
                                <span class="text-xs text-gray-400">No access</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="flex items-center gap-2">
                                <span class="sdot <?= $u['is_active'] ? 'sdot-on' : 'sdot-off' ?>"></span>
                                <span class="text-xs font-semibold <?= $u['is_active'] ? 'text-emerald-600' : 'text-red-500' ?>"><?= $u['is_active'] ? 'Active' : 'Inactive' ?></span>
                            </div>
                        </td>
                        <td class="text-xs text-gray-400"><?= $u['last_login_at'] ? date('d M Y, H:i',strtotime($u['last_login_at'])) : '<span class="italic">Never</span>' ?></td>
                        <td class="text-xs text-gray-400"><?= date('d M Y',strtotime($u['created_at'])) ?></td>
                        <td>
                            <div class="flex items-center justify-end gap-1">
                                <button onclick="openEditModal(<?= $u['id'] ?>)" class="w-8 h-8 rounded-lg border border-gray-200 flex items-center justify-center text-gray-500 hover:text-blue-600 hover:border-blue-300 hover:bg-blue-50 transition-all" title="Edit"><i class="fas fa-edit text-xs"></i></button>
                                <?php if ($u['id']!=1 && $u['id']!=($_SESSION['admin_user_id']??0)): ?>
                                <button onclick="confirmDelete(<?= $u['id'] ?>,'<?= htmlspecialchars($u['first_name'].' '.$u['last_name']) ?>')" class="w-8 h-8 rounded-lg border border-gray-200 flex items-center justify-center text-gray-500 hover:text-red-600 hover:border-red-300 hover:bg-red-50 transition-all" title="Delete"><i class="fas fa-trash-alt text-xs"></i></button>
                                <?php else: ?><div class="w-8 h-8 flex items-center justify-center"><i class="fas fa-lock text-xs text-gray-300"></i></div><?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <div class="px-5 py-3 border-t border-gray-100 text-xs text-gray-400 flex items-center justify-between">
                <span>Showing <?= count($adminUsers) ?> user<?= count($adminUsers)!==1?'s':'' ?></span>
                <span><i class="fas fa-info-circle"></i> ID #1 and your own account are protected from deletion</span>
            </div>
        </div>

    </main>
</div>

<!-- ═══ CREATE / EDIT MODAL ═══ -->
<div id="userModal" class="modal-overlay" onclick="if(event.target===this)closeModal()">
<div class="modal-box">
    <div class="modal-header">
        <div class="flex items-center gap-3">
            <div id="modalIcon" class="w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center"><i class="fas fa-user-plus text-blue-600"></i></div>
            <div>
                <h3 id="modalTitle" class="font-bold text-gray-800 text-lg">Create New User</h3>
                <p id="modalSub" class="text-xs text-gray-400 mt-0.5">Fill in details and assign page access</p>
            </div>
        </div>
        <button onclick="closeModal()" class="w-8 h-8 rounded-lg border border-gray-200 flex items-center justify-center text-gray-400 hover:text-gray-600 hover:bg-gray-50 transition-all"><i class="fas fa-times text-sm"></i></button>
    </div>

    <div class="modal-body space-y-5">
        <form id="userForm" method="POST">
            <input type="hidden" name="_action" id="formAction" value="create">
            <input type="hidden" name="user_id" id="formUserId">

            <!-- Step 1: User Details -->
            <div class="modal-section space-y-4 mb-5">
                <h4 class="text-sm font-bold text-gray-700 flex items-center gap-2">
                    <span class="w-5 h-5 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center text-xs font-black">1</span>
                    User Details
                </h4>
                <div class="grid grid-cols-2 gap-3">
                    <div><label class="flabel">First Name <span class="text-red-500">*</span></label><input type="text" name="first_name" id="fFirstName" class="finput" placeholder="John"></div>
                    <div><label class="flabel">Last Name <span class="text-red-500">*</span></label><input type="text" name="last_name" id="fLastName" class="finput" placeholder="Doe"></div>
                </div>
                <div><label class="flabel">Email Address <span class="text-red-500">*</span></label><input type="email" name="email" id="fEmail" class="finput" placeholder="john@example.com"></div>
                <div>
                    <label class="flabel" id="pwdLabel">Password <span class="text-red-500">*</span></label>
                    <div class="relative">
                        <input type="password" name="password" id="fPassword" class="finput pr-10" placeholder="Min 8 characters">
                        <button type="button" onclick="togglePwd()" class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"><i class="fas fa-eye text-xs" id="pwdEyeIcon"></i></button>
                    </div>
                    <p id="pwdHint" class="text-xs text-gray-400 mt-1 hidden">Leave blank to keep current password</p>
                </div>
                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="flabel">Role <span class="text-red-500">*</span></label>
                        <select name="role" id="fRole" class="finput" onchange="onRoleChange()">
                            <option value="subadmin">Subadmin</option>
                            <option value="admin">Admin</option>
                            <option value="editor">Editor</option>
                            <option value="reviewer">Reviewer</option>
                        </select>
                    </div>
                    <div>
                        <label class="flabel">Status</label>
                        <div class="flex items-center h-10 gap-3">
                            <label class="toggle-wrap">
                                <input type="checkbox" name="is_active" id="fActive" class="toggle-input" checked>
                                <div class="toggle-track"></div>
                                <div class="toggle-thumb"></div>
                                <span class="text-sm text-gray-600" id="activeLabel">Active</span>
                            </label>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Step 2: Page Access — one card per page file -->
            <div class="modal-section space-y-3" id="permsSection">
                <div class="flex items-center justify-between flex-wrap gap-2">
                    <h4 class="text-sm font-bold text-gray-700 flex items-center gap-2">
                        <span class="w-5 h-5 rounded-full bg-purple-100 text-purple-600 flex items-center justify-center text-xs font-black">2</span>
                        Page Access
                        <span id="permCount" class="text-xs font-medium bg-purple-50 text-purple-700 px-2 py-0.5 rounded-full">0 selected</span>
                    </h4>
                    <div class="flex items-center gap-2">
                        <button type="button" onclick="selectAllPerms(true)"  class="text-xs text-blue-600 hover:underline">Select All</button>
                        <span class="text-gray-300">|</span>
                        <button type="button" onclick="selectAllPerms(false)" class="text-xs text-gray-500 hover:underline">Clear All</button>
                    </div>
                </div>

                <!-- Section tabs -->
                <div class="flex gap-1 flex-wrap border-b border-gray-100 pb-2">
                    <?php $gi = 0; foreach ($NAV_GROUPS as $groupName => $items): ?>
                    <button type="button" class="pg-tab <?= $gi===0?'active':'' ?>" onclick="switchPermGroup(this,'pg-<?= $gi ?>')">
                        <?= htmlspecialchars($groupName) ?>
                    </button>
                    <?php $gi++; endforeach; ?>
                </div>

                <!-- Permission cards: one per page file -->
                <?php $gi = 0; foreach ($NAV_GROUPS as $groupName => $items): ?>
                <div id="pg-<?= $gi ?>" class="perm-group <?= $gi===0?'':'hidden' ?> grid grid-cols-1 sm:grid-cols-2 gap-2">
                    <?php foreach ($items as $item):
                        $pkey   = $item['perm'];   // e.g. submissions.php
                        $plabel = $item['label'];
                        $svg    = $item['icon'];
                    ?>
                    <label class="perm-card" id="pcard-<?= htmlspecialchars($pkey) ?>" onclick="togglePermCard(this)">
                        <input type="checkbox" name="permissions[]" value="<?= htmlspecialchars($pkey) ?>" class="perm-checkbox hidden">
                        <div class="perm-check"></div>
                        <div class="perm-icon-wrap">
                            <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="perm-icon">
                                <?= $svg ?>
                            </svg>
                        </div>
                        <div class="min-w-0 flex-1">
                            <div class="text-xs font-semibold text-gray-700 truncate"><?= htmlspecialchars($plabel) ?></div>
                            <div class="text-xs text-gray-400 font-mono truncate"><?= htmlspecialchars($pkey) ?></div>
                        </div>
                    </label>
                    <?php endforeach; ?>
                </div>
                <?php $gi++; endforeach; ?>

                <div id="superadminNotice" class="hidden text-sm text-amber-700 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2 flex items-center gap-2">
                    <i class="fas fa-infinity"></i> Superadmin has full access. Permissions not applicable.
                </div>
                <div id="subadminTip" class="hidden text-sm text-pink-700 bg-pink-50 border border-pink-200 rounded-lg px-3 py-2 flex items-center gap-2">
                    <i class="fas fa-user-tie"></i> Select only the pages this subadmin should access.
                </div>
            </div>
        </form>
    </div>

    <div class="modal-footer">
        <button type="button" onclick="closeModal()" class="px-4 py-2 text-sm text-gray-600 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">Cancel</button>
        <button type="button" onclick="submitForm()" id="submitBtn" class="px-5 py-2 text-sm font-semibold bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2">
            <i class="fas fa-save text-xs"></i> <span id="submitLabel">Create User</span>
        </button>
    </div>
</div>
</div>

<!-- ═══ DELETE CONFIRM ═══ -->
<div id="confirmOverlay" class="confirm-overlay" onclick="if(event.target===this)closeConfirm()">
<div class="bg-white rounded-2xl shadow-2xl p-6 w-full max-w-sm mx-4">
    <div class="flex items-center gap-3 mb-4">
        <div class="w-12 h-12 rounded-full bg-red-100 flex items-center justify-center flex-shrink-0"><i class="fas fa-trash-alt text-red-500 text-lg"></i></div>
        <div><h3 class="font-bold text-gray-800">Delete User?</h3><p class="text-sm text-gray-500 mt-0.5">This cannot be undone.</p></div>
    </div>
    <p class="text-sm text-gray-600 mb-5">You are about to delete <strong id="deleteUserName"></strong>. All their page permissions will also be removed.</p>
    <form method="POST" id="deleteForm">
        <input type="hidden" name="_action" value="delete">
        <input type="hidden" name="user_id" id="deleteUserId">
        <div class="flex gap-2">
            <button type="button" onclick="closeConfirm()" class="flex-1 px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 hover:bg-gray-50">Cancel</button>
            <button type="submit" class="flex-1 px-4 py-2 bg-red-600 text-white rounded-lg text-sm font-semibold hover:bg-red-700">Delete</button>
        </div>
    </form>
</div>
</div>

<!-- ═══ PERMISSIONS VIEWER ═══ -->
<div id="permsPopup" class="confirm-overlay" onclick="if(event.target===this)closePermsPopup()">
<div class="bg-white rounded-2xl shadow-2xl p-6 w-full max-w-md mx-4 max-h-96 overflow-y-auto">
    <div class="flex items-center justify-between mb-4">
        <h3 class="font-bold text-gray-800 flex items-center gap-2"><i class="fas fa-shield-alt text-blue-500"></i> Assigned Pages</h3>
        <button onclick="closePermsPopup()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
    </div>
    <div id="permsPopupContent" class="space-y-2"></div>
</div>
</div>

<div id="toast" class="toast"></div>

<!-- Pass NAV_GROUPS to JS for label lookup in popup -->
<script>
const NAV_GROUPS = <?= json_encode($NAV_GROUPS) ?>;
</script>

<script>
function toggleSidebar(){document.querySelector('.sidebar')?.classList.toggle('collapsed');document.getElementById('content')?.classList.toggle('collapsed-sidebar');}
function toggleMobileSidebar(){document.querySelector('.sidebar')?.classList.toggle('mobile-open');}

const dm=document.getElementById('darkModeToggle');
if(localStorage.getItem('darkMode')==='1'){document.body.classList.add('dark');dm.innerHTML='<i class="fas fa-sun"></i>';}
dm?.addEventListener('click',()=>{document.body.classList.toggle('dark');const on=document.body.classList.contains('dark');dm.innerHTML=on?'<i class="fas fa-sun"></i>':'<i class="fas fa-moon"></i>';localStorage.setItem('darkMode',on?'1':'0');});

function togglePwd(){const i=document.getElementById('fPassword'),e=document.getElementById('pwdEyeIcon');if(i.type==='password'){i.type='text';e.classList.replace('fa-eye','fa-eye-slash');}else{i.type='password';e.classList.replace('fa-eye-slash','fa-eye');}}

document.getElementById('fActive')?.addEventListener('change',function(){document.getElementById('activeLabel').textContent=this.checked?'Active':'Inactive';});

function switchPermGroup(tab,groupId){
    document.querySelectorAll('.pg-tab').forEach(t=>t.classList.remove('active'));
    document.querySelectorAll('.perm-group').forEach(g=>g.classList.add('hidden'));
    tab.classList.add('active');
    document.getElementById(groupId)?.classList.remove('hidden');
}

function togglePermCard(card){const cb=card.querySelector('.perm-checkbox');cb.checked=!cb.checked;card.classList.toggle('checked',cb.checked);updatePermCount();}
function updatePermCount(){const n=document.querySelectorAll('.perm-checkbox:checked').length;document.getElementById('permCount').textContent=n+' selected';}
function selectAllPerms(val){document.querySelectorAll('.perm-checkbox').forEach(cb=>{cb.checked=val;cb.closest('.perm-card').classList.toggle('checked',val);});updatePermCount();}

function onRoleChange(){
    const role=document.getElementById('fRole').value;
    const isSA=role==='superadmin',isSub=role==='subadmin';
    document.getElementById('superadminNotice').classList.toggle('hidden',!isSA);
    document.getElementById('subadminTip').classList.toggle('hidden',!isSub);
    document.querySelectorAll('.perm-card').forEach(c=>{c.style.opacity=isSA?'.4':'1';c.style.pointerEvents=isSA?'none':'auto';});
}

function resetForm(){
    document.getElementById('userForm').reset();
    document.querySelectorAll('.perm-checkbox').forEach(cb=>{cb.checked=false;cb.closest('.perm-card').classList.remove('checked');});
    updatePermCount();
    document.getElementById('activeLabel').textContent='Active';
    document.getElementById('superadminNotice').classList.add('hidden');
    document.getElementById('subadminTip').classList.add('hidden');
    document.querySelectorAll('.perm-card').forEach(c=>{c.style.opacity='1';c.style.pointerEvents='auto';});
    document.querySelectorAll('.pg-tab')[0]?.click();
}

function openCreateModal(){
    resetForm();
    document.getElementById('formAction').value='create';
    document.getElementById('formUserId').value='';
    document.getElementById('modalTitle').textContent='Create New User';
    document.getElementById('modalSub').textContent='Fill in details and assign page access';
    document.getElementById('modalIcon').innerHTML='<i class="fas fa-user-plus text-blue-600"></i>';
    document.getElementById('pwdLabel').innerHTML='Password <span class="text-red-500">*</span>';
    document.getElementById('fPassword').required=true;
    document.getElementById('pwdHint').classList.add('hidden');
    document.getElementById('submitLabel').textContent='Create User';
    document.getElementById('userModal').classList.add('open');
}

function openEditModal(userId){
    resetForm();
    fetch(`?action=get_user&id=${userId}`)
        .then(r=>r.json())
        .then(data=>{
            if(!data.user){showToast('User not found','error');return;}
            const u=data.user;
            document.getElementById('formAction').value='update';
            document.getElementById('formUserId').value=u.id;
            document.getElementById('fFirstName').value=u.first_name||'';
            document.getElementById('fLastName').value=u.last_name||'';
            document.getElementById('fEmail').value=u.email||'';
            document.getElementById('fRole').value=u.role||'subadmin';
            document.getElementById('fActive').checked=u.is_active==1;
            document.getElementById('activeLabel').textContent=u.is_active==1?'Active':'Inactive';
            document.getElementById('fPassword').required=false;
            document.getElementById('pwdHint').classList.remove('hidden');
            document.getElementById('pwdLabel').innerHTML='New Password';

            // Tick checkboxes by filename key
            (data.permissions||[]).forEach(pkey=>{
                // pkey is e.g. "submissions.php" — id is "pcard-submissions.php"
                const safeId='pcard-'+pkey;
                const card=document.getElementById(safeId);
                if(card){card.querySelector('.perm-checkbox').checked=true;card.classList.add('checked');}
            });
            updatePermCount();
            onRoleChange();

            document.getElementById('modalTitle').textContent='Edit User';
            document.getElementById('modalSub').textContent=`Editing ${u.first_name} ${u.last_name}`;
            document.getElementById('modalIcon').innerHTML='<i class="fas fa-user-edit text-blue-600"></i>';
            document.getElementById('submitLabel').textContent='Save Changes';
            document.getElementById('userModal').classList.add('open');
        })
        .catch(()=>showToast('Failed to load user','error'));
}

function closeModal(){document.getElementById('userModal').classList.remove('open');}
function submitForm(){document.getElementById('userForm').submit();}
function confirmDelete(id,name){document.getElementById('deleteUserId').value=id;document.getElementById('deleteUserName').textContent=name;document.getElementById('confirmOverlay').classList.add('open');}
function closeConfirm(){document.getElementById('confirmOverlay').classList.remove('open');}

function showPermsPopup(perms){
    const container=document.getElementById('permsPopupContent');
    // Build label map: perm key (filename) → label
    const labelMap={};
    const iconMap={};
    Object.values(NAV_GROUPS).forEach(items=>{
        items.forEach(item=>{labelMap[item.perm]=item.label;iconMap[item.perm]=item.icon;});
    });
    if(!perms||perms.length===0){
        container.innerHTML='<p class="text-sm text-gray-400">No pages assigned.</p>';
    } else {
        container.innerHTML=perms.map(p=>`
            <div class="flex items-center gap-3 py-2 border-b border-gray-50 last:border-0">
                <div class="w-7 h-7 rounded-lg bg-blue-50 flex items-center justify-center flex-shrink-0">
                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#2563EB" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${iconMap[p]||''}</svg>
                </div>
                <span class="text-sm text-gray-700 font-medium flex-1">${labelMap[p]||p}</span>
                <code class="text-xs text-gray-400 bg-gray-50 px-1.5 py-0.5 rounded font-mono">${p}</code>
            </div>`).join('');
    }
    document.getElementById('permsPopup').classList.add('open');
}
function closePermsPopup(){document.getElementById('permsPopup').classList.remove('open');}

function showToast(msg,type='success'){
    const t=document.getElementById('toast');
    t.className=`toast toast-${type}`;
    t.innerHTML=`<i class="fas fa-${type==='success'?'check-circle':'exclamation-circle'}"></i> ${msg}`;
    setTimeout(()=>t.classList.add('show'),10);
    setTimeout(()=>t.classList.remove('show'),3500);
}

<?php if($flash['msg']): ?>
setTimeout(()=>showToast(<?= json_encode(strip_tags($flash['msg'])) ?>,<?= json_encode($flash['type']) ?>),300);
<?php endif; ?>

document.addEventListener('keydown',e=>{
    if(e.key==='Escape'){closeModal();closeConfirm();closePermsPopup();}
    if((e.ctrlKey||e.metaKey)&&e.key==='k'){e.preventDefault();openCreateModal();}
});
</script>
</body>
</html>