<?php ($purchase = $purchase ?? new \App\Models\Purchase()); ?>
<?php $__env->startSection('title', $purchase->exists ? 'Edit Purchase' : 'Add Purchase'); ?>
<?php $__env->startSection('content'); ?>
<div class="page-shell">
    <div class="page-head"><div><h1 class="page-title"><?php echo e($purchase->exists ? 'Edit Purchase' : 'Advanced Purchase'); ?></h1><div class="page-subtitle">Purchase items full entry, PO, partial payment, landed cost, batch/expiry and approval flow</div></div><a href="<?php echo e(route('admin.purchases.index')); ?>" class="btn btn-light">Purchase List</a></div>

    <form method="POST" action="<?php echo e($purchase->exists ? route('admin.purchases.update', $purchase) : route('admin.purchases.store')); ?>" class="card panel-tight">
        <?php echo csrf_field(); ?>
        <?php if($purchase->exists): ?> <?php echo method_field('PUT'); ?> <?php endif; ?>

        <div class="grid-4">
            <div><label>Purchase Type</label><select name="purchase_type"><option value="Purchase" <?php if(old('purchase_type', $purchase->purchase_type ?? 'Purchase')==='Purchase'): echo 'selected'; endif; ?>>Purchase</option><option value="Purchase Order" <?php if(old('purchase_type', $purchase->purchase_type ?? '')==='Purchase Order'): echo 'selected'; endif; ?>>Purchase Order</option></select></div>
            <div><label>Invoice No</label><input type="text" name="invoice_no" value="<?php echo e(old('invoice_no', $purchase->invoice_no)); ?>" placeholder="Auto if left blank"></div>
            <div><label>PO No</label><input type="text" name="po_no" value="<?php echo e(old('po_no', $purchase->po_no)); ?>" placeholder="Auto if left blank"></div>
            <div><label>Approval Status</label><select name="approval_status"><option value="Approved" <?php if(old('approval_status', $purchase->approval_status ?? 'Approved')==='Approved'): echo 'selected'; endif; ?>>Approved</option><option value="Pending" <?php if(old('approval_status', $purchase->approval_status ?? '')==='Pending'): echo 'selected'; endif; ?>>Pending</option></select></div>
            <div><label>Branch</label><select name="branch_id"><option value="">Select branch</option><?php $__currentLoopData = ($branches ?? collect()); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $branch): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($branch->id); ?>" <?php if(old('branch_id', $purchase->branch_id)==$branch->id): echo 'selected'; endif; ?>><?php echo e($branch->name); ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select></div><div><label>Supplier</label><select name="supplier_id" id="supplierSelect"><option value="">Select supplier</option><?php $__currentLoopData = $suppliers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $supplier): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($supplier->id); ?>" data-name="<?php echo e($supplier->name); ?>" <?php if(old('supplier_id', $purchase->supplier_id)==$supplier->id): echo 'selected'; endif; ?>><?php echo e($supplier->name); ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select></div>
            <div><label>Supplier Name</label><input type="text" name="supplier_name" id="supplierName" value="<?php echo e(old('supplier_name', $purchase->supplier_name)); ?>" required></div>
            <div><label>Purchase Date</label><input type="date" name="purchase_date" value="<?php echo e(old('purchase_date', $purchase->purchase_date ?: now()->toDateString())); ?>" required></div>
            <div><label>Received Status</label><select name="received_status"><option value="Received" <?php if(old('received_status', $purchase->received_status ?? 'Received')==='Received'): echo 'selected'; endif; ?>>Received</option><option value="Pending" <?php if(old('received_status', $purchase->received_status ?? '')==='Pending'): echo 'selected'; endif; ?>>Pending</option><option value="Partial" <?php if(old('received_status', $purchase->received_status ?? '')==='Partial'): echo 'selected'; endif; ?>>Partial</option></select></div>
            <div><label>Payment Method</label><select name="payment_method"><option value="Cash">Cash</option><option <?php if(old('payment_method', $purchase->payment_method ?? '')==='Bank'): echo 'selected'; endif; ?>>Bank</option><option <?php if(old('payment_method', $purchase->payment_method ?? '')==='Mobile Banking'): echo 'selected'; endif; ?>>Mobile Banking</option><option <?php if(old('payment_method', $purchase->payment_method ?? '')==='Card'): echo 'selected'; endif; ?>>Card</option><option <?php if(old('payment_method', $purchase->payment_method ?? '')==='Due'): echo 'selected'; endif; ?>>Due</option><option <?php if(old('payment_method', $purchase->payment_method ?? '')==='bKash'): echo 'selected'; endif; ?>>bKash</option><option <?php if(old('payment_method', $purchase->payment_method ?? '')==='Nagad'): echo 'selected'; endif; ?>>Nagad</option><option <?php if(old('payment_method', $purchase->payment_method ?? '')==='Rocket'): echo 'selected'; endif; ?>>Rocket</option></select></div>
            <div><label>Initial Paid Amount</label><input type="number" step="0.01" min="0" name="paid_amount" value="<?php echo e(old('paid_amount', $purchase->paid_amount ?? 0)); ?>"></div>
            <div><label>Batch No (Global)</label><input type="text" name="batch_no" value="<?php echo e(old('batch_no', $purchase->batch_no)); ?>"></div>
            <div><label>Expiry Date (Global)</label><input type="date" name="expiry_date" value="<?php echo e(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">
                <?php $__currentLoopData = $oldRows; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $idx => $row): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <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[<?php echo e($idx); ?>][product_id]" class="product-select"><option value="">Select product</option><?php $__currentLoopData = $products; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $product): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($product->id); ?>" data-cost="<?php echo e($product->original_price); ?>" <?php if(($row['product_id'] ?? '')==$product->id): echo 'selected'; endif; ?>><?php echo e($product->product_name); ?> (<?php echo e($product->product_code); ?>)</option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select></div>
                    <div><label>Qty</label><input type="number" min="1" name="rows[<?php echo e($idx); ?>][qty]" value="<?php echo e($row['qty'] ?? 1); ?>" class="qty"></div>
                    <div><label>Unit Cost</label><input type="number" step="0.01" min="0" name="rows[<?php echo e($idx); ?>][unit_cost]" value="<?php echo e($row['unit_cost'] ?? 0); ?>" class="unit-cost"></div>
                    <div><label>Discount</label><input type="number" step="0.01" min="0" name="rows[<?php echo e($idx); ?>][discount]" value="<?php echo e($row['discount'] ?? 0); ?>" class="discount"></div>
                    <div><label>Batch No</label><input type="text" name="rows[<?php echo e($idx); ?>][batch_no]" value="<?php echo e($row['batch_no'] ?? ''); ?>"></div>
                    <div><label>Expiry Date</label><input type="date" name="rows[<?php echo e($idx); ?>][expiry_date]" value="<?php echo e($row['expiry_date'] ?? ''); ?>"></div>
                </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </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="<?php echo e(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="<?php echo e(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="<?php echo e(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="<?php echo e(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="<?php echo e(old('grand_total', $purchase->grand_total ?? 0)); ?>" required></div>
        </div>
        <div style="margin-top:12px"><label>Notes</label><textarea name="notes" rows="3"><?php echo e(old('notes', $purchase->notes)); ?></textarea></div>

        <?php 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="<?php echo e(now()->toDateString()); ?>"></div><div style="grid-column: span 2;"><label>Payment Note</label><input type="text" name="payment_notes" value=""></div></div>
            <?php 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><?php $__currentLoopData = $payments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $pay): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><tr><td><?php echo e($pay->payment_date); ?></td><td><?php echo e(number_format($pay->amount,2)); ?></td><td><?php echo e($pay->payment_method); ?></td><td><?php echo e($pay->payment_type); ?></td><td><?php echo e($pay->notes); ?></td></tr><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></tbody></table></div><?php endif; ?>
        </div>
        <?php endif; ?>
        <div class="form-actions"><button class="btn primary"><?php echo e($purchase->exists ? 'Update Purchase' : 'Save Purchase'); ?></button><a href="<?php echo e(route('admin.purchases.index')); ?>" class="btn btn-light">Cancel</a></div>
    </form>
</div>
<script>
let rowIndex = <?php echo e(count($oldRows)); ?>;
function addRow(){
    const wrap = document.getElementById('purchaseRows');
    const html = `<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[${rowIndex}][product_id]" class="product-select"><option value="">Select product</option><?php $__currentLoopData = $products; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $product): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($product->id); ?>" data-cost="<?php echo e($product->original_price); ?>"><?php echo e($product->product_name); ?> (<?php echo e($product->product_code); ?>)</option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select></div><div><label>Qty</label><input type="number" min="1" name="rows[${rowIndex}][qty]" value="1" class="qty"></div><div><label>Unit Cost</label><input type="number" step="0.01" min="0" name="rows[${rowIndex}][unit_cost]" value="0" class="unit-cost"></div><div><label>Discount</label><input type="number" step="0.01" min="0" name="rows[${rowIndex}][discount]" value="0" class="discount"></div><div><label>Batch No</label><input type="text" name="rows[${rowIndex}][batch_no]" value=""></div><div><label>Expiry Date</label><input type="date" name="rows[${rowIndex}][expiry_date]" value=""></div></div>`;
    wrap.insertAdjacentHTML('beforeend', html); rowIndex++; bindCalc();
}
function bindCalc(){
 document.querySelectorAll('.product-select').forEach(s=>s.onchange=function(){ const c=this.selectedOptions[0]?.dataset?.cost||0; const u=this.closest('.purchase-row').querySelector('.unit-cost'); if(!u.value||parseFloat(u.value)===0) u.value=c; calcTotals();});
 document.querySelectorAll('.qty,.unit-cost,.discount,#discount_total,#transport_cost,#landed_cost').forEach(el=>el.oninput=calcTotals);
}
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();
document.getElementById('supplierSelect')?.addEventListener('change', function(){ document.getElementById('supplierName').value = this.selectedOptions[0]?.dataset?.name || ''; });
</script>
<?php $__env->stopSection(); ?>

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