<?php
include 'is_logged.php';
require_once "../db.php";
require_once "../php_conexion.php";
require_once "../funciones.php";

$id_moneda = get_row('perfil', 'moneda', 'id_perfil', 1);
$fecha_actual = date('Y-m-d');
$hora_actual = date('H:i');

// =================== CAJA ACTUAL =====================
$sqlCaja = mysqli_query($conexion, "SELECT * FROM detalle_caja WHERE estado_caja = 0 LIMIT 1");
$saldo_inicial = 0;
$id_caja = null;

if ($rw = mysqli_fetch_array($sqlCaja)) {
    $id_caja = $rw['caja_id'];
    $saldo_inicial = floatval($rw['s_inicial']);
}


// =================== VENTAS =====================
$sqlVentas = "SELECT monto_factura FROM facturas_ventas WHERE control_caja = '$id_caja'";
$resultVentas = $conexion->query($sqlVentas);
$totalVenta = 0;
while ($row = $resultVentas->fetch_assoc()) {
    $totalVenta += $row['monto_factura'];
}

// =================== COMPRAS =====================
$sqlCompras = "SELECT monto_factura FROM facturas_compras WHERE condiciones = 1 AND control_caja = '$id_caja'";
$resultCompras = $conexion->query($sqlCompras);
$totalCompra = 0;
while ($row = $resultCompras->fetch_assoc()) {
    $totalCompra += $row['monto_factura'];
}

// =================== EGRESOS =====================
$sqlEgresos = "SELECT SUM(monto_caja) AS total_egresos FROM caja_chica WHERE control_caja = '$id_caja'";
$resultEgresos = $conexion->query($sqlEgresos);
$totalEgresos = 0;
if ($row = $resultEgresos->fetch_assoc()) {
    $totalEgresos = floatval($row['total_egresos']);
}

// =================== FORMAS DE PAGO =====================
$pagoPorForma = [];
$sqlPagos = "
    SELECT pago_codigo AS codigo_pago, 
           SUM(monto_factura) AS total_pago 
    FROM facturas_ventas 
    WHERE control_caja = '$id_caja'
    GROUP BY pago_codigo
";
$resultPagos = $conexion->query($sqlPagos);

// Catálogo
$formaPagoMap = [];
$catalogo = $conexion->query("SELECT codigo, descripcion FROM catalogo_forma_pago");
while ($row = $catalogo->fetch_assoc()) {
    $formaPagoMap[$row['codigo']] = $row['descripcion'];
}

$totalGeneralPagos = 0;
$efectivoRecibido = 0;

while ($row = $resultPagos->fetch_assoc()) {
    $codigo = $row['codigo_pago'];
    $descripcion = $formaPagoMap[$codigo] ?? "Código $codigo";
    $monto = $row['total_pago'];
    $totalGeneralPagos += $monto;

    if ($codigo === '01') {
        $efectivoRecibido += $monto;
    }

    $pagoPorForma[] = [
        'codigo' => $codigo,
        'descripcion' => $descripcion,
        'total' => $monto
    ];
}

// =================== TOTAL REAL EN CAJA FÍSICA =====================
$totalRealCajaFisica = ($saldo_inicial + $efectivoRecibido) - ($totalCompra + $totalEgresos);
?>

<!-- =================== INTERFAZ =================== -->
 <input type="hidden" name="id_caja" value="<?php echo $id_caja; ?>">
<div class="card shadow-sm border-0 mb-4">
    <div class="card-body">
        <div class="row">
            <div class="col-md-4">
                <label><strong>📅 Fecha:</strong></label>
                <input type="date" class="form-control" name="fecha" value="<?php echo $fecha_actual; ?>" readonly>
            </div>
            <div class="col-md-4">
                <label><strong>🕒 Hora:</strong></label>
                <input type="time" class="form-control" name="hora" value="<?php echo $hora_actual; ?>" readonly>
            </div>
            <div class="col-md-4">
                <label><strong>🔐 Saldo Inicial de Caja:</strong></label>
                <input type="text" class="form-control bg-light"
                       value="<?php echo $id_moneda . ' ' . number_format($saldo_inicial, 2); ?>" readonly>
            </div>
        </div>
    </div>
</div>

<div class="card shadow-sm border-0 mb-4">
    <div class="card-body">
        <div class="row">
            <div class="col-md-4">
                <label><strong>💰 Total Ventas (Todos los métodos):</strong></label>
                <input type="text" class="form-control bg-light"
                       value="<?php echo $id_moneda . ' ' . number_format($totalGeneralPagos, 2); ?>" readonly>
            </div>
            <div class="col-md-4">
                <label><strong>📦 Total Compras:</strong></label>
                <input type="text" class="form-control bg-light"
                       value="<?php echo $id_moneda . ' ' . number_format($totalCompra, 2); ?>" readonly>
            </div>
            <div class="col-md-4">
                <label><strong>📤 Egresos Caja Chica:</strong></label>
                <input type="text" class="form-control bg-warning-subtle"
                       value="<?php echo $id_moneda . ' ' . number_format($totalEgresos, 2); ?>" readonly>
            </div>
        </div>
    </div>
</div>

<!-- =================== DESGLOSE DE FORMAS DE PAGO =================== -->
<div class="card border-info shadow-sm mb-3">
    <div class="card-header bg-info text-white font-weight-bold">
        <i class="fa fa-credit-card-alt"></i> Desglose por Forma de Pago
    </div>
    <div class="card-body p-2">
        <table class="table table-sm table-bordered table-striped mb-0">
            <thead class="thead-light">
                <tr>
                    <th>🧾 Forma de Pago</th>
                    <th class="text-right">💲 Monto Total</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($pagoPorForma as $index => $pago): ?>
    <tr>
        <td><?php echo htmlspecialchars($pago['descripcion']); ?></td>
        <td class="text-right"><?php echo $id_moneda . ' ' . number_format($pago['total'], 2); ?></td>
    </tr>
    <input type="hidden" name="pagos[<?php echo $index; ?>][codigo]" value="<?php echo $pago['codigo']; ?>">
    <input type="hidden" name="pagos[<?php echo $index; ?>][descripcion]" value="<?php echo htmlspecialchars($pago['descripcion']); ?>">
    <input type="hidden" name="pagos[<?php echo $index; ?>][monto]" value="<?php echo $pago['total']; ?>">
<?php endforeach; ?>

                <tr class="table-secondary font-weight-bold">
                    <td class="text-right">Total Ingresos</td>
                    <td class="text-right"><?php echo $id_moneda . ' ' . number_format($totalGeneralPagos, 2); ?></td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<!-- =================== TOTAL REAL EN CAJA FÍSICA =================== -->
<div class="card shadow border-0 mt-4">
    <div class="card-body text-center bg-gradient bg-dark text-dark rounded">
        <h4 class="mb-3">
            <i class="fa fa-cash-register"></i> TOTAL REAL EN CAJA FÍSICA
        </h4>
        <h1 class="display-4 fw-bold text-success">
            <?php echo $id_moneda . ' ' . number_format($totalRealCajaFisica, 2); ?>
        </h1>
        <p class="mb-4 text-dark-50">
            Saldo Inicial + Efectivo Recibido − Compras − Egresos
        </p>

        <div class="row justify-content-center">
            <div class="col-md-6 col-lg-4">
                <label for="efectivo_usuario" class="form-label text-dark"><strong>💵 Efectivo Declarado por Usuario:</strong></label>
                <input type="number" step="0.01" name="efectivo_usuario" class="form-control text-center fs-5" id="efectivo_usuario" placeholder="Ej. 250.00">
            </div>
        </div>

        <div class="mt-4">
            <h5 class="text-dark">⚖️ Diferencia</h5>
            <div id="diferencia_caja" class="fw-bold fs-3">--</div>
        </div>
    </div>
</div>
<input type="hidden" name="saldo_inicial" value="<?php echo $saldo_inicial; ?>">
<input type="hidden" name="total_ventas" value="<?php echo $totalGeneralPagos; ?>">
<input type="hidden" name="total_compras" value="<?php echo $totalCompra; ?>">
<input type="hidden" name="total_egresos" value="<?php echo $totalEgresos; ?>">
<input type="hidden" name="total_real" value="<?php echo $totalRealCajaFisica; ?>">

<!-- =================== JS: CÁLCULO DE DIFERENCIA =================== -->
<script>
document.getElementById('efectivo_usuario').addEventListener('input', function () {
    let declarado = parseFloat(this.value) || 0;
    let esperado = <?php echo $totalRealCajaFisica; ?>;
    let diferencia = declarado - esperado;

    let salida = document.getElementById('diferencia_caja');
    salida.innerText = "<?php echo $id_moneda; ?> " + diferencia.toFixed(2);

    salida.className = "fw-bold fs-3"; // Reset
    if (Math.abs(diferencia) < 0.01) {
        salida.classList.add("text-success");
    } else if (diferencia < 0) {
        salida.classList.add("text-danger");
    } else {
        salida.classList.add("text-warning");
    }
});
</script>
