<?php
require_once __DIR__ . '/auth.php';

if (admin_logged_in()) {
    header('Location: dashboard.php');
    exit;
}

$error = '';
$ip = client_ip();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    admin_check_csrf();

    [$locked, $minutes] = admin_lock_state($ip);
    if ($locked) {
        $error = 'Too many attempts. Try again in ' . $minutes . ' minute(s).';
    } else {
        $user = trim((string) ($_POST['username'] ?? ''));
        $pass = (string) ($_POST['password'] ?? '');

        if (hash_equals(ADMIN_USER, $user) && password_verify($pass, ADMIN_PASS_HASH)) {
            session_regenerate_id(true);
            $_SESSION['admin_ok'] = true;
            $_SESSION['admin_since'] = time();
            admin_clear_failures($ip);
            header('Location: dashboard.php');
            exit;
        }

        admin_register_failure($ip);
        $error = 'Wrong username or password.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<title>PKO @ 50 : Admin</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Cinzel:wght@400;500;600&family=Lato:wght@300;400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="admin.css?v=2">
</head>
<body class="login-page">
  <form class="login" method="post" autocomplete="on">
    <span class="brand">PKO <span class="at">@</span> 50</span>
    <h1>Guest list access</h1>
    <input type="hidden" name="csrf" value="<?= e(admin_csrf()) ?>">

    <?php if ($error !== ''): ?>
      <p class="alert"><?= e($error) ?></p>
    <?php endif; ?>

    <label for="username">Username</label>
    <input type="text" id="username" name="username" autocomplete="username" required autofocus>

    <label for="password">Password</label>
    <input type="password" id="password" name="password" autocomplete="current-password" required>

    <button type="submit">Sign in</button>
  </form>
</body>
</html>
