<?php
/**
 * Módulo: Historial de Ventas v2.2 - Full Responsive & Professional UI
 */
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') {
    die("Acceso denegado.");
}

$prefijo = $_SESSION['IDUg'] ?? '1'; 
$IDU_SOLO = $_SESSION['IDU'] ?? '0';

// Nombres de tablas según esquema
$tb_ventas_c  = $prefijo . "-Ventas_Cabecera";
$tb_ventas_d  = $prefijo . "-Ventas_Detalle";
$tb_clientes  = $prefijo . "-Clientes";
$tb_docs      = $prefijo . "-Documentos_Generados";
?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

<style>
    :root { 
        --ui-primary: #3867d6; --ui-success: #20bf6b; 
        --ui-danger: #eb3b5a; --ui-dark: #2d3436; --ui-bg: #f1f2f6;
    }

    html, body { height: 100%; margin: 0; padding: 0; background-color: var(--ui-bg); font-family: 'Segoe UI', sans-serif; overflow: hidden; }

    /* Contenedor Principal Full Screen */
    .history-app { display: flex; flex-direction: column; height: 100vh; width: 100vw; }

    /* Header */
    .app-header { background: var(--ui-dark); color: #fff; padding: 12px 25px; display: flex; justify-content: space-between; align-items: center; border-bottom: 4px solid var(--ui-primary); flex-shrink: 0; }
    
    /* Panel de Métricas Responsivo */
    .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 15px; padding: 15px 25px; background: #fff; border-bottom: 1px solid #ddd; flex-shrink: 0; }
    .stat-card { background: var(--ui-bg); padding: 15px; border-radius: 12px; display: flex; align-items: center; gap: 15px; border: 1px solid #e1e8ed; }
    .stat-icon { width: 50px; height: 50px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; color: #fff; }

    /* Barra de Filtros */
    .filter-bar { padding: 10px 25px; background: #fff; border-bottom: 1px solid #eee; display: flex; gap: 15px; align-items: center; flex-wrap: wrap; }

    /* Tabla Pro con Scroll Independiente */
    .table-responsive-container { flex: 1; overflow: auto; padding: 0 25px 25px 25px; }
    .main-table { width: 100%; border-collapse: separate; border-spacing: 0; background: #fff; border-radius: 15px; overflow: hidden; box-shadow: 0 10px 30px rgba(0,0,0,0.05); }
    .main-table thead { position: sticky; top: 0; z-index: 10; background: var(--ui-dark); color: #fff; }
    .main-table th { padding: 18px 15px; text-align: left; font-weight: 600; font-size: 0.9rem; text-transform: uppercase; letter-spacing: 1px; }
    .main-table td { padding: 15px; border-bottom: 1px solid #f1f1f1; font-size: 1rem; color: #4b5563; }
    .main-table tbody tr:hover { background-color: #f9fafb; cursor: default; }

    /* Badges y Botones */
    .badge-pay { padding: 6px 12px; border-radius: 50px; font-size: 0.8rem; font-weight: 800; }
    .bg-efectivo { background: #dcfce7; color: #15803d; }
    .bg-tarjeta { background: #dbeafe; color: #1e40af; }

    .btn-action { width: 42px; height: 42px; border-radius: 10px; border: none; display: inline-flex; align-items: center; justify-content: center; transition: 0.3s; cursor: pointer; color: #fff; }
    .btn-view { background: #4b5563; }
    .btn-print { background: var(--ui-success); }
    .btn-action:hover { transform: translateY(-3px); box-shadow: 0 4px 10px rgba(0,0,0,0.2); }

    /* Ajustes para Móvil */
    @media (max-width: 768px) {
        .app-header { flex-direction: column; text-align: center; gap: 10px; }
        .filter-bar { justify-content: center; }
        .stat-card { padding: 10px; }
        .main-table th, .main-table td { padding: 10px; font-size: 0.85rem; }
        .total-cell { font-weight: 900; }
    }
</style>

<div class="history-app">
    <header class="app-header">
        <div>
            <h2 class="m-0 font-weight-bold"><i class="fas fa-file-invoice-dollar mr-2"></i> BITÁCORA DE VENTAS</h2>
            <small class="opacity-75">Auditoría General de Transacciones</small>
        </div>
        <div class="d-flex align-items-center gap-3">
            <span class="badge badge-primary p-2">Sincronizado <i class="fas fa-check-circle"></i></span>
        </div>
    </header>

    <section class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon" style="background:var(--ui-primary)"><i class="fas fa-receipt"></i></div>
            <div><h3 class="m-0 font-weight-bold" id="txt-count">0</h3><small class="text-muted">TRANSACCIONES</small></div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="background:var(--ui-success)"><i class="fas fa-wallet"></i></div>
            <div><h3 class="m-0 font-weight-bold" id="txt-total">$ 0.00</h3><small class="text-muted">TOTAL RECAUDADO</small></div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="background:var(--ui-warning)"><i class="fas fa-chart-pie"></i></div>
            <div><h3 class="m-0 font-weight-bold" id="txt-avg">$ 0.00</h3><small class="text-muted">TICKET PROMEDIO</small></div>
        </div>
    </section>

    <div class="filter-bar">
        <div class="input-group" style="max-width: 300px;">
            <div class="input-group-prepend"><span class="input-group-text">Fecha:</span></div>
            <input type="date" id="input-fecha" class="form-control" onchange="loadSalesHistory()" value="<?php echo date('Y-m-d'); ?>">
        </div>
        <button class="btn btn-dark px-4" onclick="loadSalesHistory()"><i class="fas fa-sync-alt mr-2"></i> Actualizar</button>
    </div>

    <div class="table-responsive-container">
        <table class="main-table">
            <thead>
                <tr>
                    <th>Folio</th>
                    <th>Hora</th>
                    <th>Mesa / Cliente</th>
                    <th>Método</th>
                    <th>Total</th>
                    <th class="text-center">Acciones</th>
                </tr>
            </thead>
            <tbody id="sales-body">
                </tbody>
        </table>
    </div>
</div>

<script>
    const DB = "MS_Datos";
    const TABS = {
        ventas_c: "<?php echo $tb_ventas_c; ?>",
        ventas_d: "<?php echo $tb_ventas_d; ?>",
        clientes: "<?php echo $tb_clientes; ?>",
        docs: "<?php echo $tb_docs; ?>"
    };

    document.addEventListener('DOMContentLoaded', loadSalesHistory);

    async function apiRequest(endpoint, sql) {
        const formData = new FormData();
        formData.append('sql', sql);
        formData.append('db', DB);
        const res = await fetch(`../librerias/AJAX/${endpoint}`, { method: 'POST', body: formData });
        const json = await res.json();
        return json.data ? json.data : json;
    }

    async function loadSalesHistory() {
        const fecha = document.getElementById('input-fecha').value;
        const sql = `
            SELECT v.ID_Venta, v.Folio, v.Fecha, v.Total, v.Metodo_Pago, c.Nombre as ClienteMesa
            FROM \`${TABS.ventas_c}\` v
            LEFT JOIN \`${TABS.clientes}\` c ON v.IDC_Cliente = c.IDC
            WHERE DATE(v.Fecha) = '${fecha}'
            ORDER BY v.Fecha DESC`;
        
        const data = await apiRequest('Select.php', sql);
        const body = document.getElementById('sales-body');
        body.innerHTML = '';

        let totalG = 0;
        let countG = 0;

        if(Array.isArray(data)) {
            countG = data.length;
            data.forEach(v => {
                totalG += parseFloat(v.Total);
                const hora = v.Fecha.split(' ')[1];
                const methodBadge = v.Metodo_Pago === 'Efectivo' ? 'bg-efectivo' : 'bg-tarjeta';
                
                body.innerHTML += `
                    <tr>
                        <td class="font-weight-bold text-dark">${v.Folio}</td>
                        <td class="text-muted">${hora}</td>
                        <td class="font-weight-bold text-primary">${v.ClienteMesa || 'Venta General'}</td>
                        <td><span class="badge-pay ${methodBadge}">${v.Metodo_Pago || 'Otro'}</span></td>
                        <td class="font-weight-bold text-dark h5">$ ${parseFloat(v.Total).toFixed(2)}</td>
                        <td class="text-center">
                            <button class="btn-action btn-view mr-2" onclick="showSaleDetails(${v.ID_Venta}, '${v.Folio}')" title="Ver Consumo">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn-action btn-print" onclick="reprintVenta('${v.Folio}')" title="Reimprimir Ticket">
                                <i class="fas fa-print"></i>
                            </button>
                        </td>
                    </tr>`;
            });
        }

        // Actualizar Metrics
        document.getElementById('txt-count').innerText = countG;
        document.getElementById('txt-total').innerText = `$ ${totalG.toFixed(2)}`;
        document.getElementById('txt-avg').innerText = `$ ${countG > 0 ? (totalG / countG).toFixed(2) : '0.00'}`;
    }

    async function showSaleDetails(idVenta, folio) {
        const sql = `SELECT Nombre_Producto, Cantidad, Precio_Venta, Subtotal FROM \`${TABS.ventas_d}\` WHERE ID_Venta = ${idVenta}`;
        const items = await apiRequest('Select.php', sql);
        
        let html = `<div style="text-align:left; font-family:'Courier New', monospace;">
                        <center><b>DETALLE DE CONSUMO</b><br>Folio: ${folio}</center><hr>`;
        
        if(Array.isArray(items)) {
            items.forEach(it => {
                html += `<div class="d-flex justify-content-between">
                            <span>${parseFloat(it.Cantidad).toFixed(0)}x ${it.Nombre_Producto}</span>
                            <b>$${parseFloat(it.Subtotal).toFixed(2)}</b>
                         </div>`;
            });
        }
        html += `</div>`;

        Swal.fire({
            title: 'Detalle de Venta',
            html: html,
            confirmButtonText: 'Cerrar',
            confirmButtonColor: '#2d3436'
        });
    }

    async function reprintVenta(folio) {
        Swal.fire({ title: 'Preparando impresión...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });

        // Buscamos el documento original en la base de datos
        const res = await apiRequest('Select.php', `SELECT * FROM \`${TABS.docs}\` WHERE UUID_Unico = '${folio}' LIMIT 1`);
        
        if(res && res.length > 0) {
            const d = res[0];
            // Insertamos una copia idéntica pero con estado PENDIENTE y marca de REIMPRESION
            const sqlInsert = `INSERT INTO \`${TABS.docs}\` 
                               (UUID_Unico, Modulo_Origen, ID_Referencia, ID_Config_Impresora, Contenido_JSON, Estado, Es_Reimpresion) 
                               VALUES ('${d.UUID_Unico}', 'ReimpresionHistorial', ${d.ID_Referencia}, ${d.ID_Config_Impresora}, '${d.Contenido_JSON}', 'PENDIENTE', 1)`;
            
            await apiRequest('Execute.php', sqlInsert);
            Swal.fire('¡Éxito!', 'Ticket enviado a la cola de impresión.', 'success');
        } else {
            Swal.fire('Error', 'No se encontró el registro digital de este ticket.', 'error');
        }
    }
</script>