<?php
/**
 * Módulo: Business Intelligence Suite v8.1 - Ultra-Wide Edition
 * UI/UX: Full Screen Architecture | AJAX Deep Analytics | Professional Modal
 */
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') { die("Acceso denegado."); }

$idUsuario  = $_SESSION['IDUg'] ?? '1'; 
$dbName     = $_SESSION['BD'] ?? "MS_Datos"; 
$prefijo    = $idUsuario . "-"; 
$vendedor   = $_SESSION['NombreUsuario'] ?? "Vendedor";

$tb_ventas_c = "{$prefijo}Ventas_Cabecera";
$tb_ventas_d = "{$prefijo}Ventas_Detalle";
$tb_clientes = "{$prefijo}Clientes";
$tb_config   = "{$prefijo}Configuracion_Impresoras";

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

try {
    $pdoImp = new PDO("mysql:host=localhost;dbname=$dbName;charset=utf8", "root", "33comRxXMysql");
    $stmtImp = $pdoImp->query("SELECT * FROM `$tb_config` WHERE Activo = 1");
    $impresorasData = $stmtImp->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $impresorasData = []; }
?>

<style>
    @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap');
    :root { --p: #4f46e5; --s: #10b981; --d: #0f172a; --bg: #f8fafc; --border: #e2e8f0; }
    
    body, html { height: 100%; margin: 0; padding: 0; font-family: 'Plus Jakarta Sans', sans-serif; background: var(--bg); overflow: hidden; }
    
    /* Layout Full Screen */
    .bi-app { display: flex; flex-direction: column; height: 100vh; width: 100vw; gap: 0; box-sizing: border-box; }

    /* SECCIÓN 1: Top Bar (Flush) */
    .section-top { background: var(--d); color: #fff; padding: 10px 25px; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 4px 12px rgba(0,0,0,0.1); flex-shrink: 0; z-index: 100; }
    
    /* SECCIÓN 2: Analytics Bar & Chart (Full Width) */
    .section-middle { background: #fff; border-bottom: 1px solid var(--border); display: flex; flex-direction: column; padding: 15px 25px; min-height: 320px; flex-shrink: 0; }
    .kpi-strip { display: flex; gap: 40px; margin-bottom: 10px; }
    .kpi-item { display: flex; align-items: center; gap: 12px; }
    .kpi-item .icon { width: 38px; height: 38px; border-radius: 10px; background: var(--bg); display: grid; place-items: center; color: var(--p); font-size: 1rem; }

    /* SECCIÓN 3: Table Log (Expansión Total) */
    .section-bottom { background: #fff; flex: 1; display: flex; flex-direction: column; overflow: hidden; }
    .table-header-tool { p: 12px 25px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; background: #fff; padding: 10px 25px; }
    
    .table-scroll { flex: 1; overflow-y: auto; }
    .pro-table { width: 100%; border-collapse: collapse; }
    .pro-table th { background: #f8fafc; padding: 12px 25px; font-size: 10px; text-transform: uppercase; font-weight: 800; color: #64748b; position: sticky; top: 0; z-index: 10; border-bottom: 1px solid var(--border); }
    .pro-table td { padding: 12px 25px; border-bottom: 1px solid #f1f5f9; font-size: 13px; color: #334155; }
    .pro-table tr:hover { background: #f8fafc; }

    /* Botones Pro */
    .btn-bi { border: none; border-radius: 10px; font-weight: 700; transition: 0.3s; display: inline-flex; align-items: center; justify-content: center; gap: 8px; }
    .btn-bi-sm { width: 32px; height: 32px; border-radius: 8px; color: white; }
    .btn-bi-p { background: var(--p); color: white; }
    .btn-bi-s { background: var(--s); color: white; }
    .btn-bi:hover { transform: translateY(-1px); filter: brightness(1.1); }

    /* Estética de Modal */
    .modal-pro { border-radius: 24px; overflow: hidden; border: none; }
    .detail-card { background: #f8fafc; border-radius: 18px; padding: 15px; margin-bottom: 12px; }

    /* Scrollbar minimalista para no romper la estética full screen */
    .table-scroll::-webkit-scrollbar { width: 6px; }
    .table-scroll::-webkit-scrollbar-thumb { background: #cbd5e0; border-radius: 10px; }
</style>

<div class="bi-app">
    <header class="section-top no-print">
        <div class="d-flex align-items-center gap-3">
            <div style="background:var(--p); width:35px; height:35px; border-radius:8px; display:grid; place-items:center;"><i class="fas fa-chart-pie text-white fa-sm"></i></div>
            <h6 class="m-0 fw-bold">Ventas <span class="opacity-50 fw-normal ms-2">| Reporte</span></h6>
        </div>
        <div class="d-flex align-items-center gap-3">
            <div class="d-flex bg-white rounded-pill p-1 shadow-sm">
                <input type="date" id="f_inicio" class="form-control form-control-sm border-0 bg-transparent fw-bold" style="width:130px" value="<?= $f_inicio ?>">
                <span class="px-1 text-dark opacity-25">/</span>
                <input type="date" id="f_fin" class="form-control form-control-sm border-0 bg-transparent fw-bold" style="width:130px" value="<?= $f_fin ?>">
                <button class="btn btn-primary btn-sm rounded-pill ms-2 px-3" onclick="reload()"><i class="fas fa-sync-alt"></i></button>
            </div>
            <button class="btn-bi btn-bi-s px-4 py-1 small" onclick="exportXLS()"><i class="fas fa-file-excel"></i> XLS</button>
        </div>
    </header>

    <section class="section-middle">
        <div class="kpi-strip">
            <div class="kpi-item">
                <div class="icon"><i class="fas fa-wallet"></i></div>
                <div><small class="text-muted d-block fw-bold small">VENTA TOTAL</small><h4 class="m-0 fw-800" id="txt-total">$ 0.00</h4></div>
            </div>
            <div class="kpi-item">
                <div class="icon" style="color:var(--s)"><i class="fas fa-shopping-bag"></i></div>
                <div><small class="text-muted d-block fw-bold small">TRANSACCIONES</small><h4 class="m-0 fw-800" id="txt-qty">0</h4></div>
            </div>
            <div class="kpi-item">
                <div class="icon" style="color:#f59e0b"><i class="fas fa-percentage"></i></div>
                <div><small class="text-muted d-block fw-bold small">TICKET PROMEDIO</small><h4 class="m-0 fw-800" id="txt-avg">$ 0.00</h4></div>
            </div>
        </div>
        <div style="flex:1"><canvas id="barChartAjax"></canvas></div>
    </section>

    <section class="section-bottom">
        <div class="table-header-tool">
            <h6 class="m-0 fw-800 text-muted small"><i class="fas fa-database me-2"></i>REPORTE DETALLADO</h6>
            <div class="input-group input-group-sm w-25">
                <span class="input-group-text bg-light border-0"><i class="fas fa-search"></i></span>
                <input type="text" id="finder" class="form-control border-0 bg-light" placeholder="Filtrar por folio o cliente..." onkeyup="filter()">
            </div>
        </div>
        <div class="table-scroll">
            <table class="pro-table" id="reportTable">
                <thead>
                    <tr>
                        <th>Folio</th>
                        <th>Cliente</th>
                        <th>Fecha / Hora</th>
                        <th>Método</th>
                        <th class="text-end">Monto Total</th>
                        <th class="text-center">Acciones</th>
                    </tr>
                </thead>
                <tbody id="salesData"></tbody>
            </table>
        </div>
    </section>
</div>

<div class="modal fade" id="modalDetails" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content modal-pro shadow-lg">
            <div class="modal-header border-0 p-4">
                <h5 class="fw-800 m-0"><i class="fas fa-search-dollar text-primary me-2"></i>Auditoría de Nota</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4 pt-0" id="detailContent"></div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalPrintEngine" tabindex="-1" data-backdrop="static">
    <div class="modal-dialog modal-xl">
        <div class="modal-content border-0 rounded-4 shadow-lg overflow-hidden">
            <div class="modal-header bg-dark text-white p-2">
                <h6 class="modal-title font-weight-bold ml-2">REIMPRESIÓN DE DOCUMENTO</h6>
                <select id="pe-select-config" class="form-control form-control-sm ml-auto" style="width:280px;" onchange="PrintEngine.render()"></select>
            </div>
            <div class="modal-body p-0" style="background:#4b4b4b; height:65vh; overflow-y:auto; display:flex; justify-content:center; padding:30px;">
                <div id="pe-hoja-digital" style="background:#fff; box-shadow:0 0 30px rgba(0,0,0,0.5);"></div>
            </div>
            <div class="modal-footer bg-light p-2">
                <button class="btn btn-primary fw-bold px-4" onclick="PrintEngine.printNow()">IMPRIMIR</button>
                <button class="btn btn-success fw-bold px-4" onclick="PrintEngine.saveToApp()">NOTIFICAR APP</button>
                <button class="btn btn-secondary" data-dismiss="modal">CERRAR</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
const CONFIG = {
    db: "<?= $dbName ?>", pref: "<?= $prefijo ?>", vend: "<?= $vendedor ?>",
    f1: "<?= $f_inicio ?>", f2: "<?= $f_fin ?>", isDay: ("<?= $f_inicio ?>" === "<?= $f_fin ?>")
};

document.addEventListener('DOMContentLoaded', () => { initBI(); });

function reload() {
    window.location.href = `index.php?A=<?php echo $_GET['A']; ?>&f_inicio=${document.getElementById('f_inicio').value}&f_fin=${document.getElementById('f_fin').value}`;
}

async function api(sql) {
    const fd = new FormData(); fd.append('sql', sql); fd.append('db', CONFIG.db);
    return await fetch('../librerias/AJAX/Select.php', { method: 'POST', body: fd }).then(r => r.json());
}

async function initBI() {
    const res = await api(`SELECT v.*, c.Nombre as Cliente, c.Telefono, c.Email FROM \`${CONFIG.pref}Ventas_Cabecera\` v LEFT JOIN \`${CONFIG.pref}Clientes\` c ON v.IDC_Cliente = c.IDC WHERE DATE(v.Fecha) BETWEEN '${CONFIG.f1}' AND '${CONFIG.f2}' ORDER BY v.Fecha DESC`);
    const body = document.getElementById('salesData');
    body.innerHTML = '';
    let tot = 0; let qty = 0;

    if(res.data) {
        qty = res.data.length;
        res.data.forEach(v => {
            tot += parseFloat(v.Total);
            body.innerHTML += `
                <tr>
                    <td class="fw-800 text-primary">${v.Folio}</td>
                    <td><div class="fw-bold text-dark">${v.Cliente || 'Público General'}</div><small class="text-muted">${v.Email || v.Telefono || ''}</small></td>
                    <td><span class="text-muted small">${v.Fecha}</span></td>
                    <td><span class="badge bg-light text-dark border px-3 rounded-pill" style="font-size:9px">${v.Metodo_Pago}</span></td>
                    <td class="text-end fw-800 text-dark">$ ${parseFloat(v.Total).toFixed(2)}</td>
                    <td class="text-center">
                        <button class="btn-bi btn-bi-sm btn-bi-p me-1" onclick="getDetails(${JSON.stringify(v).replace(/"/g, '&quot;')})"><i class="fas fa-eye"></i></button>
                        <button class="btn-bi btn-bi-sm btn-bi-s" onclick="reprint(${JSON.stringify(v).replace(/"/g, '&quot;')})"><i class="fas fa-print"></i></button>
                    </td>
                </tr>`;
        });
    }

    document.getElementById('txt-total').innerText = `$ ${tot.toLocaleString('es-MX', {minimumFractionDigits:2})}`;
    document.getElementById('txt-qty').innerText = qty;
    document.getElementById('txt-avg').innerText = `$ ${qty > 0 ? (tot/qty).toFixed(2) : '0.00'}`;

    loadChart();
}

async function loadChart() {
    const group = CONFIG.isDay ? "HOUR(Fecha)" : "DATE(Fecha)";

    const res = await api(`SELECT ${group} as punto, SUM(Total) as monto FROM \`${CONFIG.pref}Ventas_Cabecera\` WHERE DATE(Fecha) BETWEEN '${CONFIG.f1}' AND '${CONFIG.f2}' AND Estado != 'Cancelado' GROUP BY punto ORDER BY punto ASC`);
    const labels = []; const points = [];
    res.data?.forEach(r => { labels.push(CONFIG.isDay ? r.punto + ":00" : r.punto); points.push(parseFloat(r.monto)); });

    new Chart(document.getElementById('barChartAjax'), {
        type: 'bar',
        data: { labels: labels, datasets: [{ label: 'Ventas ($)', data: points, backgroundColor: '#6366f1', borderRadius: 6, maxBarThickness: 50 }] },
        options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true }, x: { grid: { display: false } } } }
    });
}

async function getDetails(v) {
    const res = await api(`SELECT * FROM \`${CONFIG.pref}Ventas_Detalle\` WHERE ID_Venta = ${v.ID_Venta}`);
    let items = '';
    res.data.forEach(i => {
        items += `<div class="d-flex justify-content-between mb-2">
                    <span class="small">${parseInt(i.Cantidad)}x ${i.Nombre_Producto}</span>
                    <b class="small">$${parseFloat(i.Subtotal).toFixed(2)}</b>
                  </div>`;
    });

    document.getElementById('detailContent').innerHTML = `
        <div class="detail-card">
            <div class="row g-2">
                <div class="col-6"><small class="text-muted d-block fw-bold" style="font-size:9px uppercase">Ticket</small><b>${v.Folio}</b></div>
                <div class="col-6 text-end"><small class="text-muted d-block fw-bold" style="font-size:9px uppercase">Método</small><span class="badge bg-white text-dark border">${v.Metodo_Pago}</span></div>
                <div class="col-12 mt-2"><small class="text-muted d-block fw-bold" style="font-size:9px uppercase">Cliente</small><b>${v.Cliente || 'General'}</b></div>
            </div>
        </div>
        <div class="px-2">${items}</div>
        <div class="detail-card mt-3 bg-white border">
            <div class="d-flex justify-content-between mb-1"><small>Subtotal:</small><b>$${parseFloat(v.Subtotal).toFixed(2)}</b></div>
            <div class="d-flex justify-content-between text-danger mb-1"><small>Descuento:</small><b>-$${parseFloat(v.Descuento).toFixed(2)}</b></div>
            <div class="d-flex justify-content-between h5 fw-800 text-primary pt-2 border-top"><span>TOTAL:</span><span>$${parseFloat(v.Total).toFixed(2)}</span></div>
        </div>
    `;
    new bootstrap.Modal(document.getElementById('modalDetails')).show();
}

async function reprint(v) {
    const res = await api(`SELECT * FROM \`${CONFIG.pref}Ventas_Detalle\` WHERE ID_Venta = ${v.ID_Venta}`);
    PrintEngine.show({
        folio: v.Folio, cliente: v.Cliente || 'Público General', vendedor: CONFIG.vend,
        items: res.data.map(i => ({ qty: i.Cantidad, nombre: i.Nombre_Producto, price: i.Precio_Venta })),
        total: v.Total, sub: v.Subtotal, dsc: v.Descuento, metodo: v.Metodo_Pago, idRef: v.ID_Venta
    });
}

function filter() {
    const q = document.getElementById('finder').value.toLowerCase();
    document.querySelectorAll('#salesData tr').forEach(r => r.style.display = r.innerText.toLowerCase().includes(q) ? '' : 'none');
}

function exportXLS() { window.open('data:application/vnd.ms-excel,' + encodeURIComponent(document.getElementById('reportTable').outerHTML)); }

// MOTOR DE IMPRESIÓN (ESTILO TICKET)
window.PrintEngine = {
    saleInfo: null, configs: <?php echo json_encode($impresorasData); ?>,
    show: function(data) {
        this.saleInfo = data;
        const select = document.getElementById('pe-select-config');
        select.innerHTML = this.configs.map(c => `<option value="${c.ID_Config}" data-conf='${JSON.stringify(c).replace(/'/g, "&apos;")}'>${c.Nombre_Perfil}</option>`).join('');
        this.render(); new bootstrap.Modal(document.getElementById('modalPrintEngine')).show();
    },
    render: function() {
        const conf = JSON.parse(document.getElementById('pe-select-config').selectedOptions[0].dataset.conf);
        const info = this.saleInfo;
        const hoja = document.getElementById('pe-hoja-digital');
        hoja.style.width = conf.Tipo_Papel.includes('58') ? '58mm' : '80mm';
        hoja.innerHTML = `<div class="p-3" style="font-size:11px; font-family:sans-serif; color:#000;">
            <center><b>${conf.Nombre_Perfil}</b><br><small>${conf.Cabecera_Texto || ''}</small></center>
            <hr style="border-top:1px dashed #000;">
            <b>FOLIO: ${info.folio}</b><br>Cajero: ${info.vendedor}<hr style="border-top:1px dashed #000;">
            ${info.items.map(i => `<div style="display:flex; justify-content:space-between"><span>${parseInt(i.qty)}x ${i.nombre}</span><span>$${(i.qty*i.price).toFixed(2)}</span></div>`).join('')}
            <hr style="border-top:1px dashed #000;"><div style="text-align:right"><b>TOTAL: $${parseFloat(info.total).toFixed(2)}</b></div>
        </div>`;
    },
    printNow: function() {
        const win = window.open('', 'Imprimir');
        win.document.write(`<html><body>${document.getElementById('pe-hoja-digital').outerHTML}</body></html>`);
        win.document.close(); win.print(); win.close();
    },
    saveToApp: async function() {
        const sql = `INSERT INTO \`${CONFIG.pref}Documentos_Generados\` (UUID_Unico, Modulo_Origen, ID_Referencia, ID_Config_Impresora, Contenido_JSON, Estado) VALUES ('${this.saleInfo.folio}', 'Reimpresion', ${this.saleInfo.idRef}, ${document.getElementById('pe-select-config').value}, '${JSON.stringify(this.saleInfo).replace(/'/g, "\\'")}', 'PENDIENTE')`;
        const fd = new FormData(); fd.append('db', CONFIG.db); fd.append('sql', sql);
        await fetch('../librerias/AJAX/Execute.php', { method: 'POST', body: fd });
        Swal.fire('OK', 'Cola de impresión actualizada', 'success');
    }
};
</script>