<div class="card-custom">
    <h4><i class="fas fa-shopping-cart me-2"></i>Nueva Compra</h4>
    <div class="row g-2 mb-3">
        <div class="col-md-4"><label class="fw-bold small">Proveedor</label><select id="c_prov" class="form-select"></select></div>
        <div class="col-md-2"><label class="fw-bold small">Tipo</label><select id="c_tipo" class="form-select"><option>FACTURA</option><option>BOLETA</option></select></div>
        <div class="col-md-3"><label class="fw-bold small">N° Doc</label><input type="text" id="c_serie" class="form-control"></div>
        <div class="col-md-3"><label class="fw-bold small">Fecha</label><input type="date" id="c_fecha" class="form-control" value="<?php echo date('Y-m-d'); ?>"></div>
    </div>
    <hr>
    <div class="card p-3 bg-light mb-3">
        <div class="row g-2 align-items-end">
            <div class="col-md-4"><label class="fw-bold small">Buscar Producto</label><input list="dl_prods" id="search_prod" class="form-control" oninput="selProd(this)"><datalist id="dl_prods"></datalist><input type="hidden" id="temp_id"><input type="hidden" id="temp_lab"></div>
            <div class="col-md-2"><label class="fw-bold small text-danger">Lote (*)</label><input type="text" id="temp_lote" class="form-control form-control-sm"></div>
            <div class="col-md-2"><label class="fw-bold small text-danger">Vencimiento (*)</label><input type="date" id="temp_venc" class="form-control form-control-sm"></div>
            <div class="col-md-1"><label class="fw-bold small">Cant</label><input type="number" id="temp_cant" class="form-control form-control-sm" value="1"></div>
            <div class="col-md-2"><label class="fw-bold small">Costo</label><input type="number" id="temp_costo" class="form-control form-control-sm"></div>
            <div class="col-md-1"><button class="btn btn-primary w-100 btn-sm" onclick="add()">+</button></div>
        </div>
        <div id="preview_prod" class="small text-muted mt-1">...</div>
    </div>
    <table class="table table-bordered"><thead class="table-dark"><tr><th>Producto</th><th>Lote</th><th>Vence</th><th>Cant</th><th>Subtotal</th><th></th></tr></thead><tbody id="cart_body"></tbody></table>
    <div class="text-end fw-bold fs-4" id="total_display">0.00</div>
    <button class="btn btn-success w-100 mt-3" onclick="save()">GUARDAR COMPRA</button>
</div>

<script>
    let cart=[];
    fetch('api.php?task=get_proveedores').then(r=>r.json()).then(d=>{let s=document.getElementById('c_prov');d.forEach(p=>{s.innerHTML+=`<option value="${p.id_proveedor}">${p.razon_social}</option>`})});
    document.getElementById('search_prod').addEventListener('input',function(e){
        if(this.value.length<2)return;
        fetch('api.php?task=search_products&term='+this.value).then(r=>r.json()).then(d=>{
            let dl=document.getElementById('dl_prods');dl.innerHTML='';
            d.forEach(p=>{let o=document.createElement('option');o.value=p.nombre;o.label=p.laboratorio;o.setAttribute('d-id',p.id_producto);o.setAttribute('d-lab',p.laboratorio);o.setAttribute('d-c',p.precio_costo);dl.appendChild(o)});
        });
    });
    function selProd(i){
        let opts=document.getElementById('dl_prods').options;
        for(let x=0;x<opts.length;x++){
            if(opts[x].value===i.value){
                document.getElementById('temp_id').value=opts[x].getAttribute('d-id');
                document.getElementById('temp_lab').value=opts[x].getAttribute('d-lab');
                document.getElementById('temp_costo').value=opts[x].getAttribute('d-c');
                document.getElementById('preview_prod').innerText=opts[x].getAttribute('d-lab');
                document.getElementById('temp_lote').focus(); break;
            }
        }
    }
    function add(){
        let id=document.getElementById('temp_id').value, nom=document.getElementById('search_prod').value,
            lote=document.getElementById('temp_lote').value, venc=document.getElementById('temp_venc').value,
            cant=parseFloat(document.getElementById('temp_cant').value), costo=parseFloat(document.getElementById('temp_costo').value);
        if(!id || !lote || !venc) return Swal.fire('Error','Faltan datos','warning');
        cart.push({id,nom,lote,venc,cant,costo,subtotal:cant*costo}); render();
        document.getElementById('search_prod').value=''; document.getElementById('temp_id').value=''; document.getElementById('temp_lote').value='';
    }
    function render(){
        let h='',t=0; cart.forEach((i,x)=>{t+=i.subtotal; h+=`<tr><td>${i.nom}</td><td>${i.lote}</td><td>${i.venc}</td><td>${i.cant}</td><td>${i.subtotal.toFixed(2)}</td><td><button onclick="cart.splice(${x},1);render()">x</button></td></tr>`});
        document.getElementById('cart_body').innerHTML=h; document.getElementById('total_display').innerText=t.toFixed(2);
    }
    function save(){
        if(cart.length===0) return;
        let d={id_prov:document.getElementById('c_prov').value, tipo_doc:document.getElementById('c_tipo').value, num_doc:document.getElementById('c_serie').value, fecha:document.getElementById('c_fecha').value, total:parseFloat(document.getElementById('total_display').innerText), items:cart};
        let fd=new FormData(); fd.append('compra',JSON.stringify(d));
        fetch('api.php?task=save_compra',{method:'POST',body:fd}).then(r=>r.json()).then(r=>{if(r.success)location.reload();else Swal.fire('Error',r.error,'error')});
    }
</script>