<?php
session_start();
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') { die("Acceso denegado."); }

$idUsuario = $_SESSION['IDU'] ?? '1'; 
$idSucursal = $_SESSION['IDS'] ?? '1';
$dbName = $_SESSION['BD'] ?? "MS_Datos"; 
$px = "1-"; 
$vendedor = $_SESSION['NombreUsuario'] ?? "Vendedor General";

try {
    $pdo = new PDO("mysql:host=localhost;dbname=$dbName;charset=utf8", "root", "33comRxXMysql"); 
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Folio
    $hoy = date('ymd'); 
    $prefijoFolio = "V-" . $hoy . "-";
    $sqlFolio = "SELECT Folio FROM `{$px}Ventas_Cabecera` WHERE Folio LIKE '$prefijoFolio%' ORDER BY ID_Venta DESC LIMIT 1";
    $resFolio = $pdo->query($sqlFolio)->fetch(PDO::FETCH_ASSOC);
    $nuevoContador = $resFolio ? intval(substr($resFolio['Folio'], -3)) + 1 : 1;
    $folioTemp = $prefijoFolio . str_pad($nuevoContador, 3, "0", STR_PAD_LEFT);

    // Catálogo Completo
    $productos = $pdo->query("SELECT p.IDP, p.sku, p.nombre, p.imagen, p.codigo_barras, 
                                     i.existencia, i.precio_venta, i.precio_mayoreo, i.precio_web, i.costo_promedio 
                             FROM `{$px}Productos_Catalogo` p 
                             INNER JOIN `{$px}Productos_Inventario` i ON p.sku = i.sku 
                             WHERE p.activo = 1 AND i.IDS = $idSucursal")->fetchAll(PDO::FETCH_ASSOC);
    
    $clientes = $pdo->query("SELECT IDC, Nombre, Telefono FROM `{$px}Clientes` WHERE EstadoCliente = 'Activo' ORDER BY Nombre ASC")->fetchAll(PDO::FETCH_ASSOC);

    $qImp = $pdo->query("SELECT ID_Config FROM `{$px}Configuracion_Impresoras` WHERE Activo = 1 LIMIT 1");
    $fImp = $qImp->fetch(PDO::FETCH_ASSOC);
    $idImpresoraBackup = $fImp['ID_Config'] ?? 1;

} catch (PDOException $e) { die("Error de BD: " . $e->getMessage()); }

$jsonProd = json_encode($productos);
$jsonCli = json_encode($clientes);
include_once('../librerias/Modulos/Impresora.php'); 
?>

<style>
    :root { --pos-accent: #f26522; --pos-dark: #1e2129; --pos-green: #00d1b2; }
    
    .pos-master { 
        height: calc(100vh - 70px); width: 100%; display: flex; flex-direction: column; 
        background: #fff; margin: -20px; border: none; overflow: hidden;
    }
    
    .pos-header-bar { background: #f1f4f8; padding: 5px 15px; border-bottom: 1px solid #d1d8e0; display: flex; gap: 15px; align-items: center; }
    .input-compact { background: #fff; border: 1px solid #ced4da; padding: 4px 8px; font-weight: bold; font-size: 0.85rem; border-radius: 4px; }

    .pos-main-content { flex: 1; display: flex; overflow: hidden; }
    
    .pos-table-area { flex: 1; display: flex; flex-direction: column; border-right: 1px solid #d1d8e0; }
    .scanner-zone { padding: 10px; background: #fff; border-bottom: 1px solid #eee; display: flex; gap: 10px; }
    .table-scroll { flex: 1; overflow-y: auto; }
    .pos-grid-table { width: 100%; border-collapse: collapse; }
    .pos-grid-table th { background: #4b6584; color: #fff; padding: 10px; font-size: 11px; text-transform: uppercase; position: sticky; top: 0; z-index: 10; }
    .pos-grid-table td { padding: 6px 10px; border-bottom: 1px solid #f1f2f6; vertical-align: middle; }

    .pos-sidebar-right { width: 320px; background: #f8f9fa; display: flex; flex-direction: column; padding: 15px; }
    
    .btn-checkout { background: var(--pos-green); color: #fff; border: none; padding: 20px; font-size: 1.4rem; font-weight: 900; border-radius: 8px; box-shadow: 0 4px 10px rgba(0,0,0,0.1); cursor: pointer; transition: 0.2s; }
    .btn-checkout:hover { background: #00b89c; transform: translateY(-2px); }

    .total-display-box { background: #000; color: #00ff00; padding: 10px 20px; border-radius: 8px; margin-top: 15px; text-align: right; border: 2px solid #333; }
    .total-label { font-size: 1rem; color: #aaa; font-weight: bold; }
    .total-value { font-size: 3rem; font-weight: 900; font-family: 'Courier New', monospace; }

    .input-edit { border: 1px solid transparent; width: 100%; font-weight: bold; text-align: center; background: transparent; }
    .input-edit:focus { background: #fff9c4; border: 1px solid var(--pos-accent); outline: none; }
    
    .cli-dropdown { position: absolute; top: 100%; left: 0; right: 0; background: white; z-index: 2000; border: 1px solid #ddd; display: none; max-height: 200px; overflow-y: auto; }
    .cli-item { padding: 8px; border-bottom: 1px solid #eee; cursor: pointer; color: #333; }
    .cli-item:hover { background: #e8f4fd; }

    .modal-search-scroll { max-height: 400px; overflow-y: auto; }
    .search-prod-item { cursor: pointer; transition: 0.2s; border-radius: 6px; }
    .search-prod-item:hover { background: #f0f7ff; transform: scale(1.02); border-color: #2196f3 !important; }
</style>

<div class="pos-master">
    <div class="pos-header-bar">
        <span class="small font-weight-bold text-muted">CLIENTE:</span>
        <div class="position-relative d-flex align-items-center">
            <input type="text" id="busCli" class="input-compact" placeholder="Público General" style="width: 200px;">
            <button class="btn btn-sm btn-primary ml-1" onclick="$('#modalNewCli').modal('show')">
                <i class="feather icon-plus"></i>
            </button>
            <div id="resCli" class="cli-dropdown shadow"></div>
        </div>
        <span class="small font-weight-bold text-muted ml-2">LISTA:</span>
        <select id="selPriceList" class="input-compact" onchange="posEngine.updatePrices()">
            <option value="precio_venta">Público</option>
            <option value="precio_mayoreo">Mayoreo</option>
            <option value="precio_web">Web</option>
        </select>
        <div class="ml-auto">
            <span class="badge badge-dark">FOLIO: <b id="lblFolio"><?php echo $folioTemp; ?></b></span>
        </div>
    </div>

    <div class="pos-main-content">
        <div class="pos-table-area">
            <div class="scanner-zone">
                <input type="text" id="posScanner" class="form-control form-control-lg border-primary" placeholder="ESCANEÉ O ESCRIBA CÓDIGO..." autofocus>
                <button class="btn btn-primary px-4" onclick="$('#modalManualSearch').modal('show')">
                    <i class="feather icon-search"></i>
                </button>
            </div>
            <div class="table-scroll">
                <table class="pos-grid-table">
                    <thead>
                        <tr>
                            <th width="70">CANT</th>
                            <th>DESCRIPCIÓN DEL PRODUCTO</th>
                            <th width="120">PRECIO U.</th>
                            <th width="100">DESC. U.</th>
                            <th width="140" class="text-right">SUBTOTAL</th>
                            <th width="40"></th>
                        </tr>
                    </thead>
                    <tbody id="cartBody"></tbody>
                </table>
            </div>
        </div>

        <div class="pos-sidebar-right">
            <div class="text-center mb-3">
                <img src="https://cdn-icons-png.flaticon.com/512/4481/4481110.png" width="45">
                <h6 class="font-weight-bold mt-2 mb-0">Resumen de Venta</h6>
                <small class="text-muted"><?php echo $vendedor; ?></small>
            </div>

            <div class="card bg-light border-0 p-3 mb-4">
                <div class="custom-control custom-switch mb-3">
                    <input type="checkbox" class="custom-control-input" id="chkFactura" onchange="posEngine.renderCart()">
                    <label class="custom-control-label small font-weight-bold" for="chkFactura">Incluir IVA (16%)</label>
                </div>
                <div class="d-flex justify-content-between small mb-1">
                    <span>Artículos en carrito:</span>
                    <b id="lblCount">0</b>
                </div>
            </div>

            <div class="mt-auto">
                <button class="btn-checkout w-100" onclick="posEngine.preCheckout()">
                    <i class="feather icon-check-circle"></i> COBRAR [F10]
                </button>

                <div class="total-display-box">
                    <div class="total-label">TOTAL A PAGAR</div>
                    <div class="total-value" id="lblTotal">$0.00</div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalNewCli" tabindex="-1">
    <div class="modal-dialog modal-sm modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-dark text-white p-2">
                <h6 class="modal-title ml-2">Nuevo Cliente</h6>
                <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body p-4">
                <div class="form-group mb-2">
                    <label class="small font-weight-bold">Nombre</label>
                    <input type="text" id="nCliNom" class="form-control form-control-sm" placeholder="Nombre completo">
                </div>
                <div class="form-group mb-3">
                    <label class="small font-weight-bold">Teléfono</label>
                    <input type="number" id="nCliTel" class="form-control form-control-sm" placeholder="10 dígitos">
                </div>
                <button class="btn btn-success btn-block font-weight-bold" onclick="posEngine.saveNewClient()">REGISTRAR</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalManualSearch" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white">
                <h6 class="modal-title"><i class="feather icon-package mr-2"></i>Catálogo de Productos</h6>
                <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body p-0">
                <div class="p-3 bg-light">
                    <input type="text" id="inputManualSearch" class="form-control" placeholder="Escriba nombre del producto..." onkeyup="posEngine.searchInModal(this.value)">
                </div>
                <div class="modal-search-scroll p-3">
                    <div id="modalProductGrid" class="row no-gutters"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
const posEngine = (function() {
    const CFG = { 
        db: '<?php echo $dbName; ?>', px: '<?php echo $px; ?>', 
        ids: '<?php echo $idSucursal; ?>', idu: '<?php echo $idUsuario; ?>', 
        fol: '<?php echo $folioTemp; ?>', vend: '<?php echo $vendedor; ?>',
        defImp: '<?php echo $idImpresoraBackup; ?>'
    };
    
    let products = <?php echo $jsonProd; ?>, clients = <?php echo $jsonCli; ?>, cart = [], clientSelected = null;

    const money = n => new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN' }).format(n);
    const cleanNum = str => parseFloat(str.replace(/[^0-9.-]+/g, "")) || 0;

    const api = async (file, sql) => {
        const fd = new FormData(); fd.append('sql', sql); fd.append('db', CFG.db);
        return fetch(`../librerias/AJAX/${file}`, { method: 'POST', body: fd }).then(r => r.json());
    };

    return {
        init: function() {
            document.addEventListener('keydown', (e) => {
                if(e.key === "F10") { e.preventDefault(); this.preCheckout(); }
                if(e.key === "Escape") { e.preventDefault(); $('#modalManualSearch').modal('hide'); $('#modalNewCli').modal('hide'); document.getElementById('posScanner').focus(); }
            });

            document.getElementById('posScanner').onkeypress = (e) => {
                if(e.key === "Enter") {
                    const term = e.target.value.trim();
                    if(term) this.handleScanner(term);
                    e.target.value = "";
                }
            };
            this.searchInModal("");
        },

        // --- REGISTRO DE CLIENTE ---
        saveNewClient: async function() {
            const nom = document.getElementById('nCliNom').value;
            const tel = document.getElementById('nCliTel').value;
            if(!nom || !tel) return alert("Por favor complete los campos");

            const r = await api('Execute.php', `INSERT INTO \`${CFG.px}Clientes\` (Nombre, Telefono, EstadoCliente, IDU) VALUES ('${nom}', '${tel}', 'Activo', 'CLI-${Date.now()}')`);
            
            if(r.last_id) {
                const newC = {IDC: r.last_id, Nombre: nom, Telefono: tel};
                clients.push(newC);
                clientSelected = newC;
                document.getElementById('busCli').value = nom;
                $('#modalNewCli').modal('hide');
                document.getElementById('nCliNom').value = "";
                document.getElementById('nCliTel').value = "";
            }
        },

        handleScanner: function(term) {
            const p = products.find(x => x.sku === term || x.codigo_barras === term);
            if(p) this.add(p);
        },

        searchInModal: function(v) {
            const grid = document.getElementById('modalProductGrid');
            const list = products.filter(p => p.nombre.toLowerCase().includes(v.toLowerCase()) || p.sku.toLowerCase().includes(v.toLowerCase()));
            grid.innerHTML = '';
            list.forEach(p => {
                grid.innerHTML += `
                <div class="col-md-6 p-1">
                    <div class="search-prod-item border p-2 d-flex align-items-center" onclick="posEngine.addBySku('${p.sku}')">
                        <img src="${p.imagen}" width="40" height="40" class="mr-2 rounded">
                        <div style="flex:1">
                            <span class="d-block font-weight-bold small">${p.nombre}</span>
                            <small class="text-muted">Stock: ${p.existencia} | SKU: ${p.sku}</small>
                        </div>
                        <div class="text-primary font-weight-bold">${money(p.precio_venta)}</div>
                    </div>
                </div>`;
            });
        },

        addBySku: function(sku) {
            const p = products.find(x => x.sku === sku);
            if(p) this.add(p);
            $('#modalManualSearch').modal('hide');
            document.getElementById('posScanner').focus();
        },

        add: function(p) {
            const list = document.getElementById('selPriceList').value;
            const exist = cart.find(i => i.sku === p.sku);
            if(exist) {
                exist.qty++;
            } else {
                cart.push({
                    sku: p.sku, nombre: p.nombre, cost: parseFloat(p.costo_promedio),
                    price: parseFloat(p[list]), qty: 1, discount: 0, series: []
                });
            }
            this.renderCart();
        },

        updatePrices: function() {
            const list = document.getElementById('selPriceList').value;
            cart.forEach(i => {
                const pData = products.find(x => x.sku === i.sku);
                i.price = parseFloat(pData[list]);
            });
            this.renderCart();
        },

        updateRow: function(idx, field, val) {
            const item = cart[idx];
            if(field === 'qty') item.qty = parseFloat(val) || 1;
            if(field === 'discount') {
                const d = parseFloat(val) || 0;
                const maxD = item.price - item.cost;
                if(d > maxD) {
                    alert(`¡Error! El descuento máximo permitido es ${money(maxD)}`);
                    item.discount = 0;
                } else { item.discount = d; }
            }
            this.renderCart();
        },

        renderCart: function() {
            const body = document.getElementById('cartBody'); body.innerHTML = '';
            let sub = 0; let count = 0;
            cart.forEach((i, idx) => {
                const net = (i.price - i.discount) * i.qty;
                sub += net;
                count += i.qty;
                body.innerHTML += `
                    <tr>
                        <td><input type="number" class="input-edit" value="${i.qty}" onchange="posEngine.updateRow(${idx}, 'qty', this.value)"></td>
                        <td><b>${i.nombre}</b><br><small class="text-muted">${i.sku}</small></td>
                        <td class="text-center font-weight-bold">${money(i.price)}</td>
                        <td><input type="number" class="input-edit text-danger" value="${i.discount}" onchange="posEngine.updateRow(${idx}, 'discount', this.value)"></td>
                        <td class="text-right font-weight-bold" style="font-size:1.1rem">${money(net)}</td>
                        <td class="text-center"><button class="btn btn-sm text-danger" onclick="posEngine.remove(${idx})">&times;</button></td>
                    </tr>`;
            });

            const bCli = document.getElementById('busCli');
            bCli.onkeyup = () => {
                const v = bCli.value.toLowerCase();
                const res = document.getElementById('resCli');
                if(v.length < 2) { res.style.display = 'none'; return; }
                const filtered = clients.filter(c => c.Nombre.toLowerCase().includes(v) || c.Telefono.includes(v));
                res.innerHTML = '';
                if(filtered.length > 0) {
                    res.style.display = 'block';
                    filtered.forEach(c => {
                        const d = document.createElement('div'); d.className = 'cli-item';
                        d.innerHTML = `<b>${c.Nombre}</b> - ${c.Telefono}`;
                        d.onclick = () => { clientSelected = c; bCli.value = c.Nombre; res.style.display = 'none'; };
                        res.appendChild(d);
                    });
                }
            };

            const hasIva = document.getElementById('chkFactura').checked;
            const total = hasIva ? sub * 1.16 : sub;
            document.getElementById('lblTotal').innerText = money(total);
            document.getElementById('lblCount').innerText = count;
        },

        remove: function(idx) { cart.splice(idx, 1); this.renderCart(); },

        preCheckout: function() {
            if(!cart.length) return alert("Carrito vacío");
            if(confirm(`¿Confirmar cobro por ${document.getElementById('lblTotal').innerText}?`)) this.exec();
        },

        exec: async function() {
            const totalF = cleanNum(document.getElementById('lblTotal').innerText);
            const hasIva = document.getElementById('chkFactura').checked;
            const subtotal = hasIva ? (totalF / 1.16) : totalF;

            const resC = await api('Execute.php', `INSERT INTO \`${CFG.px}Ventas_Cabecera\` (Folio, IDC_Cliente, IDU_Usuario, IDS_Sucursal, Subtotal, Total, Estado) VALUES ('${CFG.fol}', ${clientSelected?clientSelected.IDC:0}, '${CFG.idu}', ${CFG.ids}, ${subtotal}, ${totalF}, 'Pagado')`);
            
            if(resC.last_id) {
                const idV = resC.last_id;
                for(const i of cart) {
                    const finalP = i.price - i.discount;
                    await api('Execute.php', `INSERT INTO \`${CFG.px}Ventas_Detalle\` (ID_Venta, SKU, Nombre_Producto, Cantidad, Precio_Venta, Costo_Original, Subtotal) VALUES (${idV}, '${i.sku}', '${i.nombre}', ${i.qty}, ${finalP}, ${i.cost}, ${finalP * i.qty})`);
                    await api('Execute.php', `UPDATE \`${CFG.px}Productos_Inventario\` SET existencia = existencia - ${i.qty} WHERE sku = '${i.sku}' AND IDS = ${CFG.ids}`);
                }

                const saleData = {
                    folio: CFG.fol, cliente: clientSelected ? clientSelected.Nombre : 'Público General',
                    vendedor: CFG.vend, total: totalF, sub: subtotal, iva: totalF - subtotal,
                    items: cart.map(item => ({...item, series: item.series || []}))
                };

                const jsonStr = JSON.stringify(saleData).replace(/'/g, "\\'");
                await api('Execute.php', `INSERT INTO \`${CFG.px}Documentos_Generados\` (UUID_Unico, Modulo_Origen, ID_Referencia, ID_Config_Impresora, Contenido_JSON, Estado) VALUES ('${CFG.fol}', 'PuntoVenta', ${idV}, ${CFG.defImp}, '${jsonStr}', 'PENDIENTE')`);

                if (typeof PrintEngine !== 'undefined') PrintEngine.show(saleData);
                else location.reload();
            }
        }
    };
})();
posEngine.init();
</script>