<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

require_once dirname(dirname(__DIR__)) . '/core/bootstrap.php';

$error = '';

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

    if (empty($email) || empty($password)) {
        $error = 'Email and password are required.';
    } else {
        $userModel = new User();
        $user = $userModel->login($email, $password);

        $allowed_roles = ['super_admin', 'admin', 'league_manager', 'club_manager', 'team_manager', 'referee', 'commissioner'];

        if ($user && in_array($user->role, $allowed_roles)) {
            // Regenerate session ID for security
            session_regenerate_id(true);
            $_SESSION['admin_user_id'] = $user->id;
            $_SESSION['admin_user_name'] = $user->username;
            $_SESSION['admin_user_role'] = $user->role;
            header('Location: ../dashboard.php');
            exit();
        } else {
            $error = 'Invalid credentials or insufficient permissions.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Admin Login</title>
    <link rel="stylesheet" href="../admin.css">
    <style>
        body { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f0f2f5; }
        .login-container { background: white; padding: 40px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); width: 100%; max-width: 400px; }
        .login-container h1 { text-align: center; color: #ff470f; margin-bottom: 20px; }
        .login-container form { display: flex; flex-direction: column; gap: 15px; }
        .login-container input { padding: 12px; border: 1px solid #ccc; border-radius: 5px; font-size: 1em; }
        .login-container button { padding: 12px; background-color: #ff470f; color: white; border: none; border-radius: 5px; font-size: 1em; font-weight: bold; cursor: pointer; }
        .error { color: #dc3545; text-align: center; margin-top: 15px; }
    </style>
</head>
<body>
    <div class="login-container">
        <h1>Admin Login</h1>
        <form action="login.php" method="POST">
            <input type="email" name="email" placeholder="Email" required>
            <input type="password" name="password" placeholder="Password" required>
            <button type="submit">Login</button>
        </form>
        <?php if ($error): ?>
            <p class="error"><?php echo $error; ?></p>
        <?php endif; ?>
    </div>
</body>
</html>