<?php
declare(strict_types=1);

/* --- Início: NUNCA remova o bloco PHP antes do HTML --- */
ob_start(); // evita "headers already sent" por BOM/whitespace

// Segurança básica de sessão
$cookieParams = session_get_cookie_params();
session_set_cookie_params([
  'lifetime' => 0,
  'path'     => $cookieParams['path'] ?? '/',
  'domain'   => $cookieParams['domain'] ?? '',
  'secure'   => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
  'httponly' => true,
  'samesite' => 'Lax',
]);
ini_set('session.use_strict_mode', '1');
session_start();

// Conexão PDO
require __DIR__.'/../db/config.php'; // ajuste se seu caminho for outro

// Para onde redirecionar após login
$defaultRedirect = '/roulette-admin-v6/admin/index.php';
$redirect = $_POST['redirect'] ?? $_GET['redirect'] ?? $defaultRedirect;

// Sanitiza redirect (somente caminhos relativos locais)
$redirect = is_string($redirect) ? $redirect : $defaultRedirect;
if (!preg_match('#^/[A-Za-z0-9._~/%\-\?\=&]*$#', $redirect)) {
  $redirect = $defaultRedirect;
}

// Se já estiver logado, manda embora
if (!empty($_SESSION['auth']['user_id'])) {
  header('Location: '.$redirect);
  exit;
}

$msg = '';
if (isset($_GET['expired']))   $msg = 'Sua sessão expirou. Faça login novamente.';
if (isset($_GET['loggedout'])) $msg = 'Você saiu com segurança.';
if (isset($_GET['denied']))    $msg = 'Acesso negado. Faça login.';

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

  $st = $pdo->prepare("SELECT id, username, password_hash FROM admins WHERE username = ?");
  $st->execute([$username]);
  $u = $st->fetch(PDO::FETCH_ASSOC);

  if ($u && password_verify($password, $u['password_hash'])) {
    session_regenerate_id(true);
    $_SESSION['auth'] = [
      'user_id'   => (int)$u['id'],
      'username'  => (string)$u['username'],
      'login_at'  => time(),
      'expires_at'=> time() + 15*60, // 15 min
    ];
    header('Location: '.$redirect); // <-- redireciona aqui
    exit;
  } else {
    $msg = 'Usuário ou senha inválidos.';
  }
}
/* --- Fim do bloco PHP crítico --- */
?>
<!doctype html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Login • Admin</title>
<style>
  *,*::before,*::after{box-sizing:border-box}
  :root{
    --bg1:#0b1020;--bg2:#0e1430;--card:#111827;--line:#2a3444;
    --text:#e5e7eb;--error:#fca5a5;--p1:#3b82f6;--p2:#06b6d4;--focus:rgba(59,130,246,.25)
  }
  html,body{height:100%}
  body{
    margin:0;color:var(--text);font-family:system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial;
    display:grid;place-items:center;padding:24px;
    background:
      radial-gradient(1200px 800px at 15% 10%, rgba(59,130,246,.08), transparent 60%),
      radial-gradient(1200px 800px at 85% 90%, rgba(6,182,212,.08), transparent 60%),
      linear-gradient(180deg,var(--bg1),var(--bg2));
  }
  .card{
    width:min(440px,94vw);background:var(--card);border:1px solid var(--line);
    border-radius:16px;padding:22px;box-shadow:0 20px 60px rgba(0,0,0,.45);overflow:hidden
  }
  h1{margin:0 0 8px;font:800 22px/1.2 system-ui}
  .msg{min-height:1.2em;margin:6px 0 10px;color:var(--error);font-weight:700;word-wrap:break-word}
  label{display:block;margin:12px 0 6px;color:#cbd5e1;font-weight:600;font-size:14px}
  .input{
    width:100%;padding:11px 12px;border-radius:12px;border:1px solid var(--line);
    background:#0b1224;color:#fff;outline:none;transition:border-color .15s,box-shadow .15s
  }
  .input:focus{border-color:var(--p1);box-shadow:0 0 0 3px var(--focus)}
  .btn{
    margin-top:16px;width:100%;padding:12px;border:0;border-radius:12px;font-weight:800;color:#fff;cursor:pointer;
    background:linear-gradient(90deg,var(--p1),var(--p2));box-shadow:0 12px 30px rgba(3,105,161,.35)
  }
  .btn:hover{filter:brightness(1.06)} .btn:active{transform:translateY(1px)}
</style>
</head>
<body>
  <form class="card" method="post" action="">
    <h1>Área Administrativa</h1>
    <div class="msg"><?= htmlspecialchars($msg ?? '') ?></div>

    <label for="user">Usuário</label>
    <input id="user" name="username" class="input" autocomplete="username" required>

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

    <!-- carrega redirect seguro -->
    <input type="hidden" name="redirect" value="<?= htmlspecialchars($redirect, ENT_QUOTES) ?>">

    <button type="submit" class="btn">Entrar</button>
  </form>
</body>
</html>
