<?php 
// Datos de configuración para el frontend
$configData = json_encode([
    'empresa'   => $config['nombre_empresa'] ?? 'Botica Guzmán',
    'moneda'    => $config['moneda'] ?? 'S/',
    'logo'      => $config['logo_url'] ?? ''
]); 
?>

<style>
    /* Diseño de tarjetas de productos con imágenes */
    .ratio-1x1 { position: relative; width: 100%; padding-top: 100%; background: #f8f9fa; }
    .ratio-1x1 img { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; transition: 0.3s; }
    .prod-card { transition: 0.3s; border: 1px solid #eee !important; cursor: pointer; border-radius: 12px; overflow: hidden; }
    .prod-card:hover { transform: translateY(-5px); box-shadow: 0 5px 15px rgba(0,0,0,0.1) !important; }
    .prod-card:hover img { transform: scale(1.1); }
    .badge-stock { position: absolute; top: 5px; right: 5px; z-index: 10; font-size: 0.7rem; }
    #cart-list { scrollbar-width: thin; }
</style>

<div class="modal fade" id="modalCliRapido" tabindex="-1">
    <div class="modal-dialog modal-sm modal-dialog-centered">
        <div class="modal-content shadow-lg border-0">
            <div class="modal-header bg-primary text-white py-2">
                <h6 class="m-0"><i class="fas fa-user-plus me-1"></i> Registro Rápido</h6>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-3">
                <div class="mb-2">
                    <label class="small fw-bold">DNI / RUC (*)</label>
                    <input type="number" id="cli_doc_r" class="form-control form-control-sm" placeholder="8 o 11 dígitos">
                </div>
                <div class="mb-2">
                    <label class="small fw-bold">Nombre / Razón Social (*)</label>
                    <input type="text" id="cli_nom_r" class="form-control form-control-sm" placeholder="Nombre completo">
                </div>
                <div class="mb-0">
                    <label class="small fw-bold">Teléfono</label>
                    <input type="text" id="cli_tel_r" class="form-control form-control-sm" placeholder="Opcional">
                </div>
            </div>
            <div class="modal-footer py-2">
                <button class="btn btn-primary btn-sm w-100 fw-bold" onclick="guardarCliR()">GUARDAR Y SELECCIONAR</button>
            </div>
        </div>
    </div>
</div>

<div id="caja-cerrada-screen" class="d-none position-absolute top-0 start-0 w-100 h-100 bg-white d-flex align-items-center justify-content-center" style="z-index:2000">
    <div class="text-center p-5 shadow rounded border">
        <i class="fas fa-lock fa-4x text-muted mb-3"></i>
        <h3 class="fw-bold">TURNO CERRADO</h3>
        <p class="text-muted small">Debe aperturar caja para poder vender.</p>
        <div class="input-group mb-3 shadow-sm">
            <span class="input-group-text"><?php echo $moneda; ?></span>
            <input type="number" id="monto-apertura" class="form-control" placeholder="Monto Inicial" value="0.00">
        </div>
        <button onclick="abrirCaja()" class="btn btn-primary w-100 fw-bold shadow">ABRIR TURNO</button>
    </div>
</div>



<div class="row h-100 g-3">
    <div class="col-lg-8 col-md-7 d-flex flex-column">
        <div class="d-flex mb-2 gap-2">
            <div class="input-group input-group-lg shadow-sm">
                <span class="input-group-text bg-white border-end-0 text-primary"><i class="fas fa-search"></i></span>
                <input type="text" id="search-pos" class="form-control border-start-0 fw-bold" placeholder="Busca nombre, principio o escanea... (F2)">
                <button class="btn btn-outline-primary" onclick="toggleCameraPos()" title="Escanear Código"><i class="fas fa-camera"></i></button>
            </div>
            <button class="btn btn-danger shadow-sm px-3" onclick="prepararCierreCaja()"><i class="fas fa-power-off"></i></button>
        </div>

        <div id="quick-edit-panel" class="card mb-3 border-primary border-2 bg-primary bg-opacity-10 shadow-sm d-none">
            <div class="card-body p-2 d-flex justify-content-between align-items-center">
                <div style="width:45%">
                    <span class="badge bg-primary mb-1">ÚLTIMO AGREGADO</span>
                    <div class="fw-bold text-truncate" id="qe-name"></div>
                    <div class="small text-muted" id="qe-price"></div>
                </div>
                <div class="d-flex align-items-center bg-white rounded border p-1">
                    <button class="btn btn-sm btn-danger fw-bold" onclick="modQuick(-1)">-</button>
                    <input type="number" id="qe-cant" class="form-control text-center fw-bold border-0 mx-1" style="width:50px" readonly>
                    <button class="btn btn-sm btn-success fw-bold" onclick="modQuick(1)">+</button>
                </div>
                <button class="btn btn-sm btn-outline-danger" onclick="delQuick()"><i class="fas fa-trash"></i></button>
            </div>
        </div>

        <div id="reader-pos" class="mb-2 rounded border bg-white shadow-sm" style="display:none; width: 100%; max-width: 400px; margin: 0 auto;"></div>
        
        <div id="pos-grid" class="row g-2 overflow-auto flex-grow-1" style="align-content: flex-start;">
            </div>
    </div>

    <div class="col-lg-4 col-md-5 d-flex flex-column h-100">
        <div class="card h-100 border-0 shadow-lg d-flex flex-column">
            <div class="card-header bg-primary text-white py-3 d-flex justify-content-between align-items-center">
                <h5 class="m-0"><i class="fas fa-shopping-basket me-2"></i>Carrito</h5>
                <span class="badge bg-white text-primary" id="cart-count">0 items</span>
            </div>
            
            <div id="cart-list" class="card-body p-2 flex-grow-1 overflow-auto bg-light"></div>

            <div class="card-footer bg-white p-3 border-top">
                <label class="small fw-bold text-muted">Cliente</label>
                <div class="input-group mb-3">
                    <select id="cliente_venta" class="form-select shadow-sm" onchange="checkDoc()">
                        <option value="1" data-doc="00000000">Público General</option>
                        <?php 
                        $c = $conn->query("SELECT id_cliente, nombre, documento FROM clientes WHERE id_cliente != 1 ORDER BY nombre ASC"); 
                        while($r = $c->fetch_assoc()): ?>
                            <option value="<?php echo $r['id_cliente']; ?>" data-doc="<?php echo $r['documento']; ?>"><?php echo htmlspecialchars($r['nombre']); ?></option>
                        <?php endwhile; ?>
                    </select>
                    <button class="btn btn-primary" onclick="new bootstrap.Modal(document.getElementById('modalCliRapido')).show()"><i class="fas fa-plus"></i></button>
                </div>

                <div class="d-flex justify-content-between align-items-center mb-3">
                    <span class="h5 fw-bold text-muted">TOTAL</span>
                    <h2 class="m-0 fw-bold text-success"><?php echo $moneda; ?><span id="cart-total">0.00</span></h2>
                </div>
                <button onclick="abrirModalPago()" class="btn btn-success w-100 py-3 fw-bold shadow">FINALIZAR COMPRA (F4)</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalPago" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-dark text-white"><h5 class="modal-title">Cobrar Venta</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <div class="modal-body p-4 text-center">
                <h6 class="text-muted fw-bold">VALOR TOTAL</h6>
                <h1 class="display-4 fw-bold text-primary mb-4"><?php echo $moneda; ?><span id="modal-total-pay">0.00</span></h1>

                <div class="btn-group w-100 mb-3 shadow-sm">
                    <input type="radio" class="btn-check" name="tipo_doc" id="doc_nv" value="NOTA_VENTA" checked onchange="checkDoc()">
                    <label class="btn btn-outline-dark fw-bold" for="doc_nv">NOTA</label>
                    <input type="radio" class="btn-check" name="tipo_doc" id="doc_bol" value="BOLETA" onchange="checkDoc()">
                    <label class="btn btn-outline-primary fw-bold" for="doc_bol">BOLETA</label>
                    <input type="radio" class="btn-check" name="tipo_doc" id="doc_fac" value="FACTURA" onchange="checkDoc()">
                    <label class="btn btn-outline-success fw-bold" for="doc_fac">FACTURA</label>
                </div>

                <div id="alert-doc" class="alert alert-danger small d-none mb-3"><i class="fas fa-exclamation-circle"></i> RUC de 11 dígitos requerido.</div>

                <div class="bg-light p-3 rounded border mb-3">
                    <label class="d-block mb-1 small fw-bold">Efectivo Recibido:</label>
                    <input type="number" id="pago-monto" class="form-control form-control-lg text-center fw-bold" onkeyup="calcVuelto()">
                </div>

                <div class="alert alert-success py-2 mb-4">
                    <small class="fw-bold d-block text-uppercase">Vuelto:</small>
                    <h3 class="fw-bold m-0"><?php echo $moneda; ?><span id="txt-vuelto">0.00</span></h3>
                </div>

                <div class="row g-2">
                    <div class="col-6"><button onclick="procesarPago('EFECTIVO')" id="btn-pay-cash" class="btn btn-success w-100 py-3 fw-bold" disabled>EFECTIVO</button></div>
                    <div class="col-6"><button onclick="procesarPago('YAPE')" class="btn btn-primary w-100 py-3 fw-bold" style="background:#742284; border:0">YAPE / PLIN</button></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let carrito = [], scannerPos = null, debounceTimer, lastIdx = -1;
const coin = "<?php echo $moneda; ?>";

document.addEventListener('DOMContentLoaded', () => { 
    verificarEstadoCaja(); 
    loadPopularProducts();
    document.getElementById('search-pos').focus(); 
});

// --- CLIENTE RÁPIDO ---
function guardarCliR() {
    let nom = document.getElementById('cli_nom_r').value;
    let doc = document.getElementById('cli_doc_r').value;
    let tel = document.getElementById('cli_tel_r').value;

    if(!nom || !doc) return Swal.fire('Error', 'Nombre y Documento son obligatorios.', 'warning');

    let fd = new FormData();
    fd.append('nombre', nom); fd.append('documento', doc); fd.append('telefono', tel);

    fetch('api.php?task=save_cliente_pos', { method: 'POST', body: fd })
    .then(r => r.json()).then(res => {
        if(res.success) {
            let sel = document.getElementById('cliente_venta');
            let opt = new Option(res.nombre, res.id);
            opt.dataset.doc = res.doc;
            sel.add(opt); sel.value = res.id;
            bootstrap.Modal.getInstance(document.getElementById('modalCliRapido')).hide();
            Swal.fire({ toast: true, position: 'top-end', icon: 'success', title: 'Cliente registrado', showConfirmButton: false, timer: 1500 });
            checkDoc();
        } else Swal.fire('Error', res.error, 'error');
    });
}

// --- BUSCADOR Y GRID ---
function loadPopularProducts() {
    fetch('api.php?task=get_popular_products').then(r => r.json()).then(renderGrid).catch(e => console.error(e));
}

document.getElementById('search-pos').addEventListener('input', (e) => { 
    clearTimeout(debounceTimer); 
    let t = e.target.value.trim(); 
    if(t.length > 1) {
        debounceTimer = setTimeout(() => {
            fetch(`api.php?task=search_products&term=${encodeURIComponent(t)}`).then(r => r.json()).then(renderGrid);
        }, 300);
    } else if(t.length === 0) loadPopularProducts();
});

function renderGrid(data) { 
    let html = ''; 
    data.forEach(p => { 
        let p_json = encodeURIComponent(JSON.stringify(p)); 
        let img = p.imagen_url ? p.imagen_url : 'https://placehold.co/200x200?text=' + encodeURIComponent(p.nombre);
        html += `
            <div class="col-6 col-md-4 col-xl-3 mb-2">
                <div class="card h-100 shadow-sm prod-card" onclick="checkAndAdd('${p_json}')">
                    <span class="badge ${p.stock < 10 ? 'bg-danger' : 'bg-success'} badge-stock">Stock: ${p.stock}</span>
                    <div class="ratio ratio-1x1"><img src="${img}" onerror="this.src='https://placehold.co/200x200?text=Error'"></div>
                    <div class="card-body p-2 text-center">
                        <div class="fw-bold small text-truncate mb-1" title="${p.nombre}">${p.nombre}</div>
                        <div class="text-primary fw-bold">${coin}${parseFloat(p.precio_venta).toFixed(2)}</div>
                    </div>
                </div>
            </div>`; 
    }); 
    document.getElementById('pos-grid').innerHTML = html || '<div class="col-12 text-center mt-5 text-muted">No se encontraron productos.</div>'; 
}

// --- LÓGICA DE CARRITO ---
async function checkAndAdd(p_json) { 
    let p = JSON.parse(decodeURIComponent(p_json)); 
    let item = carrito.find(i => i.id === p.id_producto); 
    if((item ? item.cant : 0) + 1 > p.stock) return Swal.fire('Sin Stock', 'No hay suficientes unidades.', 'error');

    // Validación Interacciones
    let pas = carrito.map(i => i.pa).filter(v => v); 
    if(p.principio_activo && pas.length > 0) {
        let fd = new FormData(); fd.append('new_pa', p.principio_activo); fd.append('cart_pas', JSON.stringify(pas));
        const res = await fetch('api.php?task=check_interactions', {method:'POST', body:fd});
        const alerts = await res.json();
        if(alerts.length > 0) {
            let rs = await Swal.fire({title:'⚠️ ALERTA MÉDICA', text: alerts[0].msg, icon:'warning', showCancelButton:true, confirmButtonText:'Agregar igual'});
            if(!rs.isConfirmed) return;
        }
    }
    addToCart(p);
}

function addToCart(p) { 
    let idx = carrito.findIndex(i => i.id === p.id_producto); 
    if(idx >= 0) { carrito[idx].cant++; lastIdx = idx; } 
    else { 
        carrito.push({id: p.id_producto, n: p.nombre, p: parseFloat(p.precio_venta), cant: 1, pa: p.principio_activo, stockMax: p.stock}); 
        lastIdx = carrito.length - 1; 
    } 
    renderCart(); renderQuickEdit(); 
    document.getElementById('search-pos').value = ''; document.getElementById('search-pos').focus();
}

function renderCart() { 
    let h = '', t = 0; 
    carrito.forEach((i, x) => { 
        t += i.p * i.cant; 
        h += `
            <div class="card mb-2 border-0 shadow-sm ${x === lastIdx ? 'border-start border-primary border-4' : ''}">
                <div class="card-body p-2 d-flex justify-content-between align-items-center">
                    <div style="width:65%" onclick="setQuick(${x})" role="button">
                        <div class="fw-bold small text-truncate">${i.n}</div>
                        <small class="text-muted">${coin}${i.p.toFixed(2)} x ${i.cant}</small>
                    </div>
                    <div class="text-end">
                        <div class="fw-bold text-success">${coin}${(i.p * i.cant).toFixed(2)}</div>
                        <i class="fas fa-trash text-danger" style="cursor:pointer" onclick="del(${x})"></i>
                    </div>
                </div>
            </div>`; 
    }); 
    document.getElementById('cart-list').innerHTML = h; 
    document.getElementById('cart-total').innerText = t.toFixed(2); 
    document.getElementById('cart-count').innerText = carrito.length + ' items';
}

function renderQuickEdit() { 
    let p = document.getElementById('quick-edit-panel'); 
    if(lastIdx === -1 || !carrito[lastIdx]) { p.classList.add('d-none'); return; }
    p.classList.remove('d-none');
    document.getElementById('qe-name').innerText = carrito[lastIdx].n;
    document.getElementById('qe-price').innerText = coin + carrito[lastIdx].p.toFixed(2);
    document.getElementById('qe-cant').value = carrito[lastIdx].cant;
}

function modQuick(v) { 
    let n = carrito[lastIdx].cant + v; 
    if(n > carrito[lastIdx].stockMax) return Swal.fire('Límite','Stock insuficiente.','warning');
    if(n <= 0) del(lastIdx); else { carrito[lastIdx].cant = n; renderCart(); renderQuickEdit(); }
}
function del(x) { carrito.splice(x, 1); lastIdx = -1; renderCart(); renderQuickEdit(); }
function delQuick() { if(lastIdx !== -1) del(lastIdx); }
function setQuick(x) { lastIdx = x; renderCart(); renderQuickEdit(); }

// --- PROCESO DE COBRO ---
function abrirModalPago() { 
    if(carrito.length === 0) return Swal.fire('Aviso','Carrito vacío.','warning'); 
    document.getElementById('modal-total-pay').innerText = document.getElementById('cart-total').innerText; 
    document.getElementById('pago-monto').value = ''; document.getElementById('txt-vuelto').innerText = '0.00';
    checkDoc(); 
    new bootstrap.Modal(document.getElementById('modalPago')).show(); 
    setTimeout(() => document.getElementById('pago-monto').focus(), 500);
}

function checkDoc() { 
    let t = document.querySelector('input[name="tipo_doc"]:checked').value; 
    let s = document.getElementById('cliente_venta');
    let doc = s.options[s.selectedIndex].dataset.doc || ''; 
    let al = document.getElementById('alert-doc'); 
    al.classList.add('d-none'); 
    if(t === 'FACTURA' && doc.length !== 11) { al.classList.remove('d-none'); return false; } 
    calcVuelto(); return true; 
}

function calcVuelto() { 
    let t = parseFloat(document.getElementById('modal-total-pay').innerText); 
    let p = parseFloat(document.getElementById('pago-monto').value) || 0; 
    let v = p - t; 
    document.getElementById('txt-vuelto').innerText = v >= 0 ? v.toFixed(2) : '0.00'; 
    document.getElementById('btn-pay-cash').disabled = (v < 0); 
}

async function procesarPago(metodo) { 
    if(!checkDoc()) return;
    let totalV = parseFloat(document.getElementById('cart-total').innerText);
    let data = {
        id_cliente: document.getElementById('cliente_venta').value,
        tipo_doc: document.querySelector('input[name="tipo_doc"]:checked').value,
        metodo_pago: metodo,
        total: totalV,
        monto_pago: (metodo === 'EFECTIVO') ? parseFloat(document.getElementById('pago-monto').value) : totalV,
        items: carrito 
    };
    Swal.fire({title:'Registrando...', didOpen:() => Swal.showLoading(), allowOutsideClick: false});
    let fd = new FormData(); fd.append('venta', JSON.stringify(data));
    try {
        const r = await fetch('api.php?task=sync_sale', {method:'POST', body:fd}).then(r => r.json());
        if(r.success) {
            Swal.fire({icon:'success', title:'Venta Exitosa', showCancelButton:true, confirmButtonText:'Ver Ticket'}).then(res => {
                if(res.isConfirmed) window.open('views/ticket.php?id_venta=' + r.id_venta, 'Ticket', 'width=400');
                location.reload();
            });
        } else Swal.fire('Error', r.error, 'error');
    } catch(e) { Swal.fire('Error','Fallo de conexión.','error'); }
}

// --- CAJA ---
function verificarEstadoCaja() { 
    fetch('api.php?task=check_caja_status').then(r => r.json()).then(res => { 
        if(res.status === 'CLOSED') document.getElementById('caja-cerrada-screen').classList.remove('d-none'); 
    }); 
}
function abrirCaja() { 
    let m = document.getElementById('monto-apertura').value; 
    let fd = new FormData(); fd.append('monto_inicial', m); 
    fetch('api.php?task=open_caja', {method:'POST', body:fd}).then(r => r.json()).then(res => { 
        if(res.success) location.reload(); else Swal.fire('Error', res.error, 'error');
    }); 
}
function prepararCierreCaja() { 
    fetch('api.php?task=get_caja_details').then(r => r.json()).then(d => { 
        Swal.fire({
            title: 'Cierre de Caja', 
            html: `<div class='text-start small'>Efectivo Hoy: <b>${coin}${d.ventas_efectivo.toFixed(2)}</b><br>Gastos: <b>${coin}${d.egresos.toFixed(2)}</b><hr>Total Sistema: <b>${coin}${d.total_calculado.toFixed(2)}</b></div><br>Monto Físico:`, 
            input: 'number', showCancelButton: true, confirmButtonText: 'Cerrar Turno'
        }).then((res) => { 
            if(res.isConfirmed && res.value !== ''){ 
                let fd = new FormData(); fd.append('monto_final', res.value); fd.append('monto_sistema', d.total_calculado); 
                fetch('api.php?task=close_caja', {method:'POST', body:fd}).then(rr => rr.json()).then(ok => { if(ok.success) location.reload(); }); 
            } 
        }); 
    }); 
}

// --- CÁMARA ESCÁNER ---
function toggleCameraPos(){ 
    let d = document.getElementById('reader-pos'); 
    if(!scannerPos){ 
        d.style.display = 'block'; 
        const config = { fps: 10, qrbox: {width: 250, height: 150} };
        if (/Android|webOS|iPhone|iPad/i.test(navigator.userAgent)) config.videoConstraints = { facingMode: "environment" };
        scannerPos = new Html5QrcodeScanner("reader-pos", config, false); 
        scannerPos.render((txt) => { 
            fetch(`api.php?task=search_products&term=${txt}`).then(r => r.json()).then(d => {
                if(d.length > 0) checkAndAdd(encodeURIComponent(JSON.stringify(d[0])));
            });
            scannerPos.clear().then(() => { d.style.display = 'none'; scannerPos = null; });
        }); 
    } else { scannerPos.clear().then(() => { d.style.display = 'none'; scannerPos = null; }); } 
}

document.addEventListener('keydown', (e) => { 
    if(e.key === 'F2') { e.preventDefault(); document.getElementById('search-pos').focus(); }
    if(e.key === 'F4') { e.preventDefault(); abrirModalPago(); }
});
</script>