<?php
/**
 * ===================================================================================
 * Edit Sub-Admin Page
 * ===================================================================================
 *
 * File: edit_admin.php
 * Location: /homework_portal/admin/edit_admin.php
 *
 * Purpose:
 * 1. Allows the Super Admin to edit a sub-admin's username and permissions.
 * 2. Fetches existing data to pre-fill the form.
 */

require_once '../config.php';
require_once 'admin_helpers.php';

// --- Security Check: Super Admin only ---
check_permission('manage_admins'); // Re-using this as only super admins can access the origin page

$sub_admin_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$errors = [];
$success_message = '';

if ($sub_admin_id <= 0) {
    header('Location: manage_admins.php');
    exit();
}

// List of available permissions
$available_permissions = [
    'manage_teachers' => 'Manage Teachers',
    'manage_classes' => 'Manage Classes',
    'manage_subjects' => 'Manage Subjects',
    'assign_subjects' => 'Assign Subjects',
    'send_message' => 'Send Messages'
];

// --- Fetch existing sub-admin data ---
try {
    $stmt = $pdo->prepare("SELECT id, username, role, permissions FROM super_admins WHERE id = ? AND role = 'sub_admin'");
    $stmt->execute([$sub_admin_id]);
    $sub_admin = $stmt->fetch();
    if (!$sub_admin) {
        header('Location: manage_admins.php?error=Sub-admin not found.');
        exit();
    }
    $current_permissions = json_decode($sub_admin['permissions'] ?? '[]', true);
} catch (PDOException $e) {
    die("Database error fetching sub-admin data.");
}

// --- Handle Form Submission to UPDATE ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_admin'])) {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? ''; // Optional
    $permissions = $_POST['permissions'] ?? [];

    if (empty($username)) $errors[] = "Username is required.";
    if (!empty($password) && strlen($password) < 8) $errors[] = "New password must be at least 8 characters.";
    if (empty($permissions)) $errors[] = "A sub-admin must have at least one permission.";

    if (empty($errors)) {
        $permissions_json = json_encode($permissions);
        
        if (!empty($password)) {
            $password_hash = password_hash($password, PASSWORD_DEFAULT);
            $sql = "UPDATE super_admins SET username = ?, permissions = ?, password_hash = ? WHERE id = ?";
            $params = [$username, $permissions_json, $password_hash, $sub_admin_id];
        } else {
            $sql = "UPDATE super_admins SET username = ?, permissions = ? WHERE id = ?";
            $params = [$username, $permissions_json, $sub_admin_id];
        }
        
        try {
            $pdo->prepare($sql)->execute($params);
            $success_message = "Sub-admin details updated successfully!";
            // Re-fetch data to show changes
            $stmt->execute([$sub_admin_id]);
            $sub_admin = $stmt->fetch();
            $current_permissions = json_decode($sub_admin['permissions'] ?? '[]', true);
        } catch (PDOException $e) {
            $errors[] = "Database error: Could not update sub-admin.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Sub-Admin - Admin Portal</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&family=Baloo+2:wght@700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Poppins', sans-serif; background-color: #f0f9ff; }
        .font-brand { font-family: 'Baloo 2', cursive; }
    </style>
</head>
<body class="min-h-screen">
    <div class="max-w-3xl mx-auto py-10">
        <div class="mb-4"><a href="manage_admins.php" class="flex items-center text-blue-600 hover:text-blue-800 font-medium"><svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path></svg>Back to Manage Admins</a></div>
        <div class="bg-white p-8 rounded-lg shadow-lg">
            <h1 class="text-2xl font-bold text-gray-800 mb-6 font-brand">Edit Sub-Admin: <?php echo e($sub_admin['username']); ?></h1>
            
            <?php if($success_message): ?><div class="p-4 mb-4 text-sm text-green-800 bg-green-100 rounded-lg"><?php echo e($success_message); ?></div><?php endif; ?>
            <?php if(!empty($errors)): ?><div class="p-4 mb-4 text-sm text-red-800 bg-red-100 rounded-lg"><ul class="list-disc list-inside"><?php foreach($errors as $e) echo "<li>".e($e)."</li>"; ?></ul></div><?php endif; ?>

            <form action="edit_admin.php?id=<?php echo $sub_admin_id; ?>" method="POST" class="space-y-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label for="username" class="block text-sm font-medium text-gray-700">Username</label>
                        <input type="text" name="username" id="username" value="<?php echo e($sub_admin['username']); ?>" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" required>
                    </div>
                    <div>
                        <label for="password" class="block text-sm font-medium text-gray-700">New Password (Optional)</label>
                        <input type="password" name="password" id="password" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" placeholder="Leave blank to keep current">
                    </div>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Permissions</label>
                    <div class="mt-2 grid grid-cols-2 md:grid-cols-3 gap-4 border p-4 rounded-md">
                        <?php foreach ($available_permissions as $key => $label): ?>
                            <label class="flex items-center">
                                <input type="checkbox" name="permissions[]" value="<?php echo $key; ?>" class="h-4 w-4 rounded" <?php echo in_array($key, $current_permissions) ? 'checked' : ''; ?>>
                                <span class="ml-2 text-sm text-gray-700"><?php echo $label; ?></span>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="flex justify-end pt-4 border-t">
                    <a href="manage_admins.php" class="px-6 py-2 text-gray-600 font-medium rounded-lg hover:bg-gray-100 mr-4">Cancel</a>
                    <button type="submit" name="update_admin" class="px-6 py-2 bg-blue-600 text-white font-semibold rounded-lg shadow hover:bg-blue-700">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</body>
</html>
