<?php $__env->startSection('title', $invoice ? 'Edit Sale' : 'New Sale'); ?>
<?php $__env->startSection('content'); ?>
<?php
    $meta = $meta ?? null;
    $payments = $payments ?? collect();
    $lines = old('rows', $hold->payload['rows'] ?? ($invoice ? $invoice->lines->map(fn($line) => [
        'product_id' => $line->product_id,
        'quantity_sold' => $line->quantity_sold,
        'selling_price' => $line->selling_price,
        'discount' => $line->discount,
    ])->toArray() : [['product_id' => '', 'quantity_sold' => 1, 'selling_price' => 0, 'discount' => 0]]));
?>
<div class="container py-3">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <h2 class="mb-0"><?php echo e($invoice ? 'Edit Sale' : 'New Sale'); ?></h2>
            <small class="text-muted">Sales selected unit-এ হবে, stock minus হবে pcs-এ.</small>
        </div>
        <a href="<?php echo e(route('admin.sales.index')); ?>" class="btn btn-outline-secondary">Back</a>
    </div>

    <form method="POST" action="<?php echo e($invoice ? route('admin.sales.update', $invoice->invoice_no) : route('admin.sales.store')); ?>" class="card card-body shadow-sm">
        <?php echo csrf_field(); ?>
        <?php if($invoice): ?> <?php echo method_field('PUT'); ?> <?php endif; ?>
        <?php if($hold): ?>
            <input type="hidden" name="hold_id" value="<?php echo e($hold->id); ?>">
        <?php endif; ?>

        <div class="row g-3 mb-3">
            <div class="col-md-4"><label class="form-label">Customer Name</label><input name="customer_name" class="form-control" value="<?php echo e(old('customer_name', $hold->payload['customer_name'] ?? $invoice->customer_name ?? '')); ?>"></div>
            <div class="col-md-4"><label class="form-label">Customer Phone</label><input name="customer_phone" class="form-control" value="<?php echo e(old('customer_phone', $hold->payload['customer_phone'] ?? $invoice->customer_phone ?? '')); ?>"></div>
            <div class="col-md-4"><label class="form-label">Customer Address</label><input name="customer_address" class="form-control" value="<?php echo e(old('customer_address', $hold->payload['customer_address'] ?? $invoice->customer_address ?? '')); ?>"></div>
            <div class="col-md-3"><label class="form-label">Branch</label><select name="branch_id" class="form-select"><option value="">Select Branch</option><?php $__currentLoopData = $branches; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $branch): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($branch->id); ?>" <?php if(old('branch_id', $invoice->branch_id ?? '')==$branch->id): echo 'selected'; endif; ?>><?php echo e($branch->name); ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select></div>
            <div class="col-md-3"><label class="form-label">Sale Date</label><input type="date" name="sale_date" class="form-control" value="<?php echo e(old('sale_date', $hold->payload['sale_date'] ?? $invoice->sale_date ?? now()->toDateString())); ?>"></div>
            <div class="col-md-3"><label class="form-label">Payment Method</label><select name="payment_method" class="form-select"><?php $__currentLoopData = ['Cash','Bank','Mobile Banking','Card','Due','bKash','Nagad','Rocket']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $method): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($method); ?>" <?php if(old('payment_method', $hold->payload['payment_method'] ?? $invoice->payment_method ?? 'Cash')===$method): echo 'selected'; endif; ?>><?php echo e($method); ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select></div>
            <div class="col-md-3"><label class="form-label">Paid Amount</label><input name="paid_amount" id="paid_amount" type="number" step="0.01" min="0" class="form-control" value="<?php echo e(old('paid_amount', $hold->payload['paid_amount'] ?? $invoice->paid_amount ?? 0)); ?>"></div>
        </div>

        <div class="card card-body mb-3">
            <div class="d-flex justify-content-between align-items-center mb-2">
                <strong>Sale Items</strong>
                <button type="button" class="btn btn-sm btn-outline-primary" onclick="addRow()">+ Add Row</button>
            </div>
            <div id="saleRows">
                <?php $__currentLoopData = $lines; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $row): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <div class="row g-2 align-items-end sale-row mb-2 border-bottom pb-2">
                        <div class="col-md-2"><label class="form-label">Barcode</label><input class="form-control barcode-input" placeholder="Scan / type barcode"></div>
                        <div class="col-md-4"><label class="form-label">Product / Variant</label><select name="rows[<?php echo e($index); ?>][product_id]" class="form-select product-select" required><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-barcode="<?php echo e($product->barcode); ?>" data-price="<?php echo e($product->selling_price); ?>" data-unit="<?php echo e($product->unit ?: 'pcs'); ?>" data-factor="<?php echo e(max(1, (int) ($product->unit_value_in_base ?? 1))); ?>" data-stock="<?php echo e((int) ($product->stock_quantity ?? 0)); ?>" <?php if(($row['product_id'] ?? '') == $product->id): echo 'selected'; endif; ?>><?php echo e($product->product_name); ?> <?php if($product->size || $product->color): ?> - <?php echo e(trim(($product->size ?? '').' '.($product->color ?? ''))); ?> <?php endif; ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select><div class="small text-muted unit-help mt-1"></div></div>
                        <div class="col-md-2"><label class="form-label">Qty</label><input name="rows[<?php echo e($index); ?>][quantity_sold]" value="<?php echo e($row['quantity_sold'] ?? 1); ?>" class="form-control qty" type="number" step="0.01" min="0.01" required></div>
                        <div class="col-md-2"><label class="form-label">Selling Price</label><input name="rows[<?php echo e($index); ?>][selling_price]" value="<?php echo e($row['selling_price'] ?? 0); ?>" class="form-control price" type="number" step="0.01" min="0" required></div>
                        <div class="col-md-1"><label class="form-label">Discount</label><input name="rows[<?php echo e($index); ?>][discount]" value="<?php echo e($row['discount'] ?? 0); ?>" class="form-control discount" type="number" step="0.01" min="0"></div>
                        <div class="col-md-1"><button type="button" class="btn btn-outline-danger w-100" onclick="this.closest('.sale-row').remove();calcTotals();">×</button></div>
                    </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </div>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-md-3"><label class="form-label">Invoice Discount</label><input name="invoice_discount" id="invoice_discount" value="<?php echo e(old('invoice_discount', $hold->payload['invoice_discount'] ?? $invoice->invoice_discount ?? 0)); ?>" class="form-control" type="number" step="0.01" min="0"></div>
            <div class="col-md-3"><label class="form-label">Tax %</label><input name="tax_percent" id="tax_percent" value="<?php echo e(old('tax_percent', $meta->tax_percent ?? 0)); ?>" class="form-control" type="number" step="0.01" min="0"></div>
            <div class="col-md-3"><label class="form-label">Bundle Discount</label><input name="bundle_discount" id="bundle_discount" value="<?php echo e(old('bundle_discount', $meta->bundle_discount ?? 0)); ?>" class="form-control" type="number" step="0.01" min="0"></div>
            <div class="col-md-3"><label class="form-label">BOGO Discount</label><input name="bogo_discount" id="bogo_discount" value="<?php echo e(old('bogo_discount', $meta->bogo_discount ?? 0)); ?>" class="form-control" type="number" step="0.01" min="0"></div>
            <div class="col-md-3"><label class="form-label">Time Discount</label><input name="time_discount" id="time_discount" value="<?php echo e(old('time_discount', $meta->time_discount ?? 0)); ?>" class="form-control" type="number" step="0.01" min="0"></div>
            <div class="col-md-3"><label class="form-label">Coupon</label><select name="coupon_code" class="form-select"><option value="">None</option><?php $__currentLoopData = $coupons; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $coupon): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($coupon->code); ?>" <?php if(old('coupon_code', $meta->coupon_code ?? '')===$coupon->code): echo 'selected'; endif; ?>><?php echo e($coupon->code); ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select></div>
            <div class="col-md-3"><label class="form-label">Gift Card</label><select name="gift_card_code" class="form-select"><option value="">None</option><?php $__currentLoopData = $giftCards; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $card): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($card->code); ?>" <?php if(old('gift_card_code', $meta->gift_card_code ?? '')===$card->code): echo 'selected'; endif; ?>><?php echo e($card->code); ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select></div>
            <div class="col-md-3"><label class="form-label">Document Type</label><select name="document_type" id="documentType" class="form-select"><option value="Invoice" <?php if(old('document_type', $meta->document_type ?? 'Invoice')==='Invoice'): echo 'selected'; endif; ?>>Invoice</option><option value="Quotation" <?php if(old('document_type', $meta->document_type ?? '')==='Quotation'): echo 'selected'; endif; ?>>Quotation</option><option value="Draft" <?php if(old('document_type', $meta->document_type ?? '')==='Draft'): echo 'selected'; endif; ?>>Draft</option><option value="Hold" <?php if(old('document_type', $meta->document_type ?? '')==='Hold'): echo 'selected'; endif; ?>>Hold</option></select></div>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-md-3"><label class="form-label">Sale Status</label><select name="sale_status" class="form-select"><option value="Completed" <?php if(old('sale_status', $meta->sale_status ?? 'Completed')==='Completed'): echo 'selected'; endif; ?>>Completed</option><option value="Suspended" <?php if(old('sale_status', $meta->sale_status ?? '')==='Suspended'): echo 'selected'; endif; ?>>Suspended</option><option value="Draft" <?php if(old('sale_status', $meta->sale_status ?? '')==='Draft'): echo 'selected'; endif; ?>>Draft</option><option value="Quotation" <?php if(old('sale_status', $meta->sale_status ?? '')==='Quotation'): echo 'selected'; endif; ?>>Quotation</option></select></div>
            <div class="col-md-3"><label class="form-label">Approval Status</label><select name="approval_status" class="form-select"><option value="Approved" <?php if(old('approval_status', $meta->approval_status ?? 'Approved')==='Approved'): echo 'selected'; endif; ?>>Approved</option><option value="Pending" <?php if(old('approval_status', $meta->approval_status ?? '')==='Pending'): echo 'selected'; endif; ?>>Pending</option></select></div>
            <div class="col-md-3"><label class="form-label">Refund Status</label><select name="refund_status" class="form-select"><option value="N/A" <?php if(old('refund_status', $meta->refund_status ?? 'N/A')==='N/A'): echo 'selected'; endif; ?>>N/A</option><option value="Pending" <?php if(old('refund_status', $meta->refund_status ?? '')==='Pending'): echo 'selected'; endif; ?>>Pending</option><option value="Approved" <?php if(old('refund_status', $meta->refund_status ?? '')==='Approved'): echo 'selected'; endif; ?>>Approved</option></select></div>
            <div class="col-md-3"><label class="form-label">Exchange Status</label><select name="exchange_status" class="form-select"><option value="N/A" <?php if(old('exchange_status', $meta->exchange_status ?? 'N/A')==='N/A'): echo 'selected'; endif; ?>>N/A</option><option value="Pending" <?php if(old('exchange_status', $meta->exchange_status ?? '')==='Pending'): echo 'selected'; endif; ?>>Pending</option><option value="Completed" <?php if(old('exchange_status', $meta->exchange_status ?? '')==='Completed'): echo 'selected'; endif; ?>>Completed</option></select></div>
            <div class="col-md-3"><label class="form-label">Area Name</label><input name="area_name" value="<?php echo e(old('area_name', $meta->area_name ?? '')); ?>" class="form-control" placeholder="Inside Dhaka / Outside Dhaka"></div>
            <div class="col-md-3"><label class="form-label">Language Mode</label><select name="language_mode" class="form-select"><option value="English" <?php if(old('language_mode', $meta->language_mode ?? 'English')==='English'): echo 'selected'; endif; ?>>English</option><option value="Bangla" <?php if(old('language_mode', $meta->language_mode ?? '')==='Bangla'): echo 'selected'; endif; ?>>Bangla</option></select></div>
            <div class="col-md-3"><label class="form-label">Cashier Shift</label><input type="hidden" name="cashier_shift_id" value="<?php echo e(old('cashier_shift_id', $openShift->id ?? '')); ?>"><input class="form-control" value="<?php echo e($openShift->shift_no ?? 'No open shift'); ?>" readonly></div>
            <div class="col-md-3"><label class="form-label">Delivery Charge</label><input name="delivery_charge" id="delivery_charge" value="<?php echo e(old('delivery_charge', $meta->delivery_charge ?? 0)); ?>" class="form-control" type="number" step="0.01" min="0"></div>
        </div>

        <div class="card card-body mb-3">
            <div class="d-flex justify-content-between align-items-center"><strong>Split Payment</strong><button type="button" class="btn btn-sm btn-outline-primary" onclick="addPaymentRow()">+ Add Payment</button></div>
            <div id="paymentRows" class="mt-2">
                <?php ($payRows = old('split_payment_method', $payments->count() ? $payments : [['payment_method'=>'Cash','amount'=>0,'gateway_name'=>'','gateway_reference'=>'']])); ?>
                <?php $__currentLoopData = $payRows; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $i => $payment): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <div class="row g-2 payment-row mb-2">
                    <div class="col-md-3"><select name="split_payment_method[]" class="form-select"><option value="">Select</option><?php $__currentLoopData = ['Cash','Bank','Card','bKash','Nagad','Rocket','Due']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $pm): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($pm); ?>" <?php if(($payment['payment_method'] ?? $payment->payment_method ?? '')===$pm): echo 'selected'; endif; ?>><?php echo e($pm); ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select></div>
                    <div class="col-md-3"><input name="split_payment_amount[]" class="form-control" type="number" step="0.01" min="0" value="<?php echo e($payment['amount'] ?? $payment->amount ?? 0); ?>" placeholder="Amount"></div>
                    <div class="col-md-3"><input name="split_gateway_name[]" class="form-control" value="<?php echo e($payment['gateway_name'] ?? $payment->gateway_name ?? ''); ?>" placeholder="Gateway name"></div>
                    <div class="col-md-2"><input name="split_gateway_reference[]" class="form-control" value="<?php echo e($payment['gateway_reference'] ?? $payment->gateway_reference ?? ''); ?>" placeholder="Reference"></div>
                    <div class="col-md-1"><button type="button" class="btn btn-outline-danger w-100" onclick="this.closest('.payment-row').remove()">×</button></div>
                </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </div>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-md-3"><label class="form-label">Subtotal</label><input id="sub_total_preview" class="form-control" readonly></div>
            <div class="col-md-3"><label class="form-label">Tax Amount</label><input id="tax_amount_preview" class="form-control" readonly></div>
            <div class="col-md-3"><label class="form-label">Grand Total</label><input id="grand_total_preview" class="form-control" readonly></div>
            <div class="col-md-3"><label class="form-label">Estimated Due</label><input id="due_preview" class="form-control" readonly></div>
        </div>

        <div class="mt-4 d-flex gap-2 flex-wrap">
            <button class="btn btn-dark"><?php echo e($invoice ? 'Update Document' : 'Save Document'); ?></button>
            <button class="btn btn-outline-secondary" type="submit" onclick="document.getElementById('documentType').value='Quotation'">Save as Quotation</button>
            <button class="btn btn-outline-info" type="submit" onclick="document.getElementById('documentType').value='Draft'">Save as Draft</button>
            <button class="btn btn-outline-warning" type="submit" onclick="document.getElementById('documentType').value='Hold'">Park / Hold</button>
            <?php if($invoice): ?>
                <a href="<?php echo e(route('admin.sales.invoice', $invoice)); ?>" class="btn btn-light">Back to Invoice</a>
            <?php else: ?>
                <a href="<?php echo e(route('admin.sales.index')); ?>" class="btn btn-light">Cancel</a>
            <?php endif; ?>
        </div>
    </form>
</div>
<script>
let rowIndex = <?php echo e(count($lines)); ?>;
function saleRowTemplate(index){return `<div class="row g-2 align-items-end sale-row mb-2 border-bottom pb-2"><div class="col-md-2"><label class="form-label">Barcode</label><input class="form-control barcode-input" placeholder="Scan / type barcode"></div><div class="col-md-4"><label class="form-label">Product / Variant</label><select name="rows[${index}][product_id]" class="form-select product-select" required><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-barcode="<?php echo e($product->barcode); ?>" data-price="<?php echo e($product->selling_price); ?>" data-unit="<?php echo e($product->unit ?: 'pcs'); ?>" data-factor="<?php echo e(max(1, (int) ($product->unit_value_in_base ?? 1))); ?>" data-stock="<?php echo e((int) ($product->stock_quantity ?? 0)); ?>"><?php echo e($product->product_name); ?> <?php if($product->size || $product->color): ?> - <?php echo e(trim(($product->size ?? '').' '.($product->color ?? ''))); ?> <?php endif; ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select><div class="small text-muted unit-help mt-1"></div></div><div class="col-md-2"><label class="form-label">Qty</label><input name="rows[${index}][quantity_sold]" value="1" class="form-control qty" type="number" step="0.01" min="0.01" required></div><div class="col-md-2"><label class="form-label">Selling Price</label><input name="rows[${index}][selling_price]" value="0" class="form-control price" type="number" step="0.01" min="0" required></div><div class="col-md-1"><label class="form-label">Discount</label><input name="rows[${index}][discount]" value="0" class="form-control discount" type="number" step="0.01" min="0"></div><div class="col-md-1"><button type="button" class="btn btn-outline-danger w-100" onclick="this.closest('.sale-row').remove();calcTotals();">×</button></div></div>`;}
function addRow(){document.getElementById('saleRows').insertAdjacentHTML('beforeend', saleRowTemplate(rowIndex)); rowIndex++; bindPos();}
function addPaymentRow(){document.getElementById('paymentRows').insertAdjacentHTML('beforeend', `<div class="row g-2 payment-row mb-2"><div class="col-md-3"><select name="split_payment_method[]" class="form-select"><option value="">Select</option><option>Cash</option><option>Bank</option><option>Card</option><option>bKash</option><option>Nagad</option><option>Rocket</option><option>Due</option></select></div><div class="col-md-3"><input name="split_payment_amount[]" class="form-control" type="number" step="0.01" min="0" value="0" placeholder="Amount"></div><div class="col-md-3"><input name="split_gateway_name[]" class="form-control" placeholder="Gateway name"></div><div class="col-md-2"><input name="split_gateway_reference[]" class="form-control" placeholder="Reference"></div><div class="col-md-1"><button type="button" class="btn btn-outline-danger w-100" onclick="this.closest('.payment-row').remove()">×</button></div></div>`);}
function refreshSaleHelp(row){const opt=row.querySelector('.product-select')?.selectedOptions?.[0];const help=row.querySelector('.unit-help');if(!help)return;const unit=opt?.dataset?.unit||'pcs';const factor=parseInt(opt?.dataset?.factor||1,10);const stock=parseInt(opt?.dataset?.stock||0,10);const display=(stock/factor).toFixed(2).replace(/\.00$/,'');help.textContent=`1 ${unit} = ${factor} pcs | Stock: ${stock} pcs (${display} ${unit})`;}
function bindPos(){document.querySelectorAll('.product-select').forEach(el=>el.onchange=function(){ const opt=this.selectedOptions[0]; const row=this.closest('.sale-row'); row.querySelector('.price').value = opt?.dataset?.price || 0; refreshSaleHelp(row); calcTotals(); }); document.querySelectorAll('.barcode-input').forEach(el=>el.oninput=function(){ const code=this.value.trim(); if(!code) return; const row=this.closest('.sale-row'); const select=row.querySelector('.product-select'); const match=[...select.options].find(o=>o.dataset.barcode===code); if(match){ select.value=match.value; row.querySelector('.price').value = match.dataset.price || 0; refreshSaleHelp(row); } calcTotals(); }); document.querySelectorAll('.qty,.price,.discount,#invoice_discount,#tax_percent,#bundle_discount,#bogo_discount,#time_discount,#delivery_charge,#paid_amount').forEach(el=>el.oninput=calcTotals); document.querySelectorAll('.sale-row').forEach(refreshSaleHelp);}
function calcTotals(){let subtotal = 0;document.querySelectorAll('.sale-row').forEach(row=>{ const q=parseFloat(row.querySelector('.qty')?.value||0); const p=parseFloat(row.querySelector('.price')?.value||0); const d=parseFloat(row.querySelector('.discount')?.value||0); subtotal += Math.max(0,(q*p)-d); }); const invDis=parseFloat(document.getElementById('invoice_discount').value||0); const taxPct=parseFloat(document.getElementById('tax_percent').value||0); const bundle=parseFloat(document.getElementById('bundle_discount').value||0); const bogo=parseFloat(document.getElementById('bogo_discount').value||0); const timeDis=parseFloat(document.getElementById('time_discount').value||0); const delivery=parseFloat(document.getElementById('delivery_charge').value||0); const taxable=Math.max(0, subtotal-invDis-bundle-bogo-timeDis); const tax=(taxable*taxPct)/100; const grand=taxable+tax+delivery; const paid=parseFloat(document.getElementById('paid_amount').value||0); document.getElementById('sub_total_preview').value=subtotal.toFixed(2); document.getElementById('tax_amount_preview').value=tax.toFixed(2); document.getElementById('grand_total_preview').value=grand.toFixed(2); document.getElementById('due_preview').value=Math.max(0, grand-paid).toFixed(2);}
bindPos(); calcTotals();
</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/sales/form.blade.php ENDPATH**/ ?>