<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

/**
 * 1. SEGURIDAD Y LOGIN (Base: MS_Usuario)
 */
if (isset($_GET['logout'])) { session_destroy(); header("Location: " . $_SERVER['PHP_SELF']); exit; }

$loginErr = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['u_user'])) {
    try {
        $pdoAuth = new PDO("mysql:host=localhost;dbname=MS_Usuario;charset=utf8", "root", "33comRxXMysql");
        $stmt = $pdoAuth->prepare("SELECT UD.*, U.Nombre FROM Usuarios_Datos UD INNER JOIN Usuarios U ON UD.IDU = U.IDU WHERE UD.User = ? AND UD.Estado = 'Activo' LIMIT 1");
        $stmt->execute([$_POST['u_user']]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && password_verify($_POST['u_pass'], $user['Password'])) {
            $_SESSION['Acceso'] = 'AccesoSiqueSi';
            $_SESSION['IDUg']   = $user['IDUg']; 
            $_SESSION['IDS']    = "1"; 
            $_SESSION['BD']     = "MS_Datos"; 
            $_SESSION['NombreUsuario'] = $user['Nombre'];
            header("Location: " . $_SERVER['PHP_SELF']); exit;
        } else { $loginErr = "Credenciales incorrectas."; }
    } catch (Exception $e) { $loginErr = $e->getMessage(); }
}

if (!isset($_SESSION['Acceso'])):
?>
<!DOCTYPE html>
<html lang="es"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
<style>body{background:#f0f2f5;display:flex;align-items:center;justify-content:center;height:100vh;}.login-card{background:#fff;padding:35px;border:3px solid #333;border-radius:20px;box-shadow:10px 10px 0 #333;width:320px;}</style></head>
<body><div class="login-card"><h4 class="text-center mb-4">🛒 POS EXPRESS</h4><?php if($loginErr): ?><div class="alert alert-danger small"><?= $loginErr ?></div><?php endif; ?><form method="POST"><input type="text" name="u_user" class="form-control mb-3" placeholder="Usuario" required><input type="password" name="u_pass" class="form-control mb-3" placeholder="Contraseña" required><button class="btn btn-dark btn-block font-weight-bold">ENTRAR</button></form></div></body></html>
<?php exit; endif; ?>

<?php
/**
 * 2. CARGA DE CONFIGURACIÓN Y BASES DE DATOS
 */
$idProp     = $_SESSION['IDUg']; 
$dbName     = $_SESSION['BD']; 
$prefijo    = $idProp . "-"; 
$vendedor   = $_SESSION['NombreUsuario'];
$idSucursal = $_SESSION['IDS'];

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

    $stmtImp = $pdo->query("SELECT * FROM `{$idProp}-Configuracion_Impresoras` WHERE Activo = 1");
    $impresorasData = $stmtImp->fetchAll(PDO::FETCH_ASSOC);

    $hoy = date('ymd'); $preFol = "NV-" . $hoy . "-";
    $resFol = $pdo->query("SELECT Folio FROM `{$prefijo}Ventas_Cabecera` WHERE Folio LIKE '$preFol%' ORDER BY ID_Venta DESC LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    $nuevoCont = $resFol ? intval(substr($resFol['Folio'], -3)) + 1 : 1;
    $folioNota = $preFol . str_pad($nuevoCont, 3, "0", STR_PAD_LEFT);
} catch (Exception $e) { die("Error: " . $e->getMessage()); }
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>POS Express - <?= $folioNota ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
    <style>
        :root { --dark: #333; --danger: #e74a3b; --bg: #f4f7fa; }
        body { background: var(--bg); font-family: 'Arial', sans-serif; }
        
        /* CONTENEDOR PRINCIPAL */
        .pos-wrapper { max-width: 900px; margin: 15px auto; background: #fff; border: 3px solid var(--dark); border-radius: 20px; box-shadow: 10px 10px 0 rgba(0,0,0,0.05); padding: 25px; }
        .box-folio { border: 2px solid var(--dark); border-radius: 12px; width: 180px; text-align: center; overflow: hidden; }
        .tit-f { background: var(--dark); color: #fff; font-size: 11px; padding: 4px; font-weight: bold; }
        .num-f { font-size: 18px; font-weight: bold; color: var(--danger); padding: 5px; }

        /* TABLA RESPONSIVA COMPACTA */
        .table-pos { width: 100%; border-collapse: collapse; border: 2px solid var(--dark); overflow: hidden; border-radius: 12px; }
        .table-pos thead { background: var(--dark); color: #fff; }
        .table-pos th { padding: 10px; font-size: 13px; text-align: center; border: 1px solid var(--dark); }
        .table-pos td { border: 1px solid var(--dark); padding: 0; }
        .table-pos input { border: none; width: 100%; padding: 12px; text-align: center; outline: none; background: transparent; }

        @media (max-width: 650px) {
            .table-pos thead { display: none; }
            .item-row { display: flex; flex-wrap: wrap; border-bottom: 2px solid var(--dark) !important; background: #fff; }
            .item-row td { display: block; border: none !important; }
            
            /* NIVEL 1: DESCRIPCIÓN */
            .item-row td[data-label="PRODUCTO"] { width: 100%; border-bottom: 1px solid #eee !important; background: #fafafa; }
            .item-row td[data-label="PRODUCTO"] input { text-align: left; font-weight: bold; padding-left: 15px; }

            /* NIVEL 2: CANTIDAD, PRECIO E IMPORTE EN LA MISMA FILA */
            .item-row td[data-label="CANT"] { width: 25%; border-right: 1px solid #eee !important; }
            .item-row td[data-label="PRECIO"] { width: 35%; border-right: 1px solid #eee !important; }
            .item-row td[data-label="TOTAL"] { width: 40%; }
            
            .item-row td::before { content: attr(data-label); display: block; font-size: 9px; color: #999; font-weight: bold; text-align: center; padding-top: 5px; }
        }

        /* PRINT ENGINE PREVIEW STYLES */
        .pe-preview-bg { background-color: #525659; display: flex; justify-content: center; padding: 30px; height: 65vh; overflow-y: auto; }
        .pe-paper { background: white; color: #000; box-shadow: 0 0 20px rgba(0,0,0,0.5); font-family: 'Segoe UI', sans-serif; margin: auto; }
        .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; }
        .t-center { text-align: center; }
        .t-divider { border-top: 1px dashed #000; margin: 10px 0; }
        .f-header { display: flex; justify-content: space-between; border-bottom: 3px solid #f26522; padding-bottom: 10px; margin-bottom: 20px; }
        .suggestions { position: absolute; background: #fff; width: 100%; z-index: 1000; border: 2px solid var(--dark); display: none; max-height: 150px; overflow-y: auto; }
        .sug-item { padding: 10px; cursor: pointer; border-bottom: 1px solid #eee; font-size: 13px; }
    </style>
</head>
<body>

<div class="pos-wrapper">
    <div class="d-flex justify-content-between flex-wrap mb-4">
        <div>
            <h4 class="mb-0 font-weight-bold">🛒 POS EXPRESS V.6</h4>
            <small>Vendedor: <b><?= $vendedor ?></b></small>
        </div>
        <div class="box-folio">
            <div class="tit-f">FOLIO NOTA</div>
            <div class="num-f"><?= $folioNota ?></div>
            <div class="tit-f"><?= date('d/m/Y') ?></div>
        </div>
    </div>

    <div class="row mb-3">
        <div class="col-md-7" style="position:relative;">
            <label class="small font-weight-bold">CLIENTE:</label>
            <input type="text" id="cli-nombre" class="form-control" placeholder="Buscar..." autocomplete="off">
            <input type="hidden" id="cli-id" value="0">
            <div id="res-cli-search" class="suggestions"></div>
        </div>
        <div class="col-md-5">
            <label class="small font-weight-bold">TELÉFONO:</label>
            <input type="text" id="cli-tel" class="form-control">
        </div>
    </div>

    <table class="table-pos mb-2">
        <thead><tr><th width="70">CANT</th><th>DESCRIPCIÓN</th><th width="110">PRECIO</th><th width="110">TOTAL</th></tr></thead>
        <tbody id="nota-body">
            <?php for($i=0; $i<3; $i++): ?>
            <tr class="item-row">
                <td data-label="CANT"><input type="number" class="val-cant" step="any" oninput="calcRow(this)"></td>
                <td data-label="PRODUCTO" style="position:relative;">
                    <input type="text" class="desc" onkeyup="searchProd(this)" placeholder="Buscar producto..." autocomplete="off">
                    <div class="suggestions"></div>
                    <input type="hidden" class="sku-hidden">
                </td>
                <td data-label="PRECIO"><input type="number" class="val-price" step="any" oninput="calcRow(this)"></td>
                <td data-label="TOTAL"><input type="text" class="val-importe" readonly value="0.00"></td>
            </tr>
            <?php endfor; ?>
        </tbody>
    </table>
    <button class="btn btn-sm btn-dark mb-4 font-weight-bold" onclick="addMoreRows()">+ FILA (F2)</button>

    <div class="row">
        <div class="col-md-7">
            <label class="small font-weight-bold">OBSERVACIONES:</label>
            <textarea id="val-obs" class="form-control mb-3" rows="2"></textarea>
            <div class="row">
                <div class="col-6">
                    <label class="small font-weight-bold">MÉTODO PAGO:</label>
                    <select id="pay-method" class="form-control">
                        <option value="Efectivo">Efectivo</option>
                        <option value="Tarjeta">Tarjeta</option>
                        <option value="Transferencia">Transferencia</option>
                    </select>
                </div>
                <div class="col-6 pt-4 text-right">
                    <label class="small font-weight-bold"><input type="checkbox" id="chk-iva" onchange="updateTotals()"> + IVA (16%)</label>
                </div>
            </div>
        </div>
        <div class="col-md-5">
            <div class="p-3 border rounded bg-light" style="border: 2px solid #333 !important;">
                <div class="d-flex justify-content-between small"><span>Subtotal:</span><span id="txt-sub">0.00</span></div>
                <div class="d-flex justify-content-between small"><span>Descuento:</span><input type="number" id="txt-desc" value="0.00" oninput="updateTotals()" style="width:70px; text-align:right; border:none; background:transparent;"></div>
                <div class="d-flex justify-content-between small"><span>IVA:</span><span id="txt-iva">0.00</span></div>
                <hr style="border-top:1px solid #333;">
                <div class="d-flex justify-content-between h4 text-danger font-weight-bold"><span>TOTAL:</span><span id="txt-total">0.00</span></div>
                <button id="btn-finalizar" class="btn btn-success btn-block py-3 font-weight-bold mt-2" onclick="saveNota()">FINALIZAR (F10)</button>
            </div>
        </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" style="border:3px solid #333 !important; border-radius:15px; overflow:hidden;">
            <div class="modal-header bg-dark text-white p-2">
                <h6 class="modal-title font-weight-bold ml-2">VISOR DE IMPRESIÓN</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 font-weight-bold" onclick="PrintEngine.printNow()">IMPRIMIR</button>
                <button class="btn btn-success font-weight-bold" onclick="PrintEngine.saveToApp()">ENVIAR A APP</button>
                <button class="btn btn-secondary" onclick="location.reload()">NUEVA VENTA</button>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>

<script>
const CFG = { px: '<?= $prefijo ?>', ids: '<?= $idSucursal ?>', idu: '<?= $idProp ?>', db: '<?= $dbName ?>', fol: '<?= $folioNota ?>', vend: '<?= $vendedor ?>' };

// Atajos
document.onkeydown = e => { 
    if(e.key === 'F2') { e.preventDefault(); addMoreRows(); }
    if(e.key === 'F10') { e.preventDefault(); saveNota(); }
};

// Lógica de Ventas
window.searchProd = async function(input) {
    const q = input.value; const sug = input.nextElementSibling;
    if(q.length < 2) { sug.style.display = 'none'; return; }
    const fd = new FormData(); fd.append('sql', `SELECT p.sku, 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.nombre LIKE '%${q}%' LIMIT 5`);
    fd.append('db', CFG.db);
    const r = await fetch('../librerias/AJAX/Select.php', { method: 'POST', body: fd }).then(res => res.json());
    sug.innerHTML = r.data.map(p => `<div class="sug-item" onclick="setProd(this, '${p.sku}', '${p.nombre}', ${p.precio_venta}, ${p.costo_promedio})">${p.nombre} ($${p.precio_venta})</div>`).join('');
    sug.style.display = 'block';
};

window.setProd = function(el, sku, nom, price, costo) {
    const row = el.closest('tr');
    row.querySelector('.desc').value = nom; row.querySelector('.sku-hidden').value = sku;
    row.querySelector('.val-price').value = price; row.querySelector('.val-cant').value = 1;
    row.dataset.costo = costo; el.parentNode.style.display = 'none'; calcRow(row.querySelector('.val-cant'));
};

function calcRow(i) {
    const r = i.closest('tr');
    const c = parseFloat(r.querySelector('.val-cant').value) || 0;
    const p = parseFloat(r.querySelector('.val-price').value) || 0;
    r.querySelector('.val-importe').value = (c * p).toFixed(2);
    updateTotals();
}

function updateTotals() {
    let s = 0; document.querySelectorAll('.val-importe').forEach(i => s += parseFloat(i.value) || 0);
    const d = parseFloat(document.getElementById('txt-desc').value) || 0;
    const b = s - d;
    const v = document.getElementById('chk-iva').checked ? (b * 0.16) : 0;
    document.getElementById('txt-sub').innerText = s.toFixed(2);
    document.getElementById('txt-iva').innerText = v.toFixed(2);
    document.getElementById('txt-total').innerText = (b + v).toFixed(2);
}

document.getElementById('cli-nombre').onkeyup = async function() {
    const q = this.value; const sug = document.getElementById('res-cli-search');
    if(q.length < 3) { sug.style.display = 'none'; return; }
    const fd = new FormData(); fd.append('sql', `SELECT IDC, Nombre, Telefono FROM \`${CFG.px}Clientes\` WHERE Nombre LIKE '%${q}%' LIMIT 5`);
    fd.append('db', CFG.db);
    const r = await fetch('../librerias/AJAX/Select.php', { method: 'POST', body: fd }).then(res => res.json());
    sug.innerHTML = r.data.map(c => `<div class="sug-item" onclick="setCli('${c.IDC}','${c.Nombre}','${c.Telefono}')">${c.Nombre}</div>`).join('');
    sug.style.display = 'block';
};

window.setCli = function(i, n, t) {
    document.getElementById('cli-id').value = i; document.getElementById('cli-nombre').value = n;
    document.getElementById('cli-tel').value = t; document.getElementById('res-cli-search').style.display = 'none';
};

function addMoreRows() {
    const b = document.getElementById('nota-body');
    const n = b.rows[0].cloneNode(true);
    n.querySelectorAll('input').forEach(i => i.value = (i.className === 'val-importe') ? "0.00" : "");
    n.querySelector('.sku-hidden').value = ""; b.appendChild(n); n.querySelector('.val-cant').focus();
}

// GUARDAR
async function saveNota() {
    const btn = document.getElementById('btn-finalizar');
    const nom = document.getElementById('cli-nombre').value.trim();
    const tot = parseFloat(document.getElementById('txt-total').innerText);
    if(!nom || tot <= 0) return alert("Verifica datos.");
    if(!confirm("¿Finalizar venta?")) return;
    btn.disabled = true; btn.innerHTML = "...";

    try {
        let idC = document.getElementById('cli-id').value;
        if(idC == "0") {
            const rC = await apiExec(`INSERT INTO \`${CFG.px}Clientes\` (IDU, Nombre, Telefono) VALUES ('CLI-${Date.now()}', '${nom}', '${document.getElementById('cli-tel').value}')`);
            idC = rC.last_id;
        }
        const items = [];
        for(let r of document.querySelectorAll('.item-row')) {
            const q = parseFloat(r.querySelector('.val-cant').value) || 0;
            const n = r.querySelector('.desc').value.trim();
            const p = parseFloat(r.querySelector('.val-price').value) || 0;
            const sk = r.querySelector('.sku-hidden').value || 'GEN-' + Date.now().toString().slice(-4);
            const cos = parseFloat(r.dataset.costo) || 0;
            if(q > 0 && n !== "") items.push({ sku: sk, nombre: n, qty: q, price: p, costo: cos });
        }
        const rV = await apiExec(`INSERT INTO \`${CFG.px}Ventas_Cabecera\` (Folio, IDC_Cliente, IDU_Usuario, IDS_Sucursal, Metodo_Pago, Subtotal, Descuento, Total, Notas_Venta) VALUES ('${CFG.fol}', ${idC}, '${CFG.idu}', ${CFG.ids}, '${document.getElementById('pay-method').value}', ${document.getElementById('txt-sub').innerText}, ${document.getElementById('txt-desc').value}, ${tot}, '${document.getElementById('val-obs').value}')`);
        const idV = rV.last_id;
        for(let it of items) { await apiExec(`INSERT INTO \`${CFG.px}Ventas_Detalle\` (ID_Venta, SKU, Nombre_Producto, Cantidad, Precio_Venta, Costo_Original, Subtotal) VALUES (${idV}, '${it.sku}', '${it.nombre}', ${it.qty}, ${it.price}, ${it.costo}, ${it.qty * it.price})`); }

        // MOSTRAR MOTOR IMPRESIÓN
        PrintEngine.show({
            folio: CFG.fol, cliente: nom, telefono: document.getElementById('cli-tel').value,
            vendedor: CFG.vend, metodo: document.getElementById('pay-method').value,
            items: items, sub: document.getElementById('txt-sub').innerText, dsc: document.getElementById('txt-desc').value,
            iva: document.getElementById('txt-iva').innerText, total: tot, obs: document.getElementById('val-obs').value, idRef: idV
        });
    } catch (e) { alert(e.message); btn.disabled = false; }
}

async function apiExec(s) {
    const fd = new FormData(); fd.append('sql', s); fd.append('db', CFG.db);
    return fetch('../librerias/AJAX/Execute.php', { method: 'POST', body: fd }).then(r => r.json());
}

// MOTOR IMPRESIÓN INTEGRADO
window.PrintEngine = {
    saleInfo: null,
    configs: <?php echo json_encode($impresorasData); ?>,
    show: function(data) {
        this.saleInfo = data;
        const sel = document.getElementById('pe-select-config');
        sel.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 conf = JSON.parse(document.getElementById('pe-select-config').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);
        hoja.className = `pe-paper pe-p-${conf.Tipo_Papel.toLowerCase().replace(" ", "")}`;
        const esG = conf.Tipo_Papel.includes('A4') || conf.Tipo_Papel.includes('A5');
        if(esG) {
            hoja.innerHTML = `<div class="f-header"><div><img src="${conf.Logo_Base64||''}" style="max-height:60px;"><div>${conf.Cabecera_Texto||''}</div></div><div class="f-folio-box"><div class="f-folio-title">NOTA</div><div style="font-size:20px; color:red; font-weight:bold;">${info.folio}</div></div></div><div class="f-client-section"><div><b>Cliente:</b> ${info.cliente}</div><div class="text-right"><b>Método:</b> ${info.metodo}</div></div><table class="f-table" width="100%"><thead><tr><th>Cant</th><th>Producto</th><th align="right">Total</th></tr></thead><tbody>${info.items.map(it => `<tr><td>${it.qty}</td><td>${it.nombre}</td><td align="right">${money(it.qty*it.price)}</td></tr>`).join('')}</tbody></table><div class="text-right mt-3">Subtotal: ${money(info.sub)}<br><b>TOTAL: ${money(info.total)}</b></div>`;
        } else {
            hoja.innerHTML = `<div class="t-center"><b>${conf.Nombre_Perfil}</b><br><small>${conf.Cabecera_Texto||''}</small></div><div class="t-divider"></div><div>FOLIO: ${info.folio}<br>Cajero: ${info.vendedor}</div><div class="t-divider"></div><table width="100%" class="small">${info.items.map(it => `<tr><td>${it.qty} x ${it.nombre}</td><td align="right">${money(it.qty*it.price)}</td></tr>`).join('')}</table><div class="t-divider"></div><div align="right"><b>TOTAL: ${money(info.total)}</b></div><div class="t-center small mt-2">${conf.Pie_Pagina_Texto||''}</div>`;
        }
    },
    printNow: function() {
        const conf = JSON.parse(document.getElementById('pe-select-config').selectedOptions[0].dataset.conf);
        const win = window.open('', '', 'width=800,height=600');
        win.document.write(`<html><head><style>@page{size:${conf.Tipo_Papel} ${conf.Orientacion};margin:0;}${document.querySelector('style').innerHTML}</style></head><body>${document.getElementById('pe-hoja-digital').outerHTML}</body></html>`);
        win.document.close(); win.print(); win.close();
    },
    saveToApp: async function() {
        const idC = document.getElementById('pe-select-config').value;
        const sql = `INSERT INTO \`${CFG.idu}-Documentos_Generados\` (UUID_Unico, Modulo_Origen, ID_Referencia, ID_Config_Impresora, Contenido_JSON, Estado) VALUES ('${this.saleInfo.folio}', 'NotaVenta', ${this.saleInfo.idRef}, ${idC}, '${JSON.stringify(this.saleInfo).replace(/'/g, "\\'")}', 'PENDIENTE')`;
        const r = await apiExec(sql); if(r.last_id) { alert("Enviado"); location.reload(); }
    }
};
</script>
</body>
</html>