<?php
require_once __DIR__ . '/../config.php';
startSecureSession();

if (!empty($_SESSION['admin_id'])) {
    header('Location: ' . BASE_URL . '/admin/dashboard.php');
    exit;
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email    = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $bucket   = 'admin_login:' . clientIp() . ':' . strtolower($email);
    $gate     = loginThrottleAllowed($bucket);

    if (!csrfValid()) {
        $error = 'Security token expired. Please try again.';
    } elseif (!$gate['allowed']) {
        $error = 'Too many failed attempts. Try again in ' . ceil($gate['retry_after'] / 60) . ' minute(s).';
    } else {
        $stmt = db()->prepare('SELECT id, name, password, role, status FROM admins WHERE email = ?');
        $stmt->execute([$email]);
        $admin = $stmt->fetch();

        if ($admin && password_verify($password, $admin['password'])) {
            if (($admin['status'] ?? 'active') === 'pending') {
                $error = 'Your account is not yet activated. Check your email for an activation link.';
            } else {
                loginThrottleClear($bucket);
                session_regenerate_id(true);   // prevent session fixation
                $_SESSION['admin_id']   = $admin['id'];
                $_SESSION['admin_name'] = $admin['name'];
                $_SESSION['admin_role'] = $admin['role'];
                header('Location: ' . BASE_URL . '/admin/dashboard.php');
                exit;
            }
        } else {
            loginThrottleFail($bucket);
            $error = 'Invalid credentials. Please try again.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin Login — RSVP System</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" media="print" onload="this.media='all'" href="https://fonts.googleapis.com/css2?family=Syne:wght@400;600;700;800&family=DM+Sans:wght@300;400;500&display=swap">
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/main.css">
</head>
<body>
<div class="login-wrap">
  <div class="login-card">
    <div class="login-logo">
      <div class="name">RSVP</div>
      <div class="sub">Admin Portal</div>
    </div>

    <?php if ($error): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <form method="POST">
      <?= csrfField() ?>
      <div class="form-group">
        <label class="form-label">Email Address</label>
        <input class="form-control" type="email" name="email"
               value="<?= htmlspecialchars($_POST['email'] ?? '') ?>"
               autocomplete="email" required>
      </div>
      <div class="form-group">
        <label class="form-label">Password</label>
        <input class="form-control" type="password" name="password"
               autocomplete="current-password" required>
      </div>
      <button class="btn btn-gold w-100 mt-3" type="submit">Sign In</button>
    </form>
    <p style="text-align:center;margin-top:16px">
      <a href="<?= BASE_URL ?>/admin/forgot_password.php" class="text-muted text-sm">Forgot your password?</a>
    </p>
  </div>
</div>
</body>
</html>
