<?= $this->extend('layouts/main_layout') ?>
<?= $this->section('content') ?>

<div class="flex items-center justify-between mb-6">
    <h2 class="text-2xl font-bold text-gray-900"><i class="bi bi-cart-plus text-2xl"></i> Registrar Venta</h2>
    <a href="<?= site_url('sales') ?>" class="bg-teal-100 border border-gray-200 rounded-lg px-4 py-2 text-sm transition hover:bg-gray-50 text-gray-600 no-underline inline-flex items-center gap-2">
        <i class="bi bi-arrow-left"></i> Volver
    </a>
</div>

<div class="grid grid-cols-1 lg:grid-cols-12 gap-6">
    <div class="lg:col-span-8">
        <div class="bg-emerald-100 rounded-xl shadow-sm border border-gray-100 mb-4">
            <div class="p-3">
                <div class="flex flex-col sm:flex-row gap-2">
                    <div class="sm:w-2/5">
                        <select id="id_categoria" class="w-full bg-teal-100 border border-gray-200 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500">
                            <option value="">Todas las categorias...</option>
                            <?php foreach ($categories as $cat): ?>
                            <option value="<?= esc($cat['nombre']) ?>"><?= esc($cat['nombre']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="sm:w-3/5">
                        <div class="flex items-center bg-teal-100 border border-gray-200 rounded-lg overflow-hidden focus-within:ring-2 focus-within:ring-teal-500">
                            <span class="px-3 text-gray-400"><i class="bi bi-search"></i></span>
                            <input type="text" id="search_producto" class="w-full py-2.5 pr-3 outline-none text-sm" placeholder="Buscar producto..." autocomplete="off">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-2" id="productGrid">
            <?php foreach ($products as $prod): ?>
            <div class="product-card-col"
                 data-categoria="<?= esc($prod['categoria_nombre']) ?>"
                 data-nombre="<?= esc($prod['nombre']) ?>">
                <div class="bg-teal-100 rounded-xl overflow-hidden cursor-pointer border border-gray-100 hover:shadow-md transition card-hover product-card"
                     data-id="<?= $prod['id_producto'] ?>"
                     data-precio="<?= $prod['precio_venta'] ?>"
                     data-stock="<?= $prod['stock_actual'] ?>"
                     data-nombre="<?= esc($prod['nombre']) ?>"
                     data-codigo="<?= esc($prod['codigo_unico']) ?>"
                     onclick="addToCart(this)">
                    <div class="relative aspect-square bg-gray-50">
                        <?php if (!empty($prod['imagen'])): ?>
                        <img src="<?= base_url('uploads/products/' . $prod['imagen']) ?>" alt="<?= esc($prod['nombre']) ?>" class="w-full h-full object-cover">
                        <?php else: ?>
                        <div class="flex items-center justify-center h-full text-gray-300">
                            <i class="bi bi-box-seam text-2xl"></i>
                        </div>
                        <?php endif; ?>
                        <span class="absolute top-1 right-1 bg-gray-700 text-white text-[.55rem] px-1.5 py-0.5 rounded"><?= esc($prod['codigo_unico']) ?></span>
                        <span class="absolute top-1 left-1 text-white text-[.55rem] px-1.5 py-0.5 rounded <?= $prod['stock_actual'] <= 5 ? 'bg-red-500' : ($prod['stock_actual'] <= 10 ? 'bg-yellow-500' : 'bg-teal-500') ?>">
                            <?= $prod['stock_actual'] ?>
                        </span>
                    </div>
                    <div class="p-2">
                        <h6 class="font-bold text-[.7rem] truncate text-gray-900 mb-0" title="<?= esc($prod['nombre']) ?>"><?= esc($prod['nombre']) ?></h6>
                        <div class="font-bold text-emerald-700 text-[.75rem]">S/ <?= number_format($prod['precio_venta'], 2) ?></div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <div class="lg:col-span-4">
        <form method="post" action="<?= site_url('sales') ?>" id="saleForm">
            <?= csrf_field() ?>
<div class="bg-emerald-100 rounded-xl shadow-sm border border-gray-100">


        
                <div id="pendingBannerContainer" hx-get="<?= site_url('sales/get-pending-html') ?>" hx-trigger="load" hx-target="#pendingBannerContainer" hx-swap="outerHTML"></div>
                <div class="flex items-center justify-between px-5 py-3 border-b border-gray-100">
                    <h5 class="font-semibold text-gray-900"><i class="bi bi-receipt"></i> Carrito</h5>
                    <span class="bg-emerald-100 text-emerald-700 rounded-lg px-2.5 py-1 text-xs font-semibold" id="cartCount">0</span>
                </div>
                <div>
                    <div id="cartEmpty" class="text-center text-gray-400 py-8">
                        <i class="bi bi-cart3 text-3xl"></i>
                        <p class="mt-2 mb-0">Carrito vacio</p>
                        <p class="text-xs">Seleccione productos</p>
                    </div>
                    <div id="cartContent" class="hidden">
                        <div id="cartItems" class="px-4 py-2"></div>
                        <hr class="border-gray-100 my-1">
                        <div class="px-4 py-3">
                            <div class="flex justify-between items-center mb-1">
                                <span class="font-bold text-gray-900">TOTAL <span class="text-xs font-normal text-gray-400">(IGV incluido)</span></span>
                                <span class="font-bold text-emerald-700 text-xl" id="cartTotal">S/ 0.00</span>
                            </div>
                            <div class="flex justify-between text-xs text-gray-400 mb-1">
                                <span>Base Imponible</span>
                                <span id="baseDisplay">S/ 0.00</span>
                            </div>
                            <div class="flex justify-between text-xs text-gray-400 mb-3">
                                <span>IGV (18%)</span>
                                <span id="igvDisplay">S/ 0.00</span>
                            </div>
                            <hr class="border-gray-100 mb-3">
                            <div class="mb-3" id="montoRecibidoContainer" style="display:none">
                                <label for="monto_recibido" class="block text-sm font-medium text-gray-500 mb-1">Monto Recibido (S/)</label>
                                <input type="number" name="monto_recibido" id="monto_recibido" step="0.01" min="0" class="w-full bg-teal-100 border border-gray-200 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500" onchange="calcularCambio()" onkeyup="calcularCambio()">
                                <div id="cambioDisplay" class="text-right text-sm font-semibold text-[#D4C800] mt-1 hidden"></div>
                            </div>
                            <div class="mb-3">
                                <label for="id_forma_pago" class="block text-sm font-medium text-gray-500 mb-1">Forma de Pago *</label>
                                <select name="id_forma_pago" id="id_forma_pago" class="w-full bg-teal-100 border border-gray-200 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500" required>
                                    <option value="">Seleccione...</option>
                                    <?php foreach ($paymentMethods as $pm): ?>
                                    <option value="<?= $pm['id_forma_pago'] ?>" <?= old('id_forma_pago') == $pm['id_forma_pago'] ? 'selected' : '' ?>>
                                        <?= ucfirst($pm['nombre']) ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="observaciones" class="block text-sm font-medium text-gray-500 mb-1">Observaciones</label>
                                <textarea name="observaciones" id="observaciones" class="w-full bg-teal-100 border border-gray-200 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500" rows="2"><?= old('observaciones') ?></textarea>
                            </div>
                            <button type="submit" class="w-full bg-teal-600 hover:bg-teal-700 text-white font-medium py-2.5 rounded-lg transition inline-flex items-center justify-center gap-2 text-sm shadow-sm" id="btnSubmit" disabled>
                                <i class="bi bi-check-circle"></i> Registrar Venta (0)
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
var cart = [];
var pendingId = null;

function savePendingCart() {
    if (cart.length === 0 && pendingId) {
        clearPendingCart();
        return;
    }
    if (cart.length === 0) return;
    var payload = JSON.stringify(cart);
    localStorage.setItem('velmox_pending_cart', payload);
    var formData = new FormData();
    formData.append('cart', payload);
    fetch('<?= site_url('sales/save-pending') ?>', {
        method: 'POST',
        body: formData,
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    }).then(function(r) { return r.json(); }).then(function(data) {
        if (data.success) pendingId = data.id;
    }).catch(function() {});
}

function restorePendingCart() {
    fetch('<?= site_url('sales/get-pending') ?>')
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.success && data.datos && data.datos.length > 0) {
                cart = data.datos;
                localStorage.setItem('velmox_pending_cart', JSON.stringify(cart));
                renderCart();
                var banner = document.getElementById('pendingBanner');
                if (banner) banner.remove();
            }
        }).catch(function() {});
}

function clearPendingCart() {
    localStorage.removeItem('velmox_pending_cart');
    pendingId = null;
    fetch('<?= site_url('sales/clear-pending') ?>', {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    }).catch(function() {});
}

document.body.addEventListener('pendingCleared', function() {
    localStorage.removeItem('velmox_pending_cart');
    pendingId = null;
});

function addToCart(el) {
    var id = parseInt(el.dataset.id);
    var precio = parseFloat(el.dataset.precio);
    var stock = parseInt(el.dataset.stock);
    var nombre = el.dataset.nombre;
    var codigo = el.dataset.codigo;

    var existing = cart.findIndex(function(item) { return item.id === id; });
    if (existing !== -1) {
        var newQty = cart[existing].cantidad + 1;
        if (newQty > stock) {
            Swal.fire({ icon: 'warning', title: 'Stock maximo alcanzado', text: nombre + ' (' + stock + ')', timer: 3000, showConfirmButton: false });
            return;
        }
        cart[existing].cantidad = newQty;
        cart[existing].subtotal = newQty * cart[existing].precio;
    } else {
        if (stock < 1) {
            Swal.fire({ icon: 'error', title: 'Producto sin stock', text: nombre + ' no tiene stock disponible', timer: 3000, showConfirmButton: false });
            return;
        }
        cart.push({
            id: id,
            nombre: nombre,
            codigo: codigo,
            precio: precio,
            stock: stock,
            cantidad: 1,
            subtotal: precio
        });
    }
    renderCart();
}

function removeFromCart(id) {
    cart = cart.filter(function(item) { return item.id !== id; });
    renderCart();
}

function updateQty(id, newQty) {
    var item = cart.find(function(item) { return item.id === id; });
    if (!item) return;
    newQty = parseInt(newQty) || 1;
    if (newQty < 1) newQty = 1;
    if (newQty > item.stock) newQty = item.stock;
    item.cantidad = newQty;
    item.subtotal = newQty * item.precio;
    renderCart();
}

function updatePrecio(id, newPrecio) {
    var item = cart.find(function(item) { return item.id === id; });
    if (!item) return;
    newPrecio = parseFloat(newPrecio) || 0;
    if (newPrecio < 0.01) newPrecio = 0.01;
    item.precio = newPrecio;
    item.subtotal = item.cantidad * newPrecio;
    renderCart();
}

function renderCart() {
    var container = document.getElementById('cartItems');
    var empty = document.getElementById('cartEmpty');
    var content = document.getElementById('cartContent');
    var count = document.getElementById('cartCount');
    var totalEl = document.getElementById('cartTotal');
    var btn = document.getElementById('btnSubmit');

    count.textContent = cart.length;

    if (cart.length === 0) {
        empty.classList.remove('hidden');
        content.classList.add('hidden');
        btn.disabled = true;
        btn.innerHTML = '<i class="bi bi-check-circle"></i> Registrar Venta (0)';
        return;
    }

    empty.classList.add('hidden');
    content.classList.remove('hidden');
    btn.disabled = false;

    var total = 0;
    var html = '';
    cart.forEach(function(item) {
        total += item.subtotal;
        html +=
            '<div class="flex items-center gap-2 py-2 border-b border-gray-100">' +
                '<div class="flex-1 min-w-0">' +
                    '<div class="font-bold text-xs truncate" title="' + item.nombre + '">' + item.nombre + '</div>' +
                    '<div class="text-gray-400 text-[.6rem]">' + item.codigo + '</div>' +
                '</div>' +
                '<div class="flex items-center gap-1">' +
                    '<button type="button" class="border border-slate-200 rounded text-gray-600 hover:bg-slate-100 py-0 px-1 text-[.6rem]" onclick="updateQty(' + item.id + ',' + (item.cantidad - 1) + ')"><i class="bi bi-dash"></i></button>' +
                    '<input type="number" name="cantidad[]" value="' + item.cantidad + '" min="1" max="' + item.stock + '" class="w-[45px] text-center text-[.7rem] border border-slate-200 rounded px-1 py-1 outline-none" onchange="updateQty(' + item.id + ', this.value)">' +
                    '<button type="button" class="border border-slate-200 rounded text-gray-600 hover:bg-slate-100 py-0 px-1 text-[.6rem]" onclick="updateQty(' + item.id + ',' + (item.cantidad + 1) + ')"><i class="bi bi-plus"></i></button>' +
                '</div>' +
                '<div class="text-right min-w-[60px]">' +
                    '<div class="text-xs font-bold">S/ ' + item.subtotal.toFixed(2) + '</div>' +
                    '<input type="number" value="' + item.precio.toFixed(2) + '" step="0.01" min="0.01" class="w-[60px] text-right text-[.6rem] text-gray-400 border border-slate-200 rounded px-1 py-0 outline-none precio-input" onchange="updatePrecio(' + item.id + ', this.value)" data-id="' + item.id + '">' +
                '</div>' +
                '<button type="button" class="text-rose-500 hover:text-rose-700 hover:bg-rose-50 rounded py-0 px-1 text-[.6rem] border border-rose-200" onclick="removeFromCart(' + item.id + ')"><i class="bi bi-x"></i></button>' +
                '<input type="hidden" name="id_producto[]" value="' + item.id + '">' +
                '<input type="hidden" name="precio_unitario[]" value="' + item.precio.toFixed(2) + '">' +
                '<input type="hidden" name="subtotal[]" value="' + item.subtotal.toFixed(2) + '">' +
            '</div>';
    });
    container.innerHTML = html;
    var igv = total * 0.18 / 1.18;
    totalEl.textContent = 'S/ ' + total.toFixed(2);
    document.getElementById('igvDisplay').textContent = 'S/ ' + igv.toFixed(2);
    document.getElementById('baseDisplay').textContent = 'S/ ' + (total - igv).toFixed(2);
    btn.innerHTML = '<i class="bi bi-check-circle"></i> Registrar Venta (S/ ' + total.toFixed(2) + ')';
    savePendingCart();
}

document.getElementById('id_categoria').addEventListener('change', filtrarProductos);
document.getElementById('search_producto').addEventListener('input', filtrarProductos);

function filtrarProductos() {
    var cat = document.getElementById('id_categoria').value;
    var query = document.getElementById('search_producto').value.toLowerCase();
    var cards = document.querySelectorAll('.product-card-col');

    cards.forEach(function(col) {
        var matchCat = cat === '' || col.dataset.categoria === cat;
        var matchText = query === '' || col.dataset.nombre.toLowerCase().indexOf(query) !== -1;
        col.style.display = (matchCat && matchText) ? '' : 'none';
    });
}

document.getElementById('saleForm').addEventListener('submit', function(e) {
    if (cart.length === 0) {
        e.preventDefault();
        Swal.fire({ icon: 'warning', title: 'Carrito vacio', text: 'Agregue al menos un producto al carrito', timer: 3000, showConfirmButton: false });
        return;
    }
    var fp = document.getElementById('id_forma_pago');
    if (fp && fp.value && fp.options[fp.selectedIndex].text.toLowerCase().includes('efectivo')) {
        var recibido = parseFloat(document.getElementById('monto_recibido').value) || 0;
        var total = cart.reduce(function(s, i) { return s + i.subtotal; }, 0);
        if (recibido < total) {
            e.preventDefault();
            Swal.fire({ icon: 'warning', title: 'Monto insuficiente', text: 'El monto recibido debe ser mayor o igual al total', timer: 3000, showConfirmButton: false });
            return;
        }
    }
    clearPendingCart();
});

document.getElementById('id_forma_pago').addEventListener('change', function() {
    var container = document.getElementById('montoRecibidoContainer');
    if (this.options[this.selectedIndex].text.toLowerCase().includes('efectivo')) {
        container.style.display = 'block';
    } else {
        container.style.display = 'none';
    }
});

function calcularCambio() {
    var recibido = parseFloat(document.getElementById('monto_recibido').value) || 0;
    var total = cart.reduce(function(s, i) { return s + i.subtotal; }, 0);
    var display = document.getElementById('cambioDisplay');
    if (recibido > total) {
        var cambio = recibido - total;
        display.textContent = 'Vuelto: S/ ' + cambio.toFixed(2);
        display.classList.remove('hidden');
    } else {
        display.classList.add('hidden');
    }
}

setInterval(savePendingCart, 30000);
</script>

<style>
.product-card { cursor: pointer; transition: transform .15s, box-shadow .15s; }
.product-card:hover { transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0,0,0,0.12) !important; }
.min-w-0 { min-width: 0; }
</style>

<?= $this->endSection() ?>