<?php
session_start();
require_once __DIR__ . '/../includes/functions.php';

$error = '';

if (isAdmin()) {
    header('Location: index.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();

    if (!rateLimit('admin_login', 7, 900)) {
        $error = 'Demasiados intentos. Espera 15 minutos antes de volver a intentar.';
    } else {
        $user = trim($_POST['username'] ?? '');
        $pass = (string)($_POST['password'] ?? '');

        $st = db()->prepare("SELECT * FROM admin_users WHERE username=? AND active=1 LIMIT 1");
        $st->execute([$user]);
        $a = $st->fetch();

        if ($a && password_verify($pass, (string)$a['password_hash'])) {
            session_regenerate_id(true);
            $_SESSION['admin_id'] = (int)$a['id'];
            $_SESSION['admin_name'] = (string)$a['name'];
            unset($_SESSION['_rate_limits']['admin_login']);

            header('Location: index.php');
            exit;
        }

        $error = 'Usuario o contraseña incorrectos.';
    }
}
?>
<!doctype html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <meta name="robots" content="noindex,nofollow">
    <title>Admin | Máscara Contra Máscara</title>
    <link rel="icon" href="../assets/img/logo.png" type="image/png">
    <link rel="stylesheet" href="assets/admin.css">
</head>
<body class="admin-login">
<form method="post" class="login-card" autocomplete="off">
    <?= csrf_field() ?>
    <img src="../assets/img/logo.png" alt="Máscara Contra Máscara">
    <h1>BACKSTAGE</h1>

    <?php if ($error): ?>
        <div class="alert"><?= e($error) ?></div>
    <?php endif; ?>

    <label>
        Usuario
        <input name="username" autocomplete="username" required autofocus>
    </label>

    <label>
        Contraseña
        <input type="password" name="password" autocomplete="current-password" required>
    </label>

    <button>ENTRAR AL PANEL</button>
    <small>Acceso administrativo de la tienda.</small>
</form>
</body>
</html>
