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

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

require_once '../includes/db.php';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    
    if (empty($email) || empty($password)) {
        $error_message = "Please enter both email and password.";
    } else {
        $stmt = $conn->prepare("SELECT * FROM admins WHERE email = ? LIMIT 1");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $admin = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if ($admin && password_verify($password, $admin['password'])) {
            session_regenerate_id(true);
            $_SESSION['admin_id'] = $admin['id'];
            $_SESSION['admin_role'] = 'admin';
            $_SESSION['admin_full_name'] = $admin['full_name'];
            
            // This forces the session to save before redirecting
            session_write_close();
            
            header("Location: dashboard.php");
            exit();
        } else {
            $error_message = "Invalid credentials. Please try again.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en" data-bs-theme="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Portal Login</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <style> body { background-color: var(--bs-body-bg); } </style>
</head>
<body>
    <div class="container"><div class="row justify-content-center align-items-center vh-100"><div class="col-md-6 col-lg-4"><div class="text-center mb-4"><i class="bi bi-shield-lock-fill fs-1"></i><h1 class="h3 mt-2">Admin Portal</h1></div><div class="card shadow-sm border-0"><div class="card-body p-4"><?php if ($error_message): ?><div class="alert alert-danger"><?php echo $error_message; ?></div><?php endif; ?><form method="POST"><div class="mb-3"><label for="email" class="form-label">Email address</label><input type="email" class="form-control" id="email" name="email" required autofocus></div><div class="mb-3"><label for="password" class="form-label">Password</label><input type="password" class="form-control" id="password" name="password" required></div><div class="d-grid mt-4"><button type="submit" class="btn btn-primary btn-lg">Sign In</button></div></form></div></div><div class="text-center mt-3"><a href="../index.php" class="text-muted small">← Back to Main Site</a></div></div></div></div>
</body>
</html>
