<?php
error_reporting(E_ALL ^ E_NOTICE);

include_once '../conexion.php';

// Permitir la conexi¨®n desde cualquier origen
header("Access-Control-Allow-Origin: *");
// Permitir la ejecuci¨®n de los m¨¦todos
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");

// Obtener los datos combinados del cuerpo de la solicitud
$datos = json_decode(file_get_contents("php://input"), true);

// Verificar si la decodificaci¨®n JSON fue exitosa
if (json_last_error() !== JSON_ERROR_NONE) {
    print_json(['error' => 'Malformed JSON: ' . json_last_error_msg()]);
    exit;
}

$sql = "Call Listar_SalidaSeries(?, ?)";
$rows = array();

$stmt = $conn->prepare($sql);
$stmt->bind_param("is", $datos[0], $datos[1]);
$stmt->execute();
$result = $stmt->get_result();

if ($result) {
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }
        $result->free();
    } else {
        print_json([]);
    }
} else {
    print_json(['error' => 'ERROR: Could not execute the query.']);
}

$stmt->close();
$conn->close();

print_json($rows);

function print_json($data) {
    header("Content-type: application/json; charset=utf-8");
    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;
    }
}
?>
