<?php

declare(strict_types=1);

require_once __DIR__ . '/includes/bootstrap.php';

if (current_user()) {
    redirect('/dashboard.php');
}

$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $email = trim((string) ($_POST['email'] ?? ''));
    $pass = (string) ($_POST['password'] ?? '');
    if ($email === '' || $pass === '') {
        $error = 'Completa correo y contraseña.';
    } elseif (!attempt_login($email, $pass)) {
        $error = 'Credenciales incorrectas o usuario inactivo.';
    } else {
        redirect('/dashboard.php');
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Iniciar sesión · <?= h(APP_NAME) ?></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=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="<?= h(url('assets/css/app.css')) ?>">
</head>
<body class="login-page">
  <div class="login-card">
    <h1>Bienvenido</h1>
    <p class="sub">Accede al panel de <?= h(APP_NAME) ?> con tu cuenta.</p>
    <?php if ($error) : ?>
      <div class="alert alert-error"><?= h($error) ?></div>
    <?php endif; ?>
    <form method="post" action="">
      <?= csrf_field() ?>
      <label class="field" for="email">Correo electrónico</label>
      <input type="email" id="email" name="email" required autocomplete="username" value="<?= h($_POST['email'] ?? '') ?>">
      <label class="field" for="password" style="margin-top:1rem;">Contraseña</label>
      <input type="password" id="password" name="password" required autocomplete="current-password">
      <div style="margin-top:1.25rem;">
        <button type="submit" class="btn btn-primary" style="width:100%;">Entrar</button>
      </div>
    </form>
    <p style="margin-top:1.25rem;font-size:0.85rem;color:#64748b;">
      Usuario demo: <code>admin@campeonato.local</code> · contraseña: <code>password</code>
    </p>
  </div>
</body>
</html>
