

<?php $__env->startSection('title', 'Edit Invoice'); ?>
<?php $__env->startSection('page-title', 'Edit Invoice'); ?>

<?php $__env->startSection('content'); ?>
    <?php
        function getCardData($invoice, $key) {
            if (!$invoice->card_info) {
                return '';
            }
            try {
                $cardData = json_decode($invoice->card_info, true);
                return $cardData[$key] ?? '';
            } catch (\Exception $e) {
                return '';
            }
        }
    ?>
    <div class="card invoice-area">
        <div class="card-body">
            <form method="POST" action="<?php echo e(route('invoices.update', $invoice->id)); ?>" id="invoiceForm">
                <?php echo csrf_field(); ?>
                <?php echo method_field('PUT'); ?>

                <div class="row">
                    <div class="col-md-8">
                        <div class="row g-2 mb-2">
                            <div class="col-md-4">
                                <label class="form-label">Invoice Number</label>
                                <input type="text" name="invoice_number" id="invoice_number" class="form-control" value="<?php echo e(old('invoice_number', $invoice->invoice_number)); ?>" required readonly>
                                <?php if(!empty($invoice->loan_number)): ?>
                                    <div class="small text-muted mt-1">Loan No: <strong><?php echo e($invoice->loan_number); ?></strong></div>
                                <?php endif; ?>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Customer</label>
                                <!-- Visible text input for immediate typing -->
                                <div style="display:flex; flex-direction: column; gap: 4px;">
                                    <input type="text" id="customer_search" class="form-control" placeholder="Type customer name to search" autocomplete="off" readonly>
                                    <!-- Contact display: populated by JS when a customer is selected -->
                                    <div id="customer_contact_display" class="small text-muted" style="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">&nbsp;</div>
                                </div>
                                    <!-- Hidden select used for form submit (default to Unknown) -->
                                    <select name="customer_id" class="form-select d-none">
                                        <option value="" data-balance="0" <?php echo e(old('customer_id', $invoice->customer_id ?? '') == '' ? 'selected' : ''); ?>>Unknown</option>
                                        <?php $__currentLoopData = $customers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $c): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($c->id); ?>" data-contact="<?php echo e($c->contact_number ?? ''); ?>" data-balance="<?php echo e($c->balance_amount ?? 0); ?>" <?php echo e(($invoice->customer_id == $c->id) ? 'selected' : ''); ?>><?php echo e($c->customer_name); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Date & Time</label>
                                <!-- Display current date and time on the right side of the customer line -->
                                <input type="text" id="current_datetime" class="form-control" readonly style="background:transparent; border:1px solid transparent; padding-left:0;">
                            </div>
                        </div>

                        <div class="row g-2 mb-2">
                            <div class="col-md-4">
                                <label class="form-label">Salesman (Optional)</label>
                                <select name="salesman_id" id="salesman_id" class="form-select">
                                    <option value="">-- Select Salesman --</option>
                                    <?php $__currentLoopData = $salesmen; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $s): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($s->id); ?>" <?php echo e(($invoice->salesman_id == $s->id) ? 'selected' : ''); ?>><?php echo e($s->name); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                        </div>

                        <div class="row g-2 mb-2 align-items-end">
                            <div class="col-md-5 col-12">
                                <label class="form-label">Barcode / Search Product</label>
                                <input type="text" id="product_search" class="form-control" placeholder="Type product name, code or barcode to search">
                            </div>
                            <div class="col-md-2 col-6">
                                <label class="form-label">Qty</label>
                                <input type="number" id="product_qty" class="form-control" value="1" min="0.001" step="0.001">
                            </div>
                            <div class="col-md-3 col-6">
                                <label class="form-label">Selling</label>
                                <input type="number" id="product_selling" class="form-control" value="0.00" min="0" step="0.01">
                            </div>
                            <div class="col-md-2 col-12">
                                <label class="form-label d-none d-md-block">&nbsp;</label>
                                <button type="button" id="productLineAddBtn" class="btn btn-success w-100">Add</button>
                            </div>
                        </div>

                        <div class="table-responsive">
                            <table class="table" id="itemsTable">
                                <thead class="table-dark">
                                    <tr>
                                        <th style="background-color: var(--primary-color) !important; color: white !important;">Product</th>
                                        <th style="background-color: var(--primary-color) !important; color: white !important;">Code</th>
                                        <th style="background-color: var(--primary-color) !important; color: white !important;">Qty</th>
                                        <th style="background-color: var(--primary-color) !important; color: white !important;">Warranty</th>
                                        <th style="background-color: var(--primary-color) !important; color: white !important;">Cost (Per)</th>
                                        <!-- Market column removed to match Create page -->
                                        <th style="background-color: var(--primary-color) !important; color: white !important;">Selling</th>
                                        <th style="background-color: var(--primary-color) !important; color: white !important;">Selling Total</th>
                                        <th style="background-color: var(--primary-color) !important; color: white !important; display: none;">Discount</th>
                                        <th style="background-color: var(--primary-color) !important; color: white !important;">Total</th>
                                        <th style="background-color: var(--primary-color) !important; color: white !important;"></th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                            </table>
                        </div>

                        
                        <!-- Bottom quick actions: Card Payment | Summary | Payments -->
                        <div class="row mt-3">
                            <div class="col-md-4">
                                <div class="card" style=display:none>
                                    <div class="card-body">
                                        <h6 class="card-title mb-2">Card Payment</h6>
                                        <div class="mb-2 d-flex align-items-center">
                                            <label class="form-label small me-2" style="min-width: 80px;">Card Number</label>
                                            <input type="text" name="card_number" id="card_number" class="form-control form-control-sm flex-fill" placeholder="XXXX-XXXX-XXXX-XXXX" value="<?php echo e(old('card_number', getCardData($invoice, 'card_number'))); ?>">
                                        </div>
                                        <div class="mb-2 d-flex align-items-center">
                                            <label class="form-label small me-2" style="min-width: 80px;">Bank</label>
                                            <select name="card_bank" id="card_bank" class="form-select form-select-sm flex-fill">
                                                <option value="">Select Bank</option>
                                                <option value="boc" <?php echo e((old('card_bank', getCardData($invoice, 'card_bank')) == 'boc') ? 'selected' : ''); ?>>Bank of Ceylon</option>
                                                <option value="peoples" <?php echo e((old('card_bank', getCardData($invoice, 'card_bank')) == 'peoples') ? 'selected' : ''); ?>>People's Bank</option>
                                                <option value="commercial" <?php echo e((old('card_bank', getCardData($invoice, 'card_bank')) == 'commercial') ? 'selected' : ''); ?>>Commercial Bank</option>
                                                <option value="hnb" <?php echo e((old('card_bank', getCardData($invoice, 'card_bank')) == 'hnb') ? 'selected' : ''); ?>>Hatton National Bank</option>
                                                <option value="sampath" <?php echo e((old('card_bank', getCardData($invoice, 'card_bank')) == 'sampath') ? 'selected' : ''); ?>>Sampath Bank</option>
                                                <option value="nationstrust" <?php echo e((old('card_bank', getCardData($invoice, 'card_bank')) == 'nationstrust') ? 'selected' : ''); ?>>National Trust Bank</option>
                                                <option value="seychelles" <?php echo e((old('card_bank', getCardData($invoice, 'card_bank')) == 'seychelles') ? 'selected' : ''); ?>>Seychelles Banking Corporation</option>
                                                <option value="union" <?php echo e((old('card_bank', getCardData($invoice, 'card_bank')) == 'union') ? 'selected' : ''); ?>>Union Bank</option>
                                                <option value="ndb" <?php echo e((old('card_bank', getCardData($invoice, 'card_bank')) == 'ndb') ? 'selected' : ''); ?>>National Development Bank</option>
                                                <option value="panasia" <?php echo e((old('card_bank', getCardData($invoice, 'card_bank')) == 'panasia') ? 'selected' : ''); ?>>Pan Asia Banking Corporation</option>
                                                <option value="cargills" <?php echo e((old('card_bank', getCardData($invoice, 'card_bank')) == 'cargills') ? 'selected' : ''); ?>>Cargills Bank</option>
                                                <option value="dfcc" <?php echo e((old('card_bank', getCardData($invoice, 'card_bank')) == 'dfcc') ? 'selected' : ''); ?>>DFCC Bank</option>
                                                <option value="lbsl" <?php echo e((old('card_bank', getCardData($invoice, 'card_bank')) == 'lbsl') ? 'selected' : ''); ?>>LankaBangla Finance</option>
                                                <option value="lbfinance" <?php echo e((old('card_bank', getCardData($invoice, 'card_bank')) == 'lbfinance') ? 'selected' : ''); ?>>LB Finance</option>
                                                <option value="softlogic" <?php echo e((old('card_bank', getCardData($invoice, 'card_bank')) == 'softlogic') ? 'selected' : ''); ?>>Softlogic Finance</option>
                                            </select>
                                        </div>
                                        <div class="mb-2 d-flex align-items-center">
                                            <label class="form-label small me-2" style="min-width: 80px;">Type</label>
                                            <select name="card_type" id="card_type" class="form-select form-select-sm flex-fill">
                                                <option value="">Select Card Type</option>
                                                <option value="visa" <?php echo e((old('card_type', getCardData($invoice, 'card_type')) == 'visa') ? 'selected' : ''); ?>>Visa</option>
                                                <option value="master" <?php echo e((old('card_type', getCardData($invoice, 'card_type')) == 'master') ? 'selected' : ''); ?>>Master</option>
                                            </select>
                                        </div>
                                        <div class="mb-2 d-flex align-items-center">
                                            <label class="form-label small me-2" style="min-width: 80px;">Amount</label>
                                            <input type="number" name="card_payment" id="card_amount" class="form-control form-control-sm flex-fill" placeholder="0.00" step="0.01" value="<?php echo e(old('card_payment', $invoice->card_payment ?? '')); ?>">
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="card" style="display:none">
                                    <div class="card-body">
                                        <h6 class="card-title mb-2">Summary</h6>
                                        <div class="d-flex justify-content-between"><small>Tax</small><strong id="sum_tax">0.00</strong></div>
                                        
                                
                                        <hr />
                                        <div class="d-flex justify-content-between"><small>Num Of Items</small><strong id="NumOfItems">0.00</strong></div>
                                        <hr />
                      
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="card">
                                    <div class="card-body">
                                        <h6 class="card-title mb-2">Payments</h6>
                                                <div class="d-flex justify-content-between"><small>Sub Total</small><strong id="summary_subtotal">0.00</strong></div>
                                                <div id="discountRowEdit" class="d-none" style="display:none !important;">
                                                    <div class="d-flex justify-content-between"><small>Discount</small><strong id="summary_discount">0.00</strong></div>
                                                </div>
                                                <div class="d-flex justify-content-between"><small>Net Total</small><strong id="summary_nettotal">0.00</strong></div>
                            <?php
                                // Determine if this invoice has loan/installment data
                                $installmentsForEdit = $invoice->installments()->orderBy('installment_number')->get();
                                $hasInstallments = ($installmentsForEdit && $installmentsForEdit->count() > 0);
                                // Use down_payment from invoice table
                                $downPayment = floatval($invoice->down_payment ?? 0);
                                $loanMonths = $hasInstallments ? $installmentsForEdit->count() : (old('loan_months') ?: 1);
                                $loanMonthly = 0;
                                if ($hasInstallments && $installmentsForEdit->count()) {
                                    $loanMonthly = $installmentsForEdit->first()->amount ?? 0;
                                } else if ($loanMonths > 0) {
                                    $netTotalPreview = $invoice->net_total ?? 0;
                                    $loanMonthly = ($netTotalPreview - $downPayment) / max(1, $loanMonths);
                                }
                                $isLoanMode = $hasInstallments || ($downPayment > 0);
                            ?>
                            <?php
                                $paidSoFar = 0;
                                try {
                                    $net = floatval($invoice->net_total ?? 0);
                                    $rem = floatval($invoice->remaining_balance ?? 0);
                                    $paidSoFar = max(0, $net - $rem);
                                } catch (\Exception $e) { $paidSoFar = 0; }
                            ?>
                            <script>
                                var paidSoFar = <?php echo e($paidSoFar); ?>;
                            </script>
                        <div id="cashPaymentRowEdit" class="mb-2" style="display:<?php echo e(((($invoice->invoice_mode ?? 'cash') === 'cash') || (($invoice->invoice_mode ?? '') === 'preorder') || ($invoice->down_payment > 0)) ? 'block' : 'none'); ?>;">
                                                    <div class="d-flex align-items-center mb-1">
                                                        <label class="form-label small me-2" style="min-width: 80px;">Paid Amount</label>
                                                        <input type="number" name="cash_payment" id="payment_cashpaid" class="form-control form-control-sm flex-fill no-spinner" value="<?php echo e(old('cash_payment', ($invoice->down_payment > 0) ? number_format($invoice->down_payment, 2, '.', '') : '')); ?>" step="0.01">
                                                    </div>
                                                    
                                                </div>
                                                <div class="d-flex align-items-center">
                                                        <label class="form-label small me-2" style="min-width: 80px;">Payment Type</label>
                                                        <select name="payment_type" id="payment_type_edit" class="form-select form-select-sm flex-fill">
                                                            <option value="cash" <?php echo e(old('payment_type', $invoice->payment_type ?? 'cash') === 'cash' ? 'selected' : ''); ?>>Cash</option>
                                                            <option value="card" <?php echo e(old('payment_type', $invoice->payment_type ?? 'cash') === 'card' ? 'selected' : ''); ?>>Card</option>
                                                            <option value="bank" <?php echo e(old('payment_type', $invoice->payment_type ?? 'cash') === 'bank' ? 'selected' : ''); ?>>Bank Transfer</option>
                                                        </select>
                                                    </div>
                                                 <div class="d-flex justify-content-between"><small>Balance</small><strong id="summary_balance">0.00</strong></div>
                                       
                                    </div>
                                </div>
                            </div>
                            <!-- Loan / Invoice Mode options (edit) -->

                            <div class="card mt-3" id="loanOptionsCardEdit" style="display:none;">
                                <div class="card-body">
                                    <h6 class="card-title mb-2">Invoice Mode</h6>
                                    <div class="mb-2">
                                        <div class="form-check form-check-inline">
                                            <input class="form-check-input" type="radio" name="invoice_mode" id="mode_cash_edit" value="cash" <?php echo e(($invoice->invoice_mode ?? 'cash') === 'cash' ? 'checked' : ''); ?>>
                                            <label class="form-check-label" for="mode_cash_edit">Cash</label>
                                        </div>
                                        <div class="form-check form-check-inline">
                                            <input class="form-check-input" type="radio" name="invoice_mode" id="mode_preorder_edit" value="preorder" <?php echo e(($invoice->invoice_mode ?? 'cash') === 'preorder' ? 'checked' : ''); ?>>
                                            <label class="form-check-label" for="mode_preorder_edit">Pre Order</label>
                                        </div>
                                        <div class="form-check form-check-inline">
                                            <input class="form-check-input" type="radio" name="invoice_mode" id="mode_loan_edit" value="loan" <?php echo e(($invoice->invoice_mode ?? 'cash') === 'loan' ? 'checked' : ''); ?>>
                                            <label class="form-check-label" for="mode_loan_edit">Loan / Installments</label>
                                        </div>
                                    </div>

                                    <div id="loanInputsEdit" style="display:<?php echo e(($invoice->payment_type ?? 'cash') === 'loan' ? 'block' : 'none'); ?>;">
                                        <div class="mb-2">
                                            <label class="form-label small">Down Payment (Rs.)</label>
                                            <!-- visible edit input should not submit directly; the hidden canonical input `loan_downpayment` is used on save -->
                                            <input type="number" id="loan_downpayment_edit" class="form-control form-control-sm" value="<?php echo e(old('loan_downpayment', number_format($invoice->down_payment ?? 0, 2, '.', ''))); ?>" step="0.01" min="0">
                                        </div>
                                        <div class="mb-2">
                                            <label class="form-label small">Periods</label>
                                            <div style="display:flex;gap:.5rem;align-items:center;">
                                                <select id="loan_frequency_edit" name="loan_frequency" class="form-select form-select-sm" style="max-width:120px;">
                                                    <option value="month" <?php echo e((old('loan_frequency', $invoice->loan_frequency ?? 'month') === 'month') ? 'selected' : ''); ?>>Month</option>
                                                    <option value="week" <?php echo e((old('loan_frequency', $invoice->loan_frequency ?? 'month') === 'week') ? 'selected' : ''); ?>>Week</option>
                                                </select>
                                                <input type="number" id="loan_months_edit" class="form-control form-control-sm" value="<?php echo e(old('loan_months', $loanMonths)); ?>" step="1" min="1" style="width:100px;">
                                                <button type="button" id="loanAddMonth" class="btn btn-sm btn-outline-primary" title="Add month">+</button>
                                                <button type="button" id="loanRemoveMonth" class="btn btn-sm btn-outline-danger" title="Remove pending month">-</button>
                                            </div>
                                        </div>
                                        <div class="mb-2">
                                            <label class="form-label small">Monthly Amount</label>
                                            <input type="text" id="loan_monthly_amount_display_edit" class="form-control form-control-sm" readonly value="<?php echo e(number_format($loanMonthly,2,'.','')); ?>">
                                        </div>
                                        <div class="mb-2">
                                            <label class="form-label small">Schedule</label>
                                            <div class="table-responsive" style="max-height:180px; overflow:auto;">
                                                <table class="table table-sm table-bordered" id="loanScheduleTableEdit">
                                                    <thead><tr><th>Installment #</th><th>Amount (Rs.)</th><th>Paid (Rs.)</th><th>Paid At</th><th>Due</th></tr></thead>
                                                    <tbody>
                                                        <?php if($hasInstallments): ?>
                                                            <?php $__currentLoopData = $installmentsForEdit; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $ins): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                                <?php
                                                                    // due_date may be a Carbon instance or a plain string depending on retrieval.
                                                                    $dueDisplay = '-';
                                                                    $paidAtDisplay = '-';
                                                                    try {
                                                                        if (!empty($ins->due_date)) {
                                                                            if (is_object($ins->due_date) && method_exists($ins->due_date, 'format')) {
                                                                                $dueDisplay = $ins->due_date->format('Y-m-d');
                                                                            } else {
                                                                                $dueDisplay = \Carbon\Carbon::parse($ins->due_date)->format('Y-m-d');
                                                                            }
                                                                        }
                                                                    } catch (\Exception $e) {
                                                                        $dueDisplay = '-';
                                                                    }
                                                                    try {
                                                                        if (!empty($ins->paid_at)) {
                                                                            if (is_object($ins->paid_at) && method_exists($ins->paid_at, 'format')) {
                                                                                $paidAtDisplay = $ins->paid_at->format('Y-m-d');
                                                                            } else {
                                                                                $paidAtDisplay = \Carbon\Carbon::parse($ins->paid_at)->format('Y-m-d');
                                                                            }
                                                                        }
                                                                    } catch (\Exception $e) {
                                                                        $paidAtDisplay = '-';
                                                                    }
                                                                ?>
                                                                <tr>
                                                                    <td><?php echo e($ins->installment_number); ?></td>
                                                                    <td><?php echo e(number_format($ins->amount,2)); ?></td>
                                                                    <td><?php echo e(number_format($ins->paid_amount ?? 0,2)); ?></td>
                                                                    <td><?php echo e($paidAtDisplay); ?></td>
                                                                    <td><?php echo e($dueDisplay); ?></td>
                                                                </tr>
                                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                        <?php else: ?>
                                                            <tr><td colspan="5" class="text-muted">No installment schedule</td></tr>
                                                        <?php endif; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                         <div class="row g-2 mb-2 align-items-end">
                             <div class="mt-3 d-flex gap-2">
                                            <button class="btn btn-primary flex-fill" id="saveInvoice">Update Invoice</button>
                                            <a href="<?php echo e(route('invoices.index')); ?>" class="btn btn-outline-secondary">Cancel</a>
                                        </div>
                        </div>
                    </div>

                    <div class="col-md-4 right-panel">
                        <!-- Last Bill Details (new) -->
                        <div class="card mb-3" style="position:sticky; top:20px;">
                            
                            <div class="card-body">
                                <h5 id="pd_name">Select a product</h5>
                                <p class="mb-1"><strong>Code:</strong> <span id="pd_code">-</span></p>
                                <p class="mb-1"><strong>Barcode:</strong> <span id="pd_barcode">-</span></p>
                                <p class="mb-1"><strong>Qty on hand:</strong> <span id="pd_qty">-</span></p>
                                <p class="mb-1"><strong>Branch:</strong> <span id="pd_branch">-</span></p>
                                <p class="mb-1"><strong>Warranty (days):</strong> <span id="pd_warranty">-</span></p>
                                <div class="table-responsive">
                                    <table class="table table-sm table-borderless mb-0">
                                        <tr>
                                            <td class="text-center" style="display: none;">
                                                <small class="text-muted">Per Item Cost</small>
                                                <div id="pd_market">-</div>
                                            </td>
                                            <td class="text-center" style="display: none;">
                                                <small class="text-muted">Wholesale</small>
                                                <div id="pd_wholesale">-</div>
                                            </td>
                                            <td class="text-center" style="display: none;">
                                                <small class="text-muted">Cost</small>
                                                <div id="pd_cost">-</div>
                                            </td>
                                            <td class="text-center">
                                                <small class="text-muted">Selling</small>
                                                <div id="pd_selling">-</div>
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                                <!-- panel Add removed: use inline Add button beside search for POS-style quick add -->
                                <div class="mt-2" id="pd_price_list">
                                    <!-- Populated by JS with saved prices for this product -->
                                </div>

                                <!-- Minimum allowed selling price (cost + 30%) -->
                                <div class="mt-2">
                                    <p class="mb-1"><strong>Min Selling:</strong> <span id="pd_min_selling">-</span></p>
                                </div>

                                <!-- Last Bill Details moved here -->
                                <hr class="my-3">
                                <h6 class="card-title mb-2">Last Bill Details</h6>
                                <div class="d-flex justify-content-between mb-1"><small class="text-muted">Invoice</small><strong id="last_bill_number">-</strong></div>
                                <div class="d-flex justify-content-between mb-1"><small class="text-muted">Date</small><span id="last_bill_date">-</span></div>
                                <div class="d-flex justify-content-between mb-1"><small class="text-muted">Total</small><strong id="last_bill_total">0.00</strong></div>
                                <div class="d-flex justify-content-between"><small class="text-muted">Paid</small><span id="last_bill_paid">0.00</span></div>
                            </div>
                        </div>
                    </div>
                </div>

                <input type="hidden" name="items" id="itemsInput">
                <!-- Hidden canonical loan fields used by shared JS when saving -->
                <input type="hidden" id="loan_downpayment" name="loan_downpayment" value="<?php echo e(old('loan_downpayment', number_format($downPayment ?? 0,2,'.',''))); ?>">
                <input type="hidden" id="loan_months" name="loan_months" value="<?php echo e(old('loan_months', $loanMonths ?? 1)); ?>">
                <input type="hidden" id="loan_schedule" name="loan_schedule" value="">
                
                <?php
                    $invoiceDateTimeForInput = '';
                    try {
                        if (!empty($invoice->date_time)) {
                            if (is_object($invoice->date_time) && method_exists($invoice->date_time, 'format')) {
                                $invoiceDateTimeForInput = $invoice->date_time->format('Y-m-d\\TH:i');
                            } else {
                                $invoiceDateTimeForInput = \Carbon\Carbon::parse($invoice->date_time)->format('Y-m-d\\TH:i');
                            }
                        }
                    } catch (\Exception $e) {
                        $invoiceDateTimeForInput = '';
                    }
                ?>
                <input type="hidden" id="date_time" name="date_time" value="<?php echo e($invoiceDateTimeForInput); ?>">
            </form>
        </div>
    </div>
<?php $__env->stopSection(); ?>

<!-- Success Modal -->
<div class="modal fade" id="successModal" tabindex="-1" aria-labelledby="successModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content">
            <div class="modal-body text-center p-4">
                <div class="mb-3">
                    <i class="fas fa-check-circle text-success" style="font-size: 3rem;"></i>
                </div>
                <h5 class="modal-title mb-3" id="successModalLabel">Success!</h5>
                <p class="mb-0" id="successMessage">Invoice updated successfully!</p>
            </div>
                <div class="modal-footer justify-content-center border-0">
                <button type="button" id="successModalOkBtn" class="btn btn-success" data-bs-dismiss="modal">OK</button>
            </div>
        </div>
    </div>
</div>

<?php $__env->startPush('styles'); ?>
<style>
/* Remove number input spinner buttons for the selling and qty inputs */
#product_selling::-webkit-outer-spin-button,
#product_selling::-webkit-inner-spin-button,
#product_qty::-webkit-outer-spin-button,
#product_qty::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
#product_selling[type=number],
#product_qty[type=number] {
    -moz-appearance: textfield;
}

/* Hide discount column in items table */
#itemsTable th:nth-child(8),
#itemsTable td:nth-child(8) {
    display: none !important;
}

/* Visual separation for right-side panel */
.right-panel { border-left: 1px solid #ececec; padding-left: 18px; }
@media (max-width: 767px){ .right-panel { border-left: none; padding-left: 0; } }

/* Make every card inside the invoice area use a green border */
.invoice-area .card {
    border: 2px solid #198754 !important;
}
.invoice-area .card .card { box-shadow: none; }
/* Make the Remove button in the items table very small for compact POS rows */
.invoice-area #itemsTable .btn-remove {
    padding: .12rem .28rem;
    font-size: .65rem;
    line-height: 1;
    height: 1.6rem;
    min-width: 2.2rem;
}
/* Green border for the items table and its cells */
.invoice-area #itemsTable {
    /* Ensure the table outer border is enforced (Bootstrap .table can override borders) */
    border: 2px solid #198754 !important;
    border-collapse: collapse;
}
.invoice-area #itemsTable th,
.invoice-area #itemsTable td {
    border: 1px solid #198754;
}
/* Hide the Warranty and Cost columns (4th and 5th) in the items table for edit view */
#itemsTable th:nth-child(4),
#itemsTable td:nth-child(4),
#itemsTable th:nth-child(5),
#itemsTable td:nth-child(5) {
    display: none !important;
}
/* If Bootstrap table styles hide the outer border, apply the green border to the responsive wrapper too */
.invoice-area .table-responsive {
    border: 2px solid #198754 !important;
    border-radius: 1.25rem;
    padding: .00rem;
}
/* Green highlight for active dropdown items */
.list-group-item.active {
    background-color: #198754 !important;
    color: white !important;
}

/* Enhanced price cards styling */
.price-card {
    transition: all 0.2s ease;
    border-radius: 0.375rem;
    margin-bottom: 0.25rem;
}
.price-card:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.price-card.btn-success {
    background-color: #198754;
    border-color: #198754;
}
.price-card .text-muted {
    font-size: 0.75rem;
}

/* Attention-grabbing animation for price cards */
.attention-flash {
    animation: priceFlash 1.5s ease-in-out 2;
}

.shake-animation {
    animation: shake 0.5s ease-in-out;
}

@keyframes priceFlash {
    0% {
        background-color: #fff3cd;
        border-color: #ffc107;
        color: #856404;
        transform: scale(1);
        box-shadow: 0 0 5px rgba(255, 193, 7, 0.3);
    }
    50% {
        background-color: #d4edda;
        border-color: #198754;
        color: #155724;
        transform: scale(1.02);
        box-shadow: 0 0 15px rgba(25, 135, 84, 0.5);
    }
    100% {
        background-color: inherit;
        border-color: inherit;
        color: inherit;
        transform: scale(1);
        box-shadow: none;
    }
}

@keyframes shake {
    0%, 100% { transform: translateX(0); }
    10%, 30%, 50%, 70%, 90% { transform: translateX(-2px); }
    20%, 40%, 60%, 80% { transform: translateX(2px); }
}

/* Special highlight for the first card */
.highlight-card {
    position: relative;
}
.highlight-card::before {
    content: "★";
    position: absolute;
    top: -5px;
    right: -5px;
    background: #ffc107;
    color: white;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    font-weight: bold;
    box-shadow: 0 2px 4px rgba(0,0,0,0.2);
    animation: starBounce 2s ease-in-out infinite;
}

@keyframes starBounce {
    0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
    40% { transform: translateY(-3px); }
    60% { transform: translateY(-1px); }
}

/* Success Modal Background Match */
#successModal .modal-content {
    background-color: var(--gray-100, #f8f9fa) !important;
}
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
document.addEventListener('DOMContentLoaded', function(){
    function updateDateTime(){
        var el = document.getElementById('current_datetime');
        if(!el) return;
        var now = new Date();
        var y = now.getFullYear();
        var m = String(now.getMonth()+1).padStart(2,'0');
        var d = String(now.getDate()).padStart(2,'0');
        var hh = String(now.getHours()).padStart(2,'0');
        var mm = String(now.getMinutes()).padStart(2,'0');
        var ss = String(now.getSeconds()).padStart(2,'0');
        el.value = y + '-' + m + '-' + d + ' ' + hh + ':' + mm + ':' + ss;
    }
    updateDateTime();
    setInterval(updateDateTime, 1000);
});
</script>
    <?php
        // Build JS-ready arrays
        $productsJs = $products->map(function($p){
            return [
                'id' => $p->id,
                'code' => $p->product_code,
                'barcode' => $p->product_barcode,
                'name' => $p->product_name,
                // expose warranty_days so the edit invoice page's JS can show it
                'warranty_days' => $p->warranty_days ?? 0,
                'qty' => $p->qty ?? 0,
                'cost' => $p->total_cost ?? 0,
                'selling' => $p->selling_price ?? 0,
                'market' => $p->market_price ?? 0,
                'is_active' => $p->is_active ?? 1,
                'branch_id' => $p->branch_id ?? null,
            ];
        })->values()->all();
        $customersJs = $customers->map(function($c){
            return ['id' => $c->id, 'name' => $c->customer_name, 'contact' => $c->contact_number ?? '', 'balance' => $c->balance_amount ?? 0, 'nic' => $c->nic ?? ''];
        })->values()->all();

        $itemsJs = [];
        foreach($invoice->items as $it){
            $itemsJs[] = [
                'item_id' => $it->item_id,
                'name' => optional($it->product)->product_name ?? ($it->item_name ?? 'Manual Item'),
                'code' => optional($it->product)->product_code ?? ($it->code ?? ''),
                'barcode' => optional($it->product)->product_barcode ?? ($it->barcode ?? ''),
                'qty' => $it->qty,
                'warranty' => $it->warranty,
                'cost' => $it->cost,
                'market_price' => $it->market_price,
                'selling_price' => $it->selling_price,
                'discount' => $it->discount,
                'total_value' => $it->total_value,
            ];
        }
    ?>

    <script>
        if (typeof window.PRODUCTS === 'undefined') {
            window.PRODUCTS = <?php echo json_encode($productsJs ?? [], 15, 512) ?>;
        }
        if (typeof window.CUSTOMERS === 'undefined') {
            window.CUSTOMERS = <?php echo json_encode($customersJs ?? [], 15, 512) ?>;
        }

        if (typeof window.PRICES === 'undefined') {
            window.PRICES = <?php echo json_encode($pricesJs ?? [], 15, 512) ?>;
        }

        window.INVOICE_ITEMS = <?php echo json_encode($itemsJs ?? [], 15, 512) ?>;

        // Provide the current invoice branch id to client JS so previews can prefer that branch's stock
        if (typeof window.INVOICE_BRANCH_ID === 'undefined') {
            window.INVOICE_BRANCH_ID = <?php echo json_encode($invoice->branch_id ?? null, 15, 512) ?>;
        }

        // Reuse same client JS logic as create via partial
    </script>

    <script>
        // Do not show the Market column on the Edit Invoice page (match Create behavior)
        try { window.SHOW_MARKET_IN_ITEMS = false; } catch(e){}
    </script>

    <?php echo $__env->make('invoices.create_js_partial', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

<script>
// Show customer balance on edit page load (after items are loaded)
document.addEventListener('DOMContentLoaded', function() {
    // Use setTimeout to ensure this runs after the invoice items are loaded
    setTimeout(function() {
        const customerSelect = document.querySelector('select[name="customer_id"]');
        if (customerSelect && customerSelect.value) {
            const selectedOption = customerSelect.options[customerSelect.selectedIndex];
            const balance = selectedOption.getAttribute('data-balance') || 0;
            
            // Directly show customer balance in the items table
            const itemsTableBody = document.querySelector('#itemsTable tbody');
            if (itemsTableBody) {
                // Remove existing balance row if any
                const existingBalanceRow = document.getElementById('customerBalanceRow');
                if (existingBalanceRow) {
                    existingBalanceRow.remove();
                }
                
                // Create and insert balance row at the top
                const balanceRow = document.createElement('tr');
                balanceRow.id = 'customerBalanceRow';
                balanceRow.style.backgroundColor = '#fff3cd';
                balanceRow.style.fontWeight = 'bold';
                balanceRow.innerHTML = `
                    <td colspan="9" style="text-align: left; padding: 8px;">
                        Customer Balance: Rs. <span id="customerBalanceDisplay">${parseFloat(balance || 0).toFixed(2)}</span>
                    </td>
                    <td></td>
                `;
                itemsTableBody.insertBefore(balanceRow, itemsTableBody.firstChild);
            }
        }
    }, 500); // 500ms delay to ensure items are loaded first
});
</script>

<script>
// Sync edit loan inputs with canonical IDs used by save logic
document.addEventListener('DOMContentLoaded', function(){
    function syncHidden() {
        try {
            const downEdit = document.getElementById('loan_downpayment_edit');
            const monthsEdit = document.getElementById('loan_months_edit');
            const hiddenDown = document.getElementById('loan_downpayment');
            const hiddenMonths = document.getElementById('loan_months');
            if(downEdit && hiddenDown) hiddenDown.value = parseFloat(downEdit.value || 0) || 0;
            if(monthsEdit && hiddenMonths) hiddenMonths.value = parseInt(monthsEdit.value || 1) || 1;
        } catch(e){}
    }

    // Recalculate totals and update summary (similar to create page)
    function recalc(){
        let subtotal = 0;
        let discount = 0;
        let netTotal = 0;

        // Calculate subtotal and discount from items
        document.querySelectorAll('#itemsTable tbody tr').forEach(tr => {
            // Skip the customer balance info row
            if (tr.id === 'customerBalanceRow') return;
            
            const qtyEl = tr.querySelector('.item-qty');
            const sellingEl = tr.querySelector('.item-selling');
            
            // Skip rows that don't have item fields (safety check)
            if (!qtyEl || !sellingEl) return;
            
            const qty = parseFloat(qtyEl.value) || 0;
            const selling = parseFloat(sellingEl.value) || 0;
            // Read user-entered discount for the row (manual input)
            const discountEl = tr.querySelector('.item-discount');
            const itemDiscount = parseFloat(discountEl?.value || 0) || 0;

            // Line total is selling * qty (what customer pays)
            const line = selling * qty;
            const totalEl = tr.querySelector('.item-total');
            if (totalEl) totalEl.innerText = line.toFixed(2);

            // Update selling total display
            const sellingTotal = selling * qty;
            const sellingTotalEl = tr.querySelector('.item-selling-total');
            if(sellingTotalEl) sellingTotalEl.innerText = sellingTotal.toFixed(2);

            subtotal += line;
            discount += itemDiscount;
        });

        // Net total = subtotal - discount
        netTotal = subtotal - discount;

        // Update summary section
        const summarySubtotalEl = document.getElementById('summary_subtotal');
        if(summarySubtotalEl) summarySubtotalEl.innerText = subtotal.toFixed(2);
        const summaryDiscountEl = document.getElementById('summary_discount');
        if(summaryDiscountEl) summaryDiscountEl.innerText = discount.toFixed(2);
        const summaryNettotalEl = document.getElementById('summary_nettotal');
        if(summaryNettotalEl) summaryNettotalEl.innerText = netTotal.toFixed(2);

        // Update balance calculation
        const summaryBalanceEl = document.getElementById('summary_balance');
        if(summaryBalanceEl) {
            // Include cash payment and down payment in balance computation
            const cashVal = parseFloat((document.getElementById('payment_cashpaid') || {}).value || 0) || 0;
            const downPaymentVal = parseFloat((document.getElementById('loan_downpayment_edit') || {}).value || 0) || 0;
            const totalPaid = cashVal + downPaymentVal;
            const remaining = Math.max(0, netTotal - totalPaid);
            summaryBalanceEl.innerText = remaining.toFixed(2);
        }

        // Update Num Of Items (total quantity of all products)
        const numOfItemsEl = document.getElementById('NumOfItems');
        if(numOfItemsEl) {
            let totalQty = 0;
            document.querySelectorAll('#itemsTable tbody tr').forEach(tr => {
                // Skip the customer balance info row
                if (tr.id === 'customerBalanceRow') return;
                const qtyEl = tr.querySelector('.item-qty');
                if (qtyEl) {
                    totalQty += parseFloat(qtyEl.value) || 0;
                }
            });
            numOfItemsEl.innerText = totalQty.toString();
        }
    }

    // Add event listeners to call recalc when items change
    function attachItemListeners() {
        // Listen for changes to quantity, selling price, and discount inputs
        document.querySelectorAll('#itemsTable .item-qty, #itemsTable .item-selling, #itemsTable .item-discount').forEach(el => {
            if (!el.__recalcAttached) {
                el.addEventListener('input', function() {
                    try { recalc(); } catch(e) { console.warn('recalc failed', e); }
                });
                el.__recalcAttached = true;
            }
        });

        // Listen for item removal
        document.querySelectorAll('#itemsTable .btn-remove').forEach(btn => {
            if (!btn.__recalcAttached) {
                btn.addEventListener('click', function() {
                    // Delay recalc to allow DOM update
                    setTimeout(function() {
                        try { recalc(); } catch(e) { console.warn('recalc failed', e); }
                    }, 10);
                });
                btn.__recalcAttached = true;
            }
        });
    }

    // FIX: Normalize loan installment amounts on page load if they show as 0
    function fixLoanInstallmentsOnLoad() {
        try {
            const tbody = document.querySelector('#loanScheduleTableEdit tbody');
            if (!tbody) return;
            
            const rows = Array.from(tbody.querySelectorAll('tr'));
            if (rows.length === 0) return;
            
            // Check if we have 0 amounts (except for fully paid installments)
            let hasZeroAmounts = false;
            const items = rows.map(r => {
                const tds = r.querySelectorAll('td');
                const inst = parseInt(tds[0]?.innerText) || 0;
                const amount = parseFloat((tds[1]?.innerText || '0').replace(/,/g, '')) || 0;
                const paid = parseFloat((tds[2]?.innerText || '0').replace(/,/g, '')) || 0;
                
                if (amount === 0 && paid === 0) {
                    hasZeroAmounts = true;
                }
                return { installment: inst, amount: amount, paid_amount: paid };
            });
            
            // If we have zero amounts and there are pending installments, recalculate
            if (hasZeroAmounts && rows.length > 0) {
                console.log('Detected zero installment amounts on page load - recalculating...');
                // Normalize to fix the amounts
                try { normalizeLoanScheduleTotals(); } catch(e) { console.warn('fixLoanInstallments normalizeLoanScheduleTotals failed', e); }
            }
        } catch(e) {
            console.warn('fixLoanInstallmentsOnLoad failed', e);
        }
    }

    // Attach listeners initially and after DOM changes
    document.addEventListener('DOMContentLoaded', function() {
        attachItemListeners();
        // Call recalc initially to ensure summary is correct
        try { recalc(); } catch(e) { console.warn('initial recalc failed', e); }
        // Fix loan installments if they show as 0 (after recalc has updated summary)
        try { fixLoanInstallmentsOnLoad(); } catch(e) { console.warn('fixLoanInstallmentsOnLoad failed', e); }
    });

    // Re-attach listeners when items are added (using MutationObserver)
    const itemsTable = document.getElementById('itemsTable');
    if (itemsTable) {
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.type === 'childList') {
                    attachItemListeners();
                }
            });
        });
        observer.observe(itemsTable, { childList: true, subtree: true });
    }

    // initial sync
    syncHidden();

    // on change sync back
    try { 
        document.getElementById('loan_downpayment_edit')?.addEventListener('input', function() {
            syncHidden();
            // When down payment changes, recalculate the loan schedule amounts
            try { 
                normalizeLoanScheduleTotals(); 
            } catch(e) { 
                console.warn('Failed to update loan schedule on downpayment change', e); 
            }
        }); 
    } catch(e){}
    try { 
        document.getElementById('loan_months_edit')?.addEventListener('input', function() {
            syncHidden();
            // When months change, rebuild and normalize the loan schedule table
            try { 
                ensureLoanScheduleExists();
                normalizeLoanScheduleTotals(); 
            } catch(e) { 
                console.warn('Failed to update loan schedule on months change', e); 
            }
        }); 
    } catch(e){}

    // Show/hide edit loan inputs when radio toggled
    try {
        const modeLoan = document.getElementById('mode_loan_edit');
        const modeCash = document.getElementById('mode_cash_edit');
        const modePreorder = document.getElementById('mode_preorder_edit');
        const loanInputs = document.getElementById('loanInputsEdit');
        const cashPaymentRow = document.getElementById('cashPaymentRowEdit');
        
        // Initialize display based on current mode
    const currentMode = <?php echo json_encode($invoice->invoice_mode ?? 'cash'); ?>;
        if (currentMode === 'cash' && cashPaymentRow) {
            cashPaymentRow.style.display = 'flex';
        }
        // If current mode is preorder, show cash payment row (allow entering Paid Amount) and hide loan inputs
        if (currentMode === 'preorder') {
            if (cashPaymentRow) cashPaymentRow.style.display = 'flex';
            if (loanInputs) loanInputs.style.display = 'none';
        }
        
        // Helper: check stock availability for current items against product stocks for the invoice branch
        function checkAvailabilityForBranch(branchId) {
            try {
                const required = {}; // product_id => qty
                document.querySelectorAll('#itemsTable tbody tr').forEach(tr => {
                    if (tr.id === 'customerBalanceRow') return;
                    const pid = tr.dataset.productId || tr.getAttribute('data-product-id') || tr.querySelector('.item-id')?.value || null;
                    if (!pid) return;
                    const qtyEl = tr.querySelector('.item-qty') || tr.querySelector('.item-qty-display');
                    const qty = parseFloat((qtyEl?.value || qtyEl?.innerText || '0')) || 0;
                    if (!required[pid]) required[pid] = 0;
                    required[pid] += qty;
                });

                // For each required product, find stock for branch
                const shortages = [];
                Object.keys(required).forEach(pid => {
                    const need = required[pid] || 0;
                    let avail = 0;
                    try {
                        const stocks = (window.PRODUCT_STOCKS || {})[pid] || [];
                        if (stocks && stocks.length) {
                            // prefer matching branch
                            let found = stocks.find(s => String(s.branch_id) === String(branchId));
                            if (!found) found = stocks[0];
                            avail = parseFloat(found.qty || 0) || 0;
                        } else {
                            avail = 0;
                        }
                    } catch(e) { avail = 0; }
                    if (avail + 0.000001 < need) {
                        shortages.push({ productId: pid, need: need, avail: avail });
                    }
                });

                return { ok: shortages.length === 0, shortages };
            } catch(e) { return { ok: true, shortages: [] }; }
        }

        if(modeLoan) modeLoan.addEventListener('change', function(){
            // When switching to a stock-consuming mode, validate availability first
            const branchId = window.INVOICE_BRANCH_ID || null;
            if (branchId) {
                const chk = checkAvailabilityForBranch(branchId);
                if (!chk.ok) {
                    alert('Cannot switch to Loan mode: insufficient stock for some products. Reduce quantities or remove items before switching.');
                    // revert radio selection back to previous (preorder)
                    try { document.getElementById('mode_preorder_edit').checked = true; } catch(e){}
                    return;
                }
            }
            if(loanInputs) loanInputs.style.display = 'block';
            if(cashPaymentRow) cashPaymentRow.style.display = 'none';
            syncHidden();
            try{ ensureLoanScheduleExists(); normalizeLoanScheduleTotals(); }catch(e){}
        });
        if(modeCash) modeCash.addEventListener('change', function(){ 
            const branchId = window.INVOICE_BRANCH_ID || null;
            if (branchId) {
                const chk = checkAvailabilityForBranch(branchId);
                if (!chk.ok) {
                    alert('Cannot switch to Cash mode: insufficient stock for some products. Reduce quantities or remove items before switching.');
                    try { document.getElementById('mode_preorder_edit').checked = true; } catch(e){}
                    return;
                }
            }
            if(loanInputs) loanInputs.style.display = 'none'; 
            if(cashPaymentRow) cashPaymentRow.style.display = 'flex';
            syncHidden(); 
        });
        if(modePreorder) modePreorder.addEventListener('change', function(){ 
            // Preorder: allow entering a paid amount similar to cash, but hide loan inputs
            if(loanInputs) loanInputs.style.display = 'none'; 
            if(cashPaymentRow) cashPaymentRow.style.display = 'flex';
            // do not clear existing paid value so edits can adjust down payment
            syncHidden(); 
        });
    } catch(e){}

    // Before save, build loan_schedule into hidden input from schedule table
    try {
        const saveBtn = document.getElementById('saveInvoice');
        if(saveBtn){
            saveBtn.addEventListener('click', function(e){
                try {
                    // Ensure schedule totals are normalized and table rebuilt before serializing
                    try { normalizeLoanScheduleTotals(); rebuildLoanScheduleTable(); } catch(_){ }

                    const rows = document.querySelectorAll('#loanScheduleTableEdit tbody tr');
                    const arr = [];
                    rows.forEach(r => {
                        const tds = r.querySelectorAll('td');
                        if(tds && tds.length >= 2){
                            const inst = parseInt(tds[0].innerText) || null;
                            const amt = parseFloat((tds[1].innerText || '').replace(/,/g,'')) || 0;
                            const due = (tds[4] && (tds[4].innerText || '').trim()) ? (tds[4].innerText || '').trim() : null;
                            if(inst){
                                const obj = { installment: inst, amount: amt };
                                if(due) obj.due_date = due;
                                arr.push(obj);
                            }
                        }
                    });
                    const hs = document.getElementById('loan_schedule');
                    if(hs) hs.value = JSON.stringify(arr);
                    // also ensure hidden canonical fields are up-to-date
                    syncHidden();
                } catch(e){ }
            });
        }
    } catch(e){}
    
    // Helpers for loan schedule editing (only affect pending months; paid months untouched)
    function parseCurrency(text){
        try { return parseFloat((text||'').toString().replace(/,/g, '')) || 0; } catch(e){ return 0; }
    }

    function formatDateISO(d){
        if(!d) return '-';
        try{ const dt = new Date(d); if(isNaN(dt)) return '-'; return dt.toISOString().slice(0,10);}catch(e){return '-';}
    }

    function rebuildLoanScheduleTable(){
        const tbody = document.querySelector('#loanScheduleTableEdit tbody');
        if(!tbody) return;
        // read current rows into objects
        const rows = Array.from(tbody.querySelectorAll('tr'));
        const items = rows.map(r => {
            const tds = r.querySelectorAll('td');
            const inst = parseInt(tds[0].innerText) || null;
            const amt = parseCurrency(tds[1].innerText || '0');
            const paid = parseCurrency(tds[2].innerText || '0');
            const paidAt = (tds[3] && tds[3].innerText && tds[3].innerText !== '-') ? tds[3].innerText.trim() : null;
            const due = (tds[4] && tds[4].innerText && tds[4].innerText !== '-') ? tds[4].innerText.trim() : null;
            return { installment: inst, amount: amt, paid_amount: paid, paid_at: paidAt, due_date: due };
        });
        // write back standardized rows
        tbody.innerHTML = '';
        items.forEach(it => {
            const tr = document.createElement('tr');
            tr.innerHTML = `<td>${it.installment}</td><td>${it.amount.toFixed(2)}</td><td>${it.paid_amount.toFixed(2)}</td><td>${it.paid_at?it.paid_at:'-'}</td><td>${it.due_date?it.due_date:'-'}</td>`;
            tbody.appendChild(tr);
        });
    }

    function getLoanScheduleObjects(){
        const tbody = document.querySelector('#loanScheduleTableEdit tbody');
        if(!tbody) return [];
        return Array.from(tbody.querySelectorAll('tr')).map(r => {
            const tds = r.querySelectorAll('td');
            // If the row doesn't have the expected columns (e.g. a placeholder row with colspan), skip it
            if(!tds || tds.length < 2) return null;
            return {
                installment: parseInt(tds[0]?.innerText) || null,
                amount: parseCurrency(tds[1]?.innerText || '0'),
                paid_amount: parseCurrency((tds[2]?.innerText) || '0'),
                paid_at: (tds[3] && tds[3].innerText && tds[3].innerText !== '-') ? tds[3].innerText.trim() : null,
                due_date: (tds[4] && tds[4].innerText && tds[4].innerText !== '-') ? tds[4].innerText.trim() : null
            };
        }).filter(Boolean);
    }

    // Ensure the loan schedule table has row entries (used when an invoice saved as Cash is switched to Loan)
    function ensureLoanScheduleExists(){
        try{
            const tbody = document.querySelector('#loanScheduleTableEdit tbody');
            if(!tbody) return;
            const rows = Array.from(tbody.querySelectorAll('tr'));
            // detect placeholder row (single td with colspan or too few td cells)
            if(rows.length === 0 || (rows.length === 1 && rows[0].querySelectorAll('td').length < 2)){
                // create default rows based on months input and compute due dates according to frequency
                const monthsEl = document.getElementById('loan_months_edit');
                const freqEl = document.getElementById('loan_frequency_edit');
                const months = Math.max(1, parseInt(monthsEl ? monthsEl.value : 1) || 1);
                const freq = (freqEl && freqEl.value) ? freqEl.value : 'month';
                // determine start date: prefer hidden #date_time (invoice date) else today
                let startVal = document.getElementById('date_time')?.value || null;
                let start = startVal ? new Date(startVal) : new Date();
                start.setHours(0,0,0,0);
                tbody.innerHTML = '';
                for(let i=1;i<=months;i++){
                    // compute due date: add i periods (1-based) to start
                    let due = new Date(start.getTime());
                    if(freq === 'week'){
                        due.setDate(due.getDate() + (7 * i));
                    } else {
                        const monthIndex = due.getMonth() + i;
                        due.setMonth(monthIndex);
                    }
                    const dueStr = due.toISOString().slice(0,10);
                    const tr = document.createElement('tr');
                    tr.innerHTML = `<td>${i}</td><td>0.00</td><td>0.00</td><td>-</td><td>${dueStr}</td>`;
                    tbody.appendChild(tr);
                }
            }
        }catch(e){ console.warn('ensureLoanScheduleExists failed', e); }
    }

    // Distribute total cents across count parts, return array of amounts in cents
    function distributeCents(totalCents, count){
        const base = Math.floor(totalCents / count);
        const remainder = totalCents - (base * count);
        const arr = new Array(count).fill(base);
        if(remainder > 0){
            // add 1 cent to the last 'remainder' entries to preserve rounding to cents
            for(let i = count - remainder; i < count; i++){
                arr[i] = arr[i] + 1;
            }
        }
        return arr;
    }

    // Ensure schedule totals always match invoice net total:
    // net total = down payment + sum(paid_amounts) + sum(pending amounts)
    function normalizeLoanScheduleTotals(){
        try{
            const tbody = document.querySelector('#loanScheduleTableEdit tbody');
            if(!tbody) return;
            const rows = getLoanScheduleObjects();
            if(!rows || rows.length === 0) return;

            // Read net total from page summary if available
            let netTotal = 0;
            const netEl = document.getElementById('summary_nettotal');
            if(netEl && netEl.innerText && netEl.innerText.trim() !== ''){
                netTotal = parseCurrency(netEl.innerText || '0');
            } else {
                // fallback: compute from current rows + downpayment
                const sumAmounts = rows.reduce((a,r)=>a + (r.amount||0), 0);
                const downEl = document.getElementById('loan_downpayment_edit');
                const down = downEl ? parseCurrency(downEl.value||downEl.innerText||'0') : 0;
                netTotal = sumAmounts + down;
            }

            const downEl = document.getElementById('loan_downpayment_edit');
            const downPayment = downEl ? parseCurrency(downEl.value||0) : 0;

            const sumPaid = rows.reduce((a,r)=>a + (r.paid_amount||0), 0);

            // pending rows (those with paid_amount <= 0)
            const pending = rows.filter(r => parseFloat(r.paid_amount||0) <= 0);
            const pendingCount = Math.max(1, pending.length);

            // target pending total = netTotal - downPayment - sumPaid
            let targetPendingTotal = parseFloat((netTotal - downPayment - sumPaid) || 0);
            if(targetPendingTotal < 0) targetPendingTotal = 0;

            const totalCents = Math.round(targetPendingTotal * 100);
            const shares = distributeCents(totalCents, pendingCount);

            // rebuild tbody with normalized pending shares
            tbody.innerHTML = '';
            let pIndex = 0;
            rows.forEach(r => {
                let amount;
                if (parseFloat(r.paid_amount||0) > 0) {
                    amount = r.amount || 0;
                } else {
                    amount = (shares[pIndex++] || 0) / 100;
                }
                const tr = document.createElement('tr');
                tr.innerHTML = `<td>${r.installment}</td><td>${amount.toFixed(2)}</td><td>${parseFloat(r.paid_amount||0).toFixed(2)}</td><td>${r.paid_at? r.paid_at:'-'}</td><td>${r.due_date? r.due_date:'-'}</td>`;
                tbody.appendChild(tr);
            });

            rebuildLoanScheduleTable();
        }catch(e){
            console.warn('normalizeLoanScheduleTotals failed', e);
        }
    }

    // Add / Remove month buttons behavior
    try {
        document.getElementById('loanAddMonth')?.addEventListener('click', function(){
            const schedule = getLoanScheduleObjects();
            if(!schedule || schedule.length === 0) return;
            // split into paid and pending
            const pending = schedule.filter(s => parseFloat(s.paid_amount) <= 0);
            const totalPendingOutstanding = pending.reduce((acc, s) => acc + (s.amount - (s.paid_amount||0)), 0);
            const totalCents = Math.round(totalPendingOutstanding * 100);
            const newCount = pending.length + 1; // add one month

            // distribute cents across newCount parts
            const shares = distributeCents(totalCents, newCount); // array of cents

            // store a full snapshot of the schedule before changing so an immediate remove can restore original rows
            try{
                const monthsInputEl = document.getElementById('loan_months_edit');
                window.__lastLoanScheduleSnapshot = {
                    schedule: schedule.map(s => ({ installment: s.installment, amount: s.amount, paid_amount: s.paid_amount, paid_at: s.paid_at, due_date: s.due_date })),
                    months: monthsInputEl ? parseInt(monthsInputEl.value||0) : null,
                    addedInstallmentNumber: Math.max(...schedule.map(s=>s.installment))+1,
                    timestamp: Date.now(),
                    action: 'add'
                };
            } catch(e) { window.__lastLoanScheduleSnapshot = null; }

            // build new table: paid rows unchanged, pending rows get shares in order, then append new month with last share
            let nextInstallmentNumber = Math.max(...schedule.map(s=>s.installment))+1;
            const tbody = document.querySelector('#loanScheduleTableEdit tbody');
            tbody.innerHTML = '';
            let pIndex = 0;
            schedule.forEach(s => {
                const amount = (parseFloat(s.paid_amount) > 0) ? s.amount : (shares[pIndex++] / 100);
                const tr = document.createElement('tr');
                tr.innerHTML = `<td>${s.installment}</td><td>${amount.toFixed(2)}</td><td>${parseFloat(s.paid_amount||0).toFixed(2)}</td><td>${s.paid_at? s.paid_at:'-'}</td><td>${s.due_date? s.due_date:'-'}</td>`;
                tbody.appendChild(tr);
            });
            // compute due for new period based on selected frequency: last due +1 month or +1 week
            const freqEl = document.getElementById('loan_frequency_edit');
            const freq = (freqEl && freqEl.value) ? freqEl.value : 'month';
            let lastDue = null;
            for(let i=schedule.length-1;i>=0;i--){ if(schedule[i].due_date) { lastDue = schedule[i].due_date; break; } }
            let newDue = '-';
            if(lastDue){
                try{
                    const d = new Date(lastDue);
                    if(freq === 'week') d.setDate(d.getDate() + 7);
                    else d.setMonth(d.getMonth() + 1);
                    newDue = d.toISOString().slice(0,10);
                }catch(e){}
            }
            const newAmt = shares[pIndex] / 100;
            const newTr = document.createElement('tr');
            newTr.innerHTML = `<td>${nextInstallmentNumber}</td><td>${newAmt.toFixed(2)}</td><td>0.00</td><td>-</td><td>${newDue}</td>`;
            tbody.appendChild(newTr);
            // update months input and hidden schedule
            const monthsInput = document.getElementById('loan_months_edit');
            if(monthsInput) monthsInput.value = parseInt(monthsInput.value||0) + 1;
            rebuildLoanScheduleTable();
            // ensure totals match the invoice net total after adding
            normalizeLoanScheduleTotals();
        });

        document.getElementById('loanRemoveMonth')?.addEventListener('click', function(){
            const schedule = getLoanScheduleObjects();
            if(!schedule || schedule.length === 0) return;
            // pending only
            const pending = schedule.filter(s => parseFloat(s.paid_amount) <= 0);
            if(pending.length <= 1){ alert('Cannot remove the last pending month'); return; }
            // remove last pending installment (the one with highest installment number among pending)
            const maxPendingInst = Math.max(...pending.map(p=>p.installment));
            const remaining = schedule.filter(s => s.installment !== maxPendingInst);
            // recompute outstanding among remaining pending
            const remainingPending = remaining.filter(s => parseFloat(s.paid_amount) <= 0);
            const totalPendingOutstanding = remainingPending.reduce((acc, s) => acc + (s.amount - (s.paid_amount||0)), 0);
            const totalCents = Math.round(totalPendingOutstanding * 100);
            const newCount = remainingPending.length;
            const shares = distributeCents(totalCents, Math.max(1,newCount));
            // rebuild tbody preserving paid rows and updating pending rows amounts using shares
            const tbody = document.querySelector('#loanScheduleTableEdit tbody');
            tbody.innerHTML = '';
            let pIndex = 0;
            // check if we should restore from recent full-schedule snapshot (to make + then - a no-op)
            const snap = window.__lastLoanScheduleSnapshot;
            const canRestoreSnapshot = snap && snap.action === 'add' && (Date.now() - (snap.timestamp || 0) < 5000) && snap.addedInstallmentNumber === maxPendingInst;
            if (canRestoreSnapshot) {
                // restore exact previous schedule (before the add). This avoids any rounding drift.
                try {
                    const tbodyRestore = document.querySelector('#loanScheduleTableEdit tbody');
                    tbodyRestore.innerHTML = '';
                    (snap.schedule || []).forEach(it => {
                        const tr = document.createElement('tr');
                        tr.innerHTML = `<td>${it.installment}</td><td>${parseFloat(it.amount||0).toFixed(2)}</td><td>${parseFloat(it.paid_amount||0).toFixed(2)}</td><td>${it.paid_at?it.paid_at:'-'}</td><td>${it.due_date?it.due_date:'-'}</td>`;
                        tbodyRestore.appendChild(tr);
                    });
                    // restore months input
                    const monthsInputEl = document.getElementById('loan_months_edit');
                    if(monthsInputEl && typeof snap.months !== 'undefined' && snap.months !== null) monthsInputEl.value = snap.months;
                    // consume the snapshot so subsequent removes don't repeatedly restore
                    window.__lastLoanScheduleSnapshot = null;
                    rebuildLoanScheduleTable();
                    // restore should preserve totals, but normalize just in case
                    normalizeLoanScheduleTotals();
                    return; // finished
                } catch(e) {
                    // fallthrough to normal recompute if restore fails
                    console.warn('Failed to restore loan schedule snapshot, falling back to recompute', e);
                }
            }
            // normal recompute path
            remaining.forEach(s => {
                let amount;
                if (parseFloat(s.paid_amount) > 0) {
                    amount = s.amount;
                } else {
                    amount = (shares[pIndex++] || 0) / 100;
                }
                const tr = document.createElement('tr');
                tr.innerHTML = `<td>${s.installment}</td><td>${amount.toFixed(2)}</td><td>${parseFloat(s.paid_amount||0).toFixed(2)}</td><td>${s.paid_at? s.paid_at:'-'}</td><td>${s.due_date? s.due_date:'-'}</td>`;
                tbody.appendChild(tr);
            });
            // adjust months input
            const monthsInput = document.getElementById('loan_months_edit');
            if(monthsInput) monthsInput.value = Math.max(1, parseInt(monthsInput.value||0) - 1);
            rebuildLoanScheduleTable();
            // ensure totals match after remove
            normalizeLoanScheduleTotals();
        });
    } catch(e){ console.warn('Loan month add/remove handlers failed', e); }

    // Attach listeners to downpayment/months visible inputs so changing them re-normalizes pending months
    try {
        function debounce(fn, wait){ let t; return function(){ const args = arguments; clearTimeout(t); t = setTimeout(function(){ fn.apply(null, args); }, wait); }; }
    var downEditEl = document.getElementById('loan_downpayment_edit');
    var monthsEditEl = document.getElementById('loan_months_edit');
    var freqEditEl = document.getElementById('loan_frequency_edit');
    var debouncedNormalize = debounce(function(){ try{ syncHidden(); normalizeLoanScheduleTotals(); }catch(e){ console.warn('normalize failed', e); } }, 250);
    if (downEditEl) downEditEl.addEventListener('input', debouncedNormalize);
    if (monthsEditEl) monthsEditEl.addEventListener('input', debouncedNormalize);
    if (freqEditEl) freqEditEl.addEventListener('change', debouncedNormalize);

        // Run once shortly after load to ensure the schedule matches net total
        setTimeout(function(){ try{ syncHidden(); normalizeLoanScheduleTotals(); }catch(e){} }, 100);
    } catch(e){ console.warn('Failed to attach loan normalize handlers', e); }
});
</script>

<style>
/* Hide spinner buttons from number inputs with no-spinner class */
.no-spinner::-webkit-outer-spin-button,
.no-spinner::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

.no-spinner {
    -moz-appearance: textfield;
}
</style>

<script>
// Handle success modal close button with vanilla JS
document.addEventListener('DOMContentLoaded', function() {
    const successModalCloseBtn = document.querySelector('#successModal [data-bs-dismiss="modal"]');
    if (successModalCloseBtn) {
        successModalCloseBtn.addEventListener('click', function() {
            const modalEl = document.getElementById('successModal');
            try {
                // Prefer Bootstrap API if available
                if (window.bootstrap && typeof bootstrap.Modal !== 'undefined') {
                    const instance = bootstrap.Modal.getInstance(modalEl) || new bootstrap.Modal(modalEl);
                    instance.hide();
                } else {
                    // Fallback: manually hide modal and remove any modal-backdrop elements
                    if (modalEl) {
                        modalEl.classList.remove('show');
                        modalEl.style.display = 'none';
                    }
                    document.body.classList.remove('modal-open');
                    document.querySelectorAll('.modal-backdrop').forEach(function(b){ b.remove(); });
                }
            } catch (e) {
                console.warn('Failed to hide success modal via bootstrap API, falling back to manual removal', e);
                if (modalEl) {
                    modalEl.classList.remove('show');
                    modalEl.style.display = 'none';
                }
                document.body.classList.remove('modal-open');
                document.querySelectorAll('.modal-backdrop').forEach(function(b){ b.remove(); });
            }
            // After hiding the modal, redirect to the invoices index so the user can verify the updated invoice
            try { setTimeout(function(){ window.location.href = <?php echo json_encode(route("invoices.index")); ?>; }, 120); } catch(e) { /* ignore */ }
        });
    }
});

// Also attach handler to OK button by id (fallback) so clicks always work
document.addEventListener('DOMContentLoaded', function(){
    try{
        const ok = document.getElementById('successModalOkBtn');
        if(!ok) return;
        if(ok.__attached) return; // idempotent
        ok.addEventListener('click', function(){
            const modalEl = document.getElementById('successModal');
            try {
                if (window.bootstrap && typeof bootstrap.Modal !== 'undefined') {
                    const instance = bootstrap.Modal.getInstance(modalEl) || new bootstrap.Modal(modalEl);
                    instance.hide();
                } else {
                    if (modalEl) { modalEl.classList.remove('show'); modalEl.style.display = 'none'; }
                    document.body.classList.remove('modal-open');
                    document.querySelectorAll('.modal-backdrop').forEach(b => b.remove());
                }
            } catch(e){
                if (modalEl) { modalEl.classList.remove('show'); modalEl.style.display = 'none'; }
                document.body.classList.remove('modal-open');
                document.querySelectorAll('.modal-backdrop').forEach(b => b.remove());
            }
            try { setTimeout(function(){ window.location.href = <?php echo json_encode(route("invoices.index")); ?>; }, 120); } catch(e){}
        });
        ok.__attached = true;
    }catch(e){ console.warn('Attach success OK handler failed', e); }
});

// Ensure salesman select is initialized on edit page (in case JS manipulations reset it)
document.addEventListener('DOMContentLoaded', function() {
    try {
        const sel = document.querySelector('select[name="salesman_id"]');
    const selectedId = <?php echo json_encode($invoice->salesman_id ?? ''); ?>;
        if (sel && selectedId && selectedId.toString().trim() !== '') {
            sel.value = selectedId;
            // Trigger change event in case other JS listens to it
            const evt = new Event('change', { bubbles: true });
            sel.dispatchEvent(evt);
        }
    } catch(e) { console.warn('Failed to initialize salesman select', e); }
});

// Toggle cash payment row on edit page based on invoice mode (cash vs loan)
document.addEventListener('DOMContentLoaded', function() {
    function toggleCashRowEdit(){
        try {
            const cashRow = document.getElementById('cashPaymentRowEdit');
            const cashInput = document.getElementById('payment_cashpaid');
            const modeLoan = document.getElementById('mode_loan_edit');
            const modeCash = document.getElementById('mode_cash_edit');
            if(!cashRow || !cashInput) return;
            if(modeLoan && modeLoan.checked){
                // Move any existing cash paid into the visible downpayment edit input
                try{
                    const prevCash = parseCurrency(cashInput.value || '0');
                    const downEdit = document.getElementById('loan_downpayment_edit');
                    if(downEdit && prevCash > 0){
                        downEdit.value = prevCash.toFixed(2);
                    }
                    // Ensure hidden canonical fields are synced as well
                    try{ syncHidden(); }catch(e){}
                }catch(e){ /* ignore parse errors */ }

                cashRow.style.display = 'none';
                cashInput.value = '';
                cashInput.removeAttribute('required');
                cashInput.disabled = true;
                try { if (typeof recalc === 'function') recalc(); } catch(e){}
                // If switching to loan mode and there is no schedule, build a default schedule
                try{ ensureLoanScheduleExists(); setTimeout(function(){ try{ normalizeLoanScheduleTotals(); }catch(e){} }, 50); }catch(e){}
            } else if(modeCash && modeCash.checked){
                cashRow.style.display = 'flex';
                cashInput.disabled = false;
                cashInput.setAttribute('required','required');
                // Restore paid so far when switching to cash mode
                if (typeof paidSoFar !== 'undefined' && paidSoFar > 0) {
                    cashInput.value = paidSoFar.toFixed(2);
                }
                try { if (typeof recalc === 'function') recalc(); } catch(e){}
            } else {
                // default to visible for safety
                cashRow.style.display = 'flex';
                cashInput.disabled = false;
                try { if (typeof recalc === 'function') recalc(); } catch(e){}
            }
        } catch(e){ console.warn('toggleCashRowEdit failed', e); }
    }
    // initial
    toggleCashRowEdit();
    // listen for mode changes
    try { document.getElementById('mode_cash_edit')?.addEventListener('change', toggleCashRowEdit); } catch(e){}
    try { document.getElementById('mode_loan_edit')?.addEventListener('change', toggleCashRowEdit); } catch(e){}

    // Ensure cash input changes update balances (call recalc if available)
    try {
        const cashInput = document.getElementById('payment_cashpaid');
        if(cashInput && !cashInput.__editListenerAttached){
            cashInput.addEventListener('input', function(){ try{ if(typeof recalc === 'function') recalc(); }catch(e){} });
            cashInput.__editListenerAttached = true;
        }
    } catch(e) { console.warn('Failed to attach cash input recalc listener on edit page', e); }
});


    // Prevent submitting the edit form when no products are added
    document.addEventListener('DOMContentLoaded', function() {
        try {
            const form = document.getElementById('invoiceForm');
            const saveBtn = document.getElementById('saveInvoice');

            function hasValidItems() {
                try {
                    const tbody = document.querySelector('#itemsTable tbody');
                    if (!tbody) return false;
                    const rows = Array.from(tbody.querySelectorAll('tr'));
                    if (!rows.length) return false;
                    // Consider a row valid if it has a numeric qty > 0 in the third column or qty input
                    for (const r of rows) {
                        try {
                            // Prefer input.item-qty when present
                            const qtyInput = r.querySelector('input.item-qty');
                            let num = 0;
                            if (qtyInput) {
                                num = parseFloat((qtyInput.value || '0').toString().replace(/,/g,'')) || 0;
                            } else {
                                const qtyCell = r.querySelector('td:nth-child(3)');
                                if (!qtyCell) continue;
                                const txt = (qtyCell.innerText || qtyCell.textContent || '').trim();
                                num = parseFloat(txt.replace(/,/g,'')) || 0;
                            }
                            if (num > 0) return true;
                        } catch(e) { continue; }
                    }
                    return false;
                } catch(e){ return false; }
            }

            if (form && !form.__itemsGuardAttached) {
                form.addEventListener('submit', function(e){
                    if (!hasValidItems()) {
                        e.preventDefault();
                        alert('Please add at least one product with quantity greater than zero before updating the invoice.');
                        try { (document.getElementById('product_search') || {}).focus(); } catch(e){}
                        return false;
                    }
                });
                form.__itemsGuardAttached = true;
            }

            // Disable Save button if no items initially
            try {
                if (saveBtn) {
                    saveBtn.disabled = !hasValidItems();
                    // Observe changes to items table to enable/disable button dynamically
                    const tbody = document.querySelector('#itemsTable tbody');
                    if (tbody) {
                        const obs = new MutationObserver(function(){ try { saveBtn.disabled = !hasValidItems(); } catch(e){} });
                        obs.observe(tbody, { childList: true, subtree: true, characterData: true });
                    }
                }
            } catch(e){}
        } catch(e) { console.warn('Items submit guard init failed', e); }
    });
    </script>

    <?php $__env->stopPush(); ?>


<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH D:\ONLINE SYSTEMS ORIGINALS\demo perera\test 06-05-2026\resources\views/invoices/edit.blade.php ENDPATH**/ ?>