<?php $__env->startSection('title','New Sales Invoice'); ?>
<?php $__env->startSection('styles'); ?><style>.billing-grid input,.billing-grid select{min-width:76px;border:0;background:transparent;padding:4px;font-size:11px}.billing-grid input:focus,.billing-grid select:focus{outline:2px solid #99c9c4;border-radius:5px}.product-picker{position:relative}.product-results{position:absolute;z-index:1020;inset-inline:0;top:39px;background:#fff;border:1px solid var(--line);border-radius:10px;box-shadow:0 14px 35px rgba(16,24,40,.16);display:none;max-height:310px;overflow:auto}.product-results.show{display:block}.product-option{padding:8px 10px;cursor:pointer;border-bottom:1px solid #f0f1f3}.product-option:hover{background:#f2f8f7}.totals-panel{min-width:300px}.grand-total{font-size:24px;color:var(--accent);letter-spacing:-.03em}</style><?php $__env->stopSection(); ?>
<?php $__env->startSection('content'); ?>
<form method="POST" action="<?php echo e(route('sales.store')); ?>" id="invoiceForm"><?php echo csrf_field(); ?><input type="hidden" name="action" id="formAction" value="finalize"><input type="hidden" name="van_session_id" value="<?php echo e($vanSession?->id); ?>">
<div class="page-head"><div><h1><?php echo e($vanSession?'Van billing · '.$vanSession->session_no:'New sales invoice'); ?></h1><p>Barcode-ready, bilingual billing · F2 product · F3 customer · F9 save · F10 print</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">Customer</label><select id="customer" name="customer_id" class="form-select" required><?php $__currentLoopData = $customers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $c): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($c->id); ?>" data-vat="<?php echo e($c->vat_number); ?>" data-credit="<?php echo e($c->credit_days); ?>" <?php if((string) old('customer_id', request('customer_id')) === (string) $c->id || (!old('customer_id') && !request('customer_id') && $c->customer_code === 'CASH')): echo 'selected'; endif; ?>><?php echo e($c->customer_code); ?> · <?php echo e($c->name_en); ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select></div>
<div class="col-lg-2" id="customerVatField"><label class="form-label">Customer VAT</label><input id="customerVat" class="form-control bg-light" readonly></div>
<div class="col-6 col-lg-2"><label class="form-label">Invoice date</label><input type="date" name="invoice_date" class="form-control" value="<?php echo e(old('invoice_date',now()->toDateString())); ?>" required></div>
<div class="col-6 col-lg-2"><label class="form-label">Warehouse</label><select id="warehouse" name="warehouse_id" class="form-select" required><?php $__currentLoopData = $warehouses; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $w): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($w->id); ?>" <?php if($vanSession?->warehouse_id===$w->id): echo 'selected'; endif; ?>><?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">Invoice type</label><select id="invoiceType" name="invoice_type" class="form-select"><option value="tax_invoice" <?php if(old('invoice_type')==='tax_invoice'): echo 'selected'; endif; ?>>Tax Invoice</option><option value="simplified_tax_invoice" <?php if(old('invoice_type')==='simplified_tax_invoice'): echo 'selected'; endif; ?>>Simplified Tax Invoice</option><option value="non_tax_invoice" <?php if(old('invoice_type')==='non_tax_invoice'): echo 'selected'; endif; ?>>Non-tax Invoice</option></select></div>
<div class="col-6 col-lg-2"><label class="form-label">Payment type</label><select id="paymentType" name="payment_type" class="form-select"><?php $__currentLoopData = ['cash','credit','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-6 col-lg-2"><label class="form-label">Price mode</label><select id="priceMode" name="price_mode" class="form-select"><option>Exclusive VAT</option><option>Inclusive VAT</option></select></div>
<div class="col-6 col-lg-1"><label class="form-label">Credit days</label><input id="creditDays" type="number" name="credit_days" class="form-control" value="0" min="0"></div>
<div class="col-6 col-lg-2"><label class="form-label">PO number</label><input name="po_number" class="form-control" value="<?php echo e(old('po_number')); ?>"></div>
<div class="col-lg-2"><label class="form-label">Salesman</label><input name="salesman" class="form-control" value="<?php echo e(old('salesman',$vanSession?->salesman?->name)); ?>"></div>
<div class="col-lg-5"><label class="form-label">Notes</label><input name="notes" class="form-control" value="<?php echo e(old('notes')); ?>"></div>
</div></div></div>
<div class="card-erp"><div class="card-erp-header"><span><i class="bi bi-upc-scan me-1 text-accent"></i>Product entry</span><small class="text-muted">Scan barcode or type name/code, then Enter</small></div><div class="card-erp-body"><div class="product-picker"><input id="productSearch" class="form-control" placeholder="Barcode / product code / English or Arabic product name" autocomplete="off"><div id="productResults" class="product-results"></div></div></div><div class="table-responsive"><table class="table table-dense billing-grid"><thead><tr><th style="width:34px">#</th><th style="min-width:260px">Description / الوصف</th><th>Unit</th><th>Qty</th><th>Price</th><th>Discount</th><th class="vat-column">VAT %</th><th class="text-end vat-column">VAT</th><th class="text-end">Total</th><th></th></tr></thead><tbody id="invoiceItems"><tr id="emptyRow"><td colspan="10" class="text-center text-muted py-5">Search or scan a product to begin billing.</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"><span>Payment allocation</span><button type="button" class="btn btn-light border btn-dense" id="addPayment"><i class="bi bi-plus"></i>Add split</button></div><div class="card-erp-body" id="payments"><div class="row g-2 payment-row"><div class="col-4"><select name="payments[0][payment_method]" class="form-select pay-method"><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 pay-amount" type="number" min="0" step="0.01" placeholder="Amount"></div><div class="col-4"><input name="payments[0][reference]" class="form-control" placeholder="Reference"></div></div></div></div><div class="form-check ms-2"><input class="form-check-input" type="checkbox" value="1" name="credit_override" id="override"><label class="form-check-label small" for="override">Authorized credit-limit override</label></div></div>
<div class="col-lg-5"><div class="card-erp totals-panel"><div class="card-erp-body"><div class="d-flex justify-content-between py-1"><span class="text-muted">Gross</span><strong id="gross">0.00</strong></div><div class="d-flex justify-content-between py-1"><span class="text-muted">Discount</span><strong id="discount">0.00</strong></div><div class="d-flex justify-content-between py-1"><span class="text-muted" id="taxableLabel">Taxable</span><strong id="taxable">0.00</strong></div><div class="d-flex justify-content-between py-1" id="vatTotalRow"><span class="text-muted">VAT</span><strong id="vat">0.00</strong></div><hr><div class="d-flex justify-content-between align-items-end"><span><small class="text-muted d-block">GRAND TOTAL</small><strong class="grand-total">SAR <span id="grand">0.00</span></strong></span><span class="text-end"><small class="text-muted d-block">Balance</small><strong id="balance">0.00</strong></span></div></div></div></div></div>
<div class="sticky-actions d-flex flex-wrap gap-2 justify-content-end mt-2"><a href="<?php echo e(route('sales.index')); ?>" class="btn btn-light border">Cancel</a><button type="button" class="btn btn-outline-secondary" data-action="hold"><i class="bi bi-pause-circle me-1"></i>Hold (F6)</button><button type="button" class="btn btn-primary" data-action="finalize"><i class="bi bi-check2-circle me-1"></i>Finalize (F9)</button><button type="button" class="btn btn-dark" data-action="finalize_print"><i class="bi bi-printer me-1"></i>Save & Print (F10)</button></div>
</form>
<?php $__env->stopSection(); ?>
<?php $__env->startSection('scripts'); ?>
<script>
const search=document.getElementById('productSearch'),results=document.getElementById('productResults'),tbody=document.getElementById('invoiceItems'),warehouse=document.getElementById('warehouse'),priceMode=document.getElementById('priceMode'),invoiceType=document.getElementById('invoiceType');let timer,rowIndex=0,paymentIndex=1;
const isNonTax=()=>invoiceType.value==='non_tax_invoice';
const money=n=>(Math.round((Number(n)+Number.EPSILON)*100)/100).toFixed(2);const safe=s=>{const d=document.createElement('div');d.textContent=s??'';return d.innerHTML};
search.addEventListener('input',()=>{clearTimeout(timer);let q=search.value.trim();if(!q){results.classList.remove('show');return}timer=setTimeout(async()=>{let r=await fetch(`<?php echo e(route('api.products.search')); ?>?q=${encodeURIComponent(q)}&warehouse_id=${warehouse.value}`,{headers:{Accept:'application/json'}}),items=await r.json();results.innerHTML=items.map((p,i)=>`<div class="product-option" data-i="${i}"><strong>${safe(p.product_code)} · ${safe(p.name_en)}</strong><small class="d-block text-muted" dir="rtl">${safe(p.name_ar)} · Stock ${p.current_stock}</small></div>`).join('')||'<div class="p-3 text-muted">No products found</div>';results.classList.add('show');results.querySelectorAll('.product-option').forEach(el=>el.onclick=()=>addItem(items[el.dataset.i]))},150)});search.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();results.querySelector('.product-option')?.click()}});
function addItem(p){document.getElementById('emptyRow')?.remove();let existing=[...tbody.querySelectorAll('tr[data-product]')].find(r=>r.dataset.product==p.id);if(existing){let q=existing.querySelector('.qty');q.value=Number(q.value)+1;recalc();results.classList.remove('show');search.value='';return}let units=p.units?.length?p.units:[{id:p.sales_unit_id,code:p.base_unit?.code||'PCS',selling_price:p.sale_price}];let selected=units.find(u=>u.id==p.sales_unit_id)||units[0];let tr=document.createElement('tr');tr.dataset.product=p.id;tr.innerHTML=`<td class="line-no"></td><td><strong>${safe(p.name_en)}</strong><small class="d-block text-muted" dir="rtl">${safe(p.name_ar)}</small><input type="hidden" name="items[${rowIndex}][product_id]" value="${p.id}"></td><td><select name="items[${rowIndex}][unit_id]" class="unit">${units.map(u=>`<option value="${u.id}" data-price="${u.selling_price||p.sale_price}" ${u.id==selected.id?'selected':''}>${safe(u.code)}</option>`).join('')}</select></td><td><input name="items[${rowIndex}][quantity]" class="qty" type="number" value="1" min="0.0001" step="0.0001"></td><td><input name="items[${rowIndex}][unit_price]" class="price" type="number" value="${selected.selling_price||p.sale_price}" min="0" step="0.01"></td><td><div class="d-flex"><input name="items[${rowIndex}][discount_value]" class="disc" type="number" value="0" min="0" step="0.01"><select name="items[${rowIndex}][discount_type]" class="disc-type"><option value="fixed">SAR</option><option value="percentage">%</option></select></div></td><td class="vat-column"><input name="items[${rowIndex}][vat_rate]" class="rate" type="number" value="${isNonTax()?0:p.vat_rate}" data-standard-rate="${p.vat_rate}" min="0" max="100" step="0.01" ${isNonTax()?'readonly':''}></td><td class="text-end vat-cell vat-column">0.00</td><td class="text-end fw-bold total-cell">0.00</td><td><button type="button" class="btn btn-link text-danger p-1 remove"><i class="bi bi-x-lg"></i></button></td>`;tbody.appendChild(tr);rowIndex++;bindRow(tr);renumber();syncInvoiceType();results.classList.remove('show');search.value='';search.focus()}
function bindRow(tr){tr.querySelectorAll('input,select').forEach(x=>x.addEventListener('input',recalc));tr.querySelector('.unit').addEventListener('change',e=>{tr.querySelector('.price').value=e.target.selectedOptions[0].dataset.price;recalc()});tr.querySelector('.remove').onclick=()=>{tr.remove();renumber();recalc();if(!tbody.children.length)tbody.innerHTML='<tr id="emptyRow"><td colspan="10" class="text-center text-muted py-5">Search or scan a product to begin billing.</td></tr>'}}
function calcRow(tr){let q=+tr.querySelector('.qty').value||0,p=+tr.querySelector('.price').value||0,rate=isNonTax()?0:(+tr.querySelector('.rate').value||0),dv=+tr.querySelector('.disc').value||0,g=q*p,d=tr.querySelector('.disc-type').value==='percentage'?g*dv/100:dv,due=Math.max(0,g-d),taxable,vat,total;if(!isNonTax()&&priceMode.value==='Inclusive VAT'){taxable=due/(1+rate/100);vat=due-taxable;total=due}else{taxable=due;vat=taxable*rate/100;total=taxable+vat}tr.querySelector('.vat-cell').textContent=money(vat);tr.querySelector('.total-cell').textContent=money(total);return{g,d,taxable,vat,total}}
function recalc(){let t={g:0,d:0,taxable:0,vat:0,total:0};tbody.querySelectorAll('tr[data-product]').forEach(r=>{let x=calcRow(r);Object.keys(t).forEach(k=>t[k]+=x[k])});gross.textContent=money(t.g);discount.textContent=money(t.d);taxable.textContent=money(t.taxable);vat.textContent=money(t.vat);grand.textContent=money(t.total);let paid=[...document.querySelectorAll('.pay-amount')].reduce((a,x)=>a+(+x.value||0),0);balance.textContent=money(Math.max(0,t.total-paid));return t}
function renumber(){tbody.querySelectorAll('tr[data-product] .line-no').forEach((x,i)=>x.textContent=i+1)}
function syncInvoiceType(){let nonTax=isNonTax();if(nonTax)priceMode.value='Exclusive VAT';tbody.querySelectorAll('.rate').forEach(rate=>{if(nonTax){if(+rate.value>0)rate.dataset.standardRate=rate.value;rate.value=0;rate.readOnly=true}else{rate.value=rate.dataset.standardRate||rate.value;rate.readOnly=false}});document.getElementById('customerVatField').classList.toggle('d-none',nonTax);document.getElementById('vatTotalRow').classList.toggle('d-none',nonTax);document.getElementById('taxableLabel').textContent=nonTax?'Subtotal':'Taxable';document.querySelectorAll('.vat-column').forEach(x=>x.classList.toggle('d-none',nonTax));recalc()}
priceMode.addEventListener('change',recalc);invoiceType.addEventListener('change',syncInvoiceType);document.getElementById('payments').addEventListener('input',recalc);document.getElementById('addPayment').onclick=()=>{let d=document.createElement('div');d.className='row g-2 payment-row mt-1';d.innerHTML=`<div class="col-4"><select name="payments[${paymentIndex}][payment_method]" class="form-select pay-field"><option>cash</option><option>bank</option><option>card</option><option>transfer</option></select></div><div class="col-4"><input name="payments[${paymentIndex}][amount]" class="form-control pay-amount pay-field" type="number" min="0" step="0.01" placeholder="Amount"></div><div class="col-3"><input name="payments[${paymentIndex}][reference]" class="form-control pay-field" placeholder="Reference"></div><div class="col-1"><button type="button" class="btn btn-link text-danger remove-pay"><i class="bi bi-x"></i></button></div>`;document.getElementById('payments').appendChild(d);d.querySelector('.remove-pay').onclick=()=>{d.remove();recalc()};paymentIndex++;syncPayment()};
function customerInfo(){let o=customer.selectedOptions[0];customerVat.value=o.dataset.vat||'Not registered';creditDays.value=o.dataset.credit||0}function syncPayment(){let credit=paymentType.value==='credit';document.querySelectorAll('#payments select,#payments input').forEach(x=>x.disabled=credit)}customer.addEventListener('change',customerInfo);customerInfo();paymentType.addEventListener('change',syncPayment);syncPayment();syncInvoiceType();document.querySelectorAll('[data-action]').forEach(b=>b.onclick=()=>{if(!tbody.querySelector('tr[data-product]'))return alert('Add at least one product.');let t=recalc();let amount=document.querySelector('.pay-amount:not(:disabled)');if(amount&&!amount.value)amount.value=money(t.total);formAction.value=b.dataset.action;document.getElementById('invoiceForm').submit()});
document.addEventListener('keydown',e=>{if(e.key==='F2'){e.preventDefault();search.focus()}if(e.key==='F3'){e.preventDefault();customer.focus()}if(e.key==='F4'){e.preventDefault();tbody.querySelector('tr[data-product]:last-child .qty')?.focus()}if(e.key==='F5'){e.preventDefault();document.querySelector('.pay-amount')?.focus()}if(e.key==='F6'){e.preventDefault();document.querySelector('[data-action="hold"]').click()}if(e.key==='F9'){e.preventDefault();document.querySelector('[data-action="finalize"]').click()}if(e.key==='F10'){e.preventDefault();document.querySelector('[data-action="finalize_print"]').click()}if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='n'){e.preventDefault();location.href='<?php echo e(route('sales.create')); ?>'}});
</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\sales\create.blade.php ENDPATH**/ ?>