<?php
try {
    $dbImp = $_SESSION['BD'] ?? "MS_Datos";
    $idProp = $_SESSION['IDUg'] ?? '1';
    $pdoImp = new PDO("mysql:host=localhost;dbname=$dbImp;charset=utf8", "root", "33comRxXMysql");
    $stmtImp = $pdoImp->query("SELECT * FROM `{$idProp}-Configuracion_Impresoras` WHERE Activo = 1");
    $impresorasData = $stmtImp->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $impresorasData = []; }
?>

<style>
    .pe-preview-bg { background-color: #525659; display: flex; justify-content: center; padding: 30px; height: 80vh; overflow-y: auto; }
    
    /* Contenedor de papel */
    .pe-paper { background: white; color: #000; box-sizing: border-box; position: relative; box-shadow: 0 0 20px rgba(0,0,0,0.5); font-family: 'Segoe UI', Arial, sans-serif; }

    /* DIMENSIONAMIENTO REAL */
    .pe-p-58mm { width: 58mm; padding: 4mm; font-size: 10px; }
    .pe-p-80mm { width: 80mm; padding: 6mm; font-size: 12px; }
    .pe-p-a4 { width: 210mm; min-height: 297mm; padding: 15mm; }
    .pe-p-a5 { width: 148mm; min-height: 210mm; padding: 10mm; }

    /* DISTRIBUCIÓN FACTURA (A4/A5) */
    .f-header { display: flex; justify-content: space-between; margin-bottom: 30px; border-bottom: 3px solid #f26522; padding-bottom: 15px; }
    .f-info-empresa { width: 60%; }
    .f-folio-box { width: 35%; border: 1px solid #ddd; border-radius: 10px; text-align: center; background: #fcfcfc; overflow: hidden; }
    .f-folio-title { background: #333; color: #fff; padding: 5px; font-weight: bold; font-size: 14px; }
    
    .f-client-section { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; background: #f9f9f9; padding: 15px; border-radius: 8px; margin-bottom: 25px; border: 1px solid #eee; }
    .f-label { color: #666; font-size: 10px; text-transform: uppercase; font-weight: bold; margin-bottom: 2px; }
    .f-value { font-size: 13px; font-weight: 600; color: #111; }

    .f-table { width: 100%; border-collapse: collapse; margin-bottom: 30px; }
    .f-table th { background: #f26522; color: white; padding: 12px 8px; text-align: left; font-size: 12px; border: 1px solid #f26522; }
    .f-table td { padding: 12px 8px; border-bottom: 1px solid #eee; font-size: 13px; }
    .f-table tr:nth-child(even) { background: #fafafa; }

    .f-footer-grid { display: grid; grid-template-columns: 1.5fr 1fr; gap: 40px; }
    .f-totals-table { width: 100%; border-collapse: collapse; }
    .f-totals-table td { padding: 8px; font-size: 14px; }
    .f-total-final { background: #fdecea; color: #d9534f; font-weight: bold; font-size: 20px !important; border-top: 2px solid #d9534f; }

    /* DISTRIBUCIÓN TICKET (58/80mm) */
    .t-center { text-align: center; margin-bottom: 10px; }
    .t-divider { border-top: 1px dashed #000; margin: 10px 0; }
</style>

<div class="modal fade" id="modalPrintEngine" tabindex="-1" data-backdrop="static">
    <div class="modal-dialog modal-xl" style="max-width: 95%;">
        <div class="modal-content border-0">
            <div class="modal-header bg-dark text-white p-2">
                <h6 class="modal-title font-weight-bold ml-2">VISOR DE IMPRESIÓN PROFESIONAL</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">
                <div class="pe-preview-bg">
                    <div id="pe-hoja-digital" class="pe-paper"></div>
                </div>
            </div>
            <div class="modal-footer bg-light p-2">
                <button class="btn btn-primary px-4 font-weight-bold" onclick="PrintEngine.printNow()">IMPRIMIR EN VENTANA</button>
                <button class="btn btn-success px-4 font-weight-bold" onclick="PrintEngine.saveToApp()">ENVIAR A LA APP</button>
                <button class="btn btn-secondary px-4" onclick="location.reload()">NUEVA VENTA</button>
            </div>
        </div>
    </div>
</div>

<script>
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)}'>${c.Nombre_Perfil} (${c.Tipo_Papel})</option>`).join('');
        this.render(); $('#modalPrintEngine').modal('show');
    },
    render: function() {
        const select = document.getElementById('pe-select-config');
        if(!select.selectedOptions[0]) return;
        const conf = JSON.parse(select.selectedOptions[0].dataset.conf);
        const info = this.saleInfo;
        const hoja = document.getElementById('pe-hoja-digital');
        const money = n => new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN' }).format(n);
        
        const esGrande = conf.Tipo_Papel.includes('A4') || conf.Tipo_Papel.includes('A5');
        hoja.className = `pe-paper pe-p-${conf.Tipo_Papel.toLowerCase().replace(" ", "")}`;

        if (esGrande) {
            // DISEÑO DISTRIBUIDO A4/A5
            hoja.innerHTML = `
                <div class="f-header">
                    <div class="f-info-empresa">
                        <img src="${conf.Logo_Base64||''}" style="max-height:70px; margin-bottom:10px; display:${conf.Logo_Base64?'block':'none'};">
                        <div style="font-size:12px; line-height:1.4;">${conf.Cabecera_Texto||'DATOS DE LA EMPRESA'}</div>
                    </div>
                    <div class="f-folio-box">
                        <div class="f-folio-title">NOTA DE VENTA</div>
                        <div style="padding:10px; color:red; font-size:18px; font-weight:bold;">${info.folio}</div>
                        <div style="background:#eee; font-size:10px; padding:3px; font-weight:bold;">FECHA DE EMISIÓN</div>
                        <div style="padding:5px; font-size:12px;">${new Date().toLocaleDateString()}</div>
                    </div>
                </div>

                <div class="f-client-section">
                    <div>
                        <div class="f-label">Información del Cliente</div>
                        <div class="f-value">${info.cliente}</div>
                        <div class="f-value" style="font-size:11px; color:#555;">Tel: ${info.telefono} | ${info.email || ''}</div>
                    </div>
                    <div style="text-align:right;">
                        <div class="f-label">Atendido por</div>
                        <div class="f-value">${info.vendedor}</div>
                        <div class="f-label" style="margin-top:5px;">Método de Pago</div>
                        <div class="f-value">${info.metodo}</div>
                    </div>
                </div>

                <table class="f-table">
                    <thead>
                        <tr>
                            <th width="10%">Cant.</th>
                            <th width="60%">Descripción del Producto</th>
                            <th width="15%" style="text-align:right;">P. Unit</th>
                            <th width="15%" style="text-align:right;">Importe</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${info.items.map(it => `
                            <tr>
                                <td align="center">${it.qty}</td>
                                <td><b>${it.nombre}</b></td>
                                <td align="right">${money(it.price)}</td>
                                <td align="right">${money(it.qty * it.price)}</td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>

                <div class="f-footer-grid">
                    <div>
                        <div class="f-label">Observaciones</div>
                        <div style="font-size:12px; border:1px solid #eee; padding:10px; border-radius:5px; min-height:60px; background:#fafafa;">
                            ${info.obs || 'Sin observaciones adicionales.'}
                        </div>
                        <div style="margin-top:20px; text-align:center;">
                            <img src="https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=${info.folio}" style="width:80px;">
                            <div style="font-size:9px; color:#999; margin-top:5px;">Comprobante Digital Válido</div>
                        </div>
                    </div>
                    <div>
                        <table class="f-totals-table">
                            <tr><td align="right">Subtotal:</td><td align="right"><b>${money(info.sub)}</b></td></tr>
                            <tr><td align="right">Descuento:</td><td align="right" style="color:green;"><b>- ${money(info.dsc)}</b></td></tr>
                            <tr><td align="right">I.V.A (16%):</td><td align="right"><b>${money(info.iva)}</b></td></tr>
                            <tr class="f-total-final"><td align="right">TOTAL:</td><td align="right">${money(info.total)}</td></tr>
                        </table>
                    </div>
                </div>
                
                <div style="position:absolute; bottom:15mm; left:15mm; right:15mm; text-align:center; font-size:10px; color:#888; border-top:1px solid #eee; padding-top:10px;">
                    ${conf.Pie_Pagina_Texto || 'Gracias por su compra.'}
                </div>
            `;
        } else {
            // DISEÑO TICKET (58/80mm)
            hoja.innerHTML = `
                <div class="t-center">
                    <img src="${conf.Logo_Base64||''}" style="max-width:80px; display:${conf.Logo_Base64?'inline':'none'};">
                    <div style="font-weight:bold; font-size:14px;">${conf.Nombre_Perfil}</div>
                    <div style="font-size:10px;">${conf.Cabecera_Texto||''}</div>
                </div>
                <div class="t-divider"></div>
                <div style="font-size:11px;">
                    <b>FOLIO: ${info.folio}</b><br>
                    Fecha: ${new Date().toLocaleDateString()}<br>
                    Cajero: ${info.vendedor}<br>
                    Cliente: ${info.cliente}
                </div>
                <div class="t-divider"></div>
                <table width="100%" style="font-size:11px;">
                    ${info.items.map(it => `
                        <tr><td colspan="2">${it.nombre}</td></tr>
                        <tr><td>${it.qty} x ${money(it.price)}</td><td align="right">${money(it.qty*it.price)}</td></tr>
                    `).join('')}
                </table>
                <div class="t-divider"></div>
                <div align="right" style="font-size:12px;">
                    Subtotal: ${money(info.sub)}<br>
                    Desc: - ${money(info.dsc)}<br>
                    IVA: ${money(info.iva)}<br>
                    <b style="font-size:16px;">TOTAL: ${money(info.total)}</b>
                </div>
                <div class="t-divider"></div>
                <div class="t-center" style="font-size:10px;">
                    ${conf.Pie_Pagina_Texto || '¡Vuelva pronto!'}
                </div>
            `;
        }
    },
    printNow: function() {
        const conf = JSON.parse(document.getElementById('pe-select-config').selectedOptions[0].dataset.conf);
        const win = window.open('', 'ImpresionV3', 'width=900,height=800');
        win.document.write(`<html><head><title>Imprimir Nota</title><style>
            @page { size: ${conf.Tipo_Papel} ${conf.Orientacion}; margin: 0; }
            body { margin: 0; padding: 0; -webkit-print-color-adjust: exact; }
            ${document.querySelector('style').innerHTML}
        </style></head><body>${document.getElementById('pe-hoja-digital').outerHTML}</body></html>`);
        win.document.close();
        win.print();
        win.close();
        location.reload();
    },
    saveToApp: async function() {
        const select = document.getElementById('pe-select-config');
        const idConfig = select.value;
        const info = this.saleInfo;
        const jsonContent = JSON.stringify(info).replace(/'/g, "\\'"); 
        const sql = `INSERT INTO \`<?php echo $idProp; ?>-Documentos_Generados\` (UUID_Unico, Modulo_Origen, ID_Referencia, ID_Config_Impresora, Contenido_JSON, Estado) VALUES ('${info.folio}', 'NotaVenta', ${info.idRef}, ${idConfig}, '${jsonContent}', 'PENDIENTE')`;
        const fd = new FormData();
        fd.append('db', '<?php echo $dbName; ?>'); fd.append('sql', sql);
        const resp = await fetch('../librerias/AJAX/Execute.php', { method: 'POST', body: fd }).then(r => r.json());
        if(resp.status === 'success' || resp.last_id) { alert("¡Enviado a la App!"); location.reload(); }
    }
};
</script>