<?php
// admin/manage-admins.php - Menaxhimi i adminave dhe worker-ave
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '../includes/config.php';

if(!isset($_SESSION['admin_logged_in'])) {
    header('Location: login.php');
    exit();
}

$message = '';
$error = '';
$current_admin = $_SESSION['admin_username'];
$current_role = $_SESSION['admin_role'] ?? 'admin';

// ============================================
// VETËM SUPER_ADMIN/ADMIN MUND TË MENAXHOJNË ADMINAT
// ============================================
if($current_role != 'super_admin' && $current_role != 'admin') {
    header('Location: dashboard.php');
    exit();
}

// ============================================
// CHECK AND FIX admin_users TABLE
// ============================================
try {
    // Check if table exists
    $pdo->query("SELECT 1 FROM admin_users LIMIT 1");
    
    // Check if email column exists
    try {
        $pdo->query("SELECT email FROM admin_users LIMIT 1");
    } catch(PDOException $e) {
        // Add missing columns
        $pdo->query("ALTER TABLE admin_users ADD COLUMN email VARCHAR(100) NULL AFTER password");
        $pdo->query("ALTER TABLE admin_users ADD COLUMN full_name VARCHAR(100) NULL AFTER email");
        $pdo->query("ALTER TABLE admin_users ADD COLUMN role ENUM('super_admin','admin','worker') DEFAULT 'admin' AFTER full_name");
        $pdo->query("ALTER TABLE admin_users ADD COLUMN is_active TINYINT(4) DEFAULT 1 AFTER role");
        $pdo->query("ALTER TABLE admin_users ADD COLUMN created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP AFTER is_active");
        $pdo->query("ALTER TABLE admin_users ADD COLUMN last_login TIMESTAMP NULL AFTER created_at");
        $message = "Database tables updated successfully!";
    }
    
    // Check if super_admin role exists
    $check = $pdo->query("SELECT COUNT(*) FROM admin_users")->fetchColumn();
    if($check == 0) {
        $default_password = password_hash('admin123', PASSWORD_DEFAULT);
        $pdo->query("
            INSERT INTO admin_users (username, password, full_name, role, is_active) 
            VALUES ('admin', '$default_password', 'Super Admin', 'super_admin', 1)
        ");
        $message = "Default admin created. Username: admin, Password: admin123";
    }
    
} catch(PDOException $e) {
    // Table doesn't exist - create it
    $pdo->query("
        CREATE TABLE IF NOT EXISTS `admin_users` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `username` varchar(50) NOT NULL,
            `password` varchar(255) NOT NULL,
            `email` varchar(100) DEFAULT NULL,
            `full_name` varchar(100) DEFAULT NULL,
            `role` enum('super_admin','admin','worker') DEFAULT 'admin',
            `is_active` tinyint(4) DEFAULT 1,
            `created_at` timestamp NULL DEFAULT current_timestamp(),
            `last_login` timestamp NULL DEFAULT NULL,
            PRIMARY KEY (`id`),
            UNIQUE KEY `username` (`username`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");
    
    // Insert default admin
    $default_password = password_hash('admin123', PASSWORD_DEFAULT);
    $pdo->query("
        INSERT INTO admin_users (username, password, full_name, role, is_active) 
        VALUES ('admin', '$default_password', 'Super Admin', 'super_admin', 1)
    ");
    $message = "Database created. Username: admin, Password: admin123";
}

// ============================================
// HANDLE ADD ADMIN
// ============================================
if(isset($_POST['add_admin'])) {
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $email = trim($_POST['email']);
    $full_name = trim($_POST['full_name']);
    $role = $_POST['role'];
    
    $errors = [];
    
    if(empty($username)) $errors[] = "Username is required";
    if(strlen($username) < 3) $errors[] = "Username must be at least 3 characters";
    if(empty($password)) $errors[] = "Password is required";
    if(strlen($password) < 6) $errors[] = "Password must be at least 6 characters";
    if($password !== $confirm_password) $errors[] = "Passwords do not match";
    if(!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Invalid email address";
    
    if(empty($errors)) {
        try {
            // Check if username exists
            $stmt = $pdo->prepare("SELECT id FROM admin_users WHERE username = ?");
            $stmt->execute([$username]);
            if($stmt->fetch()) {
                $error = "Username already exists!";
            } else {
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("
                    INSERT INTO admin_users (username, password, email, full_name, role, is_active) 
                    VALUES (?, ?, ?, ?, ?, 1)
                ");
                if($stmt->execute([$username, $hashed_password, $email, $full_name, $role])) {
                    $message = "User <strong>" . htmlspecialchars($username) . "</strong> added successfully!";
                    $_POST = array();
                } else {
                    $error = "Failed to add user.";
                }
            }
        } catch(PDOException $e) {
            $error = "Database error: " . $e->getMessage();
        }
    } else {
        $error = implode("<br>", $errors);
    }
}

// ============================================
// HANDLE UPDATE ADMIN
// ============================================
if(isset($_POST['update_admin'])) {
    $id = (int)$_POST['id'];
    $email = trim($_POST['email']);
    $full_name = trim($_POST['full_name']);
    $role = $_POST['role'];
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    $new_password = $_POST['new_password'];
    $confirm_new_password = $_POST['confirm_new_password'];
    
    $errors = [];
    if(!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Invalid email address";
    if(!empty($new_password) && strlen($new_password) < 6) $errors[] = "Password must be at least 6 characters";
    if(!empty($new_password) && $new_password !== $confirm_new_password) $errors[] = "Passwords do not match";
    
    // Prevent deactivating yourself
    try {
        $stmt = $pdo->prepare("SELECT username, role FROM admin_users WHERE id = ?");
        $stmt->execute([$id]);
        $admin = $stmt->fetch();
        if($admin && $admin['username'] == $current_admin && $is_active == 0) {
            $errors[] = "You cannot deactivate your own account!";
        }
        if($admin && $admin['username'] == $current_admin && $role != $current_role) {
            $errors[] = "You cannot change your own role!";
        }
    } catch(PDOException $e) {
        $errors[] = "Database error: " . $e->getMessage();
    }
    
    if(empty($errors)) {
        try {
            $sql = "UPDATE admin_users SET email = ?, full_name = ?, role = ?, is_active = ? WHERE id = ?";
            $params = [$email, $full_name, $role, $is_active, $id];
            
            if(!empty($new_password)) {
                $sql = "UPDATE admin_users SET email = ?, full_name = ?, role = ?, is_active = ?, password = ? WHERE id = ?";
                $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                $params = [$email, $full_name, $role, $is_active, $hashed_password, $id];
            }
            
            $stmt = $pdo->prepare($sql);
            if($stmt->execute($params)) {
                $message = "User updated successfully!";
            } else {
                $error = "Failed to update user.";
            }
        } catch(PDOException $e) {
            $error = "Database error: " . $e->getMessage();
        }
    } else {
        $error = implode("<br>", $errors);
    }
}

// ============================================
// HANDLE DELETE ADMIN
// ============================================
if(isset($_GET['delete_id'])) {
    $id = (int)$_GET['delete_id'];
    
    try {
        // Prevent deleting yourself
        $stmt = $pdo->prepare("SELECT username, role FROM admin_users WHERE id = ?");
        $stmt->execute([$id]);
        $admin = $stmt->fetch();
        
        if($admin) {
            if($admin['username'] == $current_admin) {
                $error = "You cannot delete your own account!";
            } else {
                // Check if this is the only super_admin
                $check_super = $pdo->query("SELECT COUNT(*) FROM admin_users WHERE role = 'super_admin' AND id != $id")->fetchColumn();
                
                if($admin['role'] == 'super_admin' && $check_super == 0) {
                    $error = "Cannot delete the only super admin!";
                } else {
                    $stmt = $pdo->prepare("DELETE FROM admin_users WHERE id = ?");
                    if($stmt->execute([$id])) {
                        $message = "User deleted successfully!";
                    } else {
                        $error = "Failed to delete user.";
                    }
                }
            }
        }
    } catch(PDOException $e) {
        $error = "Database error: " . $e->getMessage();
    }
}

// ============================================
// GET ALL ADMINS
// ============================================
$admins = [];
try {
    $admins = $pdo->query("
        SELECT id, username, email, full_name, role, is_active, created_at, last_login 
        FROM admin_users 
        ORDER BY id
    ")->fetchAll();
} catch(PDOException $e) {
    // If columns still missing, try without them
    try {
        $admins = $pdo->query("
            SELECT id, username, role, is_active 
            FROM admin_users 
            ORDER BY id
        ")->fetchAll();
        // Add empty values for missing columns
        foreach($admins as &$a) {
            $a['email'] = '';
            $a['full_name'] = '';
            $a['created_at'] = '';
            $a['last_login'] = '';
        }
    } catch(PDOException $e2) {
        $error = "Database error: " . $e2->getMessage();
        $admins = [];
    }
}

$page_title = 'Manage Users';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?> - Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; }
        
        .sidebar {
            width: 260px;
            background: #1a1a2e;
            color: white;
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
            z-index: 100;
        }
        .sidebar-header { padding: 24px 20px; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .sidebar-header h2 { font-size: 18px; font-weight: 600; }
        .sidebar-nav { padding: 20px 0; }
        .sidebar-nav a {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 20px;
            color: #cbd5e1;
            text-decoration: none;
            font-size: 14px;
            transition: all 0.2s;
        }
        .sidebar-nav a i { width: 20px; }
        .sidebar-nav a:hover, .sidebar-nav a.active { background: #0066cc; color: white; }
        
        .main-content { margin-left: 260px; padding: 24px; }
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
            flex-wrap: wrap;
            gap: 16px;
        }
        .page-header h1 { font-size: 24px; font-weight: 600; }
        .page-header h1 i { color: #0066cc; margin-right: 10px; }
        
        .alert-success {
            background: #d1fae5;
            color: #065f46;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 3px solid #10b981;
        }
        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 3px solid #dc2626;
        }
        
        .admin-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 24px;
        }
        
        .card {
            background: white;
            border-radius: 12px;
            border: 1px solid #e5e7eb;
            overflow: hidden;
        }
        .card-header {
            background: #f9fafb;
            padding: 16px 20px;
            border-bottom: 1px solid #e5e7eb;
            font-weight: 600;
            font-size: 16px;
        }
        .card-header i {
            color: #0066cc;
            margin-right: 8px;
        }
        .card-body {
            padding: 20px;
        }
        
        .form-group {
            margin-bottom: 16px;
        }
        .form-group label {
            display: block;
            margin-bottom: 6px;
            font-weight: 500;
            font-size: 13px;
            color: #374151;
        }
        .form-group label .required {
            color: #dc2626;
        }
        .form-group input, .form-group select {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.2s;
        }
        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: #0066cc;
            box-shadow: 0 0 0 3px rgba(0,102,204,0.1);
        }
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }
        .help-text {
            font-size: 11px;
            color: #6b7280;
            margin-top: 4px;
        }
        
        .btn-primary {
            background: #0066cc;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s;
        }
        .btn-primary:hover {
            background: #0052a3;
        }
        .btn-primary:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .btn-sm {
            padding: 4px 10px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 11px;
            font-weight: 500;
        }
        .btn-edit { background: #0066cc; color: white; }
        .btn-edit:hover { background: #0052a3; }
        .btn-delete { background: #dc2626; color: white; }
        .btn-delete:hover { background: #b91c1c; }
        .btn-toggle { background: #10b981; color: white; }
        .btn-toggle:hover { background: #059669; }
        .btn-toggle-off { background: #6b7280; color: white; }
        .btn-toggle-off:hover { background: #4b5563; }
        
        .admin-table {
            width: 100%;
            border-collapse: collapse;
        }
        .admin-table th, .admin-table td {
            padding: 10px 12px;
            text-align: left;
            border-bottom: 1px solid #f0f0f0;
            font-size: 13px;
        }
        .admin-table th {
            background: #f9fafb;
            font-weight: 600;
        }
        .admin-table tr:hover {
            background: #f8fafc;
        }
        
        .role-badge {
            display: inline-block;
            padding: 3px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }
        .role-super_admin { background: #fef3c7; color: #92400e; }
        .role-admin { background: #dbeafe; color: #1e40af; }
        .role-worker { background: #e0e7ff; color: #3730a3; }
        
        .status-badge {
            display: inline-block;
            padding: 3px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }
        .status-active { background: #d1fae5; color: #065f46; }
        .status-inactive { background: #fee2e2; color: #991b1b; }
        
        .current-user-badge {
            background: #d1fae5;
            color: #065f46;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 10px;
            font-weight: 600;
            margin-left: 6px;
        }
        
        .action-buttons {
            display: flex;
            gap: 4px;
            flex-wrap: wrap;
        }
        
        .empty-state {
            text-align: center;
            padding: 40px;
            color: #6b7280;
        }
        .empty-state i {
            font-size: 32px;
            color: #cbd5e1;
            margin-bottom: 12px;
            display: block;
        }
        
        /* Modal */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            justify-content: center;
            align-items: center;
            z-index: 1000;
            backdrop-filter: blur(4px);
        }
        .modal-content {
            background: white;
            border-radius: 16px;
            width: 500px;
            max-width: 95%;
            max-height: 90vh;
            overflow-y: auto;
            animation: modalSlideIn 0.3s ease;
        }
        @keyframes modalSlideIn {
            from { opacity: 0; transform: translateY(-30px) scale(0.95); }
            to { opacity: 1; transform: translateY(0) scale(1); }
        }
        .modal-header {
            padding: 16px 20px;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #f9fafb;
        }
        .modal-header h3 { font-size: 18px; font-weight: 600; }
        .modal-header .close { font-size: 24px; cursor: pointer; color: #6b7280; }
        .modal-header .close:hover { color: #dc2626; }
        .modal-body { padding: 20px; }
        .modal-footer {
            padding: 16px 20px;
            border-top: 1px solid #e5e7eb;
            display: flex;
            justify-content: flex-end;
            gap: 12px;
            background: #f9fafb;
        }
        
        @media (max-width: 900px) {
            .admin-grid {
                grid-template-columns: 1fr;
            }
        }
        
        @media (max-width: 768px) {
            .sidebar { width: 100%; position: relative; height: auto; }
            .main-content { margin-left: 0; }
            .form-row { grid-template-columns: 1fr; }
            .admin-table { display: block; overflow-x: auto; }
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="sidebar-header"><h2><i class="fas fa-car"></i> Car Rental Admin</h2></div>
        <div class="sidebar-nav">
            <a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
            <a href="cars.php"><i class="fas fa-car"></i> Cars</a>
            <a href="create-reservation.php"><i class="fas fa-plus-square"></i> Create Reservation</a>
            <a href="reservations.php"><i class="fas fa-calendar-check"></i> Reservations</a>
            <a href="calendar.php"><i class="fas fa-calendar-alt"></i> Calendar</a>
            <a href="price-list.php"><i class="fas fa-tags"></i> Price Rules</a>
            <a href="extras.php"><i class="fas fa-cogs"></i> Extras</a>
            <a href="email-settings.php"><i class="fas fa-envelope"></i> Email Settings</a>
            <a href="settings.php"><i class="fas fa-cog"></i> Settings</a>
            <a href="manage-admins.php" class="active"><i class="fas fa-user-shield"></i> Users</a>
            <a href="clients.php"><i class="fas fa-users"></i> Clients</a>
            <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>
    
    <div class="main-content">
        <div class="page-header">
            <h1><i class="fas fa-user-shield"></i> Manage Users</h1>
            <span style="font-size: 13px; color: #6b7280;">
                <i class="fas fa-info-circle"></i> 
                <strong>Admin:</strong> Full access &nbsp;|&nbsp; 
                <strong>Worker:</strong> View-only (no edit/delete)
            </span>
        </div>
        
        <?php if($message): ?>
            <div class="alert-success"><i class="fas fa-check-circle"></i> <?php echo $message; ?></div>
        <?php endif; ?>
        <?php if($error): ?>
            <div class="alert-error"><i class="fas fa-exclamation-circle"></i> <?php echo $error; ?></div>
        <?php endif; ?>
        
        <div class="admin-grid">
            <!-- Left Column: Add User Form -->
            <div class="card">
                <div class="card-header">
                    <i class="fas fa-user-plus"></i> Add New User
                </div>
                <div class="card-body">
                    <form method="POST">
                        <div class="form-group">
                            <label>Username <span class="required">*</span></label>
                            <input type="text" name="username" placeholder="Enter username" required value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>">
                            <div class="help-text">Minimum 3 characters</div>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label>Password <span class="required">*</span></label>
                                <input type="password" name="password" placeholder="Enter password" required>
                                <div class="help-text">Minimum 6 characters</div>
                            </div>
                            <div class="form-group">
                                <label>Confirm Password <span class="required">*</span></label>
                                <input type="password" name="confirm_password" placeholder="Confirm password" required>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>Email</label>
                            <input type="email" name="email" placeholder="user@example.com" value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>">
                        </div>
                        <div class="form-group">
                            <label>Full Name</label>
                            <input type="text" name="full_name" placeholder="Full name" value="<?php echo htmlspecialchars($_POST['full_name'] ?? ''); ?>">
                        </div>
                        <div class="form-group">
                            <label>Role</label>
                            <select name="role">
                                <option value="admin" <?php echo ($_POST['role'] ?? '') == 'admin' ? 'selected' : ''; ?>>Admin - Full Access</option>
                                <option value="worker" <?php echo ($_POST['role'] ?? '') == 'worker' ? 'selected' : ''; ?>>Worker - View Only</option>
                            </select>
                            <div class="help-text">
                                <strong>Admin:</strong> Full access to all features (except super_admin actions)<br>
                                <strong>Worker:</strong> View only - cannot create, edit, or delete anything
                            </div>
                        </div>
                        <button type="submit" name="add_admin" class="btn-primary">
                            <i class="fas fa-plus"></i> Add User
                        </button>
                    </form>
                </div>
            </div>
            
            <!-- Right Column: User List -->
            <div class="card">
                <div class="card-header">
                    <i class="fas fa-list"></i> Users List
                    <span style="float: right; font-size: 13px; font-weight: normal; color: #6b7280;">
                        <?php echo count($admins); ?> user(s)
                    </span>
                </div>
                <div class="card-body">
                    <?php if(count($admins) > 0): ?>
                        <div style="overflow-x: auto;">
                            <table class="admin-table">
                                <thead>
                                    <tr>
                                        <th>Username</th>
                                        <th>Name</th>
                                        <th>Role</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($admins as $admin): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo htmlspecialchars($admin['username']); ?></strong>
                                            <?php if($admin['username'] == $current_admin): ?>
                                                <span class="current-user-badge"><i class="fas fa-user-check"></i> You</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo htmlspecialchars($admin['full_name'] ?? '-'); ?></td>
                                        <td>
                                            <span class="role-badge role-<?php echo $admin['role'] ?? 'admin'; ?>">
                                                <?php echo ucfirst(str_replace('_', ' ', $admin['role'] ?? 'admin')); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="status-badge status-<?php echo ($admin['is_active'] ?? 1) ? 'active' : 'inactive'; ?>">
                                                <?php echo ($admin['is_active'] ?? 1) ? 'Active' : 'Inactive'; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="action-buttons">
                                                <button class="btn-sm btn-edit" onclick="editAdmin(<?php echo $admin['id']; ?>, '<?php echo addslashes($admin['username']); ?>', '<?php echo addslashes($admin['email'] ?? ''); ?>', '<?php echo addslashes($admin['full_name'] ?? ''); ?>', '<?php echo $admin['role'] ?? 'admin'; ?>', <?php echo $admin['is_active'] ?? 1; ?>)">
                                                    <i class="fas fa-edit"></i> Edit
                                                </button>
                                                <?php if($admin['username'] != $current_admin): ?>
                                                    <a href="?delete_id=<?php echo $admin['id']; ?>" class="btn-sm btn-delete" onclick="return confirm('Delete this user?')">
                                                        <i class="fas fa-trash"></i>
                                                    </a>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <i class="fas fa-users"></i>
                            <p>No users found</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- Info Note -->
        <div style="margin-top: 24px; background: #eff6ff; padding: 16px 20px; border-radius: 12px; border-left: 4px solid #0066cc;">
            <p style="font-size: 13px; color: #1e40af;">
                <i class="fas fa-info-circle"></i> 
                <strong>Roles:</strong> 
                <span style="background: #fef3c7; padding: 2px 10px; border-radius: 12px; margin: 0 4px;">Super Admin</span> 
                - Full access (cannot be deleted or deactivated by others) &nbsp;|&nbsp;
                <span style="background: #dbeafe; padding: 2px 10px; border-radius: 12px; margin: 0 4px;">Admin</span> 
                - Full access &nbsp;|&nbsp;
                <span style="background: #e0e7ff; padding: 2px 10px; border-radius: 12px; margin: 0 4px;">Worker</span> 
                - View only (cannot create, edit, or delete)
            </p>
            <p style="font-size: 12px; color: #1e40af; margin-top: 6px;">
                <i class="fas fa-lock"></i> Workers cannot access: Cars (edit/delete), Price Rules (edit), Extras (edit), Email Settings, Settings
            </p>
        </div>
    </div>
    
    <!-- Edit Admin Modal -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="fas fa-user-edit"></i> Edit User</h3>
                <span class="close" onclick="closeEditModal()">&times;</span>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="id" id="edit_id">
                    <input type="hidden" name="update_admin" value="1">
                    
                    <div class="form-group">
                        <label>Username</label>
                        <input type="text" id="edit_username" disabled style="background: #f3f4f6; cursor: not-allowed;">
                        <div class="help-text">Username cannot be changed</div>
                    </div>
                    <div class="form-group">
                        <label>Email</label>
                        <input type="email" name="email" id="edit_email" placeholder="user@example.com">
                    </div>
                    <div class="form-group">
                        <label>Full Name</label>
                        <input type="text" name="full_name" id="edit_full_name" placeholder="Full name">
                    </div>
                    <div class="form-group">
                        <label>Role</label>
                        <select name="role" id="edit_role">
                            <option value="admin">Admin - Full Access</option>
                            <option value="worker">Worker - View Only</option>
                        </select>
                        <div class="help-text">
                            <strong>Admin:</strong> Full access to all features<br>
                            <strong>Worker:</strong> View only - cannot create, edit, or delete anything
                        </div>
                    </div>
                    <div class="form-group">
                        <label>
                            <input type="checkbox" name="is_active" id="edit_is_active" value="1">
                            Active
                        </label>
                        <div class="help-text">If inactive, this user cannot log in</div>
                    </div>
                    <hr style="border: none; border-top: 1px solid #e5e7eb; margin: 16px 0;">
                    <div class="form-group">
                        <label>New Password</label>
                        <input type="password" name="new_password" id="edit_password" placeholder="Leave empty to keep current password">
                        <div class="help-text">Minimum 6 characters. Leave empty to keep current password.</div>
                    </div>
                    <div class="form-group">
                        <label>Confirm New Password</label>
                        <input type="password" name="confirm_new_password" id="edit_confirm_password" placeholder="Confirm new password">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-sm btn-delete" onclick="closeEditModal()" style="padding: 8px 16px;">Cancel</button>
                    <button type="submit" class="btn-primary" style="padding: 8px 20px;">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        function editAdmin(id, username, email, full_name, role, is_active) {
            document.getElementById('edit_id').value = id;
            document.getElementById('edit_username').value = username;
            document.getElementById('edit_email').value = email || '';
            document.getElementById('edit_full_name').value = full_name || '';
            document.getElementById('edit_role').value = role || 'admin';
            document.getElementById('edit_is_active').checked = is_active == 1;
            document.getElementById('edit_password').value = '';
            document.getElementById('edit_confirm_password').value = '';
            
            document.getElementById('editModal').style.display = 'flex';
        }
        
        function closeEditModal() {
            document.getElementById('editModal').style.display = 'none';
        }
        
        window.onclick = function(event) {
            if(event.target == document.getElementById('editModal')) {
                closeEditModal();
            }
        }
    </script>
</body>
</html>