<?php
session_start();
include("conexion.php");

// Validar método POST
if($_SERVER['REQUEST_METHOD'] !== 'POST'){
    header("Location: login.php");
    exit;
}

// Rate limiting básico por sesión
if(!isset($_SESSION['login_intentos'])){
    $_SESSION['login_intentos'] = 0;
    $_SESSION['login_ultimo'] = time();
}

// Reiniciar después de 15 minutos
if(time() - $_SESSION['login_ultimo'] > 900){
    $_SESSION['login_intentos'] = 0;
}

$_SESSION['login_intentos']++;
$_SESSION['login_ultimo'] = time();

if($_SESSION['login_intentos'] > 5){
    header("Location: login.php?error=bloqueado");
    exit;
}

$user = sanitizar($_POST['usuario'] ?? '');
$pass = $_POST['password'] ?? '';

if(empty($user) || empty($pass)){
    header("Location: login.php?error=1");
    exit;
}

$stmt = $conexion->prepare("SELECT * FROM usuarios WHERE usuario=?");
$stmt->bind_param("s", $user);
$stmt->execute();
$result = $stmt->get_result();

if($result->num_rows > 0){
    $datos = $result->fetch_assoc();

    if(password_verify($pass, $datos['password'])){
        // Reiniciar intentos de login
        $_SESSION['login_intentos'] = 0;

        session_regenerate_id(true);
        $_SESSION['admin'] = $datos['usuario'];
        $_SESSION['rol'] = $datos['rol'];
        $_SESSION['nombre_usuario'] = $datos['nombre_completo'] ?? $datos['usuario'];

        header("Location: loading.php");
        exit;
    }
}

$stmt->close();
header("Location: login.php?error=1");
exit;
?>