<?php
// admin/login.php
@session_start();
require_once '../db.php';

if (!empty($_SESSION['admin_id'])) {
    header('Location: panel.php');
    exit;
}

$pdo = pdo();
$errores = '';

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

    if ($usuario === '' || $password === '') {
        $errores = 'Completá usuario y contraseña.';
    } else {
        $stmt = $pdo->prepare("SELECT * FROM usuarios_admin WHERE usuario = :usuario AND activo = 1 LIMIT 1");
        $stmt->execute([':usuario' => $usuario]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password_hash'])) {
            $_SESSION['admin_id']     = $user['id'];
            $_SESSION['admin_usuario'] = $user['usuario'];
            $_SESSION['admin_rol']     = $user['rol'];

            $pdo->prepare("UPDATE usuarios_admin SET ultimo_login = NOW() WHERE id = :id")
                ->execute([':id' => $user['id']]);

            header('Location: panel.php');
            exit;
        } else {
            $errores = 'Usuario o contraseña incorrectos.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Login - Cabañas Santiago</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light d-flex align-items-center" style="min-height:100vh;">
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-4">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h4 class="mb-3 text-center">Panel Administrativo</h4>

                    <?php if ($errores): ?>
                        <div class="alert alert-danger py-2"><?php echo htmlspecialchars($errores); ?></div>
                    <?php endif; ?>

                    <form method="post" autocomplete="off">
                        <div class="mb-3">
                            <label class="form-label">Usuario</label>
                            <input type="text" name="usuario" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Contraseña</label>
                            <input type="password" name="password" class="form-control" required>
                        </div>
                        <button class="btn btn-primary w-100" type="submit">Ingresar</button>
                    </form>
                </div>
            </div>
            <p class="text-center text-muted mt-3 mb-0" style="font-size:0.85rem;">
                Cabañas Santiago - Sistema Interno
            </p>
        </div>
    </div>
</div>
</body>
</html>
