<?php
require_once __DIR__ . '/inc/helpers.php';

// En login todavía NO hay sesión, pero podemos intentar migración segura
// para evitar "Unknown column avatar_url" en instalaciones antiguas.
ensure_schema_safe();

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

$pdo = db();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $username = trim((string)($_POST['username'] ?? ''));
  $password = (string)($_POST['password'] ?? '');

  // Si la columna avatar_url no existe aún, no la pedimos.
  $hasAvatar = table_exists('users') && table_has_column('users','avatar_url');
  $sql = $hasAvatar
    ? "SELECT id, username, password_hash, is_admin, avatar_url FROM users WHERE username=? LIMIT 1"
    : "SELECT id, username, password_hash, is_admin FROM users WHERE username=? LIMIT 1";

  $st = $pdo->prepare($sql);
  $st->execute([$username]);
  $u = $st->fetch();

  if (!$u || !password_verify($password, $u['password_hash'])) {
    flash_set('danger', 'Usuario o contraseña incorrectos.');
    redirect('login.php');
  }

  $_SESSION['user'] = [
    'id' => (int)$u['id'],
    'username' => $u['username'],
    'is_admin' => (int)($u['is_admin'] ?? 0),
    'avatar_url' => $u['avatar_url'] ?? null
  ];

  flash_set('success', 'Bienvenido.');
  redirect('dashboard.php');
}

$flash = flash_get();
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Login</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
  <div class="container" style="max-width:420px; margin-top:10vh;">
    <?php foreach($flash as $f): ?>
      <div class="alert alert-<?= h($f['type']) ?>"><?= h($f['msg']) ?></div>
    <?php endforeach; ?>

    <div class="card shadow-sm">
      <div class="card-body">
        <h5 class="mb-3">Acceso</h5>
        <form method="post" autocomplete="off">
          <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
          <div class="mb-3">
            <label class="form-label">Usuario</label>
            <input class="form-control" name="username" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Contraseña</label>
            <input class="form-control" type="password" name="password" required>
          </div>
          <button class="btn btn-primary w-100">Entrar</button>
        </form>
      </div>
    </div>
  </div>
</body>
</html>
