<?php
require_once '../functions.php';
requireAdminAuth();

$admin = getCurrentAdmin();

// Only super_admin can access
if ($admin['role'] !== 'super_admin') {
    setFlash('Access denied. Super Admin only.', 'error');
    header('Location: dashboard.php');
    exit();
}

$db = getDB();

$error = '';
$success = '';

// CSRF Protection
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Helper function: Validate email format
function isValidEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

// Helper function: Check if username exists
function usernameExists($db, $username) {
    $stmt = $db->prepare("SELECT id FROM admin_users WHERE username = ?");
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $stmt->store_result();
    $exists = $stmt->num_rows > 0;
    $stmt->close();
    return $exists;
}

// Helper function: Check if email exists
function emailExists($db, $email) {
    $stmt = $db->prepare("SELECT id FROM admin_users WHERE email = ?");
    $stmt->bind_param('s', $email);
    $stmt->execute();
    $stmt->store_result();
    $exists = $stmt->num_rows > 0;
    $stmt->close();
    return $exists;
}

// Helper function: Log activity
function logAdminActivity($db, $adminId, $action, $description, $userId = null) {
    $ip = $_SERVER['REMOTE_ADDR'] ?? null;
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? null;

    $stmt = $db->prepare("INSERT INTO activity_logs (user_id, admin_id, action, description, ip_address, user_agent) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->bind_param('iissss', $userId, $adminId, $action, $description, $ip, $userAgent);
    $stmt->execute();
    $stmt->close();
}

// Helper function: Validate password strength
function validatePasswordStrength($password) {
    if (strlen($password) < 8) {
        return 'Password must be at least 8 characters long.';
    }
    if (!preg_match('/[A-Z]/', $password)) {
        return 'Password must contain at least one uppercase letter.';
    }
    if (!preg_match('/[a-z]/', $password)) {
        return 'Password must contain at least one lowercase letter.';
    }
    if (!preg_match('/[0-9]/', $password)) {
        return 'Password must contain at least one number.';
    }
    if (!preg_match('/[!@#$%^&*(),.?":{}|<>]/', $password)) {
        return 'Password must contain at least one special character.';
    }
    return true;
}

// Create admin
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_admin'])) {
    // CSRF Validation
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $error = 'Invalid security token. Please refresh the page and try again.';
    } else {
        $username = trim($_POST['username'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $firstName = trim($_POST['first_name'] ?? '');
        $lastName = trim($_POST['last_name'] ?? '');
        $password = $_POST['password'] ?? '';
        $role = $_POST['role'] ?? 'admin';

        // Validation
        if (empty($username) || empty($email) || empty($firstName) || empty($lastName) || empty($password)) {
            $error = 'Please fill in all required fields.';
        } elseif (strlen($username) < 3 || strlen($username) > 60) {
            $error = 'Username must be between 3 and 60 characters.';
        } elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
            $error = 'Username can only contain letters, numbers, and underscores.';
        } elseif (!isValidEmail($email)) {
            $error = 'Please enter a valid email address.';
        } elseif (strlen($email) > 180) {
            $error = 'Email must not exceed 180 characters.';
        } elseif (strlen($firstName) > 80 || strlen($lastName) > 80) {
            $error = 'First and last names must not exceed 80 characters each.';
        } elseif (!in_array($role, ['super_admin', 'admin', 'support'])) {
            $error = 'Invalid role selected.';
        } else {
            $passwordCheck = validatePasswordStrength($password);
            if ($passwordCheck !== true) {
                $error = $passwordCheck;
            } elseif (usernameExists($db, $username)) {
                $error = 'Username already exists. Please choose a different one.';
            } elseif (emailExists($db, $email)) {
                $error = 'Email address already exists. Please use a different one.';
            } else {
                // All validation passed - create admin
                $hashed = hashPassword($password);

                $db->begin_transaction();

                try {
                    $stmt = $db->prepare("INSERT INTO admin_users (username, password, email, first_name, last_name, role, is_active) VALUES (?, ?, ?, ?, ?, ?, 1)");
                    $stmt->bind_param('ssssss', $username, $hashed, $email, $firstName, $lastName, $role);

                    if ($stmt->execute()) {
                        $newAdminId = $stmt->insert_id;
                        $stmt->close();

                        // Log activity
                        logAdminActivity($db, $admin['id'], 'admin_created', "Created new administrator: {$username} (ID: {$newAdminId}, Role: {$role})");

                        $db->commit();

                        $success = 'Administrator created successfully!';

                        // Regenerate CSRF token after successful action
                        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));

                        // Clear form data
                        $username = $email = $firstName = $lastName = '';
                    } else {
                        throw new Exception('Failed to create administrator: ' . $stmt->error);
                    }
                } catch (Exception $e) {
                    $db->rollback();
                    $error = 'An error occurred while creating the administrator. Please try again.';
                    // Log error for admin review
                    error_log("Admin creation error: " . $e->getMessage());
                }
            }
        }
    }
}

// Toggle status with prepared statement
if (isset($_GET['toggle'])) {
    // CSRF check for GET actions
    if (!isset($_GET['csrf']) || $_GET['csrf'] !== $_SESSION['csrf_token']) {
        setFlash('Invalid security token.', 'error');
        header('Location: adminmanage.php');
        exit();
    }

    $adminId = intval($_GET['toggle']);

    // Prevent self-toggle
    if ($adminId === (int)$admin['id']) {
        setFlash('You cannot disable your own account.', 'error');
        header('Location: adminmanage.php');
        exit();
    }

    // Verify target admin exists and get current status
    $stmt = $db->prepare("SELECT username, is_active, role FROM admin_users WHERE id = ?");
    $stmt->bind_param('i', $adminId);
    $stmt->execute();
    $result = $stmt->get_result();
    $targetAdmin = $result->fetch_assoc();
    $stmt->close();

    if ($targetAdmin) {
        $newStatus = $targetAdmin['is_active'] ? 0 : 1;
        $action = $newStatus ? 'enabled' : 'disabled';

        $stmt = $db->prepare("UPDATE admin_users SET is_active = ? WHERE id = ?");
        $stmt->bind_param('ii', $newStatus, $adminId);

        if ($stmt->execute()) {
            $stmt->close();

            // Log activity
            logAdminActivity($db, $admin['id'], 'admin_status_toggle', "{$action} administrator: {$targetAdmin['username']} (ID: {$adminId})");

            setFlash("Administrator {$targetAdmin['username']} has been {$action}.", 'success');
        } else {
            $stmt->close();
            setFlash('Failed to update administrator status.', 'error');
        }
    } else {
        setFlash('Administrator not found.', 'error');
    }

    header('Location: adminmanage.php');
    exit();
}

// Search functionality
$search = trim($_GET['search'] ?? '');
$roleFilter = $_GET['role'] ?? '';
$statusFilter = $_GET['status'] ?? '';

// Build query with filters
$query = "SELECT * FROM admin_users WHERE 1=1";
$params = [];
$types = '';

if (!empty($search)) {
    $query .= " AND (username LIKE ? OR email LIKE ? OR first_name LIKE ? OR last_name LIKE ?)";
    $searchTerm = "%{$search}%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $types .= 'ssss';
}

if (!empty($roleFilter) && in_array($roleFilter, ['super_admin', 'admin', 'support'])) {
    $query .= " AND role = ?";
    $params[] = $roleFilter;
    $types .= 's';
}

if ($statusFilter !== '' && in_array($statusFilter, ['0', '1'])) {
    $query .= " AND is_active = ?";
    $params[] = (int)$statusFilter;
    $types .= 'i';
}

$query .= " ORDER BY id DESC";

$stmt = $db->prepare($query);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$admins = $stmt->get_result();
$stmt->close();

// Get counts for dashboard stats
$totalAdmins = $db->query("SELECT COUNT(*) as count FROM admin_users")->fetch_assoc()['count'];
$activeAdmins = $db->query("SELECT COUNT(*) as count FROM admin_users WHERE is_active = 1")->fetch_assoc()['count'];
$superAdmins = $db->query("SELECT COUNT(*) as count FROM admin_users WHERE role = 'super_admin'")->fetch_assoc()['count'];

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Staff Management - <?php echo e(SITE_NAME); ?></title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <style>
        /* ============================================
           RESPONSIVE STAFF MANAGEMENT PAGE
           Updated to align with database schema
           ============================================ */

        :root {
            --primary: #2563eb;
            --primary-dark: #1d4ed8;
            --primary-light: #dbeafe;
            --success: #10b981;
            --success-light: #d1fae5;
            --danger: #ef4444;
            --danger-light: #fee2e2;
            --warning: #f59e0b;
            --warning-light: #fef3c7;
            --info: #3b82f6;
            --info-light: #dbeafe;
            --secondary: #6b7280;
            --gray: #9ca3af;
            --light-gray: #f3f4f6;
            --dark: #1f2937;
            --white: #ffffff;
            --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
            --shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
            --radius: 12px;
            --radius-sm: 8px;
            --radius-lg: 16px;
        }

        * { box-sizing: border-box; }

        .staff-management-container {
            display: grid;
            grid-template-columns: 1fr 2fr;
            gap: 24px;
            padding: 0;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 16px;
            margin-bottom: 24px;
        }

        .stat-card {
            background: var(--white);
            border-radius: var(--radius);
            padding: 20px;
            box-shadow: var(--shadow-sm);
            border: 1px solid #e5e7eb;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }

        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow);
        }

        .stat-icon {
            width: 40px;
            height: 40px;
            border-radius: var(--radius-sm);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 12px;
        }

        .stat-icon.blue { background: var(--primary-light); color: var(--primary); }
        .stat-icon.green { background: var(--success-light); color: var(--success); }
        .stat-icon.purple { background: #f3e8ff; color: #7c3aed; }

        .stat-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--dark);
            line-height: 1;
        }

        .stat-label {
            font-size: 0.875rem;
            color: var(--secondary);
            margin-top: 4px;
        }

        .card {
            background: var(--white);
            border-radius: var(--radius);
            box-shadow: var(--shadow);
            overflow: hidden;
            border: 1px solid #e5e7eb;
            transition: box-shadow 0.2s ease;
        }

        .card:hover { box-shadow: var(--shadow-lg); }

        .card-header {
            padding: 20px 24px;
            border-bottom: 1px solid #e5e7eb;
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .card-title {
            font-size: 1.1rem;
            font-weight: 700;
            color: var(--dark);
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .card-body { padding: 24px; }

        .filter-bar {
            display: flex;
            gap: 12px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .search-input {
            flex: 1;
            min-width: 200px;
            padding: 10px 14px;
            border: 1px solid #d1d5db;
            border-radius: var(--radius-sm);
            font-size: 0.95rem;
            transition: all 0.2s ease;
        }

        .search-input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
        }

        .filter-select {
            padding: 10px 14px;
            border: 1px solid #d1d5db;
            border-radius: var(--radius-sm);
            font-size: 0.95rem;
            background: var(--white);
            cursor: pointer;
            min-width: 140px;
        }

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

        .form-label {
            display: block;
            font-size: 0.875rem;
            font-weight: 600;
            color: var(--dark);
            margin-bottom: 6px;
        }

        .form-label .required { color: var(--danger); margin-left: 2px; }

        .form-control {
            width: 100%;
            padding: 12px 14px;
            border: 1px solid #d1d5db;
            border-radius: var(--radius-sm);
            font-size: 0.95rem;
            transition: all 0.2s ease;
            background: var(--white);
        }

        .form-control:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
        }

        .form-control.is-invalid {
            border-color: var(--danger);
            box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
        }

        .invalid-feedback {
            color: var(--danger);
            font-size: 0.875rem;
            margin-top: 4px;
            display: none;
        }

        .form-control.is-invalid + .invalid-feedback { display: block; }

        select.form-control {
            cursor: pointer;
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%236b7280' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 12px center;
            padding-right: 40px;
        }

        .password-strength {
            margin-top: 8px;
            height: 4px;
            background: #e5e7eb;
            border-radius: 2px;
            overflow: hidden;
        }

        .password-strength-bar {
            height: 100%;
            width: 0;
            transition: all 0.3s ease;
            border-radius: 2px;
        }

        .password-strength-bar.weak { width: 25%; background: var(--danger); }
        .password-strength-bar.fair { width: 50%; background: var(--warning); }
        .password-strength-bar.good { width: 75%; background: var(--info); }
        .password-strength-bar.strong { width: 100%; background: var(--success); }

        .password-hint {
            font-size: 0.8rem;
            color: var(--secondary);
            margin-top: 6px;
            padding: 0;
            list-style: none;
        }

        .password-hint li {
            display: flex;
            align-items: center;
            gap: 6px;
            margin-bottom: 2px;
        }

        .password-hint li.met { color: var(--success); }
        .password-hint li.met::before { content: "✓"; font-weight: 700; }
        .password-hint li:not(.met)::before { content: "○"; opacity: 0.5; }

        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            padding: 10px 20px;
            border-radius: var(--radius-sm);
            font-size: 0.875rem;
            font-weight: 600;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
            text-decoration: none;
        }

        .btn:active { transform: scale(0.98); }

        .btn-primary {
            background: var(--primary);
            color: white;
        }

        .btn-primary:hover {
            background: var(--primary-dark);
            transform: translateY(-1px);
            box-shadow: var(--shadow);
        }

        .btn-sm { padding: 6px 14px; font-size: 0.8rem; }

        .btn-success {
            background: var(--success);
            color: white;
        }

        .btn-success:hover { background: #059669; }

        .btn-warning {
            background: var(--warning);
            color: white;
        }

        .btn-warning:hover { background: #d97706; }

        .btn-danger {
            background: var(--danger);
            color: white;
        }

        .btn-danger:hover { background: #dc2626; }

        .btn-outline {
            background: transparent;
            border: 1px solid #d1d5db;
            color: var(--secondary);
        }

        .btn-outline:hover {
            background: var(--light-gray);
            border-color: var(--gray);
        }

        .w-100 { width: 100%; }

        .table-container {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
            border-radius: 0 0 var(--radius) var(--radius);
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 800px;
        }

        .data-table thead {
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
        }

        .data-table th {
            padding: 14px 16px;
            text-align: left;
            font-size: 0.8rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: var(--secondary);
            border-bottom: 2px solid #e5e7eb;
            white-space: nowrap;
        }

        .data-table td {
            padding: 14px 16px;
            border-bottom: 1px solid #f3f4f6;
            font-size: 0.9rem;
            color: var(--dark);
            vertical-align: middle;
        }

        .data-table tbody tr { transition: background 0.15s ease; }
        .data-table tbody tr:hover { background: #f8fafc; }
        .data-table tbody tr:last-child td { border-bottom: none; }

        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }

        .status-badge.success { background: var(--success-light); color: #065f46; }
        .status-badge.danger { background: var(--danger-light); color: #991b1b; }
        .status-badge.info { background: var(--info-light); color: #1e40af; }
        .status-badge.secondary { background: #f3f4f6; color: #4b5563; }
        .status-badge.warning { background: var(--warning-light); color: #92400e; }

        .status-badge::before {
            content: "";
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: currentColor;
            opacity: 0.6;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 14px;
            flex-shrink: 0;
            box-shadow: var(--shadow-sm);
            border: 2px solid var(--white);
            position: relative;
            overflow: hidden;
        }

        .user-avatar.inactive {
            background: linear-gradient(135deg, var(--gray) 0%, var(--secondary) 100%);
            opacity: 0.7;
        }

        .user-avatar img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .user-details {
            display: flex;
            flex-direction: column;
        }

        .user-name {
            font-weight: 600;
            color: var(--dark);
            line-height: 1.2;
        }

        .user-meta {
            font-size: 0.8rem;
            color: var(--gray);
        }

        .alert {
            padding: 14px 18px;
            border-radius: var(--radius-sm);
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 0.9rem;
            font-weight: 500;
            animation: slideIn 0.3s ease;
        }

        .alert-danger {
            background: var(--danger-light);
            border: 1px solid #fecaca;
            color: #991b1b;
        }

        .alert-success {
            background: var(--success-light);
            border: 1px solid #bbf7d0;
            color: #166534;
        }

        .alert-info {
            background: var(--info-light);
            border: 1px solid #bfdbfe;
            color: #1e40af;
        }

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

        .text-center { text-align: center; }

        .empty-state {
            padding: 48px;
            text-align: center;
            color: var(--gray);
        }

        .empty-state svg {
            margin-bottom: 16px;
            opacity: 0.5;
        }

        .empty-state-title {
            font-weight: 600;
            color: var(--dark);
            margin-bottom: 4px;
        }

        .empty-state-desc { font-size: 0.9rem; }

        .tooltip {
            position: relative;
        }

        .tooltip::after {
            content: attr(data-tooltip);
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%) translateY(-4px);
            background: var(--dark);
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.75rem;
            white-space: nowrap;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.2s ease;
        }

        .tooltip:hover::after { opacity: 1; }

        @media (max-width: 768px) {
            .staff-management-container {
                grid-template-columns: 1fr;
                gap: 16px;
            }

            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
                gap: 12px;
                margin-bottom: 16px;
            }

            .card-header { padding: 16px 18px; }
            .card-title { font-size: 1rem; }
            .card-body { padding: 18px; }
            .filter-bar { flex-direction: column; }
            .search-input, .filter-select { width: 100%; }
            .form-group { margin-bottom: 14px; }
            .form-control { padding: 10px 12px; font-size: 16px; }
            .btn { padding: 12px 20px; font-size: 0.9rem; }
            .btn-sm { padding: 8px 14px; font-size: 0.8rem; }
            .data-table th, .data-table td { padding: 12px 14px; }
            .user-avatar { width: 36px; height: 36px; font-size: 13px; }
            .alert { padding: 12px 14px; font-size: 0.85rem; }
        }

        @media (max-width: 480px) {
            .stats-grid { grid-template-columns: 1fr; }
            .card-header {
                padding: 14px 16px;
                flex-direction: column;
                gap: 10px;
                align-items: flex-start;
            }
            .card-body { padding: 14px; }
            .form-label { font-size: 0.8rem; }
            .form-control { padding: 10px 12px; font-size: 16px; }
            .data-table th, .data-table td { padding: 10px 12px; font-size: 0.85rem; }
            .status-badge { padding: 3px 8px; font-size: 0.7rem; }
            .user-avatar { width: 32px; height: 32px; font-size: 12px; }
            .user-info { gap: 8px; }
            .btn { padding: 10px 16px; }
            .btn-sm { padding: 6px 10px; font-size: 0.75rem; }
        }

        @media (min-width: 769px) and (max-width: 1024px) {
            .staff-management-container {
                grid-template-columns: 1fr 1.5fr;
                gap: 20px;
            }
        }

        @media (min-width: 1400px) {
            .staff-management-container {
                grid-template-columns: 1fr 2.5fr;
                gap: 32px;
            }
            .card-body { padding: 28px; }
            .data-table th, .data-table td { padding: 16px 20px; }
        }

        @media (hover: none) and (pointer: coarse) {
            .btn:active { transform: scale(0.98); }
            .form-control { font-size: 16px; }
            .data-table tbody tr:active { background: #eef2ff; }
        }

        @media (prefers-color-scheme: dark) {
            :root {
                --dark: #f3f4f6;
                --white: #1f2937;
                --light-gray: #374151;
            }
            .card, .stat-card {
                background: #1f2937;
                border-color: #374151;
            }
            .card-header {
                background: linear-gradient(135deg, #111827 0%, #1f2937 100%);
                border-color: #374151;
            }
            .form-control, .search-input, .filter-select {
                background: #374151;
                border-color: #4b5563;
                color: #f3f4f6;
            }
            .data-table thead {
                background: linear-gradient(135deg, #111827 0%, #1f2937 100%);
            }
            .data-table th {
                color: #9ca3af;
                border-color: #374151;
            }
            .data-table td {
                color: #e5e7eb;
                border-color: #374151;
            }
            .data-table tbody tr:hover { background: #374151; }
            .user-avatar { border-color: #1f2937; }
        }

        .table-container::-webkit-scrollbar { height: 8px; }
        .table-container::-webkit-scrollbar-track {
            background: #f1f5f9;
            border-radius: 4px;
        }
        .table-container::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 4px;
        }
        .table-container::-webkit-scrollbar-thumb:hover { background: #94a3b8; }

        @media (prefers-reduced-motion: reduce) {
            *, *::before, *::after {
                animation-duration: 0.01ms !important;
                animation-iteration-count: 1 !important;
                transition-duration: 0.01ms !important;
            }
        }

        .sr-only {
            position: absolute;
            width: 1px;
            height: 1px;
            padding: 0;
            margin: -1px;
            overflow: hidden;
            clip: rect(0, 0, 0, 0);
            white-space: nowrap;
            border-width: 0;
        }

        :focus-visible {
            outline: 2px solid var(--primary);
            outline-offset: 2px;
        }
    </style>
</head>
<body>
    <?php include 'includes/admin-sidebar.php'; ?>

    <div class="main-content">
        <?php include 'includes/admin-header.php'; ?>

        <div class="page-content">
            <?php if ($error): ?>
                <div class="alert alert-danger fade-in" role="alert">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>
                    <?php echo e($error); ?>
                </div>
            <?php endif; ?>

            <?php if ($success): ?>
                <div class="alert alert-success fade-in" role="alert">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>
                    <?php echo e($success); ?>
                </div>
            <?php endif; ?>

            <!-- Stats Overview -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon blue">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>
                    </div>
                    <div class="stat-value"><?php echo number_format($totalAdmins); ?></div>
                    <div class="stat-label">Total Staff</div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon green">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>
                    </div>
                    <div class="stat-value"><?php echo number_format($activeAdmins); ?></div>
                    <div class="stat-label">Active</div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon purple">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path></svg>
                    </div>
                    <div class="stat-value"><?php echo number_format($superAdmins); ?></div>
                    <div class="stat-label">Super Admins</div>
                </div>
            </div>

            <div class="staff-management-container">
                <!-- Add Administrator Card -->
                <div class="card">
                    <div class="card-header">
                        <span class="card-title">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="8.5" cy="7" r="4"></circle><line x1="20" y1="8" x2="20" y2="14"></line><line x1="23" y1="11" x2="17" y2="11"></line></svg>
                            Add Administrator
                        </span>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="" novalidate>
                            <input type="hidden" name="csrf_token" value="<?php echo e($_SESSION['csrf_token']); ?>">
                            <input type="hidden" name="create_admin" value="1">

                            <div class="form-group">
                                <label class="form-label">
                                    Username
                                    <span class="required">*</span>
                                </label>
                                <input type="text" name="username" class="form-control" required 
                                       placeholder="Unique username" autocomplete="off" 
                                       pattern="[a-zA-Z0-9_]{3,60}"
                                       value="<?php echo e($_POST['username'] ?? ''); ?>"
                                       maxlength="60">
                                <div class="invalid-feedback">Username must be 3-60 characters, alphanumeric and underscores only.</div>
                            </div>

                            <div class="form-group">
                                <label class="form-label">
                                    First Name
                                    <span class="required">*</span>
                                </label>
                                <input type="text" name="first_name" class="form-control" required 
                                       placeholder="First name" maxlength="80"
                                       value="<?php echo e($_POST['first_name'] ?? ''); ?>">
                            </div>

                            <div class="form-group">
                                <label class="form-label">
                                    Last Name
                                    <span class="required">*</span>
                                </label>
                                <input type="text" name="last_name" class="form-control" required 
                                       placeholder="Last name" maxlength="80"
                                       value="<?php echo e($_POST['last_name'] ?? ''); ?>">
                            </div>

                            <div class="form-group">
                                <label class="form-label">
                                    Email
                                    <span class="required">*</span>
                                </label>
                                <input type="email" name="email" class="form-control" required 
                                       placeholder="Email address" maxlength="180"
                                       value="<?php echo e($_POST['email'] ?? ''); ?>">
                            </div>

                            <div class="form-group">
                                <label class="form-label">
                                    Password
                                    <span class="required">*</span>
                                </label>
                                <input type="password" name="password" class="form-control" required 
                                       minlength="8" placeholder="Min 8 characters" 
                                       autocomplete="new-password" id="passwordInput"
                                       aria-describedby="passwordHelp">
                                <div class="password-strength">
                                    <div class="password-strength-bar" id="strengthBar"></div>
                                </div>
                                <ul class="password-hint" id="passwordHint">
                                    <li id="lengthHint">At least 8 characters</li>
                                    <li id="upperHint">One uppercase letter</li>
                                    <li id="lowerHint">One lowercase letter</li>
                                    <li id="numberHint">One number</li>
                                    <li id="specialHint">One special character</li>
                                </ul>
                            </div>

                            <div class="form-group">
                                <label class="form-label">
                                    Role
                                    <span class="required">*</span>
                                </label>
                                <select name="role" class="form-control" required>
                                    <option value="admin" <?php echo ($_POST['role'] ?? '') === 'admin' ? 'selected' : ''; ?>>Admin</option>
                                    <option value="super_admin" <?php echo ($_POST['role'] ?? '') === 'super_admin' ? 'selected' : ''; ?>>Super Admin</option>
                                    <option value="support" <?php echo ($_POST['role'] ?? '') === 'support' ? 'selected' : ''; ?>>Support</option>
                                </select>
                            </div>

                            <button type="submit" class="btn btn-primary w-100">
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
                                Create Administrator
                            </button>
                        </form>
                    </div>
                </div>

                <!-- Administrators List Card -->
                <div class="card">
                    <div class="card-header">
                        <span class="card-title">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>
                            Administrators
                        </span>
                    </div>
                    <div class="card-body" style="padding: 0;">
                        <!-- Filter Bar -->
                        <div style="padding: 20px 24px; border-bottom: 1px solid #e5e7eb;">
                            <form method="GET" action="" class="filter-bar">
                                <input type="text" name="search" class="search-input" 
                                       placeholder="Search by name, username, or email..." 
                                       value="<?php echo e($search); ?>">
                                <select name="role" class="filter-select">
                                    <option value="">All Roles</option>
                                    <option value="super_admin" <?php echo $roleFilter === 'super_admin' ? 'selected' : ''; ?>>Super Admin</option>
                                    <option value="admin" <?php echo $roleFilter === 'admin' ? 'selected' : ''; ?>>Admin</option>
                                    <option value="support" <?php echo $roleFilter === 'support' ? 'selected' : ''; ?>>Support</option>
                                </select>
                                <select name="status" class="filter-select">
                                    <option value="">All Status</option>
                                    <option value="1" <?php echo $statusFilter === '1' ? 'selected' : ''; ?>>Active</option>
                                    <option value="0" <?php echo $statusFilter === '0' ? 'selected' : ''; ?>>Inactive</option>
                                </select>
                                <button type="submit" class="btn btn-primary btn-sm">
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
                                    Filter
                                </button>
                                <?php if ($search || $roleFilter || $statusFilter !== ''): ?>
                                    <a href="adminmanage.php" class="btn btn-outline btn-sm">Clear</a>
                                <?php endif; ?>
                            </form>
                        </div>

                        <div class="table-container">
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>Administrator</th>
                                        <th>Username</th>
                                        <th>Email</th>
                                        <th>Role</th>
                                        <th>Status</th>
                                        <th>Last Login</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if ($admins && $admins->num_rows > 0): ?>
                                        <?php while ($a = $admins->fetch_assoc()): 
                                            $computedFullName = trim(($a['first_name'] ?? '') . ' ' . ($a['last_name'] ?? ''));
                                            if (empty($computedFullName)) { 
                                                $computedFullName = $a['username']; 
                                            }
                                            $initials = strtoupper(substr($a['first_name'] ?? $a['username'], 0, 1) . substr($a['last_name'] ?? '', 0, 1));
                                            if (strlen($initials) < 2) {
                                                $initials = strtoupper(substr($a['username'], 0, 2));
                                            }
                                            $isSelf = ((int)$a['id'] === (int)$admin['id']);
                                            $csrfToken = e($_SESSION['csrf_token']);
                                        ?>
                                            <tr>
                                                <td>
                                                    <div class="user-info">
                                                        <div class="user-avatar <?php echo $a['is_active'] ? '' : 'inactive'; ?>" aria-hidden="true">
                                                            <?php if (!empty($a['avatar'])): ?>
                                                                <img src="<?php echo e($a['avatar']); ?>" alt="">
                                                            <?php else: ?>
                                                                <?php echo e($initials); ?>
                                                            <?php endif; ?>
                                                        </div>
                                                        <div class="user-details">
                                                            <span class="user-name"><?php echo e($computedFullName); ?></span>
                                                            <?php if ($isSelf): ?>
                                                                <span class="user-meta">You</span>
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td><?php echo e($a['username']); ?></td>
                                                <td><?php echo e($a['email']); ?></td>
                                                <td>
                                                    <span class="status-badge <?php 
                                                        echo match($a['role']) {
                                                            'super_admin' => 'danger',
                                                            'admin' => 'info',
                                                            'support' => 'warning',
                                                            default => 'secondary'
                                                        };
                                                    ?>">
                                                        <?php echo e(ucfirst(str_replace('_', ' ', $a['role']))); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <span class="status-badge <?php echo $a['is_active'] ? 'success' : 'secondary'; ?>">
                                                        <?php echo $a['is_active'] ? 'Active' : 'Inactive'; ?>
                                                    </span>
                                                </td>
                                                <td style="font-size: 0.85rem; color: var(--secondary);">
                                                    <?php echo $a['last_login'] ? e(formatDateShort($a['last_login'])) : '<em>Never</em>'; ?>
                                                </td>
                                                <td>
                                                    <?php if (!$isSelf): ?>
                                                        <a href="?toggle=<?php echo (int)$a['id']; ?>&csrf=<?php echo $csrfToken; ?>" 
                                                           class="btn btn-sm <?php echo $a['is_active'] ? 'btn-warning' : 'btn-success'; ?>"
                                                           onclick="return confirmAction(this, '<?php echo $a['is_active'] ? 'disable' : 'enable'; ?>', '<?php echo e($a['username']); ?>')">
                                                            <?php echo $a['is_active'] ? 'Disable' : 'Enable'; ?>
                                                        </a>
                                                    <?php else: ?>
                                                        <span class="tooltip" data-tooltip="Cannot modify your own account">
                                                            <button class="btn btn-sm btn-outline" disabled style="opacity: 0.5; cursor: not-allowed;">
                                                                You
                                                            </button>
                                                        </span>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="7">
                                                <div class="empty-state">
                                                    <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
                                                        <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
                                                        <circle cx="9" cy="7" r="4"></circle>
                                                        <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
                                                        <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
                                                    </svg>
                                                    <div class="empty-state-title">No administrators found</div>
                                                    <div class="empty-state-desc">Try adjusting your search or filters</div>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Password strength indicator
        document.addEventListener('DOMContentLoaded', function() {
            const passwordInput = document.getElementById('passwordInput');
            const strengthBar = document.getElementById('strengthBar');
            const hints = {
                length: document.getElementById('lengthHint'),
                upper: document.getElementById('upperHint'),
                lower: document.getElementById('lowerHint'),
                number: document.getElementById('numberHint'),
                special: document.getElementById('specialHint')
            };

            if (passwordInput) {
                passwordInput.addEventListener('input', function() {
                    const val = this.value;
                    let strength = 0;

                    const checks = {
                        length: val.length >= 8,
                        upper: /[A-Z]/.test(val),
                        lower: /[a-z]/.test(val),
                        number: /[0-9]/.test(val),
                        special: /[!@#$%^&*(),.?":{}|<>]/.test(val)
                    };

                    for (const [key, met] of Object.entries(checks)) {
                        if (hints[key]) {
                            hints[key].classList.toggle('met', met);
                        }
                        if (met) strength++;
                    }

                    strengthBar.className = 'password-strength-bar';
                    if (strength <= 1) {
                        strengthBar.classList.add('weak');
                    } else if (strength <= 2) {
                        strengthBar.classList.add('fair');
                    } else if (strength <= 3) {
                        strengthBar.classList.add('good');
                    } else if (strength >= 4) {
                        strengthBar.classList.add('strong');
                    }
                });
            }
        });

        // Confirmation dialog for toggle actions
        function confirmAction(link, action, username) {
            const message = `Are you sure you want to ${action} the administrator "${username}"?`;
            if (confirm(message)) {
                link.style.opacity = '0.6';
                link.style.pointerEvents = 'none';
                link.innerHTML = 'Processing...';
                return true;
            }
            return false;
        }

        // Auto-dismiss alerts after 5 seconds
        document.addEventListener('DOMContentLoaded', function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                setTimeout(function() {
                    alert.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
                    alert.style.opacity = '0';
                    alert.style.transform = 'translateY(-10px)';
                    setTimeout(function() {
                        alert.remove();
                    }, 500);
                }, 5000);
            });
        });

        // Form validation enhancement
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.querySelector('form[method="POST"]');
            if (form) {
                form.addEventListener('submit', function(e) {
                    const requiredFields = form.querySelectorAll('[required]');
                    let valid = true;

                    requiredFields.forEach(function(field) {
                        if (!field.value.trim()) {
                            valid = false;
                            field.classList.add('is-invalid');
                        } else {
                            field.classList.remove('is-invalid');
                        }
                    });

                    if (!valid) {
                        e.preventDefault();
                        const firstInvalid = form.querySelector('.is-invalid');
                        if (firstInvalid) {
                            firstInvalid.focus();
                        }
                    }
                });

                form.querySelectorAll('.form-control').forEach(function(field) {
                    field.addEventListener('input', function() {
                        this.classList.remove('is-invalid');
                    });
                });
            }
        });
    </script>
</body>
</html>