<?php
session_start();
require_once '../connection.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: ../admin-login.php');
    exit();
}

// Fetch current admin data
$admin_id = $_SESSION['admin_id'];
$query = "SELECT * FROM admin_table WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    session_destroy();
    header('Location: ../admin-login.php');
    exit();
}

$current_admin = $result->fetch_assoc();
$stmt->close();

// Initialize variables
$message = '';
$message_type = '';
$edit_mode = false;
$admin_to_edit = null;
$current_password_error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    switch ($action) {
        case 'add_admin':
            // Add new admin
            $email = trim($_POST['email']);
            $password = $_POST['password'];
            $confirm_password = $_POST['confirm_password'];
            
            // Validation
            if (empty($email) || empty($password)) {
                $message = "Email and password are required!";
                $message_type = "error";
            } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $message = "Please enter a valid email address!";
                $message_type = "error";
            } elseif ($password !== $confirm_password) {
                $message = "Passwords do not match!";
                $message_type = "error";
            } elseif (strlen($password) < 8) {
                $message = "Password must be at least 8 characters!";
                $message_type = "error";
            } else {
                // Check if email already exists
                $check_query = "SELECT id FROM admin_table WHERE email = ?";
                $check_stmt = $conn->prepare($check_query);
                $check_stmt->bind_param("s", $email);
                $check_stmt->execute();
                $check_result = $check_stmt->get_result();
                
                if ($check_result->num_rows > 0) {
                    $message = "Email already exists!";
                    $message_type = "error";
                    $check_stmt->close();
                } else {
                    $check_stmt->close();
                    
                    // Hash password
                    $password_hash = password_hash($password, PASSWORD_DEFAULT);
                    
                    // Insert new admin
                    $insert_query = "INSERT INTO admin_table (email, password) VALUES (?, ?)";
                    $insert_stmt = $conn->prepare($insert_query);
                    $insert_stmt->bind_param("ss", $email, $password_hash);
                    
                    if ($insert_stmt->execute()) {
                        $message = "Admin added successfully!";
                        $message_type = "success";
                    } else {
                        $message = "Error adding admin: " . $insert_stmt->error;
                        $message_type = "error";
                    }
                    $insert_stmt->close();
                }
            }
            break;
            
        case 'edit_admin':
            // Edit existing admin
            $admin_id = intval($_POST['admin_id']);
            $email = trim($_POST['email']);
            $new_password = $_POST['new_password'];
            $confirm_password = $_POST['confirm_password'];
            
            // Validation
            if (empty($email)) {
                $message = "Email is required!";
                $message_type = "error";
            } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $message = "Please enter a valid email address!";
                $message_type = "error";
            } else {
                // Check if email already exists for other admin
                $check_query = "SELECT id FROM admin_table WHERE email = ? AND id != ?";
                $check_stmt = $conn->prepare($check_query);
                $check_stmt->bind_param("si", $email, $admin_id);
                $check_stmt->execute();
                $check_result = $check_stmt->get_result();
                
                if ($check_result->num_rows > 0) {
                    $message = "Email already exists for another admin!";
                    $message_type = "error";
                    $check_stmt->close();
                } else {
                    $check_stmt->close();
                    
                    if (!empty($new_password)) {
                        // Password change requested
                        if ($new_password !== $confirm_password) {
                            $message = "New passwords do not match!";
                            $message_type = "error";
                        } elseif (strlen($new_password) < 8) {
                            $message = "New password must be at least 8 characters!";
                            $message_type = "error";
                        } else {
                            // Update with new password
                            $password_hash = password_hash($new_password, PASSWORD_DEFAULT);
                            $update_query = "UPDATE admin_table SET email = ?, password = ? WHERE id = ?";
                            $update_stmt = $conn->prepare($update_query);
                            $update_stmt->bind_param("ssi", $email, $password_hash, $admin_id);
                            
                            if ($update_stmt->execute()) {
                                $message = "Admin updated successfully with new password!";
                                $message_type = "success";
                            } else {
                                $message = "Error updating admin: " . $update_stmt->error;
                                $message_type = "error";
                            }
                            $update_stmt->close();
                        }
                    } else {
                        // Update only email
                        $update_query = "UPDATE admin_table SET email = ? WHERE id = ?";
                        $update_stmt = $conn->prepare($update_query);
                        $update_stmt->bind_param("si", $email, $admin_id);
                        
                        if ($update_stmt->execute()) {
                            $message = "Admin updated successfully!";
                            $message_type = "success";
                        } else {
                            $message = "Error updating admin: " . $update_stmt->error;
                            $message_type = "error";
                        }
                        $update_stmt->close();
                    }
                    
                    // If editing current admin, update session
                    if ($admin_id == $_SESSION['admin_id']) {
                        $_SESSION['admin_email'] = $email;
                        // Reload current admin data
                        $query = "SELECT * FROM admin_table WHERE id = ?";
                        $stmt = $conn->prepare($query);
                        $stmt->bind_param("i", $admin_id);
                        $stmt->execute();
                        $result = $stmt->get_result();
                        $current_admin = $result->fetch_assoc();
                        $stmt->close();
                    }
                }
            }
            break;
            
        case 'update_profile':
            // Update current admin's profile
            $email = trim($_POST['email']);
            $current_password = $_POST['current_password'];
            $new_password = $_POST['new_password'];
            $confirm_password = $_POST['confirm_password'];
            
            // Validation
            if (empty($email)) {
                $message = "Email is required!";
                $message_type = "error";
            } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $message = "Please enter a valid email address!";
                $message_type = "error";
            } else {
                // Check if email already exists for other admin
                $check_query = "SELECT id FROM admin_table WHERE email = ? AND id != ?";
                $check_stmt = $conn->prepare($check_query);
                $check_stmt->bind_param("si", $email, $admin_id);
                $check_stmt->execute();
                $check_result = $check_stmt->get_result();
                
                if ($check_result->num_rows > 0) {
                    $message = "Email already exists for another admin!";
                    $message_type = "error";
                    $check_stmt->close();
                } else {
                    $check_stmt->close();
                    
                    if (!empty($new_password)) {
                        // Password change requested - verify current password
                        $verify_query = "SELECT password FROM admin_table WHERE id = ?";
                        $verify_stmt = $conn->prepare($verify_query);
                        $verify_stmt->bind_param("i", $admin_id);
                        $verify_stmt->execute();
                        $verify_result = $verify_stmt->get_result();
                        $admin_data = $verify_result->fetch_assoc();
                        
                        if (!password_verify($current_password, $admin_data['password'])) {
                            $current_password_error = "Current password is incorrect!";
                            $message = $current_password_error;
                            $message_type = "error";
                            $verify_stmt->close();
                        } elseif ($new_password !== $confirm_password) {
                            $message = "New passwords do not match!";
                            $message_type = "error";
                            $verify_stmt->close();
                        } elseif (strlen($new_password) < 8) {
                            $message = "New password must be at least 8 characters!";
                            $message_type = "error";
                            $verify_stmt->close();
                        } else {
                            $verify_stmt->close();
                            
                            // Update with new password
                            $password_hash = password_hash($new_password, PASSWORD_DEFAULT);
                            $update_query = "UPDATE admin_table SET email = ?, password = ? WHERE id = ?";
                            $update_stmt = $conn->prepare($update_query);
                            $update_stmt->bind_param("ssi", $email, $password_hash, $admin_id);
                            
                            if ($update_stmt->execute()) {
                                $_SESSION['admin_email'] = $email;
                                $message = "Profile updated successfully with new password!";
                                $message_type = "success";
                                
                                // Reload current admin data
                                $query = "SELECT * FROM admin_table WHERE id = ?";
                                $stmt = $conn->prepare($query);
                                $stmt->bind_param("i", $admin_id);
                                $stmt->execute();
                                $result = $stmt->get_result();
                                $current_admin = $result->fetch_assoc();
                                $stmt->close();
                            } else {
                                $message = "Error updating profile: " . $update_stmt->error;
                                $message_type = "error";
                            }
                            $update_stmt->close();
                        }
                    } else {
                        // Update only email
                        $update_query = "UPDATE admin_table SET email = ? WHERE id = ?";
                        $update_stmt = $conn->prepare($update_query);
                        $update_stmt->bind_param("si", $email, $admin_id);
                        
                        if ($update_stmt->execute()) {
                            $_SESSION['admin_email'] = $email;
                            $message = "Profile updated successfully!";
                            $message_type = "success";
                            
                            // Reload current admin data
                            $query = "SELECT * FROM admin_table WHERE id = ?";
                            $stmt = $conn->prepare($query);
                            $stmt->bind_param("i", $admin_id);
                            $stmt->execute();
                            $result = $stmt->get_result();
                            $current_admin = $result->fetch_assoc();
                            $stmt->close();
                        } else {
                            $message = "Error updating profile: " . $update_stmt->error;
                            $message_type = "error";
                        }
                        $update_stmt->close();
                    }
                }
            }
            break;
            
        case 'delete_admin':
            // Delete admin (cannot delete self)
            $admin_id_to_delete = intval($_POST['admin_id']);
            
            if ($admin_id_to_delete == $_SESSION['admin_id']) {
                $message = "You cannot delete your own account!";
                $message_type = "error";
            } else {
                $delete_query = "DELETE FROM admin_table WHERE id = ?";
                $delete_stmt = $conn->prepare($delete_query);
                $delete_stmt->bind_param("i", $admin_id_to_delete);
                
                if ($delete_stmt->execute()) {
                    $message = "Admin deleted successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error deleting admin: " . $delete_stmt->error;
                    $message_type = "error";
                }
                $delete_stmt->close();
            }
            break;
    }
}

// Handle edit request
if (isset($_GET['edit'])) {
    $edit_id = intval($_GET['edit']);
    $query = "SELECT * FROM admin_table WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $edit_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $admin_to_edit = $result->fetch_assoc();
        $edit_mode = true;
    }
    $stmt->close();
}

// Fetch all admins
$query = "SELECT id, email, created_at FROM admin_table ORDER BY created_at DESC";
$result = $conn->query($query);
$admins = [];
while ($row = $result->fetch_assoc()) {
    $admins[] = $row;
}

// Get total admin count
$total_admins = count($admins);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Admins - Admin Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: {
                            50: '#eff6ff',
                            100: '#dbeafe',
                            200: '#bfdbfe',
                            300: '#93c5fd',
                            400: '#60a5fa',
                            500: '#3b82f6',
                            600: '#2563eb',
                            700: '#1d4ed8',
                            800: '#1e40af',
                            900: '#1e3a8a',
                        }
                    },
                    fontFamily: {
                        'inter': ['Inter', 'system-ui', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }
    </style>
</head>
<body class="bg-gray-50 font-inter">
    
    <?php include("nav.php"); ?>

    <!-- Main Content -->
    <div class="main-content ml-64">
        <!-- Header -->
        <header class="bg-white shadow-sm border-b border-gray-200 px-8 py-4">
            <div class="flex items-center justify-between">
                <div>
                    <h2 class="text-2xl font-bold text-gray-800">Manage Administrators</h2>
                    <p class="text-gray-600">Total Admins: <?php echo number_format($total_admins); ?></p>
                </div>
                
                <div class="flex items-center space-x-4">
                    <!-- Add Admin Button -->
                    <button onclick="toggleAddAdminForm()" class="flex items-center space-x-2 px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition">
                        <i class="fas fa-user-plus"></i>
                        <span>Add New Admin</span>
                    </button>
                </div>
            </div>
        </header>

        <!-- Message Alert -->
        <?php if (!empty($message)): ?>
        <div class="mx-8 mt-6">
            <div class="p-4 rounded-lg <?php echo $message_type == 'success' ? 'bg-green-100 text-green-700 border border-green-200' : 'bg-red-100 text-red-700 border border-red-200'; ?>">
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <i class="fas <?php echo $message_type == 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'; ?> mr-2"></i>
                        <span><?php echo $message; ?></span>
                    </div>
                    <button onclick="this.parentElement.parentElement.remove()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Add/Edit Admin Form -->
        <div id="addAdminForm" class="<?php echo $edit_mode ? '' : 'hidden'; ?> mx-8 mt-6 bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-xl font-bold text-gray-800">
                    <?php echo $edit_mode ? 'Edit Administrator' : 'Add New Administrator'; ?>
                </h3>
                <button onclick="toggleAddAdminForm()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            
            <form method="POST" action="" class="space-y-4">
                <input type="hidden" name="action" value="<?php echo $edit_mode ? 'edit_admin' : 'add_admin'; ?>">
                <?php if ($edit_mode): ?>
                <input type="hidden" name="admin_id" value="<?php echo $admin_to_edit['id']; ?>">
                <?php endif; ?>
                
                <div class="space-y-4">
                    <!-- Email -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Email Address *</label>
                        <input type="email" name="email" required
                               value="<?php echo $edit_mode ? htmlspecialchars($admin_to_edit['email']) : ''; ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                    </div>
                    
                    <!-- Password (for add or optional change) -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <?php if (!$edit_mode): ?>
                        <!-- For new admin -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Password *</label>
                            <input type="password" name="password" required minlength="8"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Confirm Password *</label>
                            <input type="password" name="confirm_password" required minlength="8"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                        </div>
                        <?php else: ?>
                        <!-- For editing admin - optional password change -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">New Password (optional)</label>
                            <input type="password" name="new_password" minlength="8"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <p class="text-xs text-gray-500 mt-1">Leave blank to keep current password</p>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Confirm New Password</label>
                            <input type="password" name="confirm_password" minlength="8"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <?php if ($edit_mode): ?>
                    <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                        <div class="flex">
                            <i class="fas fa-exclamation-triangle text-yellow-400 mt-0.5 mr-3"></i>
                            <div>
                                <p class="text-sm text-yellow-800">
                                    <strong>Note:</strong> Leave password fields blank if you don't want to change the password.
                                </p>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <div class="pt-4 border-t border-gray-200">
                    <div class="flex justify-end space-x-3">
                        <button type="button" onclick="toggleAddAdminForm()" class="px-6 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition">
                            Cancel
                        </button>
                        <button type="submit" class="px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition">
                            <?php echo $edit_mode ? 'Update Admin' : 'Add Admin'; ?>
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <!-- My Profile Section -->
        <div class="mx-8 mt-6 bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <h3 class="text-xl font-bold text-gray-800 mb-6">My Profile</h3>
            
            <form method="POST" action="" class="space-y-4">
                <input type="hidden" name="action" value="update_profile">
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Current Email -->
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-1">Current Email</label>
                        <div class="flex items-center space-x-3">
                            <div class="w-12 h-12 bg-primary-100 rounded-full flex items-center justify-center">
                                <i class="fas fa-user-shield text-primary-600"></i>
                            </div>
                            <div>
                                <p class="font-medium text-gray-800"><?php echo htmlspecialchars($current_admin['email']); ?></p>
                                <p class="text-sm text-gray-500">Member since <?php echo date('M d, Y', strtotime($current_admin['created_at'])); ?></p>
                            </div>
                        </div>
                    </div>
                    
                    <!-- New Email -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">New Email Address</label>
                        <input type="email" name="email" required
                               value="<?php echo htmlspecialchars($current_admin['email']); ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                    </div>
                    
                    <!-- Current Password (for verification) -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Current Password *</label>
                        <input type="password" name="current_password" required
                               class="w-full px-4 py-2 border <?php echo !empty($current_password_error) ? 'border-red-300' : 'border-gray-300'; ?> rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                        <?php if (!empty($current_password_error)): ?>
                        <p class="text-sm text-red-600 mt-1"><?php echo $current_password_error; ?></p>
                        <?php else: ?>
                        <p class="text-xs text-gray-500 mt-1">Required for verification</p>
                        <?php endif; ?>
                    </div>
                    
                    <!-- New Password (optional) -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">New Password (optional)</label>
                        <input type="password" name="new_password" minlength="8"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                    </div>
                    
                    <!-- Confirm New Password -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Confirm New Password</label>
                        <input type="password" name="confirm_password" minlength="8"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                    </div>
                </div>
                
                <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mt-4">
                    <div class="flex">
                        <i class="fas fa-info-circle text-blue-400 mt-0.5 mr-3"></i>
                        <div>
                            <p class="text-sm text-blue-800">
                                <strong>Security Note:</strong> Changing your email or password will update your login credentials immediately. 
                                You'll need to use the new credentials for your next login.
                            </p>
                        </div>
                    </div>
                </div>
                
                <div class="pt-4 border-t border-gray-200">
                    <button type="submit" class="px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition">
                        Update My Profile
                    </button>
                </div>
            </form>
        </div>

        <!-- Admins List -->
        <div class="mx-8 my-6 bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800">Administrator Accounts</h3>
                <p class="text-sm text-gray-600">Manage all administrator accounts with caution</p>
            </div>
            
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead class="bg-gray-50">
                        <tr class="text-left text-sm text-gray-500 border-b border-gray-200">
                            <th class="py-3 px-6 font-medium">Admin</th>
                            <th class="py-3 px-6 font-medium">Email</th>
                            <th class="py-3 px-6 font-medium">Created</th>
                            <th class="py-3 px-6 font-medium">Status</th>
                            <th class="py-3 px-6 font-medium">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200">
                        <?php if (empty($admins)): ?>
                        <tr>
                            <td colspan="5" class="py-8 text-center text-gray-500">
                                <i class="fas fa-user-shield text-3xl mb-2 block"></i>
                                No administrators found
                            </td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($admins as $admin): ?>
                        <tr class="hover:bg-gray-50 transition">
                            <!-- Admin Info -->
                            <td class="py-4 px-6">
                                <div class="flex items-center">
                                    <div class="w-10 h-10 bg-primary-100 rounded-full flex items-center justify-center mr-3">
                                        <i class="fas fa-user-shield text-primary-600"></i>
                                    </div>
                                    <div>
                                        <p class="font-medium text-gray-800">
                                            <?php echo 'Admin #' . $admin['id']; ?>
                                        </p>
                                        <p class="text-sm text-gray-500">
                                            <?php echo $admin['id'] == $current_admin['id'] ? 'You' : 'Administrator'; ?>
                                        </p>
                                    </div>
                                </div>
                            </td>
                            
                            <!-- Email -->
                            <td class="py-4 px-6">
                                <p class="text-gray-600"><?php echo htmlspecialchars($admin['email']); ?></p>
                            </td>
                            
                            <!-- Created Date -->
                            <td class="py-4 px-6">
                                <p class="text-sm text-gray-600">
                                    <?php echo date('M d, Y', strtotime($admin['created_at'])); ?>
                                </p>
                                <p class="text-xs text-gray-400">
                                    <?php echo date('h:i A', strtotime($admin['created_at'])); ?>
                                </p>
                            </td>
                            
                            <!-- Status -->
                            <td class="py-4 px-6">
                                <?php if ($admin['id'] == $current_admin['id']): ?>
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                    <i class="fas fa-circle text-[8px] mr-1"></i>
                                    Current User
                                </span>
                                <?php else: ?>
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                    <i class="fas fa-circle text-[8px] mr-1"></i>
                                    Active
                                </span>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Actions -->
                            <td class="py-4 px-6">
                                <div class="flex items-center space-x-2">
                                    <!-- Edit -->
                                    <a href="?edit=<?php echo $admin['id']; ?>" 
                                       class="text-blue-600 hover:text-blue-800 p-1" 
                                       title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    
                                    <!-- Delete (only if not current user) -->
                                    <?php if ($admin['id'] != $current_admin['id']): ?>
                                    <form method="POST" action="" class="inline" onsubmit="return confirm('Are you sure you want to delete this admin? This action cannot be undone.')">
                                        <input type="hidden" name="action" value="delete_admin">
                                        <input type="hidden" name="admin_id" value="<?php echo $admin['id']; ?>">
                                        <button type="submit" class="text-red-600 hover:text-red-800 p-1" title="Delete">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                    <?php else: ?>
                                    <span class="text-gray-400 p-1" title="Cannot delete your own account">
                                        <i class="fas fa-trash"></i>
                                    </span>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Security Guidelines -->
        <div class="mx-8 mb-8">
            <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-6">
                <h4 class="text-lg font-semibold text-yellow-800 mb-3">
                    <i class="fas fa-shield-alt mr-2"></i> Security Guidelines
                </h4>
                <ul class="space-y-2 text-sm text-yellow-700">
                    <li class="flex items-start">
                        <i class="fas fa-check-circle mt-0.5 mr-2 text-yellow-500"></i>
                        <span>Always use strong passwords (minimum 8 characters with mixed case, numbers, and symbols)</span>
                    </li>
                    <li class="flex items-start">
                        <i class="fas fa-check-circle mt-0.5 mr-2 text-yellow-500"></i>
                        <span>Never share your admin credentials with anyone</span>
                    </li>
                    <li class="flex items-start">
                        <i class="fas fa-check-circle mt-0.5 mr-2 text-yellow-500"></i>
                        <span>Regularly update passwords for all admin accounts</span>
                    </li>
                    <li class="flex items-start">
                        <i class="fas fa-check-circle mt-0.5 mr-2 text-yellow-500"></i>
                        <span>Only grant admin access to trusted personnel</span>
                    </li>
                    <li class="flex items-start">
                        <i class="fas fa-check-circle mt-0.5 mr-2 text-yellow-500"></i>
                        <span>Monitor admin activities regularly for suspicious behavior</span>
                    </li>
                </ul>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <script>
        // Toggle add admin form
        function toggleAddAdminForm() {
            const form = document.getElementById('addAdminForm');
            form.classList.toggle('hidden');
            
            if (!form.classList.contains('hidden')) {
                form.scrollIntoView({ behavior: 'smooth' });
            } else {
                // Remove edit parameter from URL
                const url = new URL(window.location);
                url.searchParams.delete('edit');
                window.history.replaceState({}, '', url);
            }
        }

        // If in edit mode, show form on page load
        <?php if ($edit_mode): ?>
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('addAdminForm');
            if (form) {
                form.classList.remove('hidden');
                form.scrollIntoView({ behavior: 'smooth' });
            }
        });
        <?php endif; ?>

        // Confirm before deleting admin
        function confirmDelete(adminId, adminEmail) {
            return confirm(`Are you sure you want to delete admin "${adminEmail}"?\n\nThis action cannot be undone and will permanently remove all access for this administrator.`);
        }

        // Toggle password visibility
        function togglePasswordVisibility(inputId) {
            const input = document.getElementById(inputId);
            const type = input.getAttribute('type') === 'password' ? 'text' : 'password';
            input.setAttribute('type', type);
        }

        // Form validation
        document.addEventListener('DOMContentLoaded', function() {
            const forms = document.querySelectorAll('form');
            forms.forEach(form => {
                form.addEventListener('submit', function(e) {
                    const passwordInputs = form.querySelectorAll('input[type="password"][name*="password"]');
                    passwordInputs.forEach(input => {
                        if (input.value && input.value.length < 8) {
                            e.preventDefault();
                            alert('Password must be at least 8 characters long!');
                            input.focus();
                            return false;
                        }
                    });
                    
                    const confirmPassword = form.querySelector('input[name="confirm_password"]');
                    const newPassword = form.querySelector('input[name="new_password"]');
                    const password = form.querySelector('input[name="password"]');
                    
                    if (confirmPassword && (newPassword || password)) {
                        const compareTo = newPassword ? newPassword.value : password.value;
                        if (confirmPassword.value !== compareTo) {
                            e.preventDefault();
                            alert('Passwords do not match!');
                            confirmPassword.focus();
                            return false;
                        }
                    }
                });
            });
        });

        // Show password strength indicator
        function checkPasswordStrength(input) {
            const password = input.value;
            const strengthIndicator = input.parentElement.querySelector('.password-strength');
            
            if (!strengthIndicator) return;
            
            let strength = 0;
            if (password.length >= 8) strength++;
            if (/[a-z]/.test(password)) strength++;
            if (/[A-Z]/.test(password)) strength++;
            if (/[0-9]/.test(password)) strength++;
            if (/[^A-Za-z0-9]/.test(password)) strength++;
            
            const colors = ['bg-red-500', 'bg-orange-500', 'bg-yellow-500', 'bg-green-400', 'bg-green-600'];
            const texts = ['Very Weak', 'Weak', 'Fair', 'Good', 'Strong'];
            
            strengthIndicator.className = `h-1 rounded-full transition-all duration-300 ${colors[strength - 1] || 'bg-red-500'} w-${strength * 20}`;
            
            const textElement = strengthIndicator.nextElementSibling;
            if (textElement && textElement.classList.contains('password-strength-text')) {
                textElement.textContent = password ? texts[strength - 1] || 'Very Weak' : '';
                textElement.className = `password-strength-text text-xs ${strength >= 4 ? 'text-green-600' : strength >= 3 ? 'text-yellow-600' : 'text-red-600'}`;
            }
        }
    </script>
</body>
</html>