<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type");

include_once '../conexion.php';

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

if (!isset($datos['filtroInicial']) || !isset($datos['filtro'])) {
    echo json_encode(["error" => "Par¨¢metros insuficientes"]);
    exit;
}

$filtroInicial = $datos['filtroInicial'];
$filtro = $datos['filtro'];

$sqlSaldoInicial = "SELECT SUM(ingreso - egreso) AS SaldoIni FROM detcaja WHERE $filtroInicial";
$sqlMovimientoCaja = "SELECT id, fecha_operacion, nrecibo, nombre_partida, ingreso, egreso, observacion FROM detcaja WHERE $filtro";

$rows = array();
$rows['SaldoInicial'] = 0.00;
$rows['Movimientos'] = array();

if ($result = mysqli_query($conn, $sqlSaldoInicial)) {
    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $rows['SaldoInicial'] = $row['SaldoIni'];
        mysqli_free_result($result);
    } else {
        $rows['SaldoInicial'] = 0.00;
    }
} else {
    echo json_encode(["error" => "ERROR: No se pudo ejecutar la consulta del saldo inicial. " . mysqli_error($conn)]);
    exit;
}

if ($result = mysqli_query($conn, $sqlMovimientoCaja)) {
    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $rows['Movimientos'][] = $row;
        }
        mysqli_free_result($result);
    } else {
        $rows['Movimientos'] = [];
    }
} else {
    echo json_encode(["error" => "ERROR: No se pudo ejecutar la consulta de movimientos de caja. " . mysqli_error($conn)]);
    exit;
}

mysqli_close($conn);

// Envolver la respuesta en un JSONArray
print_json(array($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;
    }
}
?>
