<?php
error_reporting(E_ALL ^ E_NOTICE);

header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
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], $datos[1])) {
        throw new Exception("Parámetros incompletos.");
    }

    // Preparar y ejecutar el procedimiento almacenado
    $stmt = $conn->prepare("SELECT * FROM listar_operaciones(:empresa_id, :filtro)");
    $stmt->bindParam(':empresa_id', $datos[0], PDO::PARAM_INT);
    $stmt->bindParam(':filtro', $datos[1], PDO::PARAM_STR);
    $stmt->execute();

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

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(["error" => "Error de base de datos: " . $e->getMessage()]);
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(["error" => "Error: " . $e->getMessage()]);
} finally {
    if (isset($stmt)) $stmt = null;
    if (isset($conn)) $conn = null;
}

function print_json($data) {
    echo json_encode($data, JSON_UNESCAPED_UNICODE);

    switch (json_last_error()) {
        case JSON_ERROR_NONE: break;
        case JSON_ERROR_DEPTH: echo ' - Maximum stack depth exceeded'; break;
        case JSON_ERROR_STATE_MISMATCH: echo ' - Underflow or the modes mismatch'; break;
        case JSON_ERROR_CTRL_CHAR: echo ' - Unexpected control character found'; break;
        case JSON_ERROR_SYNTAX: echo ' - Syntax error, malformed JSON'; break;
        case JSON_ERROR_UTF8: echo ' - Malformed UTF-8 characters, possibly incorrectly encoded'; break;
        default: echo ' - Unknown error'; break;
    }
}
?>
