<?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['filtroVenta']) || !isset($datos['filtroCob']) || !isset($datos['filtroCaja'])) {
    echo json_encode(["error" => "Parámetros insuficientes"]);
    exit;
}

$filtroInicial = $datos['filtroInicial'];
$filtroVenta = $datos['filtroVenta'];
$filtroCob = $datos['filtroCob'];
$filtroCaja = $datos['filtroCaja'];

$rows = array();
$rows['SaldoInicial'] = 0.00;
$rows['Movimientos'] = array();
$rows['VentasFacturas'] = 0.00;
$rows['VentasBoletas'] = 0.00;
$rows['NotasCredito'] = 0.00;
$rows['VentasTickets'] = 0.00;
$rows['NotasVenta'] = 0.00;
$rows['Cobranza'] = 0.00;
$rows['OtrosIngresos'] = 0.00;

// Saldo Inicial
$sqlSaldoInicial = "SELECT SUM(ingreso - egreso) AS SaldoIni FROM detcaja $filtroInicial";
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 {
    echo json_encode(["error" => "ERROR: No se pudo ejecutar la consulta del saldo inicial. " . mysqli_error($conn)]);
    exit;
}

// Ventas al contado de facturas
$sqlVentasFacturas = "SELECT SUM(total) AS Cont_Facturas FROM ventas $filtroVenta AND docfiscal_id = 2";
if ($result = mysqli_query($conn, $sqlVentasFacturas)) {
    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $rows['VentasFacturas'] = $row['Cont_Facturas'];
        mysqli_free_result($result);
    }
}

// Ventas al contado de boletas
$sqlVentasBoletas = "SELECT SUM(total) AS Cont_Boletas FROM ventas $filtroVenta AND docfiscal_id = 4";
if ($result = mysqli_query($conn, $sqlVentasBoletas)) {
    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $rows['VentasBoletas'] = $row['Cont_Boletas'];
        mysqli_free_result($result);
    }
}

// Ventas al contado de notas de crédito
$sqlNotasCredito = "SELECT SUM(total) AS Cont_NotasCredito FROM ventas $filtroVenta AND docfiscal_id = 5";
if ($result = mysqli_query($conn, $sqlNotasCredito)) {
    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $rows['NotasCredito'] = $row['Cont_NotasCredito'];
        mysqli_free_result($result);
    }
}

// Ventas al contado de tickets
$sqlVentasTickets = "SELECT SUM(total) AS Cont_Tickets FROM ventas $filtroVenta AND docfiscal_id = 8";
if ($result = mysqli_query($conn, $sqlVentasTickets)) {
    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $rows['VentasTickets'] = $row['Cont_Tickets'];
        mysqli_free_result($result);
    }
}

// Ventas al contado de notas de venta
$sqlNotasVenta = "SELECT SUM(total) AS Cont_NotasVta FROM ventas $filtroVenta AND docfiscal_id = 9";
if ($result = mysqli_query($conn, $sqlNotasVenta)) {
    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $rows['NotasVenta'] = $row['Cont_NotasVta'];
        mysqli_free_result($result);
    }
}

// Cobranza de créditos
$sqlCobranza = "SELECT SUM(importe) AS Total_Cobranza FROM cobranza $filtroCob";
if ($result = mysqli_query($conn, $sqlCobranza)) {
    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $rows['Cobranza'] = $row['Total_Cobranza'];
        mysqli_free_result($result);
    }
}

// Otros ingresos
$sqlOtrosIngresos = "SELECT SUM(ingreso) AS OtrosIng FROM detcaja $filtroCaja AND operacion = 'BOX'";
if ($result = mysqli_query($conn, $sqlOtrosIngresos)) {
    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $rows['OtrosIngresos'] = $row['OtrosIng'];
        mysqli_free_result($result);
    }
}

// Movimientos de caja
$sqlMovimientoCaja = "SELECT nrecibo, nombre_partida, egreso, observacion FROM detcaja $filtroCaja AND operacion = 'BOX' AND egreso > 0";
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);
    }
}

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;
    }
}
?>
