<?php 
// Configuración básica y moneda
if(!isset($conn)) require_once 'db.php';
$config = $conn->query("SELECT * FROM configuracion LIMIT 1")->fetch_assoc();
$moneda = $config['moneda'] ?? 'S/';
?>

<div class="container-fluid py-4">
    <div class="card border-0 shadow-sm mb-4 bg-white">
        <div class="card-body p-4">
            <div class="row align-items-center">
                <div class="col-md-7">
                    <h4 class="fw-bold m-0 text-primary">
                        <i class="fas fa-chart-bar me-2"></i>Reporte General de Ventas
                    </h4>
                    <p class="text-muted small m-0 mt-1">Consulta el historial detallado, filtra por fechas y exporta tu contabilidad.</p>
                </div>
                <div class="col-md-5 text-md-end mt-3 mt-md-0">
                    <div class="d-inline-block bg-light p-3 rounded-3 border border-success border-opacity-25 shadow-sm">
                        <h6 class="text-muted small fw-bold mb-1 text-uppercase">Total Filtrado</h6>
                        <h2 class="fw-bold text-success m-0"><?php echo $moneda; ?> <span id="txt-total-periodo">0.00</span></h2>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body bg-light rounded">
            <div class="row g-3 align-items-end">
                <div class="col-md-3">
                    <label class="form-label small fw-bold text-muted">Fecha de Inicio</label>
                    <div class="input-group">
                        <span class="input-group-text bg-white border-end-0"><i class="fas fa-calendar-alt text-muted"></i></span>
                        <input type="date" id="rep-ini" class="form-control border-start-0" value="<?php echo date('Y-m-01'); ?>">
                    </div>
                </div>
                <div class="col-md-3">
                    <label class="form-label small fw-bold text-muted">Fecha de Fin</label>
                    <div class="input-group">
                        <span class="input-group-text bg-white border-end-0"><i class="fas fa-calendar-alt text-muted"></i></span>
                        <input type="date" id="rep-fin" class="form-control border-start-0" value="<?php echo date('Y-m-d'); ?>">
                    </div>
                </div>
                <div class="col-md-4">
                    <button class="btn btn-primary w-100 fw-bold shadow-sm py-2" onclick="consultarVentas()">
                        <i class="fas fa-search me-2"></i>BUSCAR VENTAS
                    </button>
                </div>
                <div class="col-md-2">
                    <button class="btn btn-success w-100 fw-bold shadow-sm py-2" onclick="exportarExcel()">
                        <i class="fas fa-file-excel me-2"></i>EXCEL
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div class="card border-0 shadow-sm">
        <div class="card-body p-0">
            <div class="table-responsive" style="max-height: 500px; overflow-y: auto;">
                <table class="table table-hover align-middle m-0" id="tabla-reportes">
                    <thead class="table-dark" style="position: sticky; top: 0; z-index: 10;">
                        <tr>
                            <th class="ps-4">ID Venta</th>
                            <th>Fecha y Hora</th>
                            <th>Detalle de Productos</th>
                            <th class="text-center">Cant.</th>
                            <th>Cliente</th>
                            <th>Método Pago</th>
                            <th class="text-end">Total</th>
                            <th class="text-center">Estado</th>
                            <th class="text-center pe-4">Ticket</th>
                        </tr>
                    </thead>
                    <tbody id="tbody-reporte">
                        <tr>
                            <td colspan="9" class="text-center py-5">
                                <i class="fas fa-inbox fa-3x text-muted mb-3 d-block"></i>
                                <span class="text-muted fw-bold">Presiona "Buscar Ventas" para cargar la información...</span>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
// Cargar automáticamente al entrar
document.addEventListener('DOMContentLoaded', () => {
    consultarVentas();
});

function consultarVentas() {
    let hoy = new Date().toISOString().split('T')[0];
    const ini = document.getElementById('rep-ini').value || hoy;
    const fin = document.getElementById('rep-fin').value || hoy;
    const tbody = document.getElementById('tbody-reporte');
    const txtTotal = document.getElementById('txt-total-periodo');

    tbody.innerHTML = '<tr><td colspan="9" class="text-center py-5"><div class="spinner-border text-primary"></div><br><span class="mt-2 d-inline-block fw-bold text-muted">Buscando...</span></td></tr>';

    // Anti-caché para forzar al hosting a dar datos frescos
    const antiCache = new Date().getTime();
    
    fetch(`api.php?task=filtered_report&ini=${ini}&fin=${fin}&nocache=${antiCache}`)
    .then(r => r.json())
    .then(res => {
        if (!res.success) {
            tbody.innerHTML = `<tr><td colspan="9" class="text-center py-4 text-danger fw-bold">${res.error || 'Error del servidor'}</td></tr>`;
            return;
        }

        // 1. LEER EL TOTAL EXACTO COMO LO ENVÍA PHP
        txtTotal.innerText = parseFloat(res.monto_global || 0).toFixed(2);

        // 2. LEER LAS FILAS EXACTAMENTE COMO LAS ENVÍA PHP
        // (Esto es lo que causaba el error reading 'length', ahora usa data_rows)
        let filas = res.data_rows || [];
        let html = '';

        if (filas.length === 0) {
            html = `<tr><td colspan="9" class="text-center py-5 text-muted fw-bold">No hay ventas registradas del ${ini} al ${fin}.</td></tr>`;
        } else {
            filas.forEach(v => {
                let badgeStatus = (v.estado === 'ANULADA') ? 'bg-danger' : 'bg-success';

                html += `
                <tr>
                    <td class="ps-4 text-secondary fw-bold">#${v.id}</td>
                    <td><div class="small">${v.fecha}</div></td>
                    <td style="max-width: 250px;">
                        <div class="text-truncate small fw-bold text-dark" title="${v.productos}">${v.productos || 'Sin detalle'}</div>
                    </td>
                    <td class="text-center"><span class="badge bg-light text-dark border">${v.unidades || 0}</span></td>
                    <td><span class="small">${v.cliente || 'Público General'}</span></td>
                    <td><span class="badge bg-info bg-opacity-10 text-info border border-info border-opacity-25">${v.pago || 'EFECTIVO'}</span></td>
                    <td class="text-end fw-bold text-primary">${parseFloat(v.total).toFixed(2)}</td>
                    <td class="text-center"><span class="badge ${badgeStatus}">${v.estado}</span></td>
                    <td class="text-center pe-4">
                        <button class="btn btn-sm btn-outline-secondary shadow-sm" onclick="imprimirTicket(${v.id})" title="Imprimir">
                            <i class="fas fa-print"></i>
                        </button>
                    </td>
                </tr>`;
            });
        }
        tbody.innerHTML = html;
    })
    .catch(err => {
        console.error("Error cargando reporte:", err);
        tbody.innerHTML = '<tr><td colspan="9" class="text-center py-5 text-danger fw-bold">Error de conexión con el servidor.</td></tr>';
    });
}

function exportarExcel() {
    let tabla = document.getElementById("tabla-reportes");
    let html = tabla.outerHTML;
    let blob = new Blob(['\uFEFF' + html], { type: 'application/vnd.ms-excel;charset=utf-8' });
    let url = URL.createObjectURL(blob);
    let a = document.createElement("a");
    a.href = url;
    let fIni = document.getElementById('rep-ini').value || 'Inicio';
    let fFin = document.getElementById('rep-fin').value || 'Fin';
    a.download = `Reporte_Ventas_${fIni}_al_${fFin}.xls`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

function imprimirTicket(id) {
    window.open(`views/ticket.php?id_venta=${id}`, 'Ticket', 'width=400,height=600,menubar=no,toolbar=no');
}
</script>