<?php
require_once('conecta.php');
mysqli_set_charset($conecta, "utf8");

// 1. Limpiamos las entradas
$desde = (isset($_POST['desde_fecha']) && !empty($_POST['desde_fecha'])) ? mysqli_real_escape_string($conecta, $_POST['desde_fecha']) : date('Y-m-d');
$hasta = (isset($_POST['hasta_fecha']) && !empty($_POST['hasta_fecha'])) ? mysqli_real_escape_string($conecta, $_POST['hasta_fecha']) : date('Y-m-d');

$sql_ventas = "SELECT v.*, c.denominacion 
               FROM venta v
               INNER JOIN cliente c ON v.cliente = c.idcliente
               WHERE DATE(v.fecha) BETWEEN '$desde' AND '$hasta' 
               AND v.anulada = 'NO'
               ORDER BY v.fecha DESC";

$res_ventas = mysqli_query($conecta, $sql_ventas) or die("Error: " . mysqli_error($conecta));

// Totales Generales
$total_g_ventas = 0; $total_g_ganancia = 0; $total_g_costo = 0; $total_g_desc = 0;
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <style>
        body { font-family: Helvetica, Arial, sans-serif; font-size: 10px; margin: 15px; }
        .tabla-maestro { width: 100%; border: 1px solid #2c3e50; border-collapse: collapse; margin-top: 10px; }
        .cabecera-v { background-color: #2c3e50; color: white; font-weight: bold; }
        .cabecera-v td { padding: 6px; }
        .tabla-detalle { width: 100%; border-collapse: collapse; margin-bottom: 15px; border: 1px solid #ccc; }
        .titulos-d { background-color: #f2f2f2; font-weight: bold; }
        .titulos-d td { padding: 4px; border: 1px solid #ccc; text-transform: uppercase; }
        .datos-d td { border: 1px solid #eee; padding: 4px; }
        .text-right { text-align: right; }
        .bold { font-weight: bold; }
    </style>
</head>
<body>

    <div style="text-align: center;">
        <h2 style="margin:0; font-size: 16px;">INFORME DE VENTAS DETALLADO</h2>
        <p>Periodo: <?php echo date('d/m/Y', strtotime($desde)); ?> al <?php echo date('d/m/Y', strtotime($hasta)); ?></p>
    </div>

    <?php 
    while($v = mysqli_fetch_assoc($res_ventas)) { 
        $total_g_ventas += (float)$v['total_venta'];
        $id_v = $v['idventa'];
        $sub_costo_total = 0; $sub_subtotal = 0; $sub_desc = 0; $sub_ganancia = 0;
    ?>
        <table class="tabla-maestro">
            <tr class="cabecera-v">
                <td>VENTA Nº: <?php echo $id_v; ?> | FECHA: <?php echo date('d/m/Y', strtotime($v['fecha'])); ?> | CLIENTE: <?php echo utf8_encode($v['denominacion']); ?></td>
            </tr>
        </table>

        <table class="tabla-detalle">
            <thead>
                <tr class="titulos-d">
                    <td>Artículo</td><td>Costo Unit.</td><td>Precio</td><td>Cant.</td><td>Importe</td><td>Subtotal</td><td>Desc.</td><td>Ganancia</td>
                </tr>
            </thead>
            <tbody>
                <?php 
                $sql_det = "SELECT d.*, a.nombre FROM det_venta d INNER JOIN articulo a ON d.idarticulo = a.idarticulo WHERE d.idventa = '$id_v' AND d.anulada = 'NO'";
                $res_det = mysqli_query($conecta, $sql_det);
                while($d = mysqli_fetch_assoc($res_det)) { 
                    $costo_linea = $d['costo'] * $d['cantidad'];
                    $sub_costo_total += $costo_linea;
                    $sub_subtotal += $d['subtotal']; 
                    $sub_desc += $d['descuento']; 
                    $sub_ganancia += $d['ganancia'];
                    
                    $total_g_costo += $costo_linea;
                    $total_g_desc += $d['descuento']; 
                    $total_g_ganancia += $d['ganancia'];
                ?>
                    <tr class="datos-d">
                        <td><?php echo utf8_encode($d['nombre']); ?></td>
                        <td class="text-right"><?php echo number_format($d['costo'], 0, ',', '.'); ?></td>
                        <td class="text-right"><?php echo number_format($d['precio'], 0, ',', '.'); ?></td>
                        <td class="text-right"><?php echo $d['cantidad']; ?></td>
                        <td class="text-right"><?php echo number_format($d['importe'], 0, ',', '.'); ?></td>
                        <td class="text-right"><?php echo number_format($d['subtotal'], 0, ',', '.'); ?></td>
                        <td class="text-right"><?php echo number_format($d['descuento'], 0, ',', '.'); ?></td>
                        <td class="text-right"><?php echo number_format($d['ganancia'], 0, ',', '.'); ?></td>
                    </tr>
                <?php } ?>
                <tr class="titulos-d bold">
                    <td>TOTALES VENTA:</td>
                    <td class="text-right"><?php echo number_format($sub_costo_total, 0, ',', '.'); ?></td>
                    <td></td><td></td>
                    <td class="text-right">-</td> <td class="text-right"><?php echo number_format($sub_subtotal, 0, ',', '.'); ?></td>
                    <td class="text-right"><?php echo number_format($sub_desc, 0, ',', '.'); ?></td>
                    <td class="text-right"><?php echo number_format($sub_ganancia, 0, ',', '.'); ?></td>
                </tr>
            </tbody>
        </table>
    <?php } ?>

    <div style="border: 2px solid #000; padding: 10px; margin-top: 20px;">
        <table width="100%">
            <tr><td class="bold">TOTAL GENERAL COSTO (Costo * Cantidad):</td><td class="text-right">Gs. <?php echo number_format($total_g_costo, 0, ',', '.'); ?></td></tr>
            <tr><td class="bold">TOTAL GENERAL DESCUENTO:</td><td class="text-right">Gs. <?php echo number_format($total_g_desc, 0, ',', '.'); ?></td></tr>
            <tr><td class="bold">TOTAL GENERAL VENTAS NETAS:</td><td class="text-right">Gs. <?php echo number_format($total_g_ventas, 0, ',', '.'); ?></td></tr>
            <tr><td class="bold" style="color: green;">TOTAL GENERAL GANANCIA:</td><td class="text-right" style="color: green;">Gs. <?php echo number_format($total_g_ganancia, 0, ',', '.'); ?></td></tr>
        </table>
    </div>
</body>
</html>