<?php
require_once('../models/usuario.php');

$boton = $_POST['boton'];

if ($boton === 'cerrar') {
    session_start();
    session_unset();
    session_destroy();
    exit;
}

if ($boton === 'ingresar') {
    $usuario = $_POST['usuario'];
    $pass = $_POST['pass'];

    $ins = new insertar();
    $array = $ins->identificar($usuario, $pass);

    if ($array[0] == 0) {
        echo 0; // login incorrecto
    } else {
        session_start();
        $_SESSION['ingreso'] = 'YES';
        $_SESSION['idusuario'] = $array[0];
        $_SESSION['usuario'] = $array[1];
        $_SESSION['permiso'] = $array[4];
        $_SESSION['id_registro'] = $array[6];
        $_SESSION['id_bodega'] = $array[7];
        $_SESSION['id_empresa'] = $array[8];

        // 🛡️ Seguridad agregada:
        $_SESSION['ip_cliente'] = $_SERVER['REMOTE_ADDR'];
        $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
        $_SESSION['ultimo_movimiento'] = time();
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));

        //echo 1; // login OK
        // Seguridad avanzada
		$_SESSION['ip_cliente'] = $_SERVER['REMOTE_ADDR'];
		$_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
		$_SESSION['ultimo_movimiento'] = time();
		$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

		// Guardar token CSRF en cookie segura
		setcookie('csrf_token', $_SESSION['csrf_token'], [
		    'expires' => time() + 3600, // 1 hora
		    'path' => '/',
		    'secure' => isset($_SERVER['HTTPS']), // Solo en HTTPS
		    'httponly' => false, // true si no usarás JS para leerla
		    'samesite' => 'Strict'
		]);

    }
}
?>
