<?php
require_once __DIR__.'/../config/config.php';
require_once __DIR__.'/../config/database.php';
require_once __DIR__.'/../includes/functions.php';
require_once __DIR__.'/../includes/admin_functions.php';
require_once __DIR__.'/../includes/admin_auth_view.php';

if (afAdminValidateSession($pdo)) { header('Location: '.SITE_URL.'/pages/admin.php'); exit; }
try { if (afAdminCount($pdo) === 0) { header('Location: '.SITE_URL.'/admin/setup.php'); exit; } } catch (Throwable $e) {}
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (!validarCsrfToken($_POST[CSRF_TOKEN_NAME] ?? '')) throw new RuntimeException('Sessão expirada. Recarregue a página.');
        afAdminLogin($pdo, (string)($_POST['email'] ?? ''), (string)($_POST['senha'] ?? ''), !empty($_POST['lembrar']));
        $return = (string)($_SESSION['admin_return_to'] ?? ''); unset($_SESSION['admin_return_to']);
        if ($return !== '' && str_starts_with($return, '/')) { header('Location: '.$return); } else { header('Location: '.SITE_URL.'/pages/admin.php'); }
        exit;
    } catch (Throwable $e) { $error = $e->getMessage(); }
}
afAdminAuthStart('Entrar no painel', 'Use a conta administrativa. Ela é separada da conta de jogador.');
if ($error !== '') echo '<div class="admin-auth-alert">'.esc($error).'</div>';
?>
<form method="post" class="admin-auth-form">
  <?=camposCsrf()?>
  <label>E-mail<input type="email" name="email" maxlength="190" autocomplete="username" required value="<?=esc($_POST['email'] ?? '')?>"></label>
  <label>Senha<input type="password" name="senha" autocomplete="current-password" required></label>
  <label class="admin-auth-check"><input type="checkbox" name="lembrar" value="1"> Manter conectado neste dispositivo</label>
  <button class="admin-auth-button" type="submit">ENTRAR NO PAINEL</button>
</form>
<div class="admin-auth-links"><a href="<?=SITE_URL?>/">← Voltar ao site</a><a href="<?=SITE_URL?>/admin/recuperar.php">Esqueci minha senha</a></div>
<?php afAdminAuthEnd();
