<?php
/* --------------------------------------------------------------------------------
   MÓDULO: HISTORIAL DE COMPRAS (INTEGRADO CON TU CONFIGURACIÓN)
   --------------------------------------------------------------------------------
*/
error_reporting(E_ALL);
ini_set('display_errors', 0);

session_start();
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') {
    die('<div class="alert alert-danger">Acceso Denegado.</div>');
}

// 1. CONTEXTO DE BASE DE DATOS (IGUAL A TU CONFIGURACIÓN)
$nombre_bd = "MS_Datos"; 
// Usamos la lógica de prefijo que me pasaste (Default 101)
$prefijo   = isset($_GET['IDU']) ? $_GET['IDU'] : ($_SESSION['IDU'] ?? '101');

$APP_CONFIG = [
    'db'     => $nombre_bd,
    'tables' => [
        'cab'    => $prefijo . "-Compras_Cabecera",
        'det'    => $prefijo . "-Compras_Detalle",
        'series' => $prefijo . "-Productos_Series", 
        'prov'   => $prefijo . "-Proveedores",
        'prod'   => $prefijo . "-Productos_Catalogo",
        'config' => $prefijo . "-Configuracion_Impresoras" // Tabla vinculada a tu código anterior
    ]
];
?>

<style>
    :root {
        --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        --dark-gradient: linear-gradient(135deg, #232526 0%, #414345 100%);
    }

    /* MODAL FULLSCREEN */
    .modal-xl-custom {
        max-width: 96% !important;
        width: 96% !important;
        margin: 10px auto;
    }
    
    .modal-body-scroll {
        max-height: 85vh;
        overflow-y: auto;
        background-color: #f4f7f6;
    }

    /* BOTONES */
    .btn-pro {
        border-radius: 8px; font-weight: 600; padding: 8px 16px; border: none;
        box-shadow: 0 4px 6px rgba(50, 50, 93, 0.11); transition: all 0.3s;
    }
    .btn-pro-dark { background: var(--dark-gradient); color: white; }
    .btn-pro-dark:hover { box-shadow: 0 5px 15px rgba(0,0,0,0.3); color: white; transform: translateY(-1px); }

    /* --- ESTILOS DE IMPRESIÓN (LIVE PREVIEW) --- */
    .preview-container {
        background: #525659;
        min-height: 100%;
        padding: 40px;
        display: flex;
        justify-content: center;
        overflow-y: auto;
    }

    .paper-sheet {
        background: white;
        box-shadow: 0 0 25px rgba(0,0,0,0.5);
        transition: all 0.3s ease; /* Transición suave al cambiar tamaño */
        padding: 15px;
        margin-bottom: 50px;
    }

    /* TAMAÑOS DE PAPEL (Coinciden con tu Config) */
    .sheet-58mm { width: 58mm; min-height: 200mm; font-family: 'Courier New', monospace; font-size: 10px; padding: 5px; }
    .sheet-80mm { width: 80mm; min-height: 200mm; font-family: 'Courier New', monospace; font-size: 11px; }
    .sheet-a5   { width: 148mm; min-height: 210mm; font-family: 'Arial', sans-serif; padding: 15mm; font-size: 12px; }
    .sheet-a4   { width: 210mm; min-height: 297mm; font-family: 'Arial', sans-serif; padding: 20mm; font-size: 13px; }

    /* ESTILOS DE IMPRESIÓN REAL */
    @media print {
        @page { margin: 0; }
        body * { visibility: hidden; }
        #areaImpresion, #areaImpresion * { visibility: visible; }
        #areaImpresion { position: absolute; left: 0; top: 0; margin: 0; padding: 0; background: white; box-shadow: none; }
        
        /* Forzar anchos en impresión */
        .sheet-58mm { width: 58mm; max-width: 58mm; }
        .sheet-80mm { width: 80mm; max-width: 80mm; }
        .sheet-a5   { width: 100%; padding: 10mm; }
        .sheet-a4   { width: 100%; padding: 15mm; }
    }
</style>

<div class="container-fluid p-4">
    
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="font-weight-bold text-dark mb-0">Gestión de Compras</h3>
            <span class="text-muted small">Panel de control de entradas</span>
        </div>
        <div class="bg-white p-2 rounded shadow-sm d-flex align-items-center">
            <i class="fas fa-filter text-muted mr-2"></i>
            <input type="date" id="filtroFecha" class="form-control border-0 font-weight-bold" value="<?php echo date('Y-m-d'); ?>" onchange="cargarListaCompras()">
        </div>
    </div>

    <div class="card shadow-sm border-0 rounded-lg overflow-hidden">
        <div class="card-body p-0">
            <table class="table table-hover mb-0 align-middle">
                <thead class="bg-light text-secondary">
                    <tr>
                        <th class="pl-4 py-3 border-0">FOLIO</th>
                        <th class="py-3 border-0">PROVEEDOR</th>
                        <th class="py-3 border-0">ESTADO</th>
                        <th class="text-right py-3 border-0">TOTAL</th>
                        <th class="text-center py-3 border-0">ACCIONES</th>
                    </tr>
                </thead>
                <tbody id="tblComprasBody">
                    <tr><td colspan="5" class="text-center py-5"><div class="spinner-border text-primary"></div></td></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="modalDetalles" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl-custom">
        <div class="modal-content border-0 shadow-lg h-100">
            <div class="modal-header bg-white border-bottom-0 py-3">
                <h5 class="modal-title font-weight-bold text-primary"><i class="fas fa-box-open mr-2"></i>Detalle de Entrada</h5>
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
            </div>
            
            <div class="modal-body modal-body-scroll" id="contenedorDetalles"></div>

            <div class="modal-footer bg-white border-top-0">
                <button type="button" class="btn btn-light text-muted font-weight-bold" data-dismiss="modal">Cerrar</button>
                <button type="button" class="btn btn-pro btn-pro-dark" id="btnImprimirModal">
                    <i class="fas fa-print mr-2"></i>Imprimir Ticket
                </button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalImpresion" tabindex="-1" data-backdrop="static" aria-hidden="true">
    <div class="modal-dialog modal-xl-custom">
        <div class="modal-content border-0 h-100">
            <div class="modal-header bg-dark text-white py-2">
                <h6 class="modal-title font-weight-light"><i class="fas fa-print mr-2"></i>Centro de Impresión</h6>
                <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body p-0 h-100">
                <div class="row no-gutters h-100">
                    <div class="col-md-3 bg-white border-right p-4 h-100 overflow-auto">
                        <h6 class="text-uppercase text-muted font-weight-bold small mb-4">Configuración</h6>
                        
                        <div class="form-group mb-4">
                            <label class="font-weight-bold text-dark">Perfil de Impresora</label>
                            <select id="selImpresora" class="form-control custom-select shadow-sm" style="height: 50px;" onchange="actualizarVistaPrevia()">
                                </select>
                            <small class="text-muted">Selecciona un perfil guardado.</small>
                        </div>

                        <div class="alert alert-info small border-0">
                            <i class="fas fa-info-circle mr-1"></i> El formato se ajusta automáticamente (A4/A5 o Ticket) según lo configurado.
                        </div>

                        <hr class="my-4">
                        
                        <button class="btn btn-pro btn-pro-dark btn-block btn-lg" onclick="window.print()">
                            <i class="fas fa-print mr-2"></i> IMPRIMIR
                        </button>
                    </div>

                    <div class="col-md-9 preview-container">
                        <div id="areaImpresion" class="paper-sheet sheet-80mm"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    const DB_CONFIG = <?php echo json_encode($APP_CONFIG); ?>;
    let CACHE_DATOS_COMPRA = null;
    let CACHE_PERFILES = [];

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

    // 1. CARGAR LISTA
    async function cargarListaCompras() {
        const fecha = document.getElementById('filtroFecha').value;
        const tbody = document.getElementById('tblComprasBody');
        tbody.innerHTML = '<tr><td colspan="5" class="text-center py-5"><div class="spinner-border text-primary"></div></td></tr>';

        const sql = `
            SELECT C.ID_Compra, C.Folio_Factura, C.Total_Compra, C.Estado, P.razon_social 
            FROM \`${DB_CONFIG.db}\`.\`${DB_CONFIG.tables.cab}\` C
            LEFT JOIN \`${DB_CONFIG.db}\`.\`${DB_CONFIG.tables.prov}\` P ON C.IDP = P.IDPr
            WHERE DATE(C.Fecha) = '${fecha}' ORDER BY C.ID_Compra DESC
        `;

        const res = await ajaxSelect(sql);
        tbody.innerHTML = '';

        if (!res.data || res.data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="5" class="text-center py-5 text-muted">No hay registros hoy.</td></tr>';
            return;
        }

        res.data.forEach(row => {
            const bgStatus = row.Estado === 'Finalizada' ? 'badge-success' : 'badge-warning';
            tbody.innerHTML += `
                <tr>
                    <td class="pl-4 font-weight-bold text-dark">${row.Folio_Factura}</td>
                    <td>${row.razon_social}</td>
                    <td><span class="badge ${bgStatus} px-3 py-1">${row.Estado}</span></td>
                    <td class="text-right font-weight-bold">$${parseFloat(row.Total_Compra).toFixed(2)}</td>
                    <td class="text-center">
                        <button class="btn btn-light btn-sm shadow-sm border mr-1" onclick="abrirModalDetalles(${row.ID_Compra})" title="Ver">
                            <i class="fas fa-eye text-primary"></i>
                        </button>
                        <button class="btn btn-dark btn-sm shadow-sm" onclick="abrirModalImpresion(${row.ID_Compra})" title="Imprimir">
                            <i class="fas fa-print"></i>
                        </button>
                    </td>
                </tr>`;
        });
    }

    // 2. OBTENER DATOS
    async function fetchFullData(idCompra) {
        Swal.fire({ title: 'Cargando...', didOpen: () => Swal.showLoading(), backdrop: 'rgba(0,0,0,0.5)', background:'transparent', showConfirmButton: false });

        const sqlCab = `SELECT C.*, P.razon_social, P.rfc, P.telefono 
                        FROM \`${DB_CONFIG.db}\`.\`${DB_CONFIG.tables.cab}\` C
                        LEFT JOIN \`${DB_CONFIG.db}\`.\`${DB_CONFIG.tables.prov}\` P ON C.IDP = P.IDPr
                        WHERE C.ID_Compra = ${idCompra}`;

        // COLLATE Fix y Columnas correctas
        const sqlDet = `SELECT D.*, CAT.nombre, CAT.sku as sku_real 
                        FROM \`${DB_CONFIG.db}\`.\`${DB_CONFIG.tables.det}\` D
                        LEFT JOIN \`${DB_CONFIG.db}\`.\`${DB_CONFIG.tables.prod}\` CAT 
                        ON D.SKU = CAT.sku COLLATE utf8mb4_unicode_ci
                        WHERE D.ID_Compra = ${idCompra}`;

        const sqlSeries = `SELECT * FROM \`${DB_CONFIG.db}\`.\`${DB_CONFIG.tables.series}\` WHERE ID_Compra = ${idCompra}`;

        try {
            const [rC, rD, rS] = await Promise.all([ajaxSelect(sqlCab), ajaxSelect(sqlDet), ajaxSelect(sqlSeries)]);
            Swal.close();
            if(!rC.data || rC.data.length === 0) throw new Error("No data");
            
            return { cabecera: rC.data[0], items: rD.data || [], series: rS.data || [] };
        } catch (e) {
            Swal.close(); console.error(e); return null;
        }
    }

    // 3. DETALLES
    async function abrirModalDetalles(idCompra) {
        const d = await fetchFullData(idCompra);
        if(!d) return;
        CACHE_DATOS_COMPRA = d;
        const c = d.cabecera;

        let rows = '';
        d.items.forEach(item => {
            const misSeries = d.series.filter(s => s.SKU == item.SKU);
            let badgeSeries = misSeries.length > 0 ? `<div class="mt-1">` + misSeries.map(s => `<span class="badge badge-light border text-muted mr-1">${s.Serie}</span>`).join('') + `</div>` : '';
            rows += `<tr><td class="align-middle pl-4"><div class="font-weight-bold text-dark">${item.nombre || 'Producto'}</div><div class="small text-muted">SKU: ${item.SKU}</div>${badgeSeries}</td><td class="text-center align-middle">${parseFloat(item.Cantidad)}</td><td class="text-right align-middle">$${parseFloat(item.Costo_Unitario).toFixed(2)}</td><td class="text-right align-middle font-weight-bold">$${parseFloat(item.Subtotal).toFixed(2)}</td></tr>`;
        });

        const html = `
            <div class="row mb-4">
                <div class="col-md-4"><div class="card p-3 shadow-sm border h-100"><small class="text-muted font-weight-bold">PROVEEDOR</small><h5 class="text-primary mt-1">${c.razon_social}</h5><div class="small text-muted">RFC: ${c.rfc || '-'}</div></div></div>
                <div class="col-md-4"><div class="card p-3 shadow-sm border h-100"><small class="text-muted font-weight-bold">FACTURA</small><h5 class="text-dark mt-1">${c.Folio_Factura}</h5><div class="small text-muted">${c.Fecha}</div></div></div>
                <div class="col-md-4"><div class="card p-3 shadow-sm border h-100 bg-dark text-white"><small class="text-white-50 font-weight-bold">TOTAL</small><h2 class="mb-0 font-weight-bold">$${parseFloat(c.Total_Compra).toFixed(2)}</h2></div></div>
            </div>
            <div class="card border-0"><div class="card-body p-0"><table class="table table-striped mb-0"><thead class="thead-light"><tr><th class="pl-4">Descripción</th><th class="text-center">Cant</th><th class="text-right">Costo</th><th class="text-right pr-4">Total</th></tr></thead><tbody>${rows}</tbody></table></div></div>
        `;

        document.getElementById('contenedorDetalles').innerHTML = html;
        document.getElementById('btnImprimirModal').onclick = () => { $('#modalDetalles').modal('hide'); abrirModalImpresion(c.ID_Compra); };
        $('#modalDetalles').modal('show');
    }

    // 4. IMPRESIÓN CORREGIDA Y SINCRONIZADA
    async function cargarPerfilesImpresora() {
        // Leemos la tabla de configuración que me pasaste
        const res = await ajaxSelect(`SELECT * FROM \`${DB_CONFIG.db}\`.\`${DB_CONFIG.tables.config}\` WHERE Activo = 1`);
        CACHE_PERFILES = res.data || [];
        const sel = document.getElementById('selImpresora');
        sel.innerHTML = '';
        
        if (CACHE_PERFILES.length === 0) {
            sel.innerHTML = '<option value="-1">Predeterminado (Ticket 80mm)</option>';
        } else {
            CACHE_PERFILES.forEach((p, i) => sel.innerHTML += `<option value="${i}">${p.Nombre_Perfil} (${p.Tipo_Papel})</option>`);
        }
    }

    async function abrirModalImpresion(id) {
        if(!CACHE_DATOS_COMPRA || CACHE_DATOS_COMPRA.cabecera.ID_Compra != id) {
            const d = await fetchFullData(id);
            if(!d) return;
            CACHE_DATOS_COMPRA = d;
        }
        $('#modalImpresion').modal('show');
        setTimeout(actualizarVistaPrevia, 200); 
    }

    function actualizarVistaPrevia() {
        if (!CACHE_DATOS_COMPRA) return;
        
        const area = document.getElementById('areaImpresion');
        const sel = document.getElementById('selImpresora');
        const idx = sel.value;
        
        // Obtenemos los datos del perfil (si no existe, usamos default)
        const perfil = CACHE_PERFILES[idx] || { Tipo_Papel: '80mm', Cabecera_Texto: 'VISTA PREVIA' };
        const c = CACHE_DATOS_COMPRA.cabecera;
        
        // --- AQUÍ ESTÁ LA LÓGICA QUE CONECTA CON TU CÓDIGO ---
        const tipoPapel = String(perfil.Tipo_Papel).toUpperCase(); // 'A4', 'A5', '80MM', '58MM'
        
        // 1. Limpieza de Clases
        area.className = 'paper-sheet';
        void area.offsetWidth; // Force Reflow

        // 2. Asignar Clase CSS Correcta
        if(tipoPapel === 'A4' || tipoPapel === 'CARTA') {
            area.classList.add('sheet-a4');
        } else if (tipoPapel === 'A5') {
            area.classList.add('sheet-a5');
        } else if (tipoPapel === '58MM') {
            area.classList.add('sheet-58mm');
        } else {
            area.classList.add('sheet-80mm'); // Default
        }

        // 3. Decidir Formato: ¿Es Hoja Grande (Tabla) o Ticket (Lista)?
        const esHojaGrande = ['A4', 'A5', 'CARTA', 'LETTER'].includes(tipoPapel);

        let htmlContent = '';

        if (esHojaGrande) {
            // --- DISEÑO TIPO TABLA (A4 / A5) ---
            let rows = CACHE_DATOS_COMPRA.items.map(item => `
                <tr>
                    <td style="padding:8px; border-bottom:1px solid #ddd;">${item.SKU}</td>
                    <td style="padding:8px; border-bottom:1px solid #ddd;">${item.nombre}</td>
                    <td align="center" style="padding:8px; border-bottom:1px solid #ddd;">${parseFloat(item.Cantidad)}</td>
                    <td align="right" style="padding:8px; border-bottom:1px solid #ddd;">$${parseFloat(item.Subtotal).toFixed(2)}</td>
                </tr>
            `).join('');

            htmlContent = `
                <div style="font-family: Arial, sans-serif; width:100%;">
                    <table width="100%" style="margin-bottom:20px;">
                        <tr>
                            <td>${perfil.Logo_Base64 ? `<img src="${perfil.Logo_Base64}" style="height:60px;">` : ''}</td>
                            <td align="right">
                                <h3 style="margin:0;">${perfil.Cabecera_Texto || 'ENTRADA DE ALMACÉN'}</h3>
                                <div>Folio: <strong>${c.Folio_Factura}</strong></div>
                                <small>${c.Fecha}</small>
                            </td>
                        </tr>
                    </table>
                    <div style="background:#f8f9fa; border:1px solid #ddd; padding:10px; margin-bottom:15px;">
                        <strong>Proveedor:</strong> ${c.razon_social}<br>
                        RFC: ${c.rfc || ''} | Tel: ${c.telefono || ''}
                    </div>
                    <table width="100%" cellspacing="0" style="font-size:12px;">
                        <thead style="background:#333; color:white;">
                            <tr><th align="left" style="padding:8px;">SKU</th><th align="left" style="padding:8px;">Descripción</th><th align="center" style="padding:8px;">Cant</th><th align="right" style="padding:8px;">Importe</th></tr>
                        </thead>
                        <tbody>${rows}</tbody>
                    </table>
                    <div style="text-align:right; margin-top:20px;"><h3>Total: $${parseFloat(c.Total_Compra).toFixed(2)}</h3></div>
                    <div style="position:fixed; bottom:0; width:100%; text-align:center; font-size:10px; border-top:1px solid #ccc; padding-top:5px;">${perfil.Pie_Pagina_Texto || 'Documento Interno'}</div>
                </div>`;
        
        } else {
            // --- DISEÑO TIPO TICKET (80mm / 58mm) ---
            let rows = CACHE_DATOS_COMPRA.items.map(item => {
                const series = CACHE_DATOS_COMPRA.series.filter(s=>s.SKU == item.SKU).map(s=>s.Serie).join(', ');
                return `
                <tr><td colspan="2" style="padding-top:4px; font-weight:bold; font-size:1em;">${item.nombre}</td></tr>
                <tr>
                    <td style="border-bottom:1px dashed #ccc; padding-bottom:4px; font-size:0.9em;">
                        ${parseFloat(item.Cantidad)} x $${parseFloat(item.Costo_Unitario).toFixed(2)}
                        ${series ? `<br><span style="font-size:0.8em;">SN: ${series}</span>` : ''}
                    </td>
                    <td align="right" style="border-bottom:1px dashed #ccc; padding-bottom:4px;">$${parseFloat(item.Subtotal).toFixed(2)}</td>
                </tr>`;
            }).join('');

            htmlContent = `
                <div style="text-align:center; font-family:'Courier New';">
                    ${perfil.Logo_Base64 ? `<img src="${perfil.Logo_Base64}" style="max-width:80%; margin-bottom:5px;">` : ''}
                    <h5 style="margin:5px 0 0; text-transform:uppercase;">${perfil.Cabecera_Texto || 'TICKET'}</h5>
                    <div style="font-size:0.8em;">${c.Fecha}</div>
                    <div style="font-weight:bold; margin-bottom:5px;">Folio: ${c.Folio_Factura}</div>
                </div>
                <div style="border-top:1px solid #000; border-bottom:1px solid #000; font-size:0.85em; text-align:center;">${c.razon_social}</div>
                <table width="100%" cellspacing="0">${rows}</table>
                <div style="text-align:right; margin-top:10px; font-weight:bold; font-size:1.2em; border-top:1px solid #000;">TOTAL: $${parseFloat(c.Total_Compra).toFixed(2)}</div>
                <div style="text-align:center; margin-top:15px; font-size:0.8em;">${perfil.Pie_Pagina_Texto || 'Gracias'}</div>`;
        }

        area.innerHTML = htmlContent;
    }

    async function ajaxSelect(sql) {
        const fd = new FormData(); fd.append('sql', sql); fd.append('db', DB_CONFIG.db);
        try { return await (await fetch('../librerias/AJAX/Select.php', { method: 'POST', body: fd })).json(); } catch (e) { return { data: [] }; }
    }
</script>