<?php
/**
 * POS MÓVIL PROFESIONAL V10 - FINAL RELEASE (PRINT & UUID FIXED)
 * Distribución intacta. UUID_Unico sincronizado con Folio.
 */
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') { die("Acceso denegado."); }

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

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

    $categorias = $pdo->query("SELECT DISTINCT categoria FROM `{$prefijo}Productos_Catalogo` WHERE activo = 1 AND categoria IS NOT NULL ORDER BY categoria ASC")->fetchAll(PDO::FETCH_COLUMN);

    $hoy = date('ymd'); 
    $prefijoFolio = "V-" . $hoy . "-";
    $sqlFolio = "SELECT Folio FROM `{$prefijo}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);

    $prods = $pdo->query("SELECT p.sku, p.nombre, p.imagen, p.categoria, i.existencia, i.precio_venta, i.costo_promedio 
                          FROM `{$prefijo}Productos_Catalogo` p 
                          INNER JOIN `{$prefijo}Productos_Inventario` i ON p.sku = i.sku 
                          WHERE p.activo = 1 AND i.IDS = $idSucursal LIMIT 100")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { die("Error: " . $e->getMessage()); }
?>

<style>
    :root { --primary: #4e73df; --success: #1cc88a; --bg: #f4f7fa; --dark: #2d3436; }
    
    .pos-wrapper-centered { 
        background: var(--bg); height: calc(100vh - 65px); width: 100%; margin: -25px; 
        display: flex; justify-content: center; 
    }

    .pos-viewport { 
        background: var(--bg); width: 100%; max-width: 600px; height: 100%; 
        display: flex; flex-direction: column; overflow: hidden; position: relative; 
        box-shadow: 0 0 20px rgba(0,0,0,0.05); 
    }

    .pos-top-section { background: #fff; padding: 15px; border-bottom: 1px solid #dee2e6; z-index: 1020; text-align: center; }
    
    .client-selector-box { 
        background: #f8f9fc; border: 1px solid #e3e6f0; border-radius: 15px; padding: 10px; 
        display: flex; align-items: center; justify-content: center; margin: 0 auto 10px auto; max-width: 90%;
    }
    
    .search-input-group { 
        background: #f1f3f9; border-radius: 12px; display: flex; align-items: center; 
        padding: 0 15px; height: 42px; margin: 10px auto; width: 100%;
    }
    .search-input-group input { border: none; background: transparent; width: 100%; outline: none; font-size: 15px; text-align: center; }

    .cat-container { display: flex; overflow-x: auto; white-space: nowrap; padding: 10px 0; justify-content: flex-start; -webkit-overflow-scrolling: touch; }
    .cat-pill { background: #fff; border: 1px solid #d1d3e2; padding: 6px 16px; border-radius: 20px; margin: 0 4px; font-size: 0.75rem; font-weight: 700; flex-shrink: 0; }
    .cat-pill.active { background: var(--primary); color: #fff; border-color: var(--primary); }

    .pos-content-area { flex: 1; overflow-y: auto; padding: 15px; padding-bottom: 160px; }
    .pos-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; }
    
    .product-item { background: #fff; border-radius: 18px; padding: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.02); text-align: center; border: 1px solid transparent; }
    .product-item:active { transform: scale(0.96); background: #f0f3ff; }
    .product-img { width: 100%; height: 100px; object-fit: contain; margin-bottom: 10px; }
    .product-name { font-size: 0.85rem; font-weight: 700; height: 2.5em; overflow: hidden; color: #333; margin-bottom: 5px; }

    .cart-card { background: #fff; border-radius: 18px; padding: 15px; margin-bottom: 12px; border-left: 5px solid var(--primary); display: flex; align-items: center; box-shadow: 0 2px 5px rgba(0,0,0,0.02); text-align: left; }
    .cart-card .item-details { flex: 1; padding-left: 10px; }

    .pos-footer-sticky { position: absolute; bottom: 0; width: 100%; background: #fff; border-top: 1px solid #e3e6f0; z-index: 1030; text-align: center; }
    
    #pay-button-container { padding: 15px 20px 0 20px; display: none; }
    .btn-pay-now { background: var(--success); color: #fff; border: none; width: 100%; padding: 18px; border-radius: 16px; font-weight: 800; font-size: 1.1rem; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 8px 20px rgba(28, 200, 138, 0.3); }
    
    .pos-nav-tabs { display: flex; justify-content: space-around; padding: 12px 0; }
    .nav-tab-item { border: none; background: none; color: #b7b9cc; font-size: 0.75rem; font-weight: 700; flex: 1; }
    .nav-tab-item.active { color: var(--primary); }
    .nav-tab-item i { font-size: 1.5rem; display: block; margin-bottom: 2px; }

    .modal-content { border-radius: 25px; border: none; text-align: center; }
    .serie-item { border-radius: 12px; margin-bottom: 8px; border: 2px solid #f1f3f9; width: 100%; padding: 12px; font-weight: 600; text-align: center; transition: 0.2s; }
    .serie-item.selected { border-color: var(--primary); background: #f0f3ff; color: var(--primary); }
</style>

<div class="pos-wrapper-centered">
    <div class="pos-viewport">
        <header class="pos-top-section">
            <div class="d-flex justify-content-between align-items-center mb-3 px-2">
                <small class="text-muted font-weight-bold">FOLIO: <span class="text-primary"><?= $folioTemp ?></span></small>
                <small class="text-muted"><i class="feather icon-pocket"></i> <?= date('d/m/Y') ?></small>
            </div>

            <div class="position-relative">
                <div class="client-selector-box" id="cli-main-trigger">
                    <div class="flex-grow-1 text-center" id="cli-active-box" onclick="pos.focusCli()">
                        <i class="feather icon-user text-primary"></i>
                        <strong id="cli-name-lbl" class="ml-1">Público General</strong>
                    </div>
                    <button class="btn btn-sm btn-primary ml-2 shadow-sm" onclick="pos.openNewCli()" style="border-radius: 10px; width: 35px; height: 35px;">+</button>
                    <button class="btn btn-sm btn-link text-danger d-none" id="btn-clear-cli" onclick="pos.resetCli()">✕</button>
                </div>
                <input type="text" id="cli-search-input" class="form-control form-control-lg d-none text-center" placeholder="Escribe nombre de cliente..." style="border-radius:15px;">
                <div id="res-cli-search" class="list-group position-absolute shadow w-100" style="z-index:2000; display:none; border-radius: 15px; margin-top:5px; overflow:hidden;"></div>
            </div>

            <div id="header-controls">
                <div class="search-input-group">
                    <i class="feather icon-maximize text-muted mr-2"></i>
                    <input type="text" id="prod-search" placeholder="Buscar producto o escanear...">
                </div>
                <div class="cat-container">
                    <button class="cat-pill active" onclick="pos.filterCat('Todas', this)">Todas</button>
                    <?php foreach($categorias as $c): ?>
                        <button class="cat-pill" onclick="pos.filterCat('<?= $c ?>', this)"><?= $c ?></button>
                    <?php endforeach; ?>
                </div>
            </div>
        </header>

        <main class="pos-content-area" id="pane-catalog">
            <div class="pos-grid" id="grid-main">
                <?php foreach($prods as $p): ?>
                <div class="product-item" data-cat="<?= $p['categoria'] ?>" onclick="pos.checkItem('<?= $p['sku'] ?>')">
                    <img src="<?= $p['imagen'] ?>" class="product-img" onerror="this.src='https://cdn-icons-png.flaticon.com/512/2652/2652218.png'">
                    <div class="product-name"><?= $p['nombre'] ?></div>
                    <div class="text-primary font-weight-bold">$<?= number_format($p['precio_venta'], 2) ?></div>
                    <div class="badge badge-light text-muted mt-2" style="font-size:0.6rem">Stock: <?= (int)$p['existencia'] ?></div>
                </div>
                <?php endforeach; ?>
            </div>
        </main>

        <main class="pos-content-area d-none" id="pane-cart">
            <div class="text-center mb-4">
                <h5 class="font-weight-bold text-dark m-0">Resumen de Venta</h5>
                <small class="text-muted">Revisa los artículos antes de cobrar</small>
            </div>
            
            <div id="cart-items-box"></div>
            
            <div class="card border-0 shadow-sm mt-4" style="border-radius:20px;">
                <div class="card-body p-4">
                    <div class="mb-4 text-center">
                        <label class="font-weight-bold d-block mb-1">Método de Pago</label>
                        <select id="pay-method" class="form-control form-control-lg mx-auto" style="border-radius:12px; width: 85%;">
                            <option value="Efectivo">Efectivo</option>
                            <option value="Tarjeta">Tarjeta</option>
                            <option value="Transferencia">Transferencia</option>
                            <option value="Credito">Crédito</option>
                        </select>
                    </div>

                    <div class="custom-control custom-switch mb-3 text-center">
                        <input type="checkbox" class="custom-control-input" id="chk-iva" onchange="pos.updateTotals()">
                        <label class="custom-control-label font-weight-bold" for="chk-iva">¿Requiere Factura? (+16%)</label>
                    </div>
                    <hr>
                    <div class="d-flex justify-content-between text-muted mb-2"><span>Subtotal</span><span id="lbl-sub">$0.00</span></div>
                    <div class="d-flex justify-content-between text-muted mb-2"><span>Impuestos</span><span id="lbl-iva">$0.00</span></div>
                    <div class="d-flex justify-content-between h4 font-weight-bold text-primary pt-2"><span>TOTAL</span><span id="lbl-total">$0.00</span></div>
                </div>
            </div>
            <div class="text-center mt-3">
                <button class="btn btn-link text-danger font-weight-bold" onclick="pos.clearCart()">VACIAR TODO</button>
            </div>
        </main>

        <footer class="pos-footer-sticky">
            <div id="pay-button-container">
                <button class="btn-pay-now" onclick="pos.checkout()">
                    <span>PAGAR AHORA</span>
                    <span id="btn-pay-total">$0.00</span>
                </button>
            </div>

            <nav class="pos-nav-tabs">
                <button class="nav-tab-item active" id="btn-tab-cat" onclick="pos.tab('catalog')">
                    <i class="feather icon-shopping-bag"></i>TIENDA
                </button>
                <button class="nav-tab-item" id="btn-tab-cart" onclick="pos.tab('cart')">
                    <i class="feather icon-file-text"></i>NOTA <span class="badge badge-danger" id="cart-badge" style="display:none;">0</span>
                </button>
            </nav>
        </footer>
    </div>
</div>

<div class="modal fade" id="mdl-series" tabindex="-1" data-backdrop="static">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content shadow-lg p-3">
            <div class="modal-header border-0 justify-content-center pb-0">
                <h6 class="modal-title font-weight-bold">Seleccionar Series</h6>
            </div>
            <div class="modal-body">
                <div id="series-list" style="max-height: 250px; overflow-y:auto; padding:5px;"></div>
            </div>
            <div class="modal-footer border-0">
                <button class="btn btn-primary btn-block py-3 font-weight-bold shadow" onclick="pos.confirmSeries()" style="border-radius:15px;">AGREGAR AL CARRITO</button>
                <button class="btn btn-link text-muted btn-block" data-dismiss="modal">Cancelar</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="mdl-new-cli" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content shadow-lg p-4">
            <h6 class="font-weight-bold mb-4">Nuevo Cliente</h6>
            <input type="text" id="nc-nom" class="form-control mb-3 text-center" placeholder="Nombre completo" style="border-radius:12px; height:45px;">
            <input type="tel" id="nc-tel" class="form-control mb-4 text-center" placeholder="Teléfono" style="border-radius:12px; height:45px;">
            <button class="btn btn-success btn-block py-3 font-weight-bold shadow" onclick="pos.saveNewCli()" style="border-radius:15px;">GUARDAR CLIENTE</button>
            <button class="btn btn-link text-muted mt-2" data-dismiss="modal">Cerrar</button>
        </div>
    </div>
</div>

<script>
const pos = (function() {
    const CFG = { db: '<?= $dbName ?>', px: '<?= $prefijo ?>', ids: '<?= $idSucursal ?>', idu: '<?= $idUsuario ?>', fol: '<?= $folioTemp ?>', vend: '<?= $vendedor ?>' };
    let cart = [], selectedCli = {IDC: 0, Nombre: 'Público General'}, seriesTemp = {sku: null, list: []};

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

    return {
        init: function() {
            document.getElementById('prod-search').onkeyup = (e) => {
                const v = e.target.value.toLowerCase();
                document.querySelectorAll('.product-item').forEach(i => i.style.display = i.innerText.toLowerCase().includes(v) ? 'block' : 'none');
            };

            document.getElementById('cli-search-input').onkeyup = async (e) => {
                const v = e.target.value.toLowerCase();
                const resBox = document.getElementById('res-cli-search');
                if(v.length < 3) { resBox.style.display='none'; return; }
                const r = await api('Select.php', `SELECT IDC, Nombre, Telefono FROM \`${CFG.px}Clientes\` WHERE Nombre LIKE '%${v}%' OR Telefono LIKE '%${v}%' LIMIT 5`);
                resBox.innerHTML = '';
                if(r.data.length) {
                    resBox.style.display = 'block';
                    r.data.forEach(c => {
                        const d = document.createElement('a'); d.className='list-group-item list-group-item-action py-3 text-center';
                        d.innerHTML = `<strong>${c.Nombre}</strong><br><small>${c.Telefono}</small>`;
                        d.onclick = () => pos.setCli(c);
                        resBox.appendChild(d);
                    });
                }
            };
        },

        tab: (t) => {
            document.getElementById('pane-catalog').classList.toggle('d-none', t !== 'catalog');
            document.getElementById('pane-cart').classList.toggle('d-none', t !== 'cart');
            document.getElementById('header-controls').style.display = (t === 'cart') ? 'none' : 'block';
            document.getElementById('pay-button-container').style.display = (t === 'cart') ? 'block' : 'none';
            document.getElementById('btn-tab-cat').classList.toggle('active', t === 'catalog');
            document.getElementById('btn-tab-cart').classList.toggle('active', t === 'cart');
            if(t === 'cart') pos.renderCart();
        },

        filterCat: (cat, btn) => {
            document.querySelectorAll('.cat-pill').forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            document.querySelectorAll('.product-item').forEach(i => {
                i.style.display = (cat === 'Todas' || i.dataset.cat === cat) ? 'block' : 'none';
            });
        },

        focusCli: () => {
            document.getElementById('cli-active-box').classList.add('d-none');
            document.getElementById('cli-search-input').classList.remove('d-none');
            document.getElementById('cli-search-input').focus();
        },
        setCli: (c) => {
            selectedCli = c;
            document.getElementById('cli-name-lbl').innerText = c.Nombre;
            document.getElementById('cli-active-box').classList.remove('d-none');
            document.getElementById('cli-search-input').classList.add('d-none');
            document.getElementById('res-cli-search').style.display='none';
            document.getElementById('btn-clear-cli').classList.remove('d-none');
        },
        resetCli: () => {
            selectedCli = {IDC: 0, Nombre: 'Público General'};
            document.getElementById('cli-name-lbl').innerText = selectedCli.Nombre;
            document.getElementById('btn-clear-cli').classList.add('d-none');
        },
        openNewCli: () => $('#mdl-new-cli').modal('show'),
        saveNewCli: async () => {
            const n = document.getElementById('nc-nom').value, t = document.getElementById('nc-tel').value;
            if(!n) return;
            const r = await api('Execute.php', `INSERT INTO \`${CFG.px}Clientes\` (Nombre, Telefono, IDU) VALUES ('${n}', '${t}', 'M-${Date.now()}')`);
            if(r.last_id) { pos.setCli({IDC: r.last_id, Nombre: n, Telefono: t}); $('#mdl-new-cli').modal('hide'); }
        },

        checkItem: async (sku) => {
            const r = await api('Select.php', `SELECT Serie FROM \`${CFG.px}Productos_Series\` WHERE SKU = '${sku}' AND Estado = 'DISPONIBLE'`);
            if(r.data.length > 0) {
                seriesTemp = {sku, list: []};
                const box = document.getElementById('series-list'); box.innerHTML = '';
                r.data.forEach(s => {
                    const b = document.createElement('button'); b.className='serie-item';
                    b.innerText = s.Serie;
                    b.onclick = function() { 
                        this.classList.toggle('selected');
                        if(this.classList.contains('selected')) seriesTemp.list.push(this.innerText);
                        else seriesTemp.list = seriesTemp.list.filter(x => x !== this.innerText);
                    };
                    box.appendChild(b);
                });
                $('#mdl-series').modal('show');
            } else pos.add(sku, 1, null);
        },
        confirmSeries: () => {
            if(!seriesTemp.list.length) return;
            seriesTemp.list.forEach(s => pos.add(seriesTemp.sku, 1, s));
            $('#mdl-series').modal('hide');
        },
        add: async (sku, qty, serie) => {
            const r = await api('Select.php', `SELECT p.nombre, i.precio_venta, i.costo_promedio FROM \`${CFG.px}Productos_Catalogo\` p INNER JOIN \`${CFG.px}Productos_Inventario\` i ON p.sku = i.sku WHERE p.sku = '${sku}' AND i.IDS = ${CFG.ids}`);
            const p = r.data[0];
            cart.push({ sku, nombre: p.nombre, price: parseFloat(p.precio_venta), cost: p.costo_promedio, qty, serie });
            pos.updateTotals();
        },
        renderCart: () => {
            const box = document.getElementById('cart-items-box'); box.innerHTML = '';
            if(!cart.length) return box.innerHTML = '<div class="text-center py-5 text-muted">Carrito Vacío</div>';
            cart.forEach((i, idx) => {
                box.innerHTML += `
                <div class="cart-card">
                    <div class="item-details">
                        <div class="font-weight-bold" style="font-size:1rem">${i.nombre}</div>
                        <small class="text-primary">${i.serie?'SN: '+i.serie:'SKU: '+i.sku}</small>
                    </div>
                    <div class="text-right pr-2">
                        <div class="font-weight-bold text-dark h6">$${i.price.toFixed(2)}</div>
                        <button class="btn btn-sm text-danger p-0" onclick="pos.remove(${idx})"><i class="feather icon-trash-2"></i></button>
                    </div>
                </div>`;
            });
        },
        updateTotals: () => {
            const sub = cart.reduce((a, b) => a + (b.price * b.qty), 0);
            const fac = document.getElementById('chk-iva').checked;
            const iva = fac ? (sub * 0.16) : 0;
            const total = sub + iva;
            document.getElementById('cart-badge').innerText = cart.length;
            document.getElementById('cart-badge').style.display = cart.length ? 'block' : 'none';
            document.getElementById('lbl-sub').innerText = `$${sub.toFixed(2)}`;
            document.getElementById('lbl-iva').innerText = `$${iva.toFixed(2)}`;
            document.getElementById('lbl-total').innerText = `$${total.toFixed(2)}`;
            document.getElementById('btn-pay-total').innerText = `$${total.toFixed(2)}`;
        },
        remove: (idx) => { cart.splice(idx, 1); pos.renderCart(); pos.updateTotals(); },
        clearCart: () => { if(confirm("¿Vaciar nota?")) { cart=[]; pos.renderCart(); pos.updateTotals(); } },
        
        checkout: async () => {
            if(!cart.length) return;
            if(!confirm("¿Deseas finalizar el pago de esta nota?")) return;
            
            const total = parseFloat(document.getElementById('lbl-total').innerText.replace('$',''));
            const sub = parseFloat(document.getElementById('lbl-sub').innerText.replace('$',''));
            const iva = parseFloat(document.getElementById('lbl-iva').innerText.replace('$',''));
            const metodoPago = document.getElementById('pay-method').value;

            // 1. Guardar Venta
            const res = await api('Execute.php', `INSERT INTO \`${CFG.px}Ventas_Cabecera\` (Folio, IDC_Cliente, IDU_Usuario, IDS_Sucursal, Total) VALUES ('${CFG.fol}', ${selectedCli.IDC}, '${CFG.idu}', ${CFG.ids}, ${total})`);
            
            if(res.last_id) {
                const idVenta = res.last_id;

                // 2. Guardar Detalles e Inventario
                for(const i of cart) {
                    await api('Execute.php', `INSERT INTO \`${CFG.px}Ventas_Detalle\` (ID_Venta, SKU, Nombre_Producto, Cantidad, Precio_Venta, Costo_Original, Subtotal) VALUES (${idVenta}, '${i.sku}', '${i.nombre}', ${i.qty}, ${i.price}, ${i.cost}, ${i.price*i.qty})`);
                    await api('Execute.php', `UPDATE \`${CFG.px}Productos_Inventario\` SET existencia = existencia - ${i.qty} WHERE sku = '${i.sku}' AND IDS = ${CFG.ids}`);
                    if(i.serie) await api('Execute.php', `UPDATE \`${CFG.px}Productos_Series\` SET Estado = 'VENDIDO' WHERE Serie = '${i.serie}' AND SKU = '${i.sku}'`);
                }

                // 3. GENERAR REGISTRO DE IMPRESIÓN (UUID = FOLIO DE NOTA)
                const printData = {
                    folio: CFG.fol,
                    fecha: new Date().toLocaleString(),
                    cliente: selectedCli.Nombre,
                    vendedor: CFG.vend,
                    productos: cart,
                    subtotal: sub,
                    iva: iva,
                    total: total,
                    metodo: metodoPago
                };

                const jsonStr = JSON.stringify(printData).replace(/'/g, "''"); // Escapar comillas
                
                // SQL Sincronizado con UUID_Unico = Folio
                const sqlPrint = `INSERT INTO \`${CFG.px}Documentos_Generados\` 
                    (UUID_Unico, Modulo_Origen, ID_Referencia, ID_Config_Impresora, Contenido_JSON, Estado) 
                    VALUES 
                    ('${CFG.fol}', 'PuntoVenta', ${idVenta}, 1, '${jsonStr}', 'PENDIENTE')`;

                await api('Execute.php', sqlPrint);

                alert("Venta guardada y enviada a impresión.");
                location.reload();
            }
        }
    };
})();
pos.init();
</script>