<?php $__env->startSection('title','New Purchase'); ?>
<?php $__env->startSection('styles'); ?><style>.picker{position:relative}.picker-results{display:none;position:absolute;z-index:10;top:39px;inset-inline:0;background:#fff;border:1px solid var(--line);border-radius:10px;box-shadow:0 14px 35px #10182825;max-height:300px;overflow:auto}.picker-results.show{display:block}.pick{padding:8px 10px;border-bottom:1px solid #eee;cursor:pointer}.pick:hover{background:#f2f8f7}.purchase-grid input,.purchase-grid select{border:0;background:transparent;min-width:70px;font-size:11px;padding:4px}</style><?php $__env->stopSection(); ?>
<?php $__env->startSection('content'); ?>
<form method="POST" action="<?php echo e(route('purchases.store')); ?>" id="purchaseForm"><?php echo csrf_field(); ?><input type="hidden" name="action" id="purchaseAction" value="finalize"><div class="page-head"><div><h1>New purchase</h1><p>Draft first or finalize to post stock, cost, VAT, payable, and accounts atomically.</p></div><span class="badge status-draft px-3 py-2">AUTO NUMBER</span></div>
<div class="card-erp"><div class="card-erp-body"><div class="row g-2"><div class="col-lg-3"><label class="form-label">Supplier</label><select name="supplier_id" class="form-select" required><?php $__currentLoopData = $suppliers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $s): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($s->id); ?>"><?php echo e($s->supplier_code); ?> · <?php echo e($s->name_en); ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select></div><div class="col-lg-2"><label class="form-label">Supplier invoice no.</label><input name="supplier_invoice_no" class="form-control"></div><div class="col-6 col-lg-2"><label class="form-label">Date</label><input type="date" name="purchase_date" class="form-control" value="<?php echo e(now()->toDateString()); ?>" required></div><div class="col-6 col-lg-2"><label class="form-label">Warehouse</label><select id="purchaseWarehouse" name="warehouse_id" class="form-select"><?php $__currentLoopData = $warehouses; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $w): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($w->id); ?>"><?php echo e($w->code); ?> · <?php echo e($w->name_en); ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select></div><div class="col-lg-1"><label class="form-label">Branch</label><select name="branch_id" class="form-select"><?php $__currentLoopData = $branches; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $b): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($b->id); ?>"><?php echo e($b->code); ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select></div><div class="col-lg-2"><label class="form-label">Payment</label><select id="purchasePaymentType" name="payment_type" class="form-select"><?php $__currentLoopData = ['credit','cash','bank','card','transfer','mixed']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $p): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option><?php echo e($p); ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select></div><div class="col-lg-2"><label class="form-label">Reference</label><input name="reference" class="form-control"></div><div class="col-lg-2"><label class="form-label">PO reference</label><input name="po_reference" class="form-control"></div><div class="col-lg-8"><label class="form-label">Notes</label><input name="notes" class="form-control"></div></div></div></div>
<div class="card-erp"><div class="card-erp-header"><span>Products</span><small class="text-muted">Search by barcode, product code, English or Arabic name</small></div><div class="card-erp-body"><div class="picker"><input id="purchaseSearch" class="form-control" placeholder="Search product to add…" autocomplete="off"><div id="purchaseResults" class="picker-results"></div></div></div><div class="table-responsive"><table class="table table-dense purchase-grid"><thead><tr><th>#</th><th style="min-width:240px">Description</th><th>Unit</th><th>Qty</th><th>Free</th><th>Cost</th><th>Discount</th><th>VAT%</th><th>Batch</th><th>Expiry</th><th class="text-end">Total</th><th></th></tr></thead><tbody id="purchaseItems"><tr id="purchaseEmpty"><td colspan="12" class="text-center text-muted py-5">Add products to the purchase.</td></tr></tbody></table></div></div>
<div class="row g-2"><div class="col-lg-7"><div class="card-erp"><div class="card-erp-header">Payment allocation</div><div class="card-erp-body"><div class="row g-2"><div class="col-4"><select name="payments[0][payment_method]" class="form-select purchase-pay-input"><option>cash</option><option>bank</option><option>card</option><option>transfer</option></select></div><div class="col-4"><input name="payments[0][amount]" class="form-control purchase-pay-input" type="number" min="0" step=".01" placeholder="Amount"></div><div class="col-4"><input name="payments[0][reference]" class="form-control purchase-pay-input" placeholder="Reference"></div></div></div></div></div><div class="col-lg-5"><div class="card-erp"><div class="card-erp-body"><div class="d-flex justify-content-between py-1"><span>Gross</span><strong id="pGross">0.00</strong></div><div class="d-flex justify-content-between py-1"><span>Discount</span><strong id="pDiscount">0.00</strong></div><div class="d-flex justify-content-between py-1"><span>Taxable</span><strong id="pTaxable">0.00</strong></div><div class="d-flex justify-content-between py-1"><span>VAT</span><strong id="pVat">0.00</strong></div><hr><div class="d-flex justify-content-between"><strong>GRAND TOTAL</strong><strong class="fs-4 text-accent">SAR <span id="pGrand">0.00</span></strong></div></div></div></div></div>
<div class="sticky-actions d-flex justify-content-end gap-2"><a href="<?php echo e(route('purchases.index')); ?>" class="btn btn-light border">Cancel</a><button type="button" class="btn btn-outline-secondary" data-paction="hold">Save draft</button><button type="button" class="btn btn-primary" data-paction="finalize">Finalize purchase</button></div></form>
<?php $__env->stopSection(); ?>
<?php $__env->startSection('scripts'); ?><script>
const ps=document.getElementById('purchaseSearch'),pr=document.getElementById('purchaseResults'),pt=document.getElementById('purchaseItems');let pi=0,tm;const em=s=>{const d=document.createElement('div');d.textContent=s??'';return d.innerHTML},m=n=>(Math.round((+n+Number.EPSILON)*100)/100).toFixed(2);ps.oninput=()=>{clearTimeout(tm);let q=ps.value.trim();if(!q){pr.classList.remove('show');return}tm=setTimeout(async()=>{let x=await fetch(`<?php echo e(route('api.products.search')); ?>?q=${encodeURIComponent(q)}&warehouse_id=${purchaseWarehouse.value}`,{headers:{Accept:'application/json'}}),a=await x.json();pr.innerHTML=a.map((p,i)=>`<div class="pick" data-i="${i}"><b>${em(p.product_code)} · ${em(p.name_en)}</b><small class="d-block text-muted" dir="rtl">${em(p.name_ar)}</small></div>`).join('')||'<div class="p-3 text-muted">No products found</div>';pr.classList.add('show');pr.querySelectorAll('.pick').forEach(e=>e.onclick=()=>addPurchase(a[e.dataset.i]))},160)};ps.onkeydown=e=>{if(e.key==='Enter'){e.preventDefault();pr.querySelector('.pick')?.click()}};
function addPurchase(p){purchaseEmpty?.remove();let units=p.units?.length?p.units:[{id:p.sales_unit_id,code:p.base_unit?.code||'PCS',purchase_price:p.cost_price}],u=units.find(x=>x.purchase_price>0)||units[0],tr=document.createElement('tr');tr.dataset.row=1;tr.innerHTML=`<td class="n"></td><td><b>${em(p.name_en)}</b><small class="d-block text-muted" dir="rtl">${em(p.name_ar)}</small><input type="hidden" name="items[${pi}][product_id]" value="${p.id}"></td><td><select name="items[${pi}][unit_id]">${units.map(x=>`<option value="${x.id}" data-cost="${x.purchase_price||p.cost_price}" ${x.id==u.id?'selected':''}>${em(x.code)}</option>`).join('')}</select></td><td><input class="q" name="items[${pi}][quantity]" type="number" value="1" min=".0001" step=".0001"></td><td><input name="items[${pi}][free_quantity]" type="number" value="0" min="0" step=".0001"></td><td><input class="c" name="items[${pi}][unit_cost]" type="number" value="${u.purchase_price||p.cost_price}" min="0" step=".0001"></td><td><div class="d-flex"><input class="d" name="items[${pi}][discount_value]" type="number" value="0" min="0" step=".01"><select class="dt" name="items[${pi}][discount_type]"><option value="fixed">SAR</option><option value="percentage">%</option></select></div></td><td><input class="v" name="items[${pi}][vat_rate]" type="number" value="${p.vat_rate}" min="0" max="100"></td><td><input name="items[${pi}][batch_number]"></td><td><input name="items[${pi}][expiry_date]" type="date"></td><td class="text-end fw-bold total">0.00</td><td><button type="button" class="btn btn-link text-danger x"><i class="bi bi-x-lg"></i></button></td>`;pt.appendChild(tr);tr.querySelectorAll('input,select').forEach(x=>x.oninput=recalcP);tr.querySelector('td:nth-child(3) select').onchange=e=>{tr.querySelector('.c').value=e.target.selectedOptions[0].dataset.cost;recalcP()};tr.querySelector('.x').onclick=()=>{tr.remove();recalcP()};pi++;numberP();recalcP();pr.classList.remove('show');ps.value='';ps.focus()}
function recalcP(){let s={g:0,d:0,t:0,v:0,z:0};pt.querySelectorAll('tr[data-row]').forEach(r=>{let g=(+r.querySelector('.q').value||0)*(+r.querySelector('.c').value||0),dv=+r.querySelector('.d').value||0,d=r.querySelector('.dt').value==='percentage'?g*dv/100:dv,t=Math.max(0,g-d),v=t*(+r.querySelector('.v').value||0)/100,z=t+v;r.querySelector('.total').textContent=m(z);s.g+=g;s.d+=d;s.t+=t;s.v+=v;s.z+=z});pGross.textContent=m(s.g);pDiscount.textContent=m(s.d);pTaxable.textContent=m(s.t);pVat.textContent=m(s.v);pGrand.textContent=m(s.z);return s}function numberP(){pt.querySelectorAll('.n').forEach((x,i)=>x.textContent=i+1)}
function togglePay(){let credit=purchasePaymentType.value==='credit';document.querySelectorAll('.purchase-pay-input').forEach(x=>x.disabled=credit)}purchasePaymentType.onchange=togglePay;togglePay();document.querySelectorAll('[data-paction]').forEach(b=>b.onclick=()=>{if(!pt.querySelector('tr[data-row]'))return alert('Add at least one product.');let total=recalcP().z,amount=document.querySelector('.purchase-pay-input[type=number]');if(!amount.disabled&&!amount.value)amount.value=m(total);purchaseAction.value=b.dataset.paction;purchaseForm.submit()});
</script><?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\saudi\resources\views/purchases/create.blade.php ENDPATH**/ ?>