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

if (!empty($_SESSION['checker_id'])) {
    header('Location: ' . BASE_URL . '/checker/scan.php');
    exit;
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $eventId  = (int)($_POST['event_id'] ?? 0);
    $bucket   = 'checker_login:' . clientIp() . ':' . strtolower($username);
    $gate     = loginThrottleAllowed($bucket);

    $db = db();

    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 {
        // Match on username + password only — never expose the global event list.
        $stmt = $db->prepare('SELECT c.*, e.title AS etitle, e.slug AS eslug
                              FROM checkers c JOIN events e ON e.id = c.event_id
                              WHERE c.username = ?');
        $stmt->execute([$username]);
        $matched = [];
        foreach ($stmt->fetchAll() as $r) {
            if (password_verify($password, $r['password'])) $matched[] = $r;
        }

        if (count($matched) === 1) {
            $checker = $matched[0];
            loginThrottleClear($bucket);
            session_regenerate_id(true);   // prevent session fixation

            $_SESSION['checker_id']    = $checker['id'];
            $_SESSION['checker_name']  = $checker['name'];
            $_SESSION['checker_event'] = $checker['event_id'];
            $_SESSION['event_title']   = $checker['etitle'] ?? '';
            $_SESSION['event_slug']    = $checker['eslug'] ?? '';

            header('Location: ' . BASE_URL . '/checker/scan.php');
            exit;
        } elseif (count($matched) > 1) {
            // Same username+password reused across events — ask the organiser to disambiguate.
            $error = 'This login is used for more than one event. Ask your organiser for a unique username.';
        } else {
            loginThrottleFail($bucket);
            $error = 'Invalid credentials.';
        }
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Checker Login — RSVP</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">Check-in 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">Username</label>
        <input class="form-control" type="text" name="username" autocomplete="username" 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>
  </div>
</div>
</body>
</html>
