@extends('admin.layouts.app')
@php($purchase = $purchase ?? new \App\Models\Purchase())
@section('title', $purchase->exists ? 'Edit Purchase' : 'Add Purchase')
@section('content')
<div class="page-shell">
    <div class="page-head"><div><h1 class="page-title">{{ $purchase->exists ? 'Edit Purchase' : 'Advanced Purchase' }}</h1><div class="page-subtitle">Purchase quantity selected unit-এ নাও, system auto pcs-এ stock save করবে.</div></div><a href="{{ route('admin.purchases.index') }}" class="btn btn-light">Purchase List</a></div>

    <form method="POST" action="{{ $purchase->exists ? route('admin.purchases.update', $purchase) : route('admin.purchases.store') }}" class="card panel-tight">
        @csrf
        @if($purchase->exists) @method('PUT') @endif

        <div class="grid-4">
            <div><label>Purchase Type</label><select name="purchase_type"><option value="Purchase" @selected(old('purchase_type', $purchase->purchase_type ?? 'Purchase')==='Purchase')>Purchase</option><option value="Purchase Order" @selected(old('purchase_type', $purchase->purchase_type ?? '')==='Purchase Order')>Purchase Order</option></select></div>
            <div><label>Invoice No</label><input type="text" name="invoice_no" value="{{ old('invoice_no', $purchase->invoice_no) }}" placeholder="Auto if left blank"></div>
            <div><label>PO No</label><input type="text" name="po_no" value="{{ old('po_no', $purchase->po_no) }}" placeholder="Auto if left blank"></div>
            <div><label>Approval Status</label><select name="approval_status"><option value="Approved" @selected(old('approval_status', $purchase->approval_status ?? 'Approved')==='Approved')>Approved</option><option value="Pending" @selected(old('approval_status', $purchase->approval_status ?? '')==='Pending')>Pending</option></select></div>
            <div><label>Branch</label><select name="branch_id"><option value="">Select branch</option>@foreach(($branches ?? collect()) as $branch)<option value="{{ $branch->id }}" @selected(old('branch_id', $purchase->branch_id)==$branch->id)>{{ $branch->name }}</option>@endforeach</select></div><div><label>Supplier</label><select name="supplier_id" id="supplierSelect"><option value="">Select supplier</option>@foreach($suppliers as $supplier)<option value="{{ $supplier->id }}" data-name="{{ $supplier->name }}" @selected(old('supplier_id', $purchase->supplier_id)==$supplier->id)>{{ $supplier->name }}</option>@endforeach</select></div>
            <div><label>Supplier Name</label><input type="text" name="supplier_name" id="supplierName" value="{{ old('supplier_name', $purchase->supplier_name) }}" required></div>
            <div><label>Purchase Date</label><input type="date" name="purchase_date" value="{{ old('purchase_date', $purchase->purchase_date ?: now()->toDateString()) }}" required></div>
            <div><label>Received Status</label><select name="received_status"><option value="Received" @selected(old('received_status', $purchase->received_status ?? 'Received')==='Received')>Received</option><option value="Pending" @selected(old('received_status', $purchase->received_status ?? '')==='Pending')>Pending</option><option value="Partial" @selected(old('received_status', $purchase->received_status ?? '')==='Partial')>Partial</option></select></div>
            <div><label>Payment Method</label><select name="payment_method"><option value="Cash" @selected(old('payment_method', $purchase->payment_method ?? 'Cash')==='Cash')>Cash</option><option value="Bank" @selected(old('payment_method', $purchase->payment_method ?? '')==='Bank')>Bank</option><option value="Mobile Banking" @selected(old('payment_method', $purchase->payment_method ?? '')==='Mobile Banking')>Mobile Banking</option><option value="Card" @selected(old('payment_method', $purchase->payment_method ?? '')==='Card')>Card</option><option value="Due" @selected(old('payment_method', $purchase->payment_method ?? '')==='Due')>Due</option><option value="bKash" @selected(old('payment_method', $purchase->payment_method ?? '')==='bKash')>bKash</option><option value="Nagad" @selected(old('payment_method', $purchase->payment_method ?? '')==='Nagad')>Nagad</option><option value="Rocket" @selected(old('payment_method', $purchase->payment_method ?? '')==='Rocket')>Rocket</option></select></div>
            <div><label>Initial Paid Amount</label><input type="number" step="0.01" min="0" name="paid_amount" value="{{ old('paid_amount', $purchase->paid_amount ?? 0) }}"></div>
            <div><label>Batch No (Global)</label><input type="text" name="batch_no" value="{{ old('batch_no', $purchase->batch_no) }}"></div>
            <div><label>Expiry Date (Global)</label><input type="date" name="expiry_date" value="{{ old('expiry_date', $purchase->expiry_date) }}"></div>
        </div>

        @php($oldRows = old('rows', $purchase->exists ? $purchase->items->map(fn($i)=>['product_id'=>$i->product_id,'qty'=>$i->qty,'unit_cost'=>$i->unit_cost,'discount'=>$i->discount,'batch_no'=>$i->batch_no,'expiry_date'=>$i->expiry_date])->toArray() : [['product_id'=>'','qty'=>1,'unit_cost'=>0,'discount'=>0,'batch_no'=>'','expiry_date'=>'']]))
        <div class="card panel-tight" style="margin-top:12px;background:#f8fafc">
            <div class="page-head"><strong>Purchase Items</strong><button type="button" class="btn" onclick="addRow()">+ Add Row</button></div>
            <div id="purchaseRows">
                @foreach($oldRows as $idx => $row)
                <div class="grid-6 purchase-row" style="margin-bottom:10px;border-bottom:1px dashed #dbe2ea;padding-bottom:10px">
                    <div><label>Product</label><select name="rows[{{ $idx }}][product_id]" class="product-select"><option value="">Select product</option>@foreach($products as $product)<option value="{{ $product->id }}" data-cost="{{ $product->original_price }}" data-unit="{{ $product->unit ?: 'pcs' }}" data-factor="{{ max(1, (int) ($product->unit_value_in_base ?? 1)) }}" @selected(($row['product_id'] ?? '')==$product->id)>{{ $product->product_name }} ({{ $product->product_code }})</option>@endforeach</select><div class="muted small unit-help" style="margin-top:4px"></div></div>
                    <div><label>Qty</label><input type="number" step="1" min="1" name="rows[{{ $idx }}][qty]" value="{{ $row['qty'] ?? 1 }}" class="qty"></div>
                    <div><label>Unit Cost</label><input type="number" step="0.01" min="0" name="rows[{{ $idx }}][unit_cost]" value="{{ $row['unit_cost'] ?? 0 }}" class="unit-cost"></div>
                    <div><label>Discount</label><input type="number" step="0.01" min="0" name="rows[{{ $idx }}][discount]" value="{{ $row['discount'] ?? 0 }}" class="discount"></div>
                    <div><label>Batch No</label><input type="text" name="rows[{{ $idx }}][batch_no]" value="{{ $row['batch_no'] ?? '' }}"></div>
                    <div><label>Expiry Date</label><input type="date" name="rows[{{ $idx }}][expiry_date]" value="{{ $row['expiry_date'] ?? '' }}"></div>
                </div>
                @endforeach
            </div>
        </div>

        <div class="grid-5" style="margin-top:12px">
            <div><label>Subtotal</label><input type="number" step="0.01" min="0" name="subtotal" id="subtotal" value="{{ old('subtotal', $purchase->subtotal ?? 0) }}" required></div>
            <div><label>Discount Total</label><input type="number" step="0.01" min="0" name="discount_total" id="discount_total" value="{{ old('discount_total', $purchase->discount_total ?? 0) }}"></div>
            <div><label>Transport Cost</label><input type="number" step="0.01" min="0" name="transport_cost" id="transport_cost" value="{{ old('transport_cost', $purchase->transport_cost ?? 0) }}"></div>
            <div><label>Landed Cost Distribution</label><input type="number" step="0.01" min="0" name="landed_cost" id="landed_cost" value="{{ old('landed_cost', $purchase->landed_cost ?? 0) }}"></div>
            <div><label>Grand Total</label><input type="number" step="0.01" min="0" name="grand_total" id="grand_total" value="{{ old('grand_total', $purchase->grand_total ?? 0) }}" required></div>
        </div>
        <div style="margin-top:12px"><label>Notes</label><textarea name="notes" rows="3">{{ old('notes', $purchase->notes) }}</textarea></div>

        @if($purchase->exists)
        <div class="card panel-tight" style="margin-top:12px;background:#fcfcfc">
            <div class="page-head"><strong>Partial Payment / Due Settlement History</strong></div>
            <div class="grid-4"><div><label>Payment Now</label><input type="number" step="0.01" min="0" name="payment_now" value="0"></div><div><label>Payment Date</label><input type="date" name="payment_date" value="{{ now()->toDateString() }}"></div><div style="grid-column: span 2;"><label>Payment Note</label><input type="text" name="payment_notes" value=""></div></div>
            @if($payments->count())<div class="table-wrap" style="margin-top:10px"><table class="table"><thead><tr><th>Date</th><th>Amount</th><th>Method</th><th>Type</th><th>Note</th></tr></thead><tbody>@foreach($payments as $pay)<tr><td>{{ $pay->payment_date }}</td><td>{{ number_format($pay->amount,2) }}</td><td>{{ $pay->payment_method }}</td><td>{{ $pay->payment_type }}</td><td>{{ $pay->notes }}</td></tr>@endforeach</tbody></table></div>@endif
        </div>
        @endif
        <div class="form-actions"><button class="btn primary">{{ $purchase->exists ? 'Update Purchase' : 'Save Purchase' }}</button><a href="{{ route('admin.purchases.index') }}" class="btn btn-light">Cancel</a></div>
    </form>
</div>
<script>
let rowIndex = {{ count($oldRows) }};
function rowTemplate(index){return `<div class="grid-6 purchase-row" style="margin-bottom:10px;border-bottom:1px dashed #dbe2ea;padding-bottom:10px"><div><label>Product</label><select name="rows[${index}][product_id]" class="product-select"><option value="">Select product</option>@foreach($products as $product)<option value="{{ $product->id }}" data-cost="{{ $product->original_price }}" data-unit="{{ $product->unit ?: 'pcs' }}" data-factor="{{ max(1, (int) ($product->unit_value_in_base ?? 1)) }}">{{ $product->product_name }} ({{ $product->product_code }})</option>@endforeach</select><div class="muted small unit-help" style="margin-top:4px"></div></div><div><label>Qty</label><input type="number" step="1" min="1" name="rows[${index}][qty]" value="1" class="qty"></div><div><label>Unit Cost</label><input type="number" step="0.01" min="0" name="rows[${index}][unit_cost]" value="0" class="unit-cost"></div><div><label>Discount</label><input type="number" step="0.01" min="0" name="rows[${index}][discount]" value="0" class="discount"></div><div><label>Batch No</label><input type="text" name="rows[${index}][batch_no]" value=""></div><div><label>Expiry Date</label><input type="date" name="rows[${index}][expiry_date]" value=""></div></div>`;}
function addRow(){document.getElementById('purchaseRows').insertAdjacentHTML('beforeend', rowTemplate(rowIndex));rowIndex++;bindCalc();}
function refreshUnitHelp(row){const opt=row.querySelector('.product-select')?.selectedOptions?.[0];const unit=opt?.dataset?.unit||'pcs';const factor=opt?.dataset?.factor||1;const help=row.querySelector('.unit-help');if(help)help.textContent=`1 ${unit} = ${factor} pcs`}
function bindCalc(){document.querySelectorAll('.product-select').forEach(s=>s.onchange=function(){ const row=this.closest('.purchase-row'); const c=this.selectedOptions[0]?.dataset?.cost||0; const u=row.querySelector('.unit-cost'); if(!u.value||parseFloat(u.value)===0) u.value=c; refreshUnitHelp(row); calcTotals();}); document.querySelectorAll('.qty,.unit-cost,.discount,#discount_total,#transport_cost,#landed_cost').forEach(el=>el.oninput=calcTotals); document.querySelectorAll('.purchase-row').forEach(refreshUnitHelp);}
function calcTotals(){let subtotal=0;document.querySelectorAll('.purchase-row').forEach(row=>{ const q=parseFloat(row.querySelector('.qty')?.value||0); const c=parseFloat(row.querySelector('.unit-cost')?.value||0); const d=parseFloat(row.querySelector('.discount')?.value||0); subtotal += Math.max(0,(q*c)-d); }); document.getElementById('subtotal').value=subtotal.toFixed(2); const dis=parseFloat(document.getElementById('discount_total').value||0); const tr=parseFloat(document.getElementById('transport_cost').value||0); const lc=parseFloat(document.getElementById('landed_cost').value||0); document.getElementById('grand_total').value=Math.max(0,subtotal-dis+tr+lc).toFixed(2);}
bindCalc(); calcTotals();
const supplierSelect = document.getElementById('supplierSelect');
const supplierName = document.getElementById('supplierName');
if (supplierSelect && supplierName) {
  const syncSupplierName = () => {
    supplierName.value = supplierSelect.selectedOptions[0]?.dataset?.name || supplierName.value || '';
  };
  supplierSelect.addEventListener('change', syncSupplierName);
  syncSupplierName();
}
</script>
@endsection
