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

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    if (!verify_csrf($token)) {
        $errors[] = 'Token inválido.';
    } else {
        $userOrEmail = $_POST['username'] ?? '';
        $password = $_POST['password'] ?? '';
        $u = verify_user($userOrEmail, $password);
        if ($u === false) {
            $errors[] = 'Usuário ou senha inválidos.';
        } else {
            login_user($u);
            header('Location: index.php');
            exit;
        }
    }
}

$token = csrf_token();
?>
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Login - Gerador de Banners</title>
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<style>
body { background: linear-gradient(160deg,#0f172a,#1e293b); color:#e6eef8; font-family:Inter,system-ui,Segoe UI,Arial; }
.card { background: rgba(255,255,255,0.03); backdrop-filter: blur(8px); border:1px solid rgba(255,255,255,0.04); }
</style>
</head>
<body class="min-h-screen flex items-center justify-center p-4">
  <div class="card rounded-xl w-full max-w-md p-8">
    <div class="text-center mb-6">
      <h1 class="text-3xl font-bold">Acesse sua conta</h1>
      <p class="text-sm text-slate-400">Entre para gerar banners exclusivos</p>
    </div>

    <?php if (!empty($errors)): ?>
      <div class="mb-4 p-3 bg-red-900/20 rounded text-sm">
        <?php foreach($errors as $e): ?><div><?php echo htmlspecialchars($e); ?></div><?php endforeach; ?>
      </div>
    <?php endif; ?>

    <form method="post" class="space-y-4">
      <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($token); ?>">
      <div>
        <label class="block text-sm mb-1">Usuário ou Email</label>
        <input name="username" required class="w-full p-3 rounded" value="<?php echo isset($_POST['username'])?htmlspecialchars($_POST['username']):''; ?>">
      </div>
      <div>
        <label class="block text-sm mb-1">Senha</label>
        <input name="password" type="password" required class="w-full p-3 rounded">
      </div>
      <div class="flex gap-2">
        <button type="submit" class="w-full bg-indigo-600 hover:bg-indigo-700 py-3 rounded font-semibold">Entrar</button>
      </div>
      <div class="text-center text-sm mt-2">
        <a href="register.php" class="text-indigo-300">Criar conta</a>
      </div>
    </form>
  </div>
</body>
</html>