<?php
/**
 * ===================================================================================
 * Admin Login Page (with Role & Permission Handling)
 * ===================================================================================
 *
 * File: login.php
 * Location: /homework_portal/admin/login.php
 *
 * Purpose:
 * 1. Provides a secure login form for all administrators.
 * 2. Fetches the admin's role and permissions upon successful login.
 * 3. Saves role and permissions to the session to enable the security system.
 */

require_once '../config.php';

// If admin is already logged in, redirect them to the dashboard
if (isset($_SESSION['admin_id'])) {
    header('Location: dashboard.php');
    exit();
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    if (empty($username) || empty($password)) {
        $errors[] = "Username and password are required.";
    } else {
        try {
            // **UPDATED QUERY**: Now fetches role and permissions
            $stmt = $pdo->prepare("SELECT id, username, password_hash, role, permissions FROM super_admins WHERE username = ?");
            $stmt->execute([$username]);
            $admin = $stmt->fetch();

            if ($admin && password_verify($password, $admin['password_hash'])) {
                // Login successful
                session_regenerate_id(true);
                
                // --- ** NEW SESSION LOGIC ** ---
                // Store basic info
                $_SESSION['admin_id'] = $admin['id'];
                $_SESSION['admin_username'] = $admin['username'];

                // Store role and permissions
                if ($admin['role'] === 'super_admin') {
                    $_SESSION['is_super_admin'] = true;
                    $_SESSION['admin_permissions'] = []; // Super admin doesn't need a list, they have all access
                } else {
                    $_SESSION['is_super_admin'] = false;
                    // Decode the JSON string of permissions into an array
                    $_SESSION['admin_permissions'] = json_decode($admin['permissions'] ?? '[]', true);
                }
                
                header('Location: dashboard.php');
                exit();
            } else {
                $errors[] = "Invalid username or password.";
            }
        } catch (PDOException $e) {
            $errors[] = "A database error occurred. Please try again.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Login - TTTEDDDEL</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&family=Baloo+2:wght@700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Poppins', sans-serif; background-color: #f0f9ff; }
    </style>
</head>
<body class="flex items-center justify-center min-h-screen p-4">
    <div class="w-full max-w-md">
        <div class="text-center mb-8">
            <h1 class="text-6xl font-bold text-red-600 tracking-widest font-sans">TTTEDDDEL</h1>
            <p class="text-sm font-semibold text-blue-800 mt-1">Teacher-Student Interactive System</p>
            <p class="text-sm text-blue-800">by Ele Infocomm Technologiess</p>
        </div>
        <div class="p-8 space-y-6 bg-white rounded-2xl shadow-lg">
            <h2 class="text-2xl font-bold text-center text-gray-700">Admin Login</h2>
            
            <?php if (!empty($errors)): ?>
                <div class="p-4 text-sm text-red-800 bg-red-100 rounded-lg" role="alert">
                    <ul class="list-disc list-inside">
                        <?php foreach ($errors as $error): ?>
                            <li><?php echo e($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <form action="login.php" method="POST" class="space-y-6">
                <div>
                    <label for="username" class="block mb-2 text-sm font-medium text-gray-700">Username</label>
                    <input type="text" name="username" id="username" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-3" required>
                </div>
                <div>
                    <label for="password" class="block mb-2 text-sm font-medium text-gray-700">Password</label>
                    <input type="password" name="password" id="password" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-3" required>
                </div>
                <button type="submit" class="w-full text-white bg-blue-600 hover:bg-blue-700 focus:ring-4 focus:outline-none focus:ring-blue-300 font-bold rounded-lg text-sm px-5 py-3 text-center transition-colors">Sign In</button>
            </form>
        </div>
    </div>
</body>
</html>
