<?php
error_reporting(E_ALL);
header("Access-Control-Allow-Methods: POST");
header("Content-Type: application/json; charset=utf-8");

include_once '../conexion.php';
include_once '../clases/TokenValidator.php';

// Llama la validación antes de cualquier consulta
$usuarioId = TokenValidator::validar($conn);

try {
    $bodyRequest = file_get_contents("php://input");
    $datos = json_decode($bodyRequest, true);

    if (!isset($datos[0])) {
        throw new Exception("Parámetro ID requerido.");
    }

    $id_orden = (int)$datos[0];

    $sql = "SELECT * FROM consultar_ordalm_id(:id_orden)";
    $stmt = $conn->prepare($sql);
    $stmt->bindValue(':id_orden', $id_orden, PDO::PARAM_INT);
    $stmt->execute();

    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode($result, JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        "error" => "ERROR: " . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
} finally {
    $conn = null;
}
?>