<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/email.php';        
$pageTitle = 'Manage Admins';
include 'side.php';

// Check if current admin is super admin
if ($_SESSION['admin_role'] !== 'super_admin') {
    setFlash('error', 'Only super admins can manage other admins!');
    redirect('dashboard.php');
}

$conn = getConnection();

// Helper function for base URL
function getBaseUrl() {
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    $scriptName = dirname($_SERVER['SCRIPT_NAME']);
    return $protocol . '://' . $host . $scriptName;
}

// Handle admin actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    switch($action) {
        case 'add':
            $username = sanitize($_POST['username']);
            $email = sanitize($_POST['email']);
            $password = $_POST['password'];
            $role = sanitize($_POST['role']);
            
            // Check for duplicates
            $checkStmt = $conn->prepare("SELECT id FROM admins WHERE username = ? OR email = ?");
            $checkStmt->bind_param("ss", $username, $email);
            $checkStmt->execute();
            if ($checkStmt->get_result()->num_rows > 0) {
                setFlash('error', 'Username or email already exists!');
                redirect('admins.php');
                exit;
            }
            
            // Hash password
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            
            // Insert admin
            $stmt = $conn->prepare("INSERT INTO admins (username, email, password, role, created_at) VALUES (?, ?, ?, ?, NOW())");
            $stmt->bind_param("ssss", $username, $email, $hashedPassword, $role);
            
            if ($stmt->execute()) {
                $adminId = $conn->insert_id;
                
                // Save permissions
                if (isset($_POST['permissions']) && is_array($_POST['permissions'])) {
                    foreach ($_POST['permissions'] as $permission) {
                        $permStmt = $conn->prepare("INSERT INTO admin_permissions (admin_id, permission) VALUES (?, ?)");
                        $permStmt->bind_param("is", $adminId, $permission);
                        $permStmt->execute();
                    }
                }
                
                // Send welcome email (without password for security)
                $subject = "Admin Account Created - " . getSiteName();
                $loginUrl = getBaseUrl() . "/login.php";
                $message = "
                    <h2>Welcome to the Admin Panel!</h2>
                    <p>Hello <strong>$username</strong>,</p>
                    <p>An admin account has been created for you on " . getSiteName() . ".</p>
                    <h3>Your Account Details:</h3>
                    <ul>
                        <li><strong>Username:</strong> $username</li>
                        <li><strong>Email:</strong> $email</li>
                        <li><strong>Role:</strong> " . ucfirst($role) . "</li>
                    </ul>
                    <p><strong>Important:</strong> Please contact the super administrator to receive your login password.</p>
                    <p><strong>Login URL:</strong> <a href='$loginUrl'>$loginUrl</a></p>
                    <p>Once you receive your password, you can login and change it in your profile settings.</p>
                    <p>If you have any questions, please contact the super administrator.</p>
                ";
                
                sendEmail($email, $username,$subject, $message);
                
                setFlash('success', 'Admin added successfully! <strong>Password:</strong> ' . htmlspecialchars($password) . ' (Share this with the admin)');
            } else {
                setFlash('error', 'Failed to add admin.');
            }
            break;
            
        case 'edit':
            $adminId = intval($_POST['admin_id']);
            $username = sanitize($_POST['username']);
            $email = sanitize($_POST['email']);
            $role = sanitize($_POST['role']);
            $status = sanitize($_POST['status']);
            
            // Check for duplicates (excluding current admin)
            $checkStmt = $conn->prepare("SELECT id FROM admins WHERE (username = ? OR email = ?) AND id != ?");
            $checkStmt->bind_param("ssi", $username, $email, $adminId);
            $checkStmt->execute();
            if ($checkStmt->get_result()->num_rows > 0) {
                setFlash('error', 'Username or email already exists!');
                redirect('admins.php');
                exit;
            }
            
            // Update admin
            $stmt = $conn->prepare("UPDATE admins SET username=?, email=?, role=?, status=? WHERE id=?");
            $stmt->bind_param("ssssi", $username, $email, $role, $status, $adminId);
            
            if ($stmt->execute()) {
                // Delete old permissions
                $conn->query("DELETE FROM admin_permissions WHERE admin_id=$adminId");
                
                // Save new permissions
                if (isset($_POST['permissions']) && is_array($_POST['permissions'])) {
                    foreach ($_POST['permissions'] as $permission) {
                        $permStmt = $conn->prepare("INSERT INTO admin_permissions (admin_id, permission) VALUES (?, ?)");
                        $permStmt->bind_param("is", $adminId, $permission);
                        $permStmt->execute();
                    }
                }
                
                setFlash('success', 'Admin updated successfully!');
            } else {
                setFlash('error', 'Failed to update admin.');
            }
            break;
            
        case 'delete':
            $adminId = intval($_POST['admin_id']);
            
            // Can't delete yourself
            if ($adminId === $_SESSION['admin_id']) {
                setFlash('error', 'You cannot delete your own account!');
                redirect('admins.php');
                exit;
            }
            
            // Delete permissions first
            $conn->query("DELETE FROM admin_permissions WHERE admin_id=$adminId");
            
            // Delete admin
            $conn->query("DELETE FROM admins WHERE id=$adminId");
            
            setFlash('success', 'Admin deleted successfully!');
            break;
            
        case 'set_password':
            $adminId = intval($_POST['admin_id']);
            $newPassword = bin2hex(random_bytes(8)); // Generate random password
            $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
            
            $stmt = $conn->prepare("UPDATE admins SET password=? WHERE id=?");
            $stmt->bind_param("si", $hashedPassword, $adminId);
            
            if ($stmt->execute()) {
                // Get admin details
                $admin = $conn->query("SELECT username, email FROM admins WHERE id=$adminId")->fetch_assoc();
                
                // Send password set notification email (without actual password)
                $subject = "New Password Set - " . getSiteName();
                $loginUrl = getBaseUrl() . "/login.php";
                $message = "
                    <h2>New Password Set</h2>
                    <p>Hello <strong>{$admin['username']}</strong>,</p>
                    <p>A new password has been set for your admin account by the super administrator.</p>
                    <p><strong>Please contact the super administrator to receive your new password.</strong></p>
                    <p><strong>Login URL:</strong> <a href='$loginUrl'>$loginUrl</a></p>
                    <p>After logging in with your new password, we recommend changing it immediately in your profile settings.</p>
                ";
                
              // AFTER
sendEmail($admin['email'], $admin['username'], $subject, $message);
                
                setFlash('success', 'Password set successfully! <strong>New password:</strong> ' . htmlspecialchars($newPassword) . ' (Share this with the admin)');
            } else {
                setFlash('error', 'Failed to reset password.');
            }
            break;
    }
    
    redirect('admins.php');
}

// Get admins
$admins = $conn->query("
    SELECT a.*, 
           (SELECT COUNT(*) FROM admin_permissions WHERE admin_id = a.id) as permission_count,
           (SELECT GROUP_CONCAT(permission) FROM admin_permissions WHERE admin_id = a.id) as permissions
    FROM admins a
    ORDER BY 
        CASE 
            WHEN a.role = 'super_admin' THEN 1
            WHEN a.role = 'admin' THEN 2
            WHEN a.role = 'moderator' THEN 3
            ELSE 4
        END,
        a.created_at DESC
");

// Get statistics
$stats = $conn->query("
    SELECT 
        COUNT(*) as total_admins,
        SUM(CASE WHEN role='super_admin' THEN 1 ELSE 0 END) as super_admins,
        SUM(CASE WHEN role='admin' THEN 1 ELSE 0 END) as admins,
        SUM(CASE WHEN role='moderator' THEN 1 ELSE 0 END) as moderators,
        SUM(CASE WHEN status='active' THEN 1 ELSE 0 END) as active_admins
    FROM admins
")->fetch_assoc();

// Ensure numeric values
foreach ($stats as $key => $value) {
    $stats[$key] = intval($value ?? 0);
}

// Define available permissions
$availablePermissions = [
    'manage_users' => 'Manage Users (view, edit, activate, deactivate)',
    'delete_users' => 'Delete Users (permanently remove users)',
    'delete_inactive_only' => 'Delete Inactive Users Only',
    'manage_withdrawals' => 'Manage Withdrawals (approve, reject)',
    'manage_transactions' => 'View & Manage Transactions',
    'manage_content' => 'Manage Content (tasks, videos, trivia, ads)',
    'manage_countries' => 'Manage Countries & Settings',
    'manage_bonuses' => 'Manage Bonus Rules',
    'manage_admins' => 'Manage Other Admins (super admin only)',
    'view_reports' => 'View Reports & Statistics',
    'view_only' => 'View Only (no editing capabilities)',
    'system_settings' => 'Manage System Settings',
];
?>

<style>
    .page-header {
        margin-bottom: 24px;
    }
    
    .page-title {
        font-size: 28px;
        font-weight: 900;
        color: var(--text-primary);
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 6px;
    }
    
    .page-title i {
        background: linear-gradient(135deg, var(--theme-color) 0%, #ec4899 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }
    
    .page-subtitle {
        font-size: 14px;
        color: var(--text-secondary);
        font-weight: 500;
    }
    
    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 16px;
        margin-bottom: 24px;
    }
    
    .stat-card {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 14px;
        padding: 20px;
        transition: all 0.3s;
    }
    
    .stat-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
        border-color: rgba(var(--theme-rgb), 0.3);
    }
    
    .stat-icon {
        width: 48px;
        height: 48px;
        background: linear-gradient(135deg, var(--theme-color) 0%, #ec4899 100%);
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 22px;
        color: white;
        margin-bottom: 12px;
    }
    
    .stat-label {
        font-size: 12px;
        color: var(--text-secondary);
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        margin-bottom: 6px;
    }
    
    .stat-value {
        font-size: 28px;
        font-weight: 900;
        color: var(--text-primary);
    }
    
    .add-admin-btn {
        padding: 12px 24px;
        background: linear-gradient(135deg, var(--theme-color) 0%, #ec4899 100%);
        color: white;
        border: none;
        border-radius: 10px;
        font-size: 14px;
        font-weight: 700;
        cursor: pointer;
        transition: all 0.3s;
        display: flex;
        align-items: center;
        gap: 8px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        margin-bottom: 24px;
    }
    
    .add-admin-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(var(--theme-rgb), 0.4);
    }
    
    .admins-table-container {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 14px;
        overflow: hidden;
    }
    
    .table-wrapper {
        overflow-x: auto;
    }
    
    .admins-table {
        width: 100%;
        border-collapse: collapse;
        min-width: 900px;
    }
    
    .admins-table thead {
        background: var(--darker-bg);
    }
    
    .admins-table th {
        padding: 16px;
        text-align: left;
        font-size: 11px;
        font-weight: 700;
        color: var(--text-secondary);
        text-transform: uppercase;
        letter-spacing: 0.5px;
        border-bottom: 1px solid var(--border-color);
    }
    
    .admins-table td {
        padding: 16px;
        font-size: 14px;
        color: var(--text-primary);
        border-bottom: 1px solid var(--border-color);
        font-weight: 500;
    }
    
    .admins-table tbody tr {
        transition: all 0.2s;
    }
    
    .admins-table tbody tr:hover {
        background: var(--darker-bg);
    }
    
    .role-badge {
        padding: 6px 12px;
        border-radius: 8px;
        font-size: 11px;
        font-weight: 700;
        text-transform: uppercase;
        display: inline-block;
    }
    
    .role-super_admin {
        background: linear-gradient(135deg, #f59e0b 0%, #ef4444 100%);
        color: white;
    }
    
    .role-admin {
        background: rgba(139, 92, 246, 0.15);
        color: #8b5cf6;
        border: 1px solid rgba(139, 92, 246, 0.3);
    }
    
    .role-moderator {
        background: rgba(59, 130, 246, 0.15);
        color: #3b82f6;
        border: 1px solid rgba(59, 130, 246, 0.3);
    }
    
    .status-badge {
        padding: 6px 12px;
        border-radius: 8px;
        font-size: 11px;
        font-weight: 700;
        text-transform: uppercase;
        display: inline-block;
    }
    
    .status-active {
        background: rgba(16, 185, 129, 0.15);
        color: #10b981;
        border: 1px solid rgba(16, 185, 129, 0.3);
    }
    
    .status-inactive {
        background: rgba(239, 68, 68, 0.15);
        color: #ef4444;
        border: 1px solid rgba(239, 68, 68, 0.3);
    }
    
    .action-buttons {
        display: flex;
        gap: 6px;
        align-items: center;
    }
    
    .btn-action {
        padding: 8px 14px;
        background: var(--darker-bg);
        color: var(--text-secondary);
        border: 1px solid var(--border-color);
        border-radius: 8px;
        font-size: 13px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s;
        display: flex;
        align-items: center;
        gap: 6px;
        white-space: nowrap;
    }
    
    .btn-action:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
    
    .btn-edit:hover { background: #8b5cf6; color: white; border-color: #8b5cf6; }
    .btn-reset:hover { background: #f59e0b; color: white; border-color: #f59e0b; }
    .btn-delete:hover { background: #ef4444; color: white; border-color: #ef4444; }
    
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.7);
        backdrop-filter: blur(4px);
        z-index: 10000;
        align-items: center;
        justify-content: center;
        padding: 20px;
        overflow-y: auto;
    }
    
    .modal.active {
        display: flex;
    }
    
    .modal-content {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 20px;
        padding: 32px;
        max-width: 700px;
        width: 100%;
        max-height: 90vh;
        overflow-y: auto;
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
    }
    
    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;
        padding-bottom: 16px;
        border-bottom: 1px solid var(--border-color);
    }
    
    .modal-title {
        font-size: 22px;
        font-weight: 900;
        color: var(--text-primary);
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .modal-title i {
        background: linear-gradient(135deg, var(--theme-color) 0%, #ec4899 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }
    
    .modal-close {
        width: 36px;
        height: 36px;
        background: var(--darker-bg);
        border: 1px solid var(--border-color);
        border-radius: 10px;
        color: var(--text-secondary);
        cursor: pointer;
        transition: all 0.3s;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 18px;
    }
    
    .modal-close:hover {
        background: var(--card-bg);
        color: var(--text-primary);
        transform: rotate(90deg);
    }
    
    .form-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 16px;
    }
    
    .form-group {
        margin-bottom: 16px;
    }
    
    .form-group.full-width {
        grid-column: 1 / -1;
    }
    
    .form-label {
        display: block;
        font-size: 13px;
        font-weight: 600;
        color: var(--text-secondary);
        margin-bottom: 6px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }
    
    .form-control {
        width: 100%;
        padding: 12px 14px;
        font-size: 14px;
        border: 1px solid var(--border-color);
        border-radius: 10px;
        background: var(--darker-bg);
        color: var(--text-primary);
        font-weight: 500;
        transition: all 0.3s;
    }
    
    .form-control:focus {
        outline: none;
        border-color: var(--theme-color);
        box-shadow: 0 0 0 3px rgba(var(--theme-rgb), 0.1);
    }
    
    .form-control option {
        background: var(--card-bg);
        color: var(--text-primary);
    }
    
    .permissions-section {
        background: var(--darker-bg);
        border: 1px solid var(--border-color);
        border-radius: 12px;
        padding: 18px;
        margin-bottom: 18px;
    }
    
    .permissions-title {
        font-size: 14px;
        font-weight: 700;
        color: var(--text-primary);
        margin-bottom: 14px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .permissions-title i {
        background: linear-gradient(135deg, var(--theme-color) 0%, #ec4899 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }
    
    .permission-item {
        display: flex;
        align-items: flex-start;
        gap: 10px;
        padding: 10px;
        border-radius: 8px;
        margin-bottom: 8px;
        transition: all 0.2s;
    }
    
    .permission-item:hover {
        background: var(--card-bg);
    }
    
    .permission-checkbox {
        width: 18px;
        height: 18px;
        margin-top: 2px;
        cursor: pointer;
        accent-color: var(--theme-color);
    }
    
    .permission-label {
        flex: 1;
        font-size: 14px;
        color: var(--text-primary);
        cursor: pointer;
    }
    
    .btn-primary {
        width: 100%;
        padding: 14px 32px;
        background: linear-gradient(135deg, var(--theme-color) 0%, #ec4899 100%);
        color: white;
        border: none;
        border-radius: 10px;
        font-size: 15px;
        font-weight: 700;
        cursor: pointer;
        transition: all 0.3s;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        margin-top: 20px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }
    
    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 24px rgba(var(--theme-rgb), 0.4);
    }
    
    .permission-count {
        display: inline-block;
        padding: 4px 8px;
        background: rgba(var(--theme-rgb), 0.15);
        color: var(--theme-color);
        border-radius: 6px;
        font-size: 11px;
        font-weight: 700;
        margin-left: 8px;
    }
    
    @media (max-width: 768px) {
        .stats-grid { grid-template-columns: 1fr; gap: 12px; }
        .form-grid { grid-template-columns: 1fr; }
        .modal-content { padding: 24px 20px; }
        .action-buttons { flex-direction: column; align-items: stretch; }
        .btn-action { justify-content: center; }
    }
</style>

<!-- Page Header -->
<div class="page-header">
    <h1 class="page-title">
        <i class="fas fa-user-shield"></i> Manage Admins
    </h1>
    <p class="page-subtitle">Add assistants, assign roles, and manage admin permissions</p>
</div>

<!-- Statistics -->
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-users-cog"></i>
        </div>
        <div class="stat-label">Total Admins</div>
        <div class="stat-value"><?php echo number_format($stats['total_admins']); ?></div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-crown"></i>
        </div>
        <div class="stat-label">Super Admins</div>
        <div class="stat-value"><?php echo number_format($stats['super_admins']); ?></div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-user-tie"></i>
        </div>
        <div class="stat-label">Admins</div>
        <div class="stat-value"><?php echo number_format($stats['admins']); ?></div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-user-check"></i>
        </div>
        <div class="stat-label">Active</div>
        <div class="stat-value"><?php echo number_format($stats['active_admins']); ?></div>
    </div>
</div>

<!-- Add Admin Button -->
<button class="add-admin-btn" onclick="openAddModal()">
    <i class="fas fa-plus"></i> Add New Admin
</button>

<!-- Admins Table -->
<div class="admins-table-container">
    <div class="table-wrapper">
        <table class="admins-table">
            <thead>
                <tr>
                    <th style="width: 60px;">ID</th>
                    <th>Username</th>
                    <th>Email</th>
                    <th>Role</th>
                    <th>Permissions</th>
                    <th style="width: 110px;">Status</th>
                    <th>Created</th>
                    <th style="width: 250px;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($admins->num_rows > 0): ?>
                    <?php while ($admin = $admins->fetch_assoc()): ?>
                    <tr>
                        <td><strong>#<?php echo $admin['id']; ?></strong></td>
                        <td>
                            <strong><?php echo htmlspecialchars($admin['username']); ?></strong>
                            <?php if ($admin['id'] === $_SESSION['admin_id']): ?>
                                <span style="color: var(--theme-color); font-size: 11px; font-weight: 700;"> (YOU)</span>
                            <?php endif; ?>
                        </td>
                        <td><?php echo htmlspecialchars($admin['email']); ?></td>
                        <td>
                            <span class="role-badge role-<?php echo $admin['role']; ?>">
                                <?php echo str_replace('_', ' ', $admin['role']); ?>
                            </span>
                        </td>
                        <td>
                            <span class="permission-count">
                                <?php echo $admin['permission_count']; ?> permissions
                            </span>
                        </td>
                        <td>
                            <span class="status-badge status-<?php echo $admin['status']; ?>">
                                <?php echo $admin['status']; ?>
                            </span>
                        </td>
                        <td><?php echo date('M j, Y', strtotime($admin['created_at'])); ?></td>
                        <td>
                            <div class="action-buttons">
                                <button class="btn-action btn-edit" onclick="editAdmin(<?php echo htmlspecialchars(json_encode($admin)); ?>)">
                                    <i class="fas fa-edit"></i> Edit
                                </button>
                                <?php if ($admin['id'] !== $_SESSION['admin_id']): ?>
                                    <button class="btn-action btn-reset" onclick="setPassword(<?php echo $admin['id']; ?>, '<?php echo htmlspecialchars($admin['username']); ?>')">
                                        <i class="fas fa-key"></i> Set Password
                                    </button>
                                    <button class="btn-action btn-delete" onclick="deleteAdmin(<?php echo $admin['id']; ?>, '<?php echo htmlspecialchars($admin['username']); ?>')">
                                        <i class="fas fa-trash"></i> Delete
                                    </button>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="8" style="text-align: center; padding: 40px; color: var(--text-secondary);">
                            <i class="fas fa-user-shield" style="font-size: 48px; margin-bottom: 16px; opacity: 0.5;"></i><br>
                            No admins found
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- ADD ADMIN MODAL -->
<div class="modal" id="addModal">
    <div class="modal-content">
        <div class="modal-header">
            <h2 class="modal-title">
                <i class="fas fa-user-plus"></i> Add New Admin
            </h2>
            <button class="modal-close" onclick="closeAddModal()">
                <i class="fas fa-times"></i>
            </button>
        </div>
        
        <form method="POST" id="addForm">
            <input type="hidden" name="action" value="add">
            
            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Username *</label>
                    <input type="text" name="username" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Email *</label>
                    <input type="email" name="email" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Password *</label>
                    <input type="password" name="password" class="form-control" required minlength="6">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Role *</label>
                    <select name="role" class="form-control" required>
                        <option value="admin">Admin</option>
                        <option value="moderator">Moderator</option>
                    </select>
                </div>
            </div>
            
            <div class="permissions-section">
                <div class="permissions-title">
                    <i class="fas fa-shield-alt"></i> Permissions
                </div>
                <?php foreach ($availablePermissions as $key => $label): ?>
                    <div class="permission-item">
                        <input type="checkbox" name="permissions[]" value="<?php echo $key; ?>" id="add_perm_<?php echo $key; ?>" class="permission-checkbox">
                        <label for="add_perm_<?php echo $key; ?>" class="permission-label"><?php echo $label; ?></label>
                    </div>
                <?php endforeach; ?>
            </div>
            
            <button type="submit" class="btn-primary">
                <i class="fas fa-plus"></i> Add Admin
            </button>
        </form>
    </div>
</div>

<!-- EDIT ADMIN MODAL -->
<div class="modal" id="editModal">
    <div class="modal-content">
        <div class="modal-header">
            <h2 class="modal-title">
                <i class="fas fa-edit"></i> Edit Admin
            </h2>
            <button class="modal-close" onclick="closeEditModal()">
                <i class="fas fa-times"></i>
            </button>
        </div>
        
        <form method="POST" id="editForm">
            <input type="hidden" name="action" value="edit">
            <input type="hidden" name="admin_id" id="editAdminId">
            
            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Username *</label>
                    <input type="text" name="username" id="editUsername" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Email *</label>
                    <input type="email" name="email" id="editEmail" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Role *</label>
                    <select name="role" id="editRole" class="form-control" required>
                        <option value="super_admin">Super Admin</option>
                        <option value="admin">Admin</option>
                        <option value="moderator">Moderator</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Status *</label>
                    <select name="status" id="editStatus" class="form-control" required>
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                    </select>
                </div>
            </div>
            
            <div class="permissions-section">
                <div class="permissions-title">
                    <i class="fas fa-shield-alt"></i> Permissions
                </div>
                <div id="editPermissionsContainer">
                    <?php foreach ($availablePermissions as $key => $label): ?>
                        <div class="permission-item">
                            <input type="checkbox" name="permissions[]" value="<?php echo $key; ?>" id="edit_perm_<?php echo $key; ?>" class="permission-checkbox">
                            <label for="edit_perm_<?php echo $key; ?>" class="permission-label"><?php echo $label; ?></label>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <button type="submit" class="btn-primary">
                <i class="fas fa-save"></i> Save Changes
            </button>
        </form>
    </div>
</div>

<script>
function openAddModal() {
    document.getElementById('addModal').classList.add('active');
}

function closeAddModal() {
    document.getElementById('addModal').classList.remove('active');
    document.getElementById('addForm').reset();
}

function editAdmin(admin) {
    document.getElementById('editAdminId').value = admin.id;
    document.getElementById('editUsername').value = admin.username;
    document.getElementById('editEmail').value = admin.email;
    document.getElementById('editRole').value = admin.role;
    document.getElementById('editStatus').value = admin.status;
    
    // Clear all checkboxes first
    document.querySelectorAll('#editPermissionsContainer input[type="checkbox"]').forEach(cb => {
        cb.checked = false;
    });
    
    // Check permissions
    if (admin.permissions) {
        const permissions = admin.permissions.split(',');
        permissions.forEach(perm => {
            const checkbox = document.getElementById('edit_perm_' + perm.trim());
            if (checkbox) {
                checkbox.checked = true;
            }
        });
    }
    
    document.getElementById('editModal').classList.add('active');
}

function closeEditModal() {
    document.getElementById('editModal').classList.remove('active');
}

function setPassword(adminId, username) {
    if (confirm(`Set new password for "${username}"? A new random password will be generated and displayed to you.`)) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="set_password">
            <input type="hidden" name="admin_id" value="${adminId}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}

function deleteAdmin(adminId, username) {
    if (confirm(`Delete admin "${username}" permanently? This action cannot be undone!`)) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="admin_id" value="${adminId}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}

// Close modals when clicking outside
document.querySelectorAll('.modal').forEach(modal => {
    modal.addEventListener('click', function(e) {
        if (e.target === this) {
            this.classList.remove('active');
        }
    });
});
</script>