@extends('layouts.app')
@section('title',($invoice->exists?'Edit':'New').' Invoice')
@section('page_title',($invoice->exists?'Edit':'New').' Customer Invoice')
@section('content')
<div class="page-head"><div><h1>{{ $invoice->exists?'Edit':'New' }} Customer Invoice</h1><p>Amounts are recalculated securely on the server before saving.</p></div><a class="btn btn-secondary" href="{{ $invoice->exists?route('invoices.show',$invoice):route('invoices.index') }}">Back</a></div>
<form method="post" action="{{ $invoice->exists?route('invoices.update',$invoice):route('invoices.store') }}">@csrf @if($invoice->exists)@method('put')@endif
<div class="card"><div class="card-head"><strong>Invoice Header</strong></div><div class="card-body"><div class="form-grid">
<div class="field"><label>Branch *</label><select class="control" name="branch_id" required>@foreach($branches as $branch)<option value="{{ $branch->id }}" @selected(old('branch_id',$invoice->branch_id ?? auth()->user()->branch_id)==$branch->id)>{{ $branch->code }} - {{ $branch->name }}</option>@endforeach</select></div>
<div class="field"><label>Customer *</label><select class="control" name="party_id" id="party_id" required><option value="">Select customer</option>@foreach($customers as $customer)<option value="{{ $customer->id }}" @selected(old('party_id',$invoice->party_id)==$customer->id)>{{ $customer->legal_name }}{{ $customer->trn?' · TRN '.$customer->trn:'' }}</option>@endforeach</select></div>
<div class="field"><label>Invoice Type</label><select class="control" name="invoice_type">@foreach(['tax_invoice'=>'Tax Invoice','simplified_tax_invoice'=>'Simplified Tax Invoice','commercial_invoice'=>'Commercial Invoice','proforma_invoice'=>'Proforma Invoice','advance_invoice'=>'Advance Invoice'] as $key=>$label)<option value="{{ $key }}" @selected(old('invoice_type',$invoice->invoice_type)===$key)>{{ $label }}</option>@endforeach</select></div>
<div class="field"><label>Pricing</label><select class="control" name="pricing_mode" id="pricing_mode"><option value="exclusive" @selected(old('pricing_mode',$invoice->pricing_mode)==='exclusive')>VAT Exclusive</option><option value="inclusive" @selected(old('pricing_mode',$invoice->pricing_mode)==='inclusive')>VAT Inclusive</option></select></div>
<div class="field"><label>Invoice Date</label><input class="control" type="date" name="issue_date" value="{{ old('issue_date',optional($invoice->issue_date)->format('Y-m-d')) }}" required></div><div class="field"><label>Date of Supply</label><input class="control" type="date" name="supply_date" value="{{ old('supply_date',optional($invoice->supply_date)->format('Y-m-d')) }}"></div><div class="field"><label>Due Date</label><input class="control" type="date" name="due_date" value="{{ old('due_date',optional($invoice->due_date)->format('Y-m-d')) }}"></div><div class="field"><label>Customer PO</label><input class="control" name="customer_po" value="{{ old('customer_po',$invoice->customer_po) }}"></div>
<div class="field"><label>Transport Job</label><select class="control" name="transport_job_id"><option value="">No job</option>@foreach($jobs as $job)<option value="{{ $job->id }}" @selected(old('transport_job_id',$invoice->transport_job_id)==$job->id)>{{ $job->job_number }} - {{ $job->pickup_location }} → {{ $job->delivery_location }}</option>@endforeach</select></div>
<div class="field"><label>Contract</label><select class="control" name="contract_id"><option value="">No contract</option>@foreach($contracts as $contract)<option value="{{ $contract->id }}" @selected(old('contract_id',$invoice->contract_id)==$contract->id)>{{ $contract->contract_number }} - {{ $contract->title }}</option>@endforeach</select></div>
<div class="field"><label>Currency</label><input class="control" name="currency_code" value="{{ old('currency_code',$invoice->currency_code ?? 'AED') }}" maxlength="3"></div><div class="field"><label>Exchange Rate</label><input class="control" type="number" step="0.00000001" name="exchange_rate" value="{{ old('exchange_rate',$invoice->exchange_rate ?? 1) }}"></div>
<div class="field"><label>Accounts Receivable</label><select class="control" name="receivable_account_id" required><option value="">Select account</option>@foreach($accounts as $account)<option value="{{ $account->id }}" @selected(old('receivable_account_id',$invoice->receivable_account_id)==$account->id)>{{ $account->code }} - {{ $account->name }}</option>@endforeach</select></div>
</div></div></div>

<div class="card" style="margin-top:18px"><div class="card-head"><strong>Invoice Lines</strong><button class="btn btn-secondary btn-sm" type="button" id="add-line">+ Add Line</button></div><div class="line-items"><table class="table" id="lines-table"><thead><tr><th>Description</th><th>Qty</th><th>Unit</th><th>Rate</th><th>Discount</th><th>Income Account</th><th>VAT Code</th><th>Taxable</th><th>VAT</th><th>Total</th><th></th></tr></thead><tbody id="line-body"></tbody></table></div><div class="card-body"><div class="totals"><div class="total-row"><span>Subtotal</span><strong id="subtotal-display">0.00</strong></div><div class="total-row"><span>Discount</span><strong id="discount-display">0.00</strong></div><div class="total-row"><span>Taxable Amount</span><strong id="taxable-display">0.00</strong></div><div class="total-row"><span>VAT</span><strong id="vat-display">0.00</strong></div><div class="total-row grand"><span>Invoice Total</span><strong id="grand-display">0.00</strong></div></div></div></div>
<div class="card" style="margin-top:18px"><div class="card-body"><div class="form-grid"><div class="field"><label>Notes</label><textarea class="control" name="notes">{{ old('notes',$invoice->notes) }}</textarea></div><div class="field"><label>Terms & Conditions</label><textarea class="control" name="terms">{{ old('terms',$invoice->terms ?? auth()->user()->company?->invoice_terms) }}</textarea></div></div></div><div class="card-head" style="justify-content:flex-end"><a class="btn btn-secondary" href="{{ route('invoices.index') }}">Cancel</a><button class="btn btn-primary">Save Draft</button></div></div>
</form>
@endsection
@push('scripts')
<script>
const accountOptions=`<option value="">Select</option>@foreach($accounts as $a)<option value="{{ $a->id }}">{{ addslashes($a->code.' - '.$a->name) }}</option>@endforeach`;
const taxOptions=`<option value="" data-rate="0">No VAT</option>@foreach($taxCodes as $t)<option value="{{ $t->id }}" data-rate="{{ (float)$t->rate }}">{{ addslashes($t->code.' - '.$t->name.' ('.$t->rate.'%)') }}</option>@endforeach`;
const existing=@json(old('items', $invoice->items->map(fn($i)=>['description'=>$i->description,'quantity'=>$i->quantity,'unit'=>$i->unit,'unit_rate'=>$i->unit_rate,'discount_amount'=>$i->discount_amount,'income_account_id'=>$i->income_account_id,'tax_code_id'=>$i->tax_code_id])->values()->all()));
let lineIndex=0;
function addLine(data={}){const i=lineIndex++;const tr=document.createElement('tr');tr.innerHTML=`<td><input class="control" name="items[${i}][description]" value="${escapeHtml(data.description||'Transport service')}" required></td><td><input class="control calc" type="number" step="0.0001" name="items[${i}][quantity]" value="${data.quantity||1}" required></td><td><input class="control" name="items[${i}][unit]" value="${escapeHtml(data.unit||'Trip')}"></td><td><input class="control calc" type="number" step="0.0001" name="items[${i}][unit_rate]" value="${data.unit_rate||0}" required></td><td><input class="control calc" type="number" step="0.0001" name="items[${i}][discount_amount]" value="${data.discount_amount||0}"></td><td><select class="control" name="items[${i}][income_account_id]" required>${accountOptions}</select></td><td><select class="control tax-select" name="items[${i}][tax_code_id]">${taxOptions}</select></td><td class="line-taxable text-right">0.00</td><td class="line-vat text-right">0.00</td><td class="line-total text-right">0.00</td><td><button class="btn btn-danger btn-sm remove" type="button">×</button></td>`;document.getElementById('line-body').appendChild(tr);tr.querySelector(`[name="items[${i}][income_account_id]"]`).value=data.income_account_id||'';tr.querySelector('.tax-select').value=data.tax_code_id||'';tr.querySelectorAll('.calc,.tax-select').forEach(e=>e.addEventListener('input',calculate));tr.querySelector('.remove').addEventListener('click',()=>{tr.remove();calculate()});calculate()}
function escapeHtml(v){return String(v).replace(/[&<>'"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[c]))}
function calculate(){let sub=0,disc=0,taxable=0,vat=0,grand=0;document.querySelectorAll('#line-body tr').forEach(tr=>{const q=parseFloat(tr.querySelector('[name$="[quantity]"]').value)||0;const r=parseFloat(tr.querySelector('[name$="[unit_rate]"]').value)||0;const d=parseFloat(tr.querySelector('[name$="[discount_amount]"]').value)||0;const tax=tr.querySelector('.tax-select');const rate=parseFloat(tax.selectedOptions[0]?.dataset.rate)||0;const gross=Math.max(0,q*r-d);let net=gross,v=0,total=gross;if(document.getElementById('pricing_mode').value==='inclusive'&&rate>0){net=gross/(1+rate/100);v=gross-net}else{v=net*rate/100;total=net+v}tr.querySelector('.line-taxable').textContent=net.toFixed(2);tr.querySelector('.line-vat').textContent=v.toFixed(2);tr.querySelector('.line-total').textContent=total.toFixed(2);sub+=q*r;disc+=d;taxable+=net;vat+=v;grand+=total});document.getElementById('subtotal-display').textContent=sub.toFixed(2);document.getElementById('discount-display').textContent=disc.toFixed(2);document.getElementById('taxable-display').textContent=taxable.toFixed(2);document.getElementById('vat-display').textContent=vat.toFixed(2);document.getElementById('grand-display').textContent=grand.toFixed(2)}
document.getElementById('add-line').addEventListener('click',()=>addLine());document.getElementById('pricing_mode').addEventListener('change',calculate);(existing.length?existing:[{}]).forEach(addLine);
</script>
@endpush
