@extends('layouts.app')

@section('title', 'Create Invoice')
@section('page-title', 'Create Invoice')

@section('content')
    <div class="card invoice-area">
        <div class="card-body">
            <form method="POST" action="{{ route('invoices.store') }}" id="invoiceForm">
                @csrf

                <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>
                                @php
                                    // Compute next invoice number from existing records (format: INV-001)
                                    $nextInvoiceNumber = 'INV-001';
                                    try {
                                        $numbers = \Illuminate\Support\Facades\DB::table('invoices')->pluck('invoice_number')->filter()->all();
                                        $max = 0;
                                        foreach($numbers as $n) {
                                            if(preg_match('/(\d+)$/', $n, $m)){
                                                $val = intval($m[1]);
                                                if($val > $max) $max = $val;
                                            }
                                        }
                                        $next = $max + 1;
                                        $nextInvoiceNumber = 'INV-'.str_pad($next, 3, '0', STR_PAD_LEFT);
                                    } catch (\Exception $e) {
                                        // fallback already set
                                    }
                                @endphp
                                <input type="text" name="invoice_number" id="invoice_number" class="form-control" value="{{ old('invoice_number', $nextInvoiceNumber) }}" required readonly>
                            </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;">
                                    <div style="display:flex; gap:6px; align-items:center;">
                                        <input type="text" id="customer_search" class="form-control" placeholder="Type customer name to search" autocomplete="off" style="flex:1">
                                        @if(auth()->user() && auth()->user()->hasAccessTo('customers.create'))
                                            <button type="button" id="createCustomerBtn" class="btn btn-outline-primary" title="Create Customer" style="white-space:nowrap; padding: .35rem .6rem;">+</button>
                                        @endif
                                    </div>
                                    <!-- 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). Kept hidden but required; JS will set value when user picks from typable dropdown -->
                                    <select name="customer_id" class="form-select d-none" required>
                                        <option value="" {{ old('customer_id', '') == '' ? 'selected' : '' }}></option>
                                        @foreach($customers as $c)
                                            <option value="{{ $c->id }}" data-contact="{{ $c->contact_number ?? '' }}" data-balance="{{ $c->balance_amount ?? 0 }}">{{ $c->customer_name }}</option>
                                        @endforeach
                                    </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Date & Time</label>
                                <input type="datetime-local" name="date_time" id="date_time" class="form-control" value="{{ old('date_time') }}" required>
                            </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>
                                    @foreach($salesmen as $s)
                                        <option value="{{ $s->id }}" {{ (old('salesman_id') == $s->id) ? 'selected' : '' }}>{{ $s->name }}</option>
                                    @endforeach
                                </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="Please select a customer first" disabled>
                            </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" disabled>
                            </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" disabled>
                            </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; display: none;">Warranty</th>
                                        <th style="background-color: var(--primary-color) !important; color: white !important; display: none;">Cost (Per)</th>
                                        <!-- Market column removed on Create page as requested -->
                                        <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>
                                    <!-- Customer balance info row -->
                                    <tr id="customerBalanceRow" style="display:none; background-color: #fff3cd; font-weight: bold;">
                                        <td colspan="9" style="text-align: center; padding: 12px; border: 2px solid #ffc107;">
                                            <i class="fas fa-info-circle text-warning"></i> 
                                            Previous Balance: Rs. <span id="customerBalanceDisplay">0.00</span>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                       
                        <!-- Bottom quick actions (moved inside left column): Card Payment | Summary | Payments -->
                        <div class="row mt-3">
                            <div class="col-md-4">
                                <div class="card" id="cardPaymentCard" style="display:none">
                                    <div class="card-body" id="cardPaymentSection">
                                        <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">
                                        </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">Bank of Ceylon</option>
                                                <option value="peoples">People's Bank</option>
                                                <option value="commercial">Commercial Bank</option>
                                                <option value="hnb">Hatton National Bank</option>
                                                <option value="sampath">Sampath Bank</option>
                                                <option value="nationstrust">National Trust Bank</option>
                                                <option value="seychelles">Seychelles Banking Corporation</option>
                                                <option value="union">Union Bank</option>
                                                <option value="ndb">National Development Bank</option>
                                                <option value="panasia">Pan Asia Banking Corporation</option>
                                                <option value="cargills">Cargills Bank</option>
                                                <option value="dfcc">DFCC Bank</option>
                                                <option value="lbsl">LankaBangla Finance</option>
                                                <option value="lbfinance">LB Finance</option>
                                                <option value="softlogic">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">Visa</option>
                                                <option value="master">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">
                                        </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 class="d-flex justify-content-between d-none" style="display:none !important"><small>Discount</small><strong id="summary_discount">0.00</strong></div>
                                        <div class="d-flex justify-content-between"><small>Net Total</small><strong id="summary_nettotal">0.00</strong></div>
                                        <div id="cashPaymentRow" class="mb-2">
                                            <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="" 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" class="form-select form-select-sm flex-fill">
                                                    <option value="cash">Cash</option>
                                                    <option value="card">Card</option>
                                                    <option value="bank">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 -->
                            <div class="card mt-3 w-100" id="loanOptionsCard" 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" value="cash" checked>
                                            <label class="form-check-label" for="mode_cash">Cash</label>
                                        </div>
                                        <div class="form-check form-check-inline">
                                            <input class="form-check-input" type="radio" name="invoice_mode" id="mode_preorder" value="preorder">
                                            <label class="form-check-label" for="mode_preorder">Pre Order</label>
                                        </div>
                                        <div class="form-check form-check-inline">
                                            <input class="form-check-input" type="radio" name="invoice_mode" id="mode_loan" value="loan">
                                            <label class="form-check-label" for="mode_loan">Loan / Installments</label>
                                        </div>
                                    </div>

                                    <div id="loanInputs" style="display:none;">
                                        <div class="mb-2 loan-number-row">
                                            <label class="form-label small">Loan Number</label>
                                            <input type="text" id="loan_number_display" class="form-control form-control-sm" readonly value="{{ $nextLoanNumber ?? '' }}">
                                            <input type="hidden" name="loan_number" id="loan_number" value="{{ $nextLoanNumber ?? '' }}">
                                        </div>
                                        <div class="mb-2">
                                            <label class="form-label small">Down Payment (Rs.)</label>
                                            <input type="number" id="loan_downpayment" class="form-control form-control-sm" value="0.00" step="0.01" min="0">
                                        </div>
                                        <div class="mb-2">
                                            <label class="form-label small">Periods</label>
                                            <div class="d-flex gap-2">
                                                <select id="loan_frequency" name="loan_frequency" class="form-select form-select-sm" style="max-width:120px;">
                                                    <option value="month" {{ (old('loan_frequency','month') === 'month') ? 'selected' : '' }}>Month</option>
                                                    <option value="week" {{ (old('loan_frequency','month') === 'week') ? 'selected' : '' }}>Week</option>
                                                </select>
                                                <input type="number" id="loan_months" class="form-control form-control-sm" value="1" step="1" min="1" style="max-width:120px;">
                                            </div>
                                        </div>
                                        <div class="mb-2">
                                            <label class="form-label small">Monthly Amount</label>
                                            <input type="text" id="loan_monthly_amount_display" class="form-control form-control-sm" readonly value="0.00">
                                        </div>
                                        <div class="mb-2">
                                            <label class="form-label small">Schedule Preview</label>
                                            <div class="table-responsive" style="max-height:180px; overflow:auto;">
                                                <table class="table table-sm table-bordered" id="loanScheduleTable">
                                                    <thead><tr><th>Installment #</th><th>Amount (Rs.)</th><th>Due Date</th></tr></thead>
                                                    <tbody></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">Save Invoice</button>
                                            <a href="{{ 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>Branch:</strong> <span id="pd_branch">-</span></p>
                                <p class="mb-1"><strong>Qty on hand:</strong> <span id="pd_qty">-</span></p>
                                <p class="mb-1"><strong>Warranty (Months):</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>

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

                                <!-- Last Bill Details moved here -->
                                <hr class="my-3">
                                <h6 class="card-title mb-2">Last Bill Details</h6>
                                @if(isset($lastInvoice) && $lastInvoice)
                                    <div class="d-flex justify-content-between mb-1"><small class="text-muted">Invoice</small><strong id="last_bill_number">{{ $lastInvoice->invoice_number }}</strong></div>
                                    <div class="d-flex justify-content-between mb-1"><small class="text-muted">Date</small><span id="last_bill_date">{{ $lastInvoice->date_time && $lastInvoice->date_time instanceof \Carbon\Carbon ? $lastInvoice->date_time->format('Y-m-d H:i') : ($lastInvoice->date_time ?: '-') }}</span></div>
                                    @php
                                        $lastTotal = 0; $lastPaid = 0; $lastRemaining = 0;
                                        foreach($lastInvoice->items as $li){ $lastTotal += ($li->selling_price ?? 0) * ($li->qty ?? 0); }
                                        $lastDiscount = $lastInvoice->total_discount ?? 0;
                                        $lastNet = ($lastInvoice->net_total ?? ($lastTotal - $lastDiscount));

                                        // Calculate last paid from remaining balance or installments (transactions table removed)
                                        if (isset($lastInvoice->remaining_balance) && $lastInvoice->remaining_balance !== null) {
                                            $lastRemaining = floatval($lastInvoice->remaining_balance);
                                            $lastPaid = max(0, $lastNet - $lastRemaining);
                                        } else {
                                            // Fallback: calculate from installments
                                            $lastPaid = $lastInvoice->installments ? $lastInvoice->installments->sum('paid_amount') : 0;
                                            $lastRemaining = max(0, $lastNet - $lastPaid);
                                        }
                                    @endphp
                                    <div class="d-flex justify-content-between mb-1"><small class="text-muted">Total</small><strong id="last_bill_total">{{ number_format($lastNet,2) }}</strong></div>
                                    <div class="d-flex justify-content-between mb-1"><small class="text-muted">Paid</small><span id="last_bill_paid">{{ number_format($lastPaid,2) }}</span></div>
                                    <div class="d-flex justify-content-between mb-2"><small class="text-muted">Balance</small><strong id="last_bill_balance">{{ number_format($lastRemaining,2) }}</strong></div>
                                    <div class="d-grid gap-2">
                                        <button type="button" onclick="printLastBillThermal()" class="btn btn-outline-success btn-sm" style="display:none;">🖨️ Print Thermal Receipt</button>
                                        <button type="button" onclick="printLastBillHalf()" class="btn btn-outline-primary btn-sm">📄 Print Half Invoice</button>
                                    </div>
                                    
                                    <!-- Hidden iframes for printing (like show page) -->
                                    <iframe id="last-bill-thermal-frame" style="display:none;"></iframe>
                                    <iframe id="last-bill-half-frame" style="display:none;"></iframe>
                                @else
                                    <div class="text-muted">No previous invoices</div>
                                @endif
                            </div>
                        </div>
                    </div>
                </div>

                <input type="hidden" name="items" id="itemsInput">
                <input type="hidden" id="loan_schedule" name="loan_schedule" value="">
            </form>
        </div>
    </div>
@endsection

<!-- 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 saved successfully!</p>
            </div>
            <div class="modal-footer justify-content-center border-0">
                <button type="button" class="btn btn-success" data-bs-dismiss="modal" id="successModalOkBtn">OK</button>
            </div>
        </div>
    </div>
</div>

@push('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; /* bootstrap-success green */
}
/* keep existing card shadows subtle */
.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 column (4th column) in the items table: header and cells */
#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>
<script>
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;
                for (const r of rows) {
                    // Skip the customer balance info row if present
                    if (r.id === 'customerBalanceRow') continue;
                    try {
                        // Prefer explicit qty input if 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) {
                                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 creating 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();
                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('Create items submit guard init failed', e); }
});
</script>

@endpush

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function(){
    var dateTimeInput = document.getElementById('date_time');
    // Only set default if no old value exists
    if (!dateTimeInput.value) {
        // Set default date/time to current date/time
        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 datetimeValue = y + '-' + m + '-' + d + 'T' + hh + ':' + mm;
        dateTimeInput.value = datetimeValue;
    }
});
</script>
        @php
        // Build a safe JS-ready array of products to inject into the page
        $productsJs = $products->map(function($p){
            return [
                'id' => $p->id,
                'code' => $p->product_code,
                'barcode' => $p->product_barcode,
                'name' => $p->product_name,
                'qty' => $p->qty ?? 0,
                'cost' => $p->total_cost ?? 0,
                'selling' => $p->selling_price ?? 0,
                'market' => $p->market_price ?? 0,
                'warranty_days' => $p->warranty_days ?? 0,
                // expose whether product is active so front-end can lock selling price when needed
                'is_active' => $p->is_active ?? 1,
            ];
        })->values()->all();
      // Build customers JS array (include contact number and balance for search)
      $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();
        // Build prices JS map (product_id => [prices]) if controller provided pricesJs
        $pricesJs = $pricesJs ?? [];
    @endphp

    <script>
        // Ensure a single global PRODUCTS array to avoid duplicate declaration errors
        if (typeof window.PRODUCTS === 'undefined') {
            window.PRODUCTS = @json($productsJs ?? []);
        }

        // Ensure a single global CUSTOMERS array
        if (typeof window.CUSTOMERS === 'undefined') {
            window.CUSTOMERS = @json($customersJs);
        }

    // Debug: log first few customers so we can verify contact numbers are present
    try { console.debug('window.CUSTOMERS injected (first 10):', (window.CUSTOMERS || []).slice(0,10)); } catch(e){}
    try { console.table((window.CUSTOMERS || []).slice(0,20)); } catch(e){}

        if (typeof window.PRICES === 'undefined') {
            window.PRICES = @json($pricesJs ?? []);
        }
    </script>

    <script>
        // Do not show the Market column on the Create Invoice page.
        // The shared JS partial will check this flag and skip creating market cells when false.
        try { window.SHOW_MARKET_IN_ITEMS = false; } catch(e){}
    </script>

    {{-- Reuse the shared invoice JS partial (same as invoices.edit) --}}
    @include('invoices.create_js_partial')

    @php $printId = request()->query('print_id'); @endphp
    <script>
    // Print functions for Last Bill Details (exactly like show page)
    function printLastBillThermal() {
        // Use hidden iframe for printing (like payment collection and show page)
        const iframe = document.getElementById('last-bill-thermal-frame');
    const lastId = {!! json_encode(optional($lastInvoice)->id ?? '') !!};
        if(!lastId) { alert('No last invoice available'); return; }
        
        iframe.src = `${location.origin}/invoices/${lastId}/print`;
        iframe.onload = function() {
            try {
                iframe.contentWindow.print();
            } catch(e) {
                console.error('Print error:', e);
            }
        };
    }


    // Open customer create in popup and refresh when closed
    document.addEventListener('DOMContentLoaded', function(){
        const createBtn = document.getElementById('createCustomerBtn');
        if(!createBtn) return;

        createBtn.addEventListener('click', function(e){
            e.preventDefault();

    // Listen for created customer messages from popup and inject into form without full reload
    window.addEventListener('message', function(e){
        try {
            if(!e.data || e.data.type !== 'customer_created') return;
            var payload = e.data.payload || {};
            if(!payload.success) return;

            var cid = payload.id;
            var cname = payload.name || '';

            // Update hidden select used for form submission
            var sel = document.querySelector('select[name="customer_id"]');
            if(sel) {
                // If option exists, select it; otherwise add option and select
                var existing = sel.querySelector('option[value="'+cid+'"]');
                if(!existing) {
                    var opt = document.createElement('option');
                    opt.value = cid;
                    opt.text = cname;
                    opt.setAttribute('data-contact', '');
                    opt.setAttribute('data-balance', '0');
                    sel.appendChild(opt);
                    existing = opt;
                }
                sel.value = cid;
                // If the shared JS expects CUSTOMERS array, add there too
                try {
                    if(typeof window.CUSTOMERS !== 'undefined') {
                        var found = (window.CUSTOMERS || []).find(function(c){ return c.id == cid; });
                        if(!found) window.CUSTOMERS.push({ id: cid, name: cname, contact: '', balance: 0, nic: '' });
                    }
                } catch(e){}

                // Trigger any UI updates that depend on selected customer (there may be an existing function)
                try { var ev = new Event('change'); sel.dispatchEvent(ev); } catch(e){}
            }

        } catch(err) { console.error('Failed to receive customer from popup', err); }
    }, false);
            // Open centered popup window
            const width = 900; const height = 700;
            const left = (window.screen.width / 2) - (width / 2);
            const top = (window.screen.height / 2) - (height / 2);

            const popup = window.open('{{ route("customers.create", ["popup" => 1]) }}', 'createCustomer', `width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`);
            if(!popup) { alert('Popup blocked. Please allow popups for this site to create a customer.'); return; }

            // Poll until popup is closed, then refresh customers list
            const timer = setInterval(function(){
                if(popup.closed) {
                    clearInterval(timer);
                    // Simple approach: reload the current page so that the customers cache and JS arrays are refreshed.
                    // This ensures the new customer is available in the hidden select and the injected CUSTOMERS array.
                    location.reload();
                }
            }, 500);
        });
    });
    function printLastBillHalf() {
        // Use hidden iframe for printing (like payment collection and show page)
        const iframe = document.getElementById('last-bill-half-frame');
    const lastId = {!! json_encode(optional($lastInvoice)->id ?? '') !!};
        if(!lastId) { alert('No last invoice available'); return; }
        
        iframe.src = `${location.origin}/invoices/${lastId}/print-half`;
        iframe.onload = function() {
            try {
                iframe.contentWindow.print();
            } catch(e) {
                console.error('Print error:', e);
            }
        };
    }

    document.addEventListener('DOMContentLoaded', function(){
    const printId = {!! json_encode($printId ?? '') !!};
        if(printId) {
            // Create hidden iframe for printing (like payment collection)
            const iframe = document.createElement('iframe');
            iframe.style.display = 'none';
            iframe.id = 'invoice-print-frame';
            document.body.appendChild(iframe);
            
            // Load print page in iframe
            iframe.src = `${location.origin}/invoices/${printId}/print`;
            
            // Print when loaded
            iframe.onload = function() {
                try {
                    iframe.contentWindow.print();
                } catch(e) {
                    console.error('Print error:', e);
                }
                // Remove iframe after a delay
                setTimeout(() => {
                    try { document.body.removeChild(iframe); } catch(e){}
                }, 2000);
            };
        }
    });
    </script>

    <script>
    // Show success modal if session success exists (for non-AJAX redirects)
    document.addEventListener('DOMContentLoaded', function() {
        @if(session('success'))
            const modalEl = document.getElementById('successModal');
            document.getElementById('successMessage').textContent = {!! json_encode(session('success')) !!};
            
            // Show modal with vanilla JS
            if (modalEl) {
                modalEl.style.display = 'block';
                modalEl.classList.add('show');
                document.body.classList.add('modal-open');
                
                // Add backdrop
                const backdrop = document.createElement('div');
                backdrop.className = 'modal-backdrop fade show';
                backdrop.id = 'success-modal-backdrop';
                document.body.appendChild(backdrop);
            }
        @endif
        
        // Handle success modal close button
        const successModalOkBtn = document.getElementById('successModalOkBtn');
        if (successModalOkBtn) {
            successModalOkBtn.addEventListener('click', function() {
                const modalEl = document.getElementById('successModal');
                const backdrop = document.getElementById('success-modal-backdrop');
                
                if (modalEl) {
                    modalEl.style.display = 'none';
                    modalEl.classList.remove('show');
                    document.body.classList.remove('modal-open');
                }
                
                if (backdrop) {
                    backdrop.remove();
                }
                
                // Reload create page for next invoice
                window.location.href = {!! json_encode(route("invoices.create")) !!};
            });
        }

        // Last Bill Print Functions
        window.printLastBillThermal = function() {
            @if(isset($lastInvoice) && $lastInvoice)
                const iframe = document.getElementById('last-bill-thermal-frame');
                iframe.src = {!! json_encode(route("invoices.print", $lastInvoice->id)) !!};
                iframe.onload = function() {
                    try {
                        iframe.contentWindow.focus();
                        iframe.contentWindow.print();
                    } catch (e) {
                        console.error('Print failed:', e);
                        alert('Print failed. Please try again.');
                    }
                };
            @endif
        };

        window.printLastBillHalf = function() {
            @if(isset($lastInvoice) && $lastInvoice)
                const iframe = document.getElementById('last-bill-half-frame');
                iframe.src = {!! json_encode(route("invoices.print-half", $lastInvoice->id)) !!};
                iframe.onload = function() {
                    try {
                        iframe.contentWindow.focus();
                        iframe.contentWindow.print();
                    } catch (e) {
                        console.error('Print failed:', e);
                        alert('Print failed. Please try again.');
                    }
                };
            @endif
        };
    });
    </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>
@endpush

@push('scripts')
<script>
// Toggle visibility based on invoice mode and lock mode when products are present for preorders
document.addEventListener('DOMContentLoaded', function(){
    const cashRow = document.getElementById('cashPaymentRow');
    const cashInput = document.getElementById('payment_cashpaid');
    const cardRow = document.getElementById('cardPaymentCard');
    const cardInput = document.getElementById('card_amount');
    const loanInputs = document.getElementById('loanInputs');
    const modeRadios = document.querySelectorAll('input[name="invoice_mode"]');
    const itemsTable = document.getElementById('itemsTable');

    if(!modeRadios || modeRadios.length === 0) return;

    const nextLoanNumber = {!! json_encode($nextLoanNumber ?? '') !!};
    const loanNumberDisplay = document.getElementById('loan_number_display');
    const loanNumberHidden = document.getElementById('loan_number');

    // Helper: count product rows in items table (exclude any special rows like customerBalanceRow)
    function getItemsCount(){
        try {
            const tbody = itemsTable.querySelector('tbody');
            if(!tbody) return 0;
            // Count only rows that represent product lines (assume rows with a remove button or data attribute)
            let count = 0;
            Array.from(tbody.children).forEach(tr => {
                if(tr.id === 'customerBalanceRow') return; // skip
                // skip empty placeholder rows if present
                if(tr.dataset && tr.dataset.placeholder === 'true') return;
                // Treat rows with at least one cell as product row
                if(tr.querySelectorAll('td').length > 0) count += 1;
            });
            return count;
        } catch(e){ return 0; }
    }

    // Lock state: when true we prevent switching away from current mode
    let modeLocked = false;

    function updateModeLock(){
        const items = getItemsCount();
        const checked = document.querySelector('input[name="invoice_mode"]:checked');
        const current = checked ? checked.value : null;

        // Only enforce lock when current mode is 'preorder' and at least one product row exists
        const shouldLock = (current === 'preorder' && items > 0);

        modeLocked = shouldLock;

        modeRadios.forEach(r => {
            // If locked, disable changing other modes; keep the checked radio enabled so form can be submitted
            if(shouldLock){
                if(!r.checked){
                    r.disabled = true;
                } else {
                    r.disabled = false;
                }
            } else {
                r.disabled = false;
            }
        });
    }

    function setMode(mode){
        // Hide all
        if(cashRow) cashRow.style.display = 'none';
        if(cardRow) cardRow.style.display = 'none';
        if(loanInputs) loanInputs.style.display = 'none';
        if(cashInput) { cashInput.disabled = true; cashInput.value = ''; }
        if(cardInput) { cardInput.disabled = true; cardInput.value = ''; }

        if(mode === 'cash'){
            if(cashRow) cashRow.style.display = 'flex';
            if(cashInput) cashInput.disabled = false;
        } else if(mode === 'loan'){
            if(loanInputs) loanInputs.style.display = 'block';
            // populate loan number display and hidden input with the next available loan number
            try {
                if (loanNumberDisplay) loanNumberDisplay.value = nextLoanNumber || '';
                if (loanNumberHidden) loanNumberHidden.value = nextLoanNumber || '';
            } catch(e){}
        } else if (mode === 'preorder') {
            // Pre Order: allow entering a paid amount similar to cash invoices.
            // Show the cash payment row and enable the paid amount input so user can accept partial payments.
            if(cashRow) cashRow.style.display = 'flex';
            if(cashInput) cashInput.disabled = false;
            // Prefer payment_type be 'cash' when entering a paid amount for preorder
            try { const ptype = document.getElementById('payment_type'); if(ptype) ptype.value = 'cash'; } catch(e){}
        }
        // trigger recalc if available to update balance display
        try { if (typeof recalc === 'function') recalc(); } catch(e){}

        // After changing mode, re-evaluate locking state
        updateModeLock();
    }

    // Intercept attempted changes to enforce lock as a fallback (in case some browsers allow click despite disabled)
    modeRadios.forEach(r => {
        r.addEventListener('change', function(e){
            // If locked and trying to change away from the locked checked radio, prevent it
            if(modeLocked){
                // If this radio is not the currently checked one, block change
                const currentlyChecked = document.querySelector('input[name="invoice_mode"]:checked');
                if(currentlyChecked && currentlyChecked.value === 'preorder' && !this.checked){
                    // Revert selection after a microtask so DOM remains consistent
                    e.preventDefault();
                    setTimeout(() => {
                        try { currentlyChecked.checked = true; } catch(_){}
                    }, 0);
                    alert('Cannot change invoice mode after adding products to a Pre Order invoice. Remove all products first to change mode.');
                    return;
                }
            }

            // If not blocked, apply mode normally
            setMode(this.value);
        });
    });

    // initialize based on current selection (or default to 'cash')
    const initial = document.querySelector('input[name="invoice_mode"]:checked');
    setMode(initial ? initial.value : 'cash');

    // Observe items table for changes so we can lock/unlock modes dynamically
    try {
        const tbody = itemsTable.querySelector('tbody');
        if(tbody){
            const mo = new MutationObserver(function(mutations){
                // small debounce via microtask
                Promise.resolve().then(updateModeLock);
            });
            mo.observe(tbody, { childList: true, subtree: false });
        }
    } catch(e){ /* ignore if MutationObserver not supported */ }

    // Add event listener to cash input to update balance in real-time
    if(cashInput) {
        cashInput.addEventListener('input', function() {
            try { if (typeof recalc === 'function') recalc(); } catch(e){}
        });
    }
});
</script>
@endpush
