<?php
/**
 * POS PROFESIONAL - RELEASE FINAL 
 * Formatos: A4, A5, 58mm, 80mm | Orientación: Vertical (Portrait) / Horizontal (Landscape)
 */
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') { die("Acceso denegado."); }

$dbName = $_SESSION['BD'] ?? "MS_Datos"; 
$idProp = $_SESSION['IDUg'] ?? '1'; 
$prefijo = "$idProp-"; 

try {
    $pdo = new PDO("mysql:host=localhost;dbname=$dbName;charset=utf8", "root", "33comRxXMysql"); 
    
    // 1. Cargar Impresoras Activas
    $stmtImp = $pdo->query("SELECT * FROM `{$prefijo}Configuracion_Impresoras` WHERE Activo = 1");
    $impresorasData = $stmtImp->fetchAll(PDO::FETCH_ASSOC);

    // 2. Generar Folio PED-YYMMDD-XXX
    $hoy = date('ymd'); 
    $prefijoFolio = "PED-" . $hoy . "-";
    $sqlF = "SELECT Folio FROM `{$prefijo}Pedidos_Ventas` WHERE Folio LIKE '$prefijoFolio%' ORDER BY ID_Pedido DESC LIMIT 1";
    $resF = $pdo->query($sqlF)->fetch(PDO::FETCH_ASSOC);
    $nuevoC = $resF ? intval(substr($resF['Folio'], -3)) + 1 : 1;
    $folioPED = $prefijoFolio . str_pad($nuevoC, 3, "0", STR_PAD_LEFT);
} catch (Exception $e) { $impresorasData = []; $folioPED = "PED-ERROR"; }
?>

<style>
    /* Estructura Principal */
    .pos-main-container { background: #f4f7f6; margin: -20px; padding: 20px; min-height: 90vh; }
    .card-custom { border: none; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); background: #fff; }
    
    /* Folio Letras Blancas */
    .folio-badge { background: #1a202c; color: #ffffff !important; padding: 10px 20px; border-radius: 8px; font-weight: bold; }
    #lbl_folio_v { color: #ffffff !important; font-weight: bold; }

    /* Banner de Cliente */
    .client-banner { background: #ebf4ff; border: 1px solid #bee3f8; border-radius: 12px; padding: 15px 20px; display: flex; align-items: center; justify-content: space-between; margin-top: 10px; }
    .client-banner i { font-size: 2rem; color: #3182ce; margin-right: 15px; }

    /* Buscador Autocomplete */
    .search-wrapper { position: relative; }
    #res-cli-search { position: absolute; top: 100%; left: 0; right: 0; z-index: 2000; background: #fff; border-radius: 12px; border: 1px solid #e3e6f0; box-shadow: 0 10px 25px rgba(0,0,0,0.1); display: none; }
    .cli-item { padding: 12px 20px; cursor: pointer; border-bottom: 1px solid #f1f3f9; }

    /* === PRINT ENGINE: DIMENSIONES REALES === */
    .pe-preview-bg { background-color: #525659; display: flex; justify-content: center; padding: 30px; height: 75vh; overflow-y: auto; }
    .pe-paper { background: white; box-shadow: 0 0 30px rgba(0,0,0,0.6); color: #000; margin-bottom: 50px; transition: all 0.3s ease; transform-origin: top center; }
    
    /* Definición de Tamaños y Orientaciones */
    .pe-p-58mm { width: 58mm; padding: 5mm; font-size: 10px; }
    .pe-p-80mm { width: 80mm; padding: 8mm; font-size: 12px; }
    
    .pe-p-a5.portrait  { width: 148mm; min-height: 210mm; padding: 15mm; }
    .pe-p-a5.landscape { width: 210mm; min-height: 148mm; padding: 15mm; }
    
    .pe-p-a4.portrait  { width: 210mm; min-height: 297mm; padding: 25mm; }
    .pe-p-a4.landscape { width: 297mm; min-height: 210mm; padding: 25mm; }

    .pe-table-pro { width: 100%; border-collapse: collapse; margin-top: 20px; }
    .pe-table-pro th { background: #f26522; color: #fff; padding: 10px; border: 1px solid #f26522; text-align: left; }
    .pe-table-pro td { padding: 10px; border: 1px solid #eee; }
</style>



<div class="pos-main-container">
    <div class="row">
        <div class="col-lg-8">
            <div class="card card-custom mb-4">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h4 class="font-weight-bold m-0">Levantar Pedido</h4>
                        <div class="folio-badge">FOLIO: <span id="lbl_folio_v"><?php echo $folioPED; ?></span></div>
                    </div>

                    <div id="cli-search-section">
                        <label class="small font-weight-bold text-muted text-uppercase">Seleccionar Cliente</label>
                        <div class="search-wrapper">
                            <div class="input-group">
                                <input type="text" id="cli-input" class="form-control form-control-lg" placeholder="Nombre o teléfono..." autocomplete="off">
                                <input type="hidden" id="sel-idc">
                                <div class="input-group-append">
                                    <button class="btn btn-primary" onclick="$('#mdl-new-cli').modal('show')"><i class="feather icon-plus"></i></button>
                                </div>
                            </div>
                            <div id="res-cli-search"></div>
                        </div>
                    </div>

                    <div id="cli-banner" class="client-banner d-none">
                        <div class="d-flex align-items-center">
                            <i class="feather icon-user"></i>
                            <div class="client-info">
                                <h6 id="cli-name-lbl" class="m-0 font-weight-bold"></h6>
                                <p id="cli-tel-lbl" class="m-0 small text-muted"></p>
                            </div>
                        </div>
                        <button class="btn btn-outline-danger btn-sm font-weight-bold" onclick="app.resetCli()">CAMBIAR</button>
                    </div>

                    <div class="p-3 rounded my-4" style="background: #f8f9fc; border: 1px dashed #cbd5e0;">
                        <div class="row g-2">
                            <div class="col-md-6"><input type="text" id="in-prod" class="form-control" placeholder="Descripción del producto"></div>
                            <div class="col-md-2"><input type="number" id="in-cant" class="form-control" value="1"></div>
                            <div class="col-md-3"><input type="number" id="in-prec" class="form-control" placeholder="Precio $"></div>
                            <div class="col-md-1"><button class="btn btn-dark w-100" onclick="app.addItem()"><i class="feather icon-plus"></i></button></div>
                        </div>
                    </div>

                    <table class="table align-middle">
                        <thead class="bg-light small"><tr><th>Descripción</th><th class="text-center">Cant</th><th class="text-right">Unitario</th><th class="text-right">Subtotal</th><th class="text-center">#</th></tr></thead>
                        <tbody id="cart-table"></tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="card card-custom p-4">
                <div class="text-center mb-4">
                    <small class="text-muted font-weight-bold">TOTAL A PAGAR</small>
                    <h1 class="font-weight-bold" id="lbl-total-top">$ 0.00</h1>
                </div>
                <div class="form-group">
                    <label class="font-weight-bold">Anticipo / Adelanto $</label>
                    <input type="number" id="in-anticipo" class="form-control form-control-lg border-success" value="0" onkeyup="app.calc()">
                </div>
                <div class="bg-light p-3 text-center border rounded mb-4">
                    <small class="text-muted font-weight-bold">RESTANTE POR COBRAR</small>
                    <h2 class="text-danger font-weight-bold m-0" id="lbl-resta">$ 0.00</h2>
                </div>
                <button class="btn btn-primary btn-lg btn-block shadow-lg font-weight-bold" onclick="app.save()">
                    <i class="feather icon-printer mr-2"></i>GUARDAR E IMPRIMIR
                </button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="mdl-new-cli" tabindex="-1">
    <div class="modal-dialog modal-sm modal-dialog-centered">
        <div class="modal-content shadow-lg p-4">
            <h5 class="font-weight-bold text-center mb-3 text-primary">Nuevo Cliente</h5>
            <input type="text" id="nc-nom" class="form-control mb-2" placeholder="Nombre completo">
            <input type="text" id="nc-tel" class="form-control mb-4" placeholder="Teléfono">
            <button class="btn btn-success btn-block py-2 font-weight-bold" onclick="app.saveNewCli()">GUARDAR REGISTRO</button>
        </div>
    </div>
</div>

<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">PREVISUALIZACIÓN DE IMPRESIÓN</h6>
                <select id="pe-select-config" class="form-control form-control-sm ml-auto" style="width:300px;" 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-outline-dark px-4 font-weight-bold" onclick="PrintEngine.printNow()">IMPRIMIR WEB (PDF)</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()">CERRAR / NUEVO</button>
            </div>
        </div>
    </div>
</div>

<script>
const AJAX_S = "../librerias/AJAX/Select.php";
const AJAX_E = "../librerias/AJAX/Execute.php";
const DB_NAME = "<?php echo $dbName; ?>";
const PREFIJO = "<?php echo $prefijo; ?>";

const app = (function() {
    let cart = [], selectedCli = null;
    const api = async (f, s) => {
        const fd = new FormData(); fd.append('sql', s); fd.append('db', DB_NAME);
        return await fetch(f, { method: 'POST', body: fd }).then(r => r.json());
    };

    return {
        init: function() {
            document.getElementById('cli-input').onkeyup = async (e) => {
                const v = e.target.value.toLowerCase();
                if(v.length < 3) return;
                const r = await api(AJAX_S, `SELECT IDC, Nombre, Telefono FROM \`${PREFIJO}Clientes\` WHERE Nombre LIKE '%${v}%' OR Telefono LIKE '%${v}%' LIMIT 5`);
                const resBox = document.getElementById('res-cli-search'); resBox.innerHTML = '';
                if(r.data && r.data.length) {
                    resBox.style.display = 'block';
                    r.data.forEach(c => {
                        const d = document.createElement('div'); d.className = 'cli-item';
                        d.innerHTML = `<b>${c.Nombre}</b><br><small>${c.Telefono}</small>`;
                        d.onclick = () => app.setCli(c); resBox.appendChild(d);
                    });
                }
            };
        },
        setCli: function(c) {
            selectedCli = c; document.getElementById('sel-idc').value = c.IDC;
            document.getElementById('cli-name-lbl').innerText = c.Nombre;
            document.getElementById('cli-tel-lbl').innerText = "Teléfono: " + (c.Telefono || 'S/T');
            document.getElementById('cli-banner').classList.remove('d-none');
            document.getElementById('cli-search-section').classList.add('d-none');
            document.getElementById('res-cli-search').style.display = 'none';
        },
        resetCli: function() {
            selectedCli = null; document.getElementById('cli-banner').classList.add('d-none');
            document.getElementById('cli-search-section').classList.remove('d-none');
            document.getElementById('cli-input').value = ''; document.getElementById('cli-input').focus();
        },
        saveNewCli: async function() {
            const n = document.getElementById('nc-nom').value, t = document.getElementById('nc-tel').value;
            if(!n) return;
            const r = await api(AJAX_E, `INSERT INTO \`${PREFIJO}Clientes\` (Nombre, Telefono, EstadoCliente) VALUES ('${n}', '${t}', 'Activo')`);
            if(r.status === 'success') { app.setCli({IDC: r.last_id, Nombre: n, Telefono: t}); $('#mdl-new-cli').modal('hide'); }
        },
        addItem: function() {
            const p = $('#in-prod').val(), c = parseFloat($('#in-cant').val()), pr = parseFloat($('#in-prec').val());
            if(!p || pr <= 0) return;
            cart.push({ producto: p, cant: c, precio: pr, total: c * pr });
            $('#in-prod, #in-prec').val(''); this.render();
        },
        render: function() {
            let h = '', t = 0;
            cart.forEach((i, idx) => { t += i.total; h += `<tr><td>${i.producto}</td><td class="text-center">${i.cant}</td><td class="text-right">$ ${i.precio.toFixed(2)}</td><td class="text-right fw-bold">$ ${i.total.toFixed(2)}</td><td class="text-center"><i class="feather icon-trash-2 text-danger pointer" onclick="app.remove(${idx})"></i></td></tr>`; });
            $('#cart-table').html(h); $('#lbl-total-top').text(`$ ${t.toFixed(2)}`); this.calc();
        },
        remove: (idx) => { cart.splice(idx, 1); app.render(); },
        calc: function() {
            const total = parseFloat($('#lbl-total-top').text().replace('$ ','')) || 0;
            const ant = parseFloat($('#in-anticipo').val()) || 0;
            $('#lbl-resta').text(`$ ${(total - ant).toFixed(2)}`);
        },
        save: async function() {
            const idc = document.getElementById('sel-idc').value;
            if(!idc || !cart.length) return alert("Falta cliente o productos");
            const fol = $('#lbl_folio_v').text();
            const total = parseFloat($('#lbl-total-top').text().replace('$ ',''));
            const ant = parseFloat($('#in-anticipo').val()) || 0;
            
            // SQL SEGURO: Sin columna 'Resta' (es generada en DB)
            const sqlV = `INSERT INTO \`${PREFIJO}Pedidos_Ventas\` (Folio, IDC, Productos_JSON, Total_Venta, Anticipo, QR_Data) VALUES ('${fol}', ${idc}, '${JSON.stringify(cart).replace(/'/g, "''")}', ${total}, ${ant}, '${fol}')`;
            const rV = await api(AJAX_E, sqlV);
            if(rV.status === 'success') {
                const printData = { folio: fol, idRef: rV.last_id, cliente: selectedCli.Nombre, items: cart, total, anticipo: ant, resta: total-ant, fecha: new Date().toLocaleString() };
                PrintEngine.show(printData);
            }
        }
    };
})();

const PrintEngine = {
    info: null,
    configs: <?php echo json_encode($impresorasData); ?>,
    show: function(data) {
        this.info = data;
        const s = document.getElementById('pe-select-config');
        s.innerHTML = this.configs.map(c => `<option value="${c.ID_Config}" data-conf='${JSON.stringify(c)}'>${c.Nombre_Perfil} (${c.Tipo_Papel} - ${c.Orientacion})</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 i = this.info; const hoja = document.getElementById('pe-hoja-digital');
        const money = n => new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN' }).format(n);
        
        // APLICAR CLASES DE PAPEL Y ORIENTACIÓN DINÁMICA
        const papel = conf.Tipo_Papel.toLowerCase();
        const ori = conf.Orientacion.toLowerCase();
        hoja.className = `pe-paper pe-p-${papel} ${ori}`;
        
        hoja.innerHTML = `
            <div style="text-align:center;">
                <img src="${conf.Logo_Base64||''}" style="max-width:${papel.includes('mm')?'85px':'160px'}; display:${conf.Logo_Base64?'block':'none'}; margin:0 auto;">
                <h3 style="margin:5px 0;">NOTA DE PEDIDO</h3>
                <div style="font-size:10px; color:#555;">${conf.Cabecera_Texto||''}</div>
                <div style="border:1px dashed #000; margin:15px 0; padding:8px; background:#f9f9f9;"><b>FOLIO: ${i.folio}</b></div>
            </div>
            <div style="font-size:0.95em; margin-bottom:15px;">
                <b>CLIENTE:</b> ${i.cliente}<br>
                <b>FECHA REGISTRO:</b> ${i.fecha}
            </div>
            <table class="pe-table-pro">
                <thead><tr><th>Cant</th><th>Producto</th><th align="right">Subtotal</th></tr></thead>
                <tbody>${i.items.map(it => `<tr><td>${it.cant}</td><td>${it.producto}</td><td align="right">${money(it.total)}</td></tr>`).join('')}</tbody>
            </table>
            <div style="text-align:right; font-weight:bold; margin-top:20px; border-top:2px solid #000; padding-top:10px;">
                TOTAL BRUTO: ${money(i.total)}<br>
                ANTICIPO: ${money(i.anticipo)}<br>
                <span style="color:red; font-size:1.2em;">SALDO RESTANTE: ${money(i.resta)}</span>
            </div>
            <div style="text-align:center; font-size:10px; margin-top:30px; border-top:1px dashed #ccc; padding-top:10px; color:#777;">
                ${conf.Pie_Pagina_Texto||''}
            </div>
        `;
    },
    saveToApp: async function() {
        const idC = document.getElementById('pe-select-config').value;
        const sql = `INSERT INTO \`${PREFIJO}Documentos_Generados\` (UUID_Unico, Modulo_Origen, ID_Referencia, ID_Config_Impresora, Contenido_JSON, Estado) VALUES ('${this.info.folio}', 'Pedidos', ${this.info.idRef}, ${idC}, '${JSON.stringify(this.info).replace(/'/g, "\\'")}', 'PENDIENTE')`;
        const r = await fetch(AJAX_E, { method: 'POST', body: new URLSearchParams({db:DB_NAME, sql:sql}) }).then(r=>r.json());
        if(r.status === 'success') { alert("Documento enviado a la cola de impresión."); location.reload(); }
    },
    printNow: function() {
        const win = window.open('', 'Print');
        win.document.write(`<html><head><style>body{font-family:Arial; padding:0; margin:0;}</style></head><body>${document.getElementById('pe-hoja-digital').innerHTML}</body></html>`);
        win.document.close(); win.print(); win.close(); location.reload();
    }
};

app.init();
</script>