<?php
// 1. Limpieza de buffer
if (ob_get_length()) ob_end_clean();
ob_start();

require_once "modelo/Db.php";
$bd = new clsbdd();

$fecha_inicio = $_GET['f_inicio'] ?? date('Y-m-d');
$fecha_fin = $_GET['f_fin'] ?? date('Y-m-d');

// 2. Cabeceras para Excel
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=Reporte_Detalle_Pagos_" . $fecha_inicio . ".xls");
header("Pragma: no-cache");
header("Expires: 0");

// 3. Consulta SQL
$sql = "SELECT 
            v.ven_codigo, 
            v.ven_fecha, 
            v.ven_tipo_pago, 
            v.ven_total,
            v.ven_entregado,
            pr.pro_nombre AS cliente,
            p.prd_nombre AS producto,
            vd.vde_cantidad,
            vd.vde_precio,
            vd.vde_subtotal AS subtotal_item
        FROM sba_ventas v
        INNER JOIN sba_ventas_detalle vd ON v.ven_codigo = vd.ven_codigo
        INNER JOIN sba_productos p ON vd.prd_codigo = p.prd_codigo
        LEFT JOIN sba_profesores pr ON v.pro_codigo = pr.pro_codigo
        WHERE DATE(v.ven_fecha) BETWEEN '$fecha_inicio' AND '$fecha_fin'
        AND v.ven_estado = 1
        ORDER BY v.ven_codigo DESC";

$datos = $bd->ejecutar_array($sql) ?: [];

// Variables para acumuladores finales
$acum_efectivo = 0;
$acum_transferencia = 0;
$acum_credito = 0;
$acum_total_general = 0;

$ultimo_id = "";
?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<table border="1">
    <thead>
        <tr style="background-color: #0d47a1; color: #FFFFFF; font-weight: bold;">
            <th>ID Venta</th>
            <th>Fecha/Hora</th>
            <th>Cliente / Docente</th>
            <th>Producto</th>
            <th>Cant.</th>
            <th>P. Unitario</th>
            <th>Subtotal Item</th>
            <th style="background-color: #2e7d32; color: #FFFFFF;">EFECTIVO</th>
            <th style="background-color: #1565c0; color: #FFFFFF;">TRANSFERENCIA</th>
            <th style="background-color: #c62828; color: #FFFFFF;">CRÉDITO</th>
            <th style="background-color: #37474f; color: #FFFFFF;">TOTAL TICKET</th>
        </tr>
    </thead>
    <tbody>
        <?php 
        foreach($datos as $d): 
            $efectivo_fila = 0;
            $transferencia_fila = 0;
            $credito_fila = 0;
            
            $tipo = $d['ven_tipo_pago'];
            $total_vnt = floatval($d['ven_total']);
            $entregado = floatval($d['ven_entregado']);

            // Calculamos montos proporcionales solo si es el inicio de un nuevo ticket
            if ($ultimo_id != $d['ven_codigo']) {
                switch ($tipo) {
                    case 'EFECTIVO':
                        $efectivo_fila = $total_vnt;
                        break;
                    case 'TRANSFERENCIA':
                        $transferencia_fila = $total_vnt;
                        break;
                    case 'CREDITO':
                        $credito_fila = $total_vnt;
                        break;
                    case 'MIXTO_EF_TR':
                        $efectivo_fila = $entregado;
                        $transferencia_fila = $total_vnt - $entregado;
                        break;
                    case 'MIXTO_EF_CR':
                        $efectivo_fila = $entregado;
                        $credito_fila = $total_vnt - $entregado;
                        break;
                    case 'MIXTO_TR_CR':
                        $transferencia_fila = $entregado;
                        $credito_fila = $total_vnt - $entregado;
                        break;
                }
                
                // Sumamos a los acumuladores globales
                $acum_efectivo += $efectivo_fila;
                $acum_transferencia += $transferencia_fila;
                $acum_credito += $credito_fila;
                $acum_total_general += $total_vnt;

                $mostrar_total = $total_vnt;
                $ultimo_id = $d['ven_codigo'];
            } else {
                $mostrar_total = 0;
            }
        ?>
        <tr>
            <td><?php echo $d['ven_codigo']; ?></td>
            <td><?php echo date('d/m/Y H:i', strtotime($d['ven_fecha'])); ?></td>
            <td><?php echo htmlspecialchars($d['cliente'] ?: 'Consumidor Final'); ?></td>
            <td><?php echo htmlspecialchars($d['producto']); ?></td>
            <td align="center"><?php echo $d['vde_cantidad']; ?></td>
            <td align="right"><?php echo number_format($d['vde_precio'], 2); ?></td>
            <td align="right"><?php echo number_format($d['subtotal_item'], 2); ?></td>
            
            <td align="right"><?php echo ($efectivo_fila > 0) ? number_format($efectivo_fila, 2) : "-"; ?></td>
            <td align="right"><?php echo ($transferencia_fila > 0) ? number_format($transferencia_fila, 2) : "-"; ?></td>
            <td align="right"><?php echo ($credito_fila > 0) ? number_format($credito_fila, 2) : "-"; ?></td>
            
            <td align="right" style="font-weight: bold; background-color: #f5f5f5;">
                <?php echo ($mostrar_total > 0) ? number_format($mostrar_total, 2) : ""; ?>
            </td>
        </tr>
        <?php endforeach; ?>
    </tbody>
    <tfoot>
        <tr style="background-color: #eeeeee; font-weight: bold;">
            <td colspan="7" align="right" style="padding: 10px;">TOTALES GENERALES DEL PERÍODO:</td>
            <td align="right" style="background-color: #c8e6c9; color: #2e7d32;">$<?php echo number_format($acum_efectivo, 2); ?></td>
            <td align="right" style="background-color: #bbdefb; color: #1565c0;">$<?php echo number_format($acum_transferencia, 2); ?></td>
            <td align="right" style="background-color: #ffcdd2; color: #c62828;">$<?php echo number_format($acum_credito, 2); ?></td>
            <td align="right" style="background-color: #cfd8dc; color: #37474f;">$<?php echo number_format($acum_total_general, 2); ?></td>
        </tr>
    </tfoot>
</table>
<?php
ob_end_flush();
exit;
?>