@extends('layouts.app')

@section('title', 'Pending Payments')
@section('page-title', 'Pending Payments')

@push('styles')
<style>
    #makePaymentModal .modal-content {
        background-color: #343a40; /* Dark background */
        color: #ffffff; /* White text for contrast */
    }
    #makePaymentModal .modal-header {
        border-bottom-color: #495057;
    }
    #makePaymentModal .modal-footer {
        border-top-color: #495057;
    }
    #makePaymentModal .form-label {
        color: #ffffff;
    }
    #makePaymentModal .form-control {
        background-color: #495057;
        border-color: #6c757d;
        color: #ffffff;
    }
    #makePaymentModal .form-control:focus {
        background-color: #495057;
        border-color: #007bff;
        color: #ffffff;
    }
    #makePaymentModal .btn-close {
        filter: invert(1);
    }
    /* Dark style for installment modal */
    #installmentModal {
        /* backdrop handled inline */
    }
    #installmentModal .modal-content,
    #installmentModal > div > div {
        background-color: #343a40 !important;
        color: #ffffff !important;
        border-radius: 8px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.5);
    }
    #installmentModal .modal-header,
    #installmentModal .modal-footer,
    #installmentModal > div > div > div:nth-child(1),
    #installmentModal > div > div > div:nth-child(3) {
        border-color: #495057 !important;
    }
    #installmentModal .table,
    #installmentModal table {
        background: #212529 !important;
        color: #fff !important;
        border-color: #495057 !important;
    }
    #installmentModal .table th,
    #installmentModal .table td {
        border-color: #495057 !important;
        color: #fff !important;
        background: transparent !important;
    }
    #installmentModal .btn-close {
        color: #fff;
        opacity: 1;
    }
    /* Add a white border around the modal inner container to create a visible frame */
    #installmentModal > div,
    #makePaymentModal > div {
        border: 2px solid #ffffff;
    }
</style>
@endpush

@section('content')
    <div class="card">
        <div class="card-body">
            <div class="d-flex justify-content-between mb-3">
                <h5>Pending Invoices</h5>
                <form method="GET" class="d-flex" style="gap:.5rem;">
                    <input name="search" value="{{ old('search', $search ?? '') }}" class="form-control form-control-sm" placeholder="Search invoice or customer">
                    <button class="btn btn-sm btn-primary">Search</button>
                </form>
            </div>

            {{-- Tabs: Pending Invoices | Upcoming Loans --}}
            <ul class="nav nav-tabs mb-3" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="tab-invoices-btn" data-bs-toggle="tab" data-bs-target="#tab-invoices" type="button" role="tab" aria-controls="tab-invoices" aria-selected="true">Pending Invoices</button>
                </li>
                <li class="nav-item" role="presentation" style="display:none;">
                    <button class="nav-link" id="tab-cash-btn" data-bs-toggle="tab" data-bs-target="#tab-cash" type="button" role="tab" aria-controls="tab-cash" aria-selected="false">Pending Cash Invoices</button>
                </li>
                <li class="nav-item" role="presentation" style="display:none;">
                    <button class="nav-link" id="tab-preorder-btn" data-bs-toggle="tab" data-bs-target="#tab-preorder" type="button" role="tab" aria-controls="tab-preorder" aria-selected="false">Pre Orders</button>
                </li>
                <li class="nav-item" role="presentation" style="display:none;">
                    <button class="nav-link" id="tab-upcoming-btn" data-bs-toggle="tab" data-bs-target="#tab-upcoming" type="button" role="tab" aria-controls="tab-upcoming" aria-selected="false">Upcoming Loans</button>
                </li>
                <li class="nav-item" role="presentation" style="display:none;">
                    <button class="nav-link" id="tab-due-btn" data-bs-toggle="tab" data-bs-target="#tab-due" type="button" role="tab" aria-controls="tab-due" aria-selected="false">Due Loans</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="tab-receipts-btn" data-bs-toggle="tab" data-bs-target="#tab-receipts" type="button" role="tab" aria-controls="tab-receipts" aria-selected="false">Receipts</button>
                </li>
            </ul>

            <div class="tab-content">
                <div class="tab-pane fade show active" id="tab-invoices" role="tabpanel" aria-labelledby="tab-invoices-btn">
                    <div class="table-responsive">
                        <table class="table table-striped table-sm">
                            <thead>
                                <tr>
                                    <th>Invoice #</th>
                                    <th>Loan No</th>
                                    <th>Date</th>
                                    <th>Customer</th>
                                    <th>Contact</th>
                                    <th>Mode</th>
                                    <th>Net Total</th>
                                    <th>Remaining</th>
                                    <th></th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($invoices as $inv)
                                    <tr id="inv-row-{{ $inv->id }}">
                                        @php
                                            $downPayment = floatval($inv->down_payment ?? 0);
                                            $allInst = $inv->installments->values();
                                        @endphp
                                        <td>{{ $inv->invoice_number }}</td>
                                        <td>{{ $inv->loan_number ?? '-' }}</td>
                                        <td>
                                            @php
                                                $dt = null;
                                                if($inv->date_time instanceof \Carbon\Carbon) {
                                                    $dt = $inv->date_time->format('Y-m-d H:i');
                                                } elseif (!empty($inv->date_time)) {
                                                    try { $dt = \Carbon\Carbon::parse($inv->date_time)->format('Y-m-d H:i'); } catch (\Exception $e) { $dt = null; }
                                                } elseif ($inv->created_at) {
                                                    $dt = $inv->created_at instanceof \Carbon\Carbon ? $inv->created_at->format('Y-m-d H:i') : (\Carbon\Carbon::parse($inv->created_at)->format('Y-m-d H:i'));
                                                }
                                            @endphp
                                            {{ $dt ?? '-' }}
                                        </td>
                                        <td>{{ $inv->customer ? $inv->customer->customer_name : 'Unknown' }}</td>
                                        <td>{{ $inv->customer ? $inv->customer->contact_number : '-' }}</td>
                                        <td>{{ $inv->invoice_mode ?? '-' }}</td>
                                        <td>{{ number_format($inv->net_total,2) }}</td>
                                        <td class="remaining-col">{{ number_format($inv->remaining_balance ?? 0,2) }}</td>
                                        <td class="text-end">
                                            @if($allInst->count() === 0)
                                                <button class="btn btn-sm btn-success btn-make-payment"
                                                    data-id="{{ $inv->id }}"
                                                    data-invoice-number="{{ $inv->invoice_number }}"
                                                    data-net-total="{{ number_format($inv->net_total ?? 0,2,'.','') }}"
                                                    data-remaining="{{ number_format($inv->remaining_balance ?? 0,2,'.','') }}"
                                                    data-items='@json($inv->items_clean ?? [])'
                                                    data-customer-name="{{ $inv->customer->customer_name ?? '' }}"
                                                    data-customer-contact="{{ $inv->customer->contact_number ?? '' }}"
                                                    data-customer-address="{{ $inv->customer->address ?? '' }}">
                                                    Make Payment
                                                </button>
                                            @else
                                                <small class="text-muted">—</small>
                                            @endif
                                        </td>
                                        <td class="text-end">
                                            @if($allInst->count() > 0)
                                                <button class="btn btn-sm btn-warning btn-pay-installment" 
                                                    data-id="{{ $inv->id }}" 
                                                    data-invoice-number="{{ $inv->invoice_number }}"
                                                    data-installments='@json($allInst)'
                                                    data-items='@json($inv->items_clean ?? [])'
                                                    data-remaining="{{ $inv->remaining_balance ?? 0 }}"
                                                    data-net-total="{{ number_format($inv->net_total ?? 0,2,'.','') }}"
                                                    data-downpayment="{{ number_format($downPayment,2,'.','') }}"
                                                    data-total-paid="{{ number_format($allInst->sum('paid_amount') ?? 0,2,'.','') }}"
                                                    data-loan-frequency="{{ $inv->loan_frequency ?? '' }}"
                                                    data-customer-name="{{ $inv->customer->customer_name ?? '' }}"
                                                    data-customer-contact="{{ $inv->customer->contact_number ?? '' }}"
                                                    data-customer-address="{{ $inv->customer->address ?? '' }}">
                                                    Pay Installment
                                                </button>
                                            @else
                                                <small class="text-muted">No installments</small>
                                            @endif
                                        </td>
                                    </tr>
                                @empty
                                    <tr><td colspan="10" class="text-center text-muted">No pending invoices found</td></tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>

                    <div class="mt-3">{{ $invoices->links() }}</div>
                </div>

                <div class="tab-pane fade" id="tab-cash" role="tabpanel" aria-labelledby="tab-cash-btn">
                    <div class="table-responsive">
                        <table class="table table-striped table-sm">
                            <thead>
                                <tr>
                                    <th>Invoice #</th>
                                    <th>Loan No</th>
                                    <th>Date</th>
                                    <th>Customer</th>
                                    <th>Contact</th>
                                    <th>Mode</th>
                                    <th>Net Total</th>
                                    <th>Remaining</th>
                                    <th></th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($pendingCashInvoices as $inv)
                                    <tr id="inv-row-{{ $inv->id }}">
                                        @php $allInst = $inv->installments->values(); @endphp
                                        <td>{{ $inv->invoice_number }}</td>
                                        <td>{{ $inv->loan_number ?? '-' }}</td>
                                        <td>{{ $inv->date_time instanceof \Carbon\Carbon ? $inv->date_time->format('Y-m-d H:i') : ($inv->date_time ?: '-') }}</td>
                                        <td>{{ $inv->customer ? $inv->customer->customer_name : 'Unknown' }}</td>
                                        <td>{{ $inv->customer ? $inv->customer->contact_number : '-' }}</td>
                                        <td>{{ $inv->invoice_mode ?? '-' }}</td>
                                        <td>{{ number_format($inv->net_total,2) }}</td>
                                        <td class="remaining-col">{{ number_format($inv->remaining_balance ?? 0,2) }}</td>
                                        <td class="text-end">
                                            @if($allInst->count() === 0)
                                                <button class="btn btn-sm btn-success btn-make-payment"
                                                    data-id="{{ $inv->id }}"
                                                    data-invoice-number="{{ $inv->invoice_number }}"
                                                    data-net-total="{{ number_format($inv->net_total ?? 0,2,'.','') }}"
                                                    data-remaining="{{ number_format($inv->remaining_balance ?? 0,2,'.','') }}"
                                                    data-items='@json($inv->items_clean ?? [])'
                                                    data-customer-name="{{ $inv->customer->customer_name ?? '' }}"
                                                    data-customer-contact="{{ $inv->customer->contact_number ?? '' }}"
                                                    data-customer-address="{{ $inv->customer->address ?? '' }}">
                                                    Make Payment
                                                </button>
                                            @else
                                                <small class="text-muted">—</small>
                                            @endif
                                        </td>
                                        <td class="text-end">
                                            @if($allInst->count() > 0)
                                                <button class="btn btn-sm btn-warning btn-pay-installment"
                                                    data-id="{{ $inv->id }}"
                                                    data-invoice-number="{{ $inv->invoice_number }}"
                                                    data-installments='@json($allInst)'
                                                    data-remaining="{{ $inv->remaining_balance ?? 0 }}"
                                                    data-net-total="{{ number_format($inv->net_total ?? 0,2,'.','') }}"
                                                    data-total-paid="{{ number_format($allInst->sum('paid_amount') ?? 0,2,'.','') }}"
                                                    data-loan-frequency="{{ $inv->loan_frequency ?? '' }}"
                                                    data-customer-name="{{ $inv->customer->customer_name ?? '' }}"
                                                    data-customer-contact="{{ $inv->customer->contact_number ?? '' }}"
                                                    data-customer-address="{{ $inv->customer->address ?? '' }}">
                                                    Pay Installment
                                                </button>
                                            @else
                                                <small class="text-muted">No installments</small>
                                            @endif
                                        </td>
                                    </tr>
                                @empty
                                    <tr><td colspan="10" class="text-center text-muted">No pending cash invoices found</td></tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                    <div class="mt-3">@if(isset($pendingCashInvoices)){{ $pendingCashInvoices->links('pagination::bootstrap-5') }}@endif</div>
                </div>

                <div class="tab-pane fade" id="tab-preorder" role="tabpanel" aria-labelledby="tab-preorder-btn">
                    <div class="table-responsive">
                        <table class="table table-striped table-sm">
                            <thead>
                                <tr>
                                    <th>Invoice #</th>
                                    <th>Loan No</th>
                                    <th>Date</th>
                                    <th>Customer</th>
                                    <th>Contact</th>
                                    <th>Mode</th>
                                    <th>Net Total</th>
                                    <th>Remaining</th>
                                    <th></th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($preorderInvoices as $inv)
                                    <tr id="inv-row-{{ $inv->id }}">
                                        @php $allInst = $inv->installments->values(); @endphp
                                        <td>{{ $inv->invoice_number }}</td>
                                        <td>{{ $inv->loan_number ?? '-' }}</td>
                                        <td>{{ $inv->date_time instanceof \Carbon\Carbon ? $inv->date_time->format('Y-m-d H:i') : ($inv->date_time ?: '-') }}</td>
                                        <td>{{ $inv->customer ? $inv->customer->customer_name : 'Unknown' }}</td>
                                        <td>{{ $inv->customer ? $inv->customer->contact_number : '-' }}</td>
                                        <td>{{ $inv->invoice_mode ?? '-' }}</td>
                                        <td>{{ number_format($inv->net_total,2) }}</td>
                                        <td class="remaining-col">{{ number_format($inv->remaining_balance ?? 0,2) }}</td>
                                        <td class="text-end">
                                            @if($allInst->count() === 0)
                                                <button class="btn btn-sm btn-success btn-make-payment"
                                                    data-id="{{ $inv->id }}"
                                                    data-invoice-number="{{ $inv->invoice_number }}"
                                                    data-net-total="{{ number_format($inv->net_total ?? 0,2,'.','') }}"
                                                    data-remaining="{{ number_format($inv->remaining_balance ?? 0,2,'.','') }}"
                                                    data-items='@json($inv->items_clean ?? [])'
                                                    data-customer-name="{{ $inv->customer->customer_name ?? '' }}"
                                                    data-customer-contact="{{ $inv->customer->contact_number ?? '' }}"
                                                    data-customer-address="{{ $inv->customer->address ?? '' }}">
                                                    Make Payment
                                                </button>
                                            @else
                                                <small class="text-muted">—</small>
                                            @endif
                                        </td>
                                        <td class="text-end">
                                            @if($allInst->count() > 0)
                                                <button class="btn btn-sm btn-warning btn-pay-installment"
                                                    data-id="{{ $inv->id }}"
                                                    data-invoice-number="{{ $inv->invoice_number }}"
                                                    data-installments='@json($allInst)'
                                                    data-remaining="{{ $inv->remaining_balance ?? 0 }}"
                                                    data-net-total="{{ number_format($inv->net_total ?? 0,2,'.','') }}"
                                                    data-total-paid="{{ number_format($allInst->sum('paid_amount') ?? 0,2,'.','') }}"
                                                    data-loan-frequency="{{ $inv->loan_frequency ?? '' }}"
                                                    data-customer-name="{{ $inv->customer->customer_name ?? '' }}"
                                                    data-customer-contact="{{ $inv->customer->contact_number ?? '' }}"
                                                    data-customer-address="{{ $inv->customer->address ?? '' }}">
                                                    Pay Installment
                                                </button>
                                            @else
                                                <small class="text-muted">No installments</small>
                                            @endif
                                        </td>
                                    </tr>
                                @empty
                                    <tr><td colspan="10" class="text-center text-muted">No preorders found</td></tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                    <div class="mt-3">@if(isset($preorderInvoices)){{ $preorderInvoices->links('pagination::bootstrap-5') }}@endif</div>
                </div>

                <div class="tab-pane fade" id="tab-upcoming" role="tabpanel" aria-labelledby="tab-upcoming-btn">
                    <div class="table-responsive">
                        <table class="table table-striped table-sm">
                            <thead>
                                <tr>
                                    <th>Invoice #</th>
                                    <th>Loan No</th>
                                    <th>Installment #</th>
                                    <th>Due Date</th>
                                    <th>For Due Days</th>
                                    <th>Amount</th>
                                    <th>Paid</th>
                                    <th>Due</th>
                                    <th>Contact</th>
                                    <th>Customer</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                                @if(isset($upcomingInstallments) && $upcomingInstallments->count())
                                    @foreach($upcomingInstallments as $inst)
                                        @php
                                            $inv = $inst->invoice;
                                            $dueAmt = max(0, floatval($inst->amount) - floatval($inst->paid_amount));
                                            $dueDays = null;
                                            try { $dueDays = \Carbon\Carbon::parse($inst->due_date)->diffInDays(now(), false); } catch(\Exception $e) { $dueDays = null; }
                                        @endphp
                                        <tr>
                                            <td>{{ $inv->invoice_number ?? '-' }}</td>
                                            <td>{{ $inv->loan_number ?? '-' }}</td>
                                            <td>{{ $inst->installment_number }}</td>
                                            <td>{{ $inst->due_date ? (\Carbon\Carbon::parse($inst->due_date)->format('Y-m-d')) : '-' }}</td>
                                            <td>{!! $dueDays !== null ? '<span class="text-success">'.number_format(round($dueDays),0).'</span>' : '-' !!}</td>
                                            <td>{{ number_format($inst->amount,2) }}</td>
                                            <td>{{ number_format($inst->paid_amount ?? 0,2) }}</td>
                                            <td>{{ number_format($dueAmt,2) }}</td>
                                            <td>{{ $inv->customer ? $inv->customer->contact_number : '-' }}</td>
                                            <td>{{ $inv->customer ? $inv->customer->customer_name : 'Unknown' }}</td>
                                            <td class="text-end">
                                                <button class="btn btn-sm btn-warning btn-pay-installment" 
                                                    data-id="{{ $inv->id ?? '' }}"
                                                    data-invoice-number="{{ $inv->invoice_number ?? '' }}"
                                                    data-installments='@json($inv->installments->values() ?? [])'
                                                    data-items='@json($inv->items_clean ?? [])'
                                                    data-remaining="{{ number_format($inv->remaining_balance ?? 0,2,'.','') }}"
                                                    data-net-total="{{ number_format($inv->net_total ?? 0,2,'.','') }}"
                                                    data-downpayment="{{ number_format($inv->down_payment ?? 0,2,'.','') }}"
                                                    data-total-paid="{{ number_format($inv->installments->sum('paid_amount') ?? 0,2,'.','') }}"
                                                    data-loan-frequency="{{ $inv->loan_frequency ?? '' }}"
                                                    data-customer-name="{{ $inv->customer->customer_name ?? '' }}"
                                                    data-customer-contact="{{ $inv->customer->contact_number ?? '' }}"
                                                    data-customer-address="{{ $inv->customer->address ?? '' }}"
                                                    >
                                                    Pay Installment
                                                </button>
                                            </td>
                                        </tr>
                                    @endforeach
                                @else
                                    <tr><td colspan="10" class="text-center text-muted">No upcoming installments found</td></tr>
                                @endif
                            </tbody>
                        </table>
                    </div>
                    <div class="mt-3">@if(isset($upcomingInstallments)){{ $upcomingInstallments->links('pagination::bootstrap-5') }}@endif</div>

                </div>

                <div class="tab-pane fade" id="tab-due" role="tabpanel" aria-labelledby="tab-due-btn">
                    <div class="table-responsive">
                        <table class="table table-striped table-sm">
                            <thead>
                                <tr>
                                    <th>Invoice #</th>
                                    <th>Loan No</th>
                                    <th>Installment #</th>
                                    <th>Due Date</th>
                                    <th>Due Days</th>
                                    <th>Amount</th>
                                    <th>Paid</th>
                                    <th>Due</th>
                                    <th>Contact</th>
                                    <th>Customer</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                                @if(isset($dueInstallments) && $dueInstallments->count())
                                    @foreach($dueInstallments as $inst)
                                        @php
                                            $inv = $inst->invoice;
                                            $dueAmt = max(0, floatval($inst->amount) - floatval($inst->paid_amount));
                                            $dueDays = null;
                                            try { $dueDays = \Carbon\Carbon::parse($inst->due_date)->diffInDays(now(), false); } catch(\Exception $e) { $dueDays = null; }
                                        @endphp
                                        <tr>
                                            <td>{{ $inv->invoice_number ?? '-' }}</td>
                                            <td>{{ $inv->loan_number ?? '-' }}</td>
                                            <td>{{ $inst->installment_number }}</td>
                                            <td>{{ $inst->due_date ? (\Carbon\Carbon::parse($inst->due_date)->format('Y-m-d')) : '-' }}</td>
                                            <td>{!! $dueDays !== null ? '<span class="text-danger">'.number_format(round($dueDays),0).'</span>' : '-' !!}</td>
                                            <td>{{ number_format($inst->amount,2) }}</td>
                                            <td>{{ number_format($inst->paid_amount ?? 0,2) }}</td>
                                            <td>{{ number_format($dueAmt,2) }}</td>
                                            <td>{{ $inv->customer ? $inv->customer->contact_number : '-' }}</td>
                                            <td>{{ $inv->customer ? $inv->customer->customer_name : 'Unknown' }}</td>
                                            <td class="text-end">
                                                <button class="btn btn-sm btn-warning btn-pay-installment" 
                                                    data-id="{{ $inv->id ?? '' }}"
                                                    data-invoice-number="{{ $inv->invoice_number ?? '' }}"
                                                    data-installments='@json($inv->installments->values() ?? [])'
                                                    data-items='@json($inv->items_clean ?? [])'
                                                    data-remaining="{{ number_format($inv->remaining_balance ?? 0,2,'.','') }}"
                                                    data-net-total="{{ number_format($inv->net_total ?? 0,2,'.','') }}"
                                                    data-downpayment="{{ number_format($inv->down_payment ?? 0,2,'.','') }}"
                                                    data-total-paid="{{ number_format($inv->installments->sum('paid_amount') ?? 0,2,'.','') }}"
                                                    data-loan-frequency="{{ $inv->loan_frequency ?? '' }}"
                                                    data-customer-name="{{ $inv->customer->customer_name ?? '' }}"
                                                    data-customer-contact="{{ $inv->customer->contact_number ?? '' }}"
                                                    data-customer-address="{{ $inv->customer->address ?? '' }}"
                                                    >
                                                    Pay Installment
                                                </button>
                                            </td>
                                        </tr>
                                    @endforeach
                                @else
                                    <tr><td colspan="11" class="text-center text-muted">No due installments found</td></tr>
                                @endif
                            </tbody>
                        </table>
                    </div>

                    <div class="mt-3">@if(isset($dueInstallments)){{ $dueInstallments->links('pagination::bootstrap-5') }}@endif</div>
                </div>
                <div class="tab-pane fade" id="tab-receipts" role="tabpanel" aria-labelledby="tab-receipts-btn">
                    <div class="table-responsive">
                        <table class="table table-striped table-sm">
                            <thead>
                                <tr>
                                    <th>Invoice #</th>
                                    <th>Loan No</th>
                                    <th>Date</th>
                                    <th>Customer</th>
                                    <th>Contact</th>
                                    <th>Mode</th>
                                    <th>Net Total</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($allInvoices as $inv)
                                    <tr>
                                        <td>{{ $inv->invoice_number }}</td>
                                        <td>{{ $inv->loan_number ?? '-' }}</td>
                                        <td>
                                            @php
                                                $dt = null;
                                                if($inv->date_time instanceof \Carbon\Carbon) {
                                                    $dt = $inv->date_time->format('Y-m-d H:i');
                                                } elseif (!empty($inv->date_time)) {
                                                    try { $dt = \Carbon\Carbon::parse($inv->date_time)->format('Y-m-d H:i'); } catch (\Exception $e) { $dt = null; }
                                                } elseif ($inv->created_at) {
                                                    $dt = $inv->created_at instanceof \Carbon\Carbon ? $inv->created_at->format('Y-m-d H:i') : (\Carbon\Carbon::parse($inv->created_at)->format('Y-m-d H:i'));
                                                }
                                            @endphp
                                            {{ $dt ?? '-' }}
                                        </td>
                                        <td>{{ $inv->customer ? $inv->customer->customer_name : 'Unknown' }}</td>
                                        <td>{{ $inv->customer ? $inv->customer->contact_number : '-' }}</td>
                                        <td>{{ $inv->invoice_mode ?? '-' }}</td>
                                        <td>{{ number_format($inv->net_total,2) }}</td>
                                        <td class="text-end">
                                            <button class="btn btn-sm btn-primary btn-receipt-print"
                                                data-invoice-id="{{ $inv->id }}"
                                                data-invoice-number="{{ $inv->invoice_number }}"
                                                data-installments='@json($inv->installments->values())'
                                                data-items='@json($inv->items_clean ?? [])'
                                                data-loan-frequency="{{ $inv->loan_frequency ?? '' }}"
                                                data-remaining="{{ $inv->remaining_balance ?? 0 }}"
                                                data-net-total="{{ number_format($inv->net_total ?? 0,2,'.','') }}"
                                                data-downpayment="{{ number_format($inv->down_payment ?? 0,2,'.','') }}"
                                                data-total-paid="{{ number_format($inv->installments->sum('paid_amount') ?? 0,2,'.','') }}"
                                                data-customer-name="{{ $inv->customer->customer_name ?? '' }}"
                                                data-customer-contact="{{ $inv->customer->contact_number ?? '' }}"
                                                data-customer-address="{{ $inv->customer->address ?? '' }}"
                                                data-print-url="{{ route('invoices.print', $inv->id) }}">
                                                Receipt Print
                                            </button>
                                        </td>
                                    </tr>
                                @empty
                                    <tr><td colspan="8" class="text-center text-muted">No invoices available for receipts</td></tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                    <div class="mt-3">{{ $allInvoices->links() }}</div>
                </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Make Payment Modal - Pure Vanilla JS Implementation -->
    <div id="makePaymentModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.7); z-index:9999; overflow:auto;">
        <div style="margin:50px auto; max-width:600px; background:#343a40; border-radius:8px; color:#fff; box-shadow:0 4px 20px rgba(0,0,0,0.5);">
            <div style="padding:20px; border-bottom:1px solid #495057; display:flex; justify-content:space-between; align-items:center;">
                <div>
                    <h5 style="margin:0;">Apply Payment <span id="mpInvoiceNumber"></span></h5>
                    <div style="color:#ced4da; font-size:0.9rem; margin-top:6px;">
                        <span id="mpNetTotal">&nbsp;</span>
                        <span id="mpRemaining" style="margin-left:12px;">&nbsp;</span>
                    </div>
                </div>
                <button id="mpCloseBtn" style="background:none; border:none; color:#fff; font-size:24px; cursor:pointer; padding:0; width:30px; height:30px;">&times;</button>
            </div>
            <div style="padding:20px;">
                <form id="makePaymentForm">
                    <input type="hidden" id="mpInvoiceId" name="invoice_id">
                    <div style="margin-bottom:15px;">
                        <label style="display:block; margin-bottom:8px; color:#fff;">Payments</label>
                        <div style="overflow-x:auto;">
                            <table id="mpPaymentsTable" style="width:100%; background:#212529; border-collapse:collapse;">
                                <thead>
                                    <tr style="border-bottom:1px solid #495057;">
                                        <th style="padding:8px; text-align:left;">Amount</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr class="mp-row">
                                        <td style="padding:8px;">
                                            <select class="form-select form-select-sm mp-payment-type" style="background:#495057; color:#fff; border:1px solid #6c757d; margin-bottom:6px;">
                                                <option value="cash">Cash</option>
                                                <option value="card">Card</option>
                                                <option value="bank">Bank</option>
                                            </select>
                                            <input type="number" step="0.01" class="form-control form-control-sm mp-amount" style="width:100%; padding:6px; background:#495057; border:1px solid #6c757d; color:#fff; border-radius:4px;">
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </form>
                <div id="mpAlert" class="alert d-none" role="alert" style="margin-top:15px; padding:12px; border-radius:4px;"></div>
            </div>
            <div style="padding:20px; border-top:1px solid #495057; display:flex; justify-content:flex-end; gap:10px;">
                <button type="button" id="mpCancelBtn" class="btn btn-secondary">Close</button>
                <button type="button" id="mpSubmit" class="btn btn-primary">Apply Payment</button>
            </div>
        </div>
    </div>
    
    <!-- Installment Modal -->
    <div id="installmentModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.7); z-index:10000; overflow:auto;">
        <div style="margin:70px auto; max-width:700px; background:#343a40; border-radius:8px; color:#fff; box-shadow:0 4px 20px rgba(0,0,0,0.5);">
            <div style="padding:16px; border-bottom:1px solid #495057; display:flex; justify-content:space-between; align-items:center;">
                <div style="display:flex; align-items:center; gap:12px;">
                    <div>
                        <h5 style="margin:0;">Installments <span id="instInvoiceNumber"></span></h5>
                    </div>
                    <div style="display:flex; flex-direction:column; color:#ced4da; font-size:0.9rem;">
                        <div id="instRemaining">&nbsp;</div>
                        <div id="instNetTotal" style="margin-top:3px;">&nbsp;</div>
                        <div id="instDownPayment" style="margin-top:3px;">&nbsp;</div>
                        <div id="instTotalPaid" style="margin-top:3px;">&nbsp;</div>
                    </div>
                </div>
                <button id="instCloseBtn" style="background:none; border:none; font-size:24px; cursor:pointer; padding:0; width:30px; height:30px; color:#fff;">&times;</button>
            </div>
            <div style="padding:16px;">
                <div style="overflow:auto; max-height:360px;">
                    <table id="instTable" class="table table-sm table-bordered">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Scheduled</th>
                                <th>Paid</th>
                                <th>Due</th>
                                <th>Status</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
                <div id="instAlert" class="alert d-none mt-2"></div>
            </div>
            <div style="padding:12px; border-top:1px solid #495057; display:flex; justify-content:space-between; gap:10px;">
                <button id="instPrintBtn" class="btn btn-info">
                    <i class="bi bi-printer"></i> Print Receipt
                </button>
                <button id="instCancelBtn" class="btn btn-secondary">Close</button>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    'use strict';
    
    const modal = document.getElementById('makePaymentModal');
    const closeBtn = document.getElementById('mpCloseBtn');
    const cancelBtn = document.getElementById('mpCancelBtn');
    const submitBtn = document.getElementById('mpSubmit');
    
    if (!modal || !closeBtn || !cancelBtn || !submitBtn) {
        console.error('Modal elements not found');
        return;
    }
    
    // Open modal function (made more robust to support repeated opens)
    function openModal(invoiceId, invoiceNumber, netTotal, remaining, items, customerName, customerContact, customerAddress) {
        // Re-query required elements each time to avoid stale references
        const modalEl = document.getElementById('makePaymentModal');
        const idInput = document.getElementById('mpInvoiceId');
        const numText = document.getElementById('mpInvoiceNumber');
        let alertEl = document.getElementById('mpAlert');
        const table = document.getElementById('mpPaymentsTable');

        if (!modalEl || !idInput || !numText || !table) {
            console.error('openModal: required modal elements missing', { modal: !!modalEl, idInput: !!idInput, numText: !!numText, table: !!table });
            if (alertEl) {
                alertEl.textContent = 'Modal error. Please refresh the page.';
                alertEl.className = 'alert alert-danger';
            } else {
                alert('Modal error. Please refresh the page.');
            }
            return;
        }

        // Ensure an alert element exists inside the modal body
        if (!alertEl) {
            try {
                alertEl = document.createElement('div');
                alertEl.id = 'mpAlert';
                alertEl.className = 'alert d-none';
                alertEl.setAttribute('role', 'alert');
                const modalBody = modalEl.querySelector('div > div > div:nth-child(2)');
                if (modalBody) modalBody.appendChild(alertEl);
            } catch (e) {
                // ignore - we'll still proceed if other elements exist
            }
        }

        // Set invoice data
        idInput.value = invoiceId;
        numText.textContent = invoiceNumber;

    // Populate Net Total and Remaining if provided
        const mpNetEl = document.getElementById('mpNetTotal');
        const mpRemEl = document.getElementById('mpRemaining');
        if (mpNetEl) {
            if (typeof netTotal !== 'undefined' && netTotal !== null && netTotal !== '') {
                mpNetEl.textContent = 'Net Total: Rs. ' + (parseFloat(netTotal) || 0).toFixed(2);
            } else { mpNetEl.textContent = ''; }
        }
        if (mpRemEl) {
            if (typeof remaining !== 'undefined' && remaining !== null && remaining !== '') {
                // Prefer using the raw numeric remaining value passed in (no formatting) so parsing is reliable
                const parsedRem = (typeof remaining === 'number') ? remaining : parseFloat(String(remaining).replace(/,/g, '')) || 0;
                mpRemEl.textContent = 'Remaining: Rs. ' + (parsedRem).toFixed(2);
                // store reliable numeric remaining on modal dataset for validation later
                try { modalEl.dataset.remainingValue = String(parsedRem); } catch(e){}
            } else { mpRemEl.textContent = ''; modalEl.dataset.remainingValue = ''; }
        }

    // Render invoice product details (if items passed)
        try {
            let productsContainer = document.getElementById('mpProducts');
            if (!productsContainer) {
                productsContainer = document.createElement('div');
                productsContainer.id = 'mpProducts';
                productsContainer.style.margin = '12px';
                // insert before the payments table
                const table = document.getElementById('mpPaymentsTable');
                if (table && table.parentNode) table.parentNode.parentNode.insertBefore(productsContainer, table.parentNode);
                else modalEl.querySelector('div')?.appendChild(productsContainer);
            }

            if (!Array.isArray(items) || items.length === 0) {
                productsContainer.innerHTML = '<div class="text-muted small">No product details available</div>';
            } else {
                let html = '<div class="table-responsive"><table class="table table-sm table-bordered"><thead><tr><th>Product</th><th>Code</th><th class="text-end">Qty</th><th class="text-end">Selling</th><th class="text-end">Total</th></tr></thead><tbody>';
                items.forEach(it => {
                    const name = it.product_name || it.name || it.item_name || (it.item ? it.item.product_name : '');
                    const code = it.product_code || it.code || (it.item ? it.item.product_code : '');
                    const qty = parseFloat(it.qty || it.quantity || 0) || 0;
                    const sell = parseFloat(it.selling_price || it.selling || 0) || 0;
                    const total = parseFloat(it.total_value || (qty * sell) || 0) || 0;
                    html += '<tr>'+
                        '<td>'+ (name || '-') +'</td>'+ 
                        '<td>'+ (code || '-') +'</td>'+ 
                        '<td class="text-end">'+ qty.toFixed(3).replace(/\.000$/,'') +'</td>'+ 
                        '<td class="text-end">'+ sell.toFixed(2) +'</td>'+ 
                        '<td class="text-end">'+ total.toFixed(2) +'</td>'+ 
                    '</tr>';
                });
                html += '</tbody></table></div>';
                productsContainer.innerHTML = html;
            }
        } catch(e) {
            console.warn('Failed to render invoice products in payment modal', e);
        }

        // Render customer details (if provided)
        try {
            let custContainer = document.getElementById('mpCustomer');
            if (!custContainer) {
                custContainer = document.createElement('div');
                custContainer.id = 'mpCustomer';
                custContainer.style.marginTop = '8px';
                custContainer.style.color = '#ced4da';
                custContainer.style.fontSize = '0.9rem';
                // Insert under the header details (mpNetTotal/mpRemaining)
                const headerRight = document.getElementById('mpNetTotal')?.parentNode || document.getElementById('mpNetTotal');
                if (headerRight && headerRight.parentNode) headerRight.parentNode.appendChild(custContainer);
                else modalEl.querySelector('div')?.appendChild(custContainer);
            }
            const nameHtml = '<div><strong>Customer:</strong> ' + (customerName ? customerName : '-') + '</div>';
            const contactHtml = customerContact ? '<div><strong>Contact:</strong> ' + customerContact + '</div>' : '';
            const addrHtml = customerAddress ? '<div><strong>Address:</strong> ' + customerAddress + '</div>' : '';
            custContainer.innerHTML = nameHtml + contactHtml + addrHtml;
        } catch(e) {
            console.warn('Failed to render customer details in make payment modal', e);
        }

        // Hide alert
        alertEl.className = 'alert d-none';
        alertEl.textContent = '';

        // Reset table to single empty row
        const tbody = table.querySelector('tbody');
        if (tbody) {
            tbody.innerHTML = '<tr class="mp-row">' +
                '<td style="padding:8px;">' +
                    '<select class="form-select form-select-sm mp-payment-type" style="background:#495057; color:#fff; border:1px solid #6c757d; margin-bottom:6px;">' +
                        '<option value="cash">Cash</option>' +
                        '<option value="card">Card</option>' +
                        '<option value="bank">Bank</option>' +
                    '</select>' +
                    '<input type="number" step="0.01" class="form-control form-control-sm mp-amount" style="width:100%; padding:6px; background:#495057; border:1px solid #6c757d; color:#fff; border-radius:4px;">' +
                '</td>' +
                '</tr>';
        }

        // Show modal
        modalEl.style.display = 'block';
        document.body.style.overflow = 'hidden';
    }
    
    // Close modal function
    function closeModal() {
        // Simply hide modal and restore scrolling. Do not force a reload here.
        // The page will reload after a successful payment; forcing reload on close
        // prevented re-opening the modal reliably in some flows.
        modal.style.display = 'none';
        document.body.style.overflow = '';
    }
    
    // Submit payment function
    async function submitPayment() {
        // Re-query elements to avoid stale references
        const idInput = document.getElementById('mpInvoiceId');
        let alertEl = document.getElementById('mpAlert');
        const table = document.getElementById('mpPaymentsTable');
        const submitBtn = document.getElementById('mpSubmit');

        // If alert element is missing, try to create a simple one inside the modal
        if (!alertEl && document.getElementById('makePaymentModal')) {
            try {
                alertEl = document.createElement('div');
                alertEl.id = 'mpAlert';
                alertEl.className = 'alert d-none';
                alertEl.setAttribute('role', 'alert');
                const modalBody = document.querySelector('#makePaymentModal div > div > div:nth-child(2)');
                if (modalBody) modalBody.appendChild(alertEl);
            } catch (e) {
                // ignore
            }
        }

        if (!idInput || !alertEl || !table || !submitBtn) {
            console.error('submitPayment: required elements missing', { idInput: !!idInput, alertEl: !!alertEl, table: !!table, submitBtn: !!submitBtn });
            // Show a helpful message to the user inside the modal if possible
            if (alertEl) {
                alertEl.textContent = 'Error: Required elements not found. Please refresh the page and try again.';
                alertEl.className = 'alert alert-danger';
            } else {
                // Fallback to alert
                alert('Error: Required elements not found. Please refresh the page and try again.');
            }
            return;
        }

        const invoiceId = idInput.value;
        if (!invoiceId) {
            return;
        }

        // Collect payment data
        const rows = table.querySelectorAll('tbody tr.mp-row');
        const payments = [];
        
        rows.forEach(row => {
            const amountEl = row.querySelector('.mp-amount');
            
            if (!amountEl) return;
            
            const amount = parseFloat(amountEl.value) || 0;
            if (amount > 0) {
                // get per-row payment type (select above the amount input)
                let ptype = 'cash';
                try { const psel = row.querySelector('.mp-payment-type'); if (psel && psel.value) ptype = psel.value; } catch(e) {}
                payments.push({
                    payment_type: ptype || 'cash',
                    remark: '',
                    amount: amount
                });
            }
        });
        
        if (payments.length === 0) {
            alertEl.textContent = 'Please enter an amount.';
            alertEl.className = 'alert alert-warning';
            return;
        }

        // Validate against remaining balance (if available). Use the numeric value saved on modal.dataset if present
        let remainingVal = null;
        try {
            const modalEl = document.getElementById('makePaymentModal');
            if (modalEl && typeof modalEl.dataset.remainingValue !== 'undefined' && modalEl.dataset.remainingValue !== '') {
                remainingVal = parseFloat(modalEl.dataset.remainingValue) || 0;
            } else {
                const remEl = document.getElementById('mpRemaining');
                if (remEl && remEl.textContent) {
                    // mpRemaining text is like 'Remaining: Rs. 123.45'
                    const num = remEl.textContent.replace(/[^0-9.\-]/g, '');
                    if (num !== '') remainingVal = parseFloat(num) || 0;
                }
            }
        } catch (e) { remainingVal = null; }

        const totalPayments = payments.reduce((s,p) => s + (parseFloat(p.amount) || 0), 0);
        if (remainingVal !== null) {
            // If remaining balance is zero, disallow adding any payments
            if (remainingVal <= 0) {
                alertEl.textContent = 'This invoice has no remaining balance.';
                alertEl.className = 'alert alert-warning';
                return;
            }
            // Do not allow total payments to exceed remaining balance
            if (totalPayments > remainingVal + 0.0001) {
                alertEl.textContent = 'Total payment cannot exceed the remaining balance (Rs. ' + remainingVal.toFixed(2) + ').';
                alertEl.className = 'alert alert-warning';
                return;
            }
        }
        
        // Disable button
        submitBtn.disabled = true;
        submitBtn.textContent = 'Saving...';
        
        try {
            const token = document.querySelector('meta[name="csrf-token"]').content;
            const formData = new FormData();
            formData.append('payments', JSON.stringify(payments));
            formData.append('_token', token);
            
            const response = await fetch('/invoices/' + invoiceId + '/make-payment', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });
            
            const result = await response.json();
            
            if (result.success) {
                window.location.reload();
            } else {
                throw new Error(result.message || 'Payment failed');
            }
        } catch (error) {
            alertEl.textContent = error.message || 'An error occurred';
            alertEl.className = 'alert alert-danger';
            submitBtn.disabled = false;
            submitBtn.textContent = 'Apply Payment';
        }
    }
    
    // Event listeners
    if (closeBtn) closeBtn.addEventListener('click', closeModal);
    if (cancelBtn) cancelBtn.addEventListener('click', closeModal);
    if (submitBtn) submitBtn.addEventListener('click', submitPayment);
    
    // Click outside modal to close
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            closeModal();
        }
    });

    // Receipt print button handler: prefer the installment-modal receipt if installments exist
    document.addEventListener('click', function(e) {
        const btn = e.target.closest && e.target.closest('.btn-receipt-print');
        if (!btn) return;
        e.preventDefault();
        // Try to read installments data
        let rawInst = btn.getAttribute('data-installments') || '[]';
        let instArr = [];
        try { instArr = JSON.parse(rawInst); } catch (er) { instArr = []; }
        const itemsRaw = btn.getAttribute('data-items') || '[]';
        let itemsArr = [];
        try { itemsArr = JSON.parse(itemsRaw); } catch (er) { itemsArr = []; }

        // helper to open print page fallback
        const openPrintPage = () => {
            const url = btn.getAttribute('data-print-url');
            if (!url) return alert('Print URL not available');
            window.open(url, '_blank');
        };

        if (Array.isArray(instArr) && instArr.length > 0) {
            // Use the existing openInstallmentModal to populate the modal and then auto-print
            const invoiceId = btn.getAttribute('data-invoice-id');
            const invoiceNumber = btn.getAttribute('data-invoice-number') || '';
            const loanFrequency = btn.getAttribute('data-loan-frequency') || null;
            const remaining = btn.getAttribute('data-remaining') || null;
            const netTotal = btn.getAttribute('data-net-total') || null;
            const downPayment = btn.getAttribute('data-downpayment') || null;
            const totalPaid = btn.getAttribute('data-total-paid') || null;
            const customerName = btn.getAttribute('data-customer-name') || '';
            const customerContact = btn.getAttribute('data-customer-contact') || '';
            const customerAddress = btn.getAttribute('data-customer-address') || '';

            // openInstallmentModal is defined below in the script; call it to populate and show modal
            try {
                openInstallmentModal(invoiceId, invoiceNumber, instArr, remaining, netTotal, downPayment, totalPaid, itemsArr, customerName, customerContact, customerAddress, loanFrequency);
                // Wait a short moment for modal content to be rendered, then call print
                setTimeout(() => {
                    // This will generate the same receipt used by the Pay Installment modal
                    printInstallmentReceipt();
                }, 300);
            } catch (err) {
                console.warn('Failed to open installment modal for printing, falling back to print page', err);
                openPrintPage();
            }
        } else {
            // No installments - print a cash invoice receipt in A5 format using client-side template
            try {
                printCashReceipt(btn);
            } catch (err) {
                console.warn('Failed to print cash receipt client-side, opening print page', err);
                openPrintPage();
            }
        }
    });

    // Print a cash invoice receipt in A5 landscape (210mm x 148mm) — upgraded professional layout
    function printCashReceipt(btn) {
        if (!btn) return;
        const invoiceNumber = btn.getAttribute('data-invoice-number') || '';
        const customerName = btn.getAttribute('data-customer-name') || '';
        const customerContact = btn.getAttribute('data-customer-contact') || '';
        const customerAddress = btn.getAttribute('data-customer-address') || '';
        const netTotal = btn.getAttribute('data-net-total') || '';
        const remaining = btn.getAttribute('data-remaining');
        const downPayment = btn.getAttribute('data-downpayment');
        const itemsRaw = btn.getAttribute('data-items') || '[]';
        let items = [];
        try { items = JSON.parse(itemsRaw); } catch(e) { items = []; }

        const printWindow = window.open('', '_blank');
        const printDoc = printWindow.document;

        const css = `
            *{box-sizing:border-box;margin:0;padding:0}
            html,body{width:210mm;height:148mm}
            body{font-family: Arial, Helvetica, sans-serif; font-size:14px; color:#111}
            .receipt{width:100%;height:100%;padding:8mm;display:flex;flex-direction:column}

            .header{display:flex;align-items:center;gap:8px;margin-bottom:8px}
            .company{flex:1}
            .company .name{font-size:24px;font-weight:900}
            .company .meta{font-size:14px;color:#444}
            .receipt-title{font-size:18px;font-weight:900;text-align:right}

            .info{display:flex;gap:12px;margin:10px 0;font-size:14px}
            .info .left{flex:1}
            .info .right{text-align:right;min-width:160px}
            .info-row{margin-bottom:3px}

            table{width:100%;border-collapse:collapse;margin-top:6px}
            thead th{font-size:13px;text-align:left;padding:10px 12px;border-bottom:2px solid #333}
            tbody td{padding:10px 12px;border-bottom:1px solid #eee;font-size:12px}
            tbody tr:nth-child(even){background:#fbfbfb}
            .text-right{text-align:right}

            .summary{margin-top:10px;display:flex;flex-direction:column;gap:8px}
            .summary .row{display:flex;justify-content:space-between;font-weight:800;font-size:16px}
            .summary .total{border-top:2px solid #111;padding-top:6px;margin-top:4px}

            .signatures{display:flex;justify-content:space-between;margin-top:8px;gap:12px}
            .sig{flex:1;border-top:1px dashed #999;padding-top:10px;text-align:center;font-size:13px;color:#333}

            .footer{margin-top:8px;text-align:center;font-size:11px;color:#666}

            @media print{html,body{width:210mm;height:148mm}body{padding:0}.receipt{padding:4mm}}
        `;

        function fmt(n){
            n = parseFloat(String(n||0).replace(/,/g,'')) || 0;
            return n.toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2});
        }

        // Build rows
        let itemsHtml = '';
        if (Array.isArray(items) && items.length){
            items.forEach((it, idx)=>{
                const name = it.product_name || it.name || it.item_name || (it.item ? it.item.product_name : '-');
                const code = it.product_code || it.code || (it.item ? it.item.product_code : '-');
                const qty = parseFloat(it.qty || it.quantity || it.qty_sold || 0) || 0;
                const price = parseFloat(it.selling_price || it.selling || it.price || 0) || 0;
                const total = parseFloat(it.total_value || (qty*price) || 0) || 0;
                itemsHtml += `<tr>`+
                    `<td class="col-product">${escapeHtml(name)}</td>`+
                    `<td class="col-code">${escapeHtml(code)}</td>`+
                    `<td class="text-right">${qty}</td>`+
                    `<td class="text-right">${fmt(price)}</td>`+
                    `<td class="text-right">${fmt(total)}</td>`+
                `</tr>`;
            });
        } else {
            itemsHtml = `<tr><td colspan="5" style="text-align:center;color:#888;padding:8px">No items</td></tr>`;
        }

    const netTotalVal = parseFloat(String(netTotal).replace(/,/g,''))||0;
    const remainingVal = (typeof remaining!=='undefined' && remaining!==null) ? parseFloat(String(remaining).replace(/,/g,''))||0 : 0;
    const downVal = (typeof downPayment!=='undefined' && downPayment!==null) ? parseFloat(String(downPayment).replace(/,/g,''))||0 : 0;
    // Total Paid = Net Total - Down Payment - Remaining
    const paidVal = Math.max(0, netTotalVal - downVal - remainingVal);


        const html = `
            <!doctype html>
            <html>
            <head>
                <meta charset="utf-8">
                <title>Receipt ${escapeHtml(invoiceNumber)}</title>
                <style>${css}</style>
            </head>
            <body>
                <div class="receipt">
                    <div class="header">
                        <div class="company">
                            <div class="name">PERERA AND SONS ENTERPRISES (PVT) LTD</div>
                            <div class="meta">No. 89/B, Nattandiya Road, Dankotuwa • Tel: 074 099 775 | 074 130 2500</div>
                        </div>
                        <div class="receipt-title">CASH INVOICE RECEIPT</div>
                    </div>

                    <div class="info">
                        <div class="left">
                            <div class="info-row"><strong>Invoice:</strong> ${escapeHtml(invoiceNumber)}</div>
                            <div class="info-row"><strong>Customer:</strong> ${escapeHtml(customerName || '-')}</div>
                            ${customerAddress ? '<div class="info-row"><strong>Address:</strong> '+escapeHtml(customerAddress)+'</div>' : ''}
                        </div>
                        <div class="right">
                            <div class="info-row"><strong>Date:</strong> ${new Date().toLocaleString()}</div>
                            <div class="info-row"><strong>Contact:</strong> ${escapeHtml(customerContact || '-')}</div>
                        </div>
                    </div>

                    <table>
                        <thead>
                            <tr>
                                <th class="col-product">Product</th>
                                <th class="col-code">Code</th>
                                <th class="col-qty">Qty</th>
                                <th class="col-price text-right">Price</th>
                                <th class="col-total text-right">Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${itemsHtml}
                        </tbody>
                    </table>

                    <div class="summary">
                        <div class="row"><span>Net Total</span><span>Rs. ${fmt(netTotalVal)}</span></div>
                        ${downVal>0?`<div class="row"><span>Advanced Payment</span><span>Rs. ${fmt(downVal)}</span></div>`:''}
                        <div class="row total"><span>Total Paid</span><span>Rs. ${fmt(paidVal)}</span></div>
                        <div class="row"><span>Balance Due</span><span>Rs. ${fmt(remainingVal)}</span></div>
                    </div>

                    <div class="signatures">
                        <div class="sig">Receiver's Signature</div>
                        <div class="sig">Authorized Signature</div>
                    </div>

                    <div>
                        <div class="footer">Thank you for your business • For returns contact within 7 days</div>
                        <div class="footer" style="margin-top:4px">Printed: ${new Date().toLocaleString()}</div>
                    </div>
                </div>
            </body>
            </html>
        `;

        printDoc.open();
        printDoc.write(html);
        printDoc.close();

        setTimeout(()=>{
            try{ printWindow.print(); }catch(e){ console.warn('print failed',e); }
        },300);
    }

    // Simple HTML escape for values inserted into the print window
    function escapeHtml(str) {
        if (typeof str !== 'string') return String(str || '');
        return str.replace(/[&<>"'`]/g, function(match) {
            return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;','`':'&#96;'}[match]);
        });
    }
    
    // Make payment button clicks
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('btn-make-payment')) {
            e.preventDefault();
            const id = e.target.getAttribute('data-id');
            const number = e.target.getAttribute('data-invoice-number');
            const netTotal = e.target.getAttribute('data-net-total') || null;
            const remaining = e.target.getAttribute('data-remaining') || null;
            const rawItems = e.target.getAttribute('data-items') || '[]';
            const customerName = e.target.getAttribute('data-customer-name') || '';
            const customerContact = e.target.getAttribute('data-customer-contact') || '';
            const customerAddress = e.target.getAttribute('data-customer-address') || '';
            let itemsArr = [];
            try { itemsArr = JSON.parse(rawItems); } catch(err) { itemsArr = []; }
            if (id && number) {
                openModal(id, number, netTotal, remaining, itemsArr, customerName, customerContact, customerAddress);
            }
        }
            if (e.target.classList.contains('btn-pay-installment')) {
            e.preventDefault();
            const id = e.target.getAttribute('data-id');
            const number = e.target.getAttribute('data-invoice-number');
            const raw = e.target.getAttribute('data-installments') || '[]';
            const rawItems = e.target.getAttribute('data-items') || '[]';
                const loanFrequency = e.target.getAttribute('data-loan-frequency') || null;
            const remaining = e.target.getAttribute('data-remaining') || null;
            const netTotal = e.target.getAttribute('data-net-total') || null;
            const downPayment = e.target.getAttribute('data-downpayment') || null;
            const totalPaid = e.target.getAttribute('data-total-paid') || null;
            const customerName = e.target.getAttribute('data-customer-name') || '';
            const customerContact = e.target.getAttribute('data-customer-contact') || '';
            const customerAddress = e.target.getAttribute('data-customer-address') || '';
            let arr = [];
            let itemsArr = [];
            try { arr = JSON.parse(raw); } catch(e){ arr = []; }
            try { itemsArr = JSON.parse(rawItems); } catch(e){ itemsArr = []; }
            openInstallmentModal(id, number, arr, remaining, netTotal, downPayment, totalPaid, itemsArr, customerName, customerContact, customerAddress, loanFrequency);
        }
    });
    
    // ESC key to close
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && modal.style.display === 'block') {
            closeModal();
        }
        // close installment modal with ESC as well
        const instModal = document.getElementById('installmentModal');
        if (e.key === 'Escape' && instModal && instModal.style.display === 'block') {
            instModal.style.display = 'none';
        }
    });
    
    // Attach handlers for Pay buttons in the installment modal
    function attachInstPayHandlers() {
        const instAlert = document.getElementById('instAlert');
        document.querySelectorAll('.btn-inst-pay').forEach(btn => {
            if (btn.dataset.instAttached) return; // avoid double attaching
            btn.dataset.instAttached = '1';
            btn.addEventListener('click', async function(ev){
                const iid = this.getAttribute('data-installment');
                const inv = this.getAttribute('data-invoice');
                if(!iid || !inv) return;
                // read amount from sibling input
                const tr = this.closest('tr');
                const amtInput = tr ? tr.querySelector('.inst-pay-amount') : null;
                const paymentTypeSelect = tr ? tr.querySelector('.inst-payment-type') : null;
                let amt = amtInput ? parseFloat(amtInput.value || 0) : 0;
                let paymentType = paymentTypeSelect ? paymentTypeSelect.value : 'cash';
                if(isNaN(amt) || amt <= 0){
                    if (instAlert) { instAlert.textContent = 'Please enter a valid amount'; instAlert.className = 'alert alert-warning'; }
                    else { alert('Please enter a valid amount'); }
                    return;
                }
                // disable button
                this.disabled = true; this.textContent = 'Paying...';
                try{
                    const token = document.querySelector('meta[name="csrf-token"]').content;
                    const formData = new FormData();
                    formData.append('_token', token);
                    formData.append('amount', amt);
                    formData.append('payment_type', paymentType);
                    const resp = await fetch(`/invoices/${inv}/installments/${iid}/pay`, {method:'POST', body: formData, headers:{'X-Requested-With':'XMLHttpRequest'}});
                    const j = await resp.json();
                    if(j.success){
                        // update remaining cell on table row
                        const row = document.getElementById('inv-row-'+inv);
                        if(row){
                            const rem = row.querySelector('.remaining-col');
                            if(rem && typeof j.remaining_balance !== 'undefined') rem.innerText = parseFloat(j.remaining_balance).toFixed(2);
                        }
                        // If server returned updated installments, rebuild the table so amounts/paid_amount display correctly
                        if (j.installments && Array.isArray(j.installments)) {
                            // rebuild tbody using same logic as below
                            const instTableBody = document.querySelector('#instTable tbody');
                            instTableBody.innerHTML = '';
                            const nextPayIndex = j.installments.findIndex(it => (parseFloat((it.amount || 0) - (it.paid_amount || 0)) > 0) && it.status !== 'paid');
                            j.installments.forEach((it, idx) => {
                                const tr2 = document.createElement('tr');
                                const due = it.due_date ? (new Date(it.due_date)).toISOString().slice(0,10) : '-';
                                const scheduled = parseFloat(it.amount||0).toFixed(2);
                                const paid = parseFloat(it.paid_amount||0).toFixed(2);
                                const outstanding = Math.max(0, parseFloat((it.amount || 0) - (it.paid_amount || 0)));
                                const canPay = (outstanding > 0) && (it.status !== 'paid') && (idx === nextPayIndex);
                                tr2.innerHTML = `<td>${it.installment_number || it.installment || it.id}</td>`+
                                    `<td>${scheduled}</td>`+
                                    `<td class="text-end">${paid}${it.paid_at ? '<div class="small text-muted">at '+(new Date(it.paid_at)).toISOString().slice(0,10)+'</div>' : ''}</td>`+
                                    `<td>${due}</td>`+
                                    `<td>${it.status||'pending'}</td>`+
                                    `<td style="min-width:300px;">`+
                                        `<div style="display:flex;gap:8px;align-items:center;">`+
                                            `${ canPay ? '<input type="number" step="0.01" class="form-control form-control-sm inst-pay-amount" value="'+outstanding.toFixed(2)+'" style="width:120px;">' : '' }`+
                                            `${ canPay ? '<select class="form-select form-select-sm inst-payment-type" style="width:120px;"><option value="cash" selected>Cash</option><option value="card">Card</option><option value="bank">Bank Transfer</option></select>' : '' }`+
                                            `${ canPay ? '<button class="btn btn-sm btn-primary btn-inst-pay" data-invoice="'+inv+'" data-installment="'+it.id+'">Pay</button>' : (it.status === 'paid' ? '<small class="text-success">Paid</small>' : '<small class="text-muted">Pay later</small>') }`+
                                        `</div>`+
                                    `</td>`;
                                instTableBody.appendChild(tr2);
                            });
                            // Reattach handlers for newly created buttons
                            attachInstPayHandlers();
                        } else {
                            // fallback: mark this installment row appropriately
                            tr.querySelector('td:nth-child(4)').innerText = 'paid';
                            tr.querySelector('td:nth-child(5)').innerHTML = '<small class="text-success">Paid</small>';
                        }
                    } else {
                        throw new Error(j.message || 'Failed to pay');
                    }
                }catch(er){
                    if (instAlert) { instAlert.textContent = er.message || 'Error paying installment'; instAlert.className = 'alert alert-danger'; }
                    else { alert(er.message || 'Error paying installment'); }
                    this.disabled = false; this.textContent = 'Pay';
                }
            });
        });
    }

    // Print receipt function (A5 size)
    function printInstallmentReceipt() {
        const invoiceNum = document.getElementById('instInvoiceNumber')?.textContent?.trim() || '';
        const remaining = document.getElementById('instRemaining')?.textContent || '';
        const netTotal = document.getElementById('instNetTotal')?.textContent || '';
        const downPayment = document.getElementById('instDownPayment')?.textContent || '';
        const totalPaid = document.getElementById('instTotalPaid')?.textContent || '';
        const table = document.getElementById('instTable');
        
        if (!table) return;

        // Create a printable window with A5 size formatting
        const printWindow = window.open('', '_blank');
        const printDoc = printWindow.document;
        
    // A5 size: 210mm x 148mm = 8.27" x 5.83" (landscape)
        const receiptHTML = `
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <title>Installment Receipt</title>
                <style>
                    @page { size: A5 landscape; margin: 6mm; }
                    * { margin: 0; padding: 0; box-sizing: border-box; }
                    html,body { width: 210mm; height: 148mm; }
                    body {
                        font-family: Arial, Helvetica, sans-serif;
                        font-size: 12px;
                        color: #222;
                        background: #fff;
                        -webkit-print-color-adjust: exact;
                    }
                    .receipt {
                        max-width: 100%;
                        padding: 6mm;
                        background: #fff;
                        color: #222;
                    }
                    .header {
                        display:flex;
                        justify-content:space-between;
                        align-items:center;
                        gap:12px;
                        margin-bottom:8px;
                        border-bottom:1px solid #e1e1e1;
                        padding-bottom:6px;
                    }
                    .company .name{font-size:18px;font-weight:700}
                    .company .meta{font-size:11px;color:#666}
                    .receipt-title{font-size:14px;font-weight:700;text-align:right}

                    .info-section{display:flex;justify-content:space-between;align-items:flex-start;margin:8px 0 6px 0}
                    .info-col{font-size:12px}
                    .info-row{margin-bottom:4px}
                    .info-label{font-weight:600;color:#333;margin-right:6px}

                    table{width:100%;border-collapse:collapse;margin-top:8px;font-size:12px}
                    thead th{background:#f7f7f7;padding:8px 10px;text-align:left;border-bottom:1px solid #ddd;font-weight:700}
                    tbody td{padding:8px 10px;border-bottom:1px solid #f0f0f0;vertical-align:middle}
                    tbody tr:nth-child(even) td{background:#fafafa}
                    .col-num{text-align:right}
                    .col-center{text-align:center}

                    .summary{margin-top:8px;display:flex;justify-content:flex-end;gap:12px;font-weight:700}
                    .footer{margin-top:10px;text-align:center;font-size:11px;color:#666}
                    .print-time{font-size:10px;color:#666;margin-top:6px;text-align:center}

                    @media print{
                        body{padding:0}
                        .receipt{padding:0;margin:0}
                    }
                </style>
            </head>
            <body>
                <div class="receipt">
                    <div class="header">
                        <div class="company">
                            <div class="name">PERERA AND SONS ENTERPRISES (PVT) LTD</div>
                            <div class="meta">No. 89/B, Nattandiya Road, Dankotuwa • Tel: 074 099 775 | 074 130 2500</div>
                        </div>
                        <div class="receipt-title">INSTALLMENT PAYMENT RECEIPT</div>
                    </div>

                    <div class="info-section">
                        <div class="info-col">
                            <div class="info-row"><span class="info-label">Invoice:</span><span>${invoiceNum}</span></div>
                            <div class="info-row"><span class="info-label">Net Total:</span><span>${netTotal}</span></div>
                        </div>
                        <div class="info-col" style="text-align:right">
                            <div class="info-row"><span class="info-label">Down Payment:</span><span>${downPayment}</span></div>
                            <div class="info-row"><span class="info-label">Total Paid:</span><span>${totalPaid}</span></div>
                            <div class="info-row" style="margin-top:4px;font-weight:800"><span class="info-label">Remaining:</span><span>${remaining}</span></div>
                        </div>
                    </div>

                    <div style="margin-top:6px;font-weight:700;margin-bottom:6px">Payment Schedule</div>
                    <table>
                        <thead>
                            <tr>
                                <th style="width:8%">#</th>
                                <th style="width:28%">Scheduled</th>
                                <th style="width:28%">Paid</th>
                                <th style="width:18%">Due</th>
                                <th style="width:18%">Status</th>
                            </tr>
                        </thead>
                        <tbody>
        `;
        
        // Get table rows
        const rows = table.querySelectorAll('tbody tr');
        let tableBody = '';
        rows.forEach(row => {
            const tds = row.querySelectorAll('td');
            if (tds.length >= 5) {
                const instNum = tds[0].textContent.trim();
                const scheduled = tds[1].textContent.trim();
                const paid = tds[2].textContent.trim().split('\\n')[0]; // Get first line (amount)
                const due = tds[3].textContent.trim();
                const status = tds[4].textContent.trim();
                tableBody += `
                    <tr>
                        <td>${instNum}</td>
                        <td>${scheduled}</td>
                        <td>${paid}</td>
                        <td>${due}</td>
                        <td>${status}</td>
                    </tr>
                `;
            }
        });
        
        const finalHTML = receiptHTML + tableBody + `
                        </tbody>
                    </table>
                    
                    <div class="footer">
                        Thank you for your payment
                    </div>
                    <div class="print-time">${new Date().toLocaleString()}</div>
                </div>
            </body>
            </html>
        `;
        
        printDoc.write(finalHTML);
        printDoc.close();
        
        // Auto print after a short delay
        setTimeout(() => {
            printWindow.print();
        }, 250);
    }

    // Installment modal logic
    function openInstallmentModal(invoiceId, invoiceNumber, installments, remaining, netTotal, downPayment, totalPaid, items, customerName, customerContact, customerAddress, loanFrequency){
        const instModal = document.getElementById('installmentModal');
        const instNum = document.getElementById('instInvoiceNumber');
        const instRemainingEl = document.getElementById('instRemaining');
        const instNetTotalEl = document.getElementById('instNetTotal');
        const instDownPaymentEl = document.getElementById('instDownPayment');
        const instTableBody = document.querySelector('#instTable tbody');
        const instAlert = document.getElementById('instAlert');
        if(!instModal || !instTableBody) return;
    instNum.textContent = ' - ' + (invoiceNumber || '');
    if (instRemainingEl) {
        if (remaining !== null && typeof remaining !== 'undefined' && remaining !== '') {
            const remVal = parseFloat(remaining) || 0;
            instRemainingEl.textContent = 'Remaining: Rs. ' + remVal.toFixed(2);
        } else {
            instRemainingEl.textContent = '';
        }
    }
        const instTotalPaidEl = document.getElementById('instTotalPaid');
        if (instNetTotalEl) {
        if (netTotal !== null && typeof netTotal !== 'undefined' && netTotal !== '') {
            const nt = parseFloat(netTotal) || 0;
            instNetTotalEl.textContent = 'Net Total: Rs. ' + nt.toFixed(2);
        } else { instNetTotalEl.textContent = ''; }
    }
    if (instDownPaymentEl) {
        if (downPayment !== null && typeof downPayment !== 'undefined' && downPayment !== '') {
            const dp = parseFloat(downPayment) || 0;
            instDownPaymentEl.textContent = 'Down Payment: Rs. ' + dp.toFixed(2);
        } else { instDownPaymentEl.textContent = ''; }
    }
    
    if (instTotalPaidEl) {
        if (typeof totalPaid !== 'undefined' && totalPaid !== null && totalPaid !== '') {
            const tp = parseFloat(totalPaid) || 0;
            instTotalPaidEl.textContent = 'Total Paid: Rs. ' + tp.toFixed(2);
        } else {
            // Fallback compute from netTotal - remaining if available
            if (netTotal !== null && typeof netTotal !== 'undefined' && remaining !== null && typeof remaining !== 'undefined') {
                const nt = parseFloat(netTotal) || 0;
                const rem = parseFloat(remaining) || 0;
                const paid = Math.max(0, nt - rem);
                instTotalPaidEl.textContent = 'Total Paid: Rs. ' + paid.toFixed(2);
            } else {
                instTotalPaidEl.textContent = '';
            }
        }
    }
    if (instAlert) { instAlert.className = 'alert d-none'; instAlert.textContent = ''; }
    // Render customer details in header (if provided)
    try {
        let custContainer = document.getElementById('instCustomer');
        if (!custContainer) {
            custContainer = document.createElement('div');
            custContainer.id = 'instCustomer';
            custContainer.style.marginLeft = '12px';
            custContainer.style.color = '#ced4da';
            custContainer.style.fontSize = '0.9rem';
            // attempt to insert into header flex container next to invoice info
            const headerFlex = instNum.parentNode && instNum.parentNode.parentNode ? instNum.parentNode.parentNode : null;
            if (headerFlex) headerFlex.appendChild(custContainer);
            else instModal.querySelector('div')?.appendChild(custContainer);
        }
    const nameHtml = '<div><strong>Customer:</strong> ' + (customerName ? customerName : '-') + '</div>';
    const contactHtml = customerContact ? '<div><strong>Contact:</strong> ' + customerContact + '</div>' : '';
    const addrHtml = customerAddress ? '<div><strong>Address:</strong> ' + customerAddress + '</div>' : '';
    const freqHtml = (loanFrequency && loanFrequency.trim() !== '') ? ('<div><strong>Schedule:</strong> ' + (loanFrequency.charAt(0).toUpperCase() + loanFrequency.slice(1)) + '</div>') : '';
    custContainer.innerHTML = nameHtml + contactHtml + addrHtml + freqHtml;
    } catch(e) {
        console.warn('Failed to render customer details in installment modal', e);
    }
    // Render invoice product details (if passed)
    try {
        let productsContainer = document.getElementById('instProducts');
        if (!productsContainer) {
            productsContainer = document.createElement('div');
            productsContainer.id = 'instProducts';
            productsContainer.style.marginBottom = '12px';
            // insert before the installments table
            const instTable = document.getElementById('instTable');
            if (instTable && instTable.parentNode) instTable.parentNode.insertBefore(productsContainer, instTable);
            else instModal.querySelector('div')?.appendChild(productsContainer);
        }
        // Build HTML for products
        if (!Array.isArray(items) || items.length === 0) {
            productsContainer.innerHTML = '<div class="text-muted small">No product details available</div>';
        } else {
            let html = '<div class="table-responsive"><table class="table table-sm table-bordered"><thead><tr><th>Product</th><th>Code</th><th class="text-end">Qty</th><th class="text-end">Selling</th><th class="text-end">Total</th></tr></thead><tbody>';
            items.forEach(it => {
                const name = it.product_name || it.name || it.item_name || (it.item ? it.item.product_name : '');
                const code = it.product_code || it.code || (it.item ? it.item.product_code : '');
                const qty = parseFloat(it.qty || it.quantity || it.qty_sold || 0) || 0;
                const sell = parseFloat(it.selling_price || it.selling || 0) || 0;
                const total = parseFloat(it.total_value || (qty * sell) || 0) || 0;
                html += '<tr>'+
                    '<td>'+ (name || '-') +'</td>'+ 
                    '<td>'+ (code || '-') +'</td>'+ 
                    '<td class="text-end">'+ qty.toFixed(3).replace(/\.000$/,'') +'</td>'+ 
                    '<td class="text-end">'+ sell.toFixed(2) +'</td>'+ 
                    '<td class="text-end">'+ total.toFixed(2) +'</td>'+ 
                '</tr>';
            });
            html += '</tbody></table></div>';
            productsContainer.innerHTML = html;
        }
    } catch(e) {
        console.warn('Failed to render invoice products in installment modal', e);
    }
        instTableBody.innerHTML = '';
            if(!Array.isArray(installments) || installments.length === 0){
            instTableBody.innerHTML = '<tr><td colspan="6" class="text-muted">No installments</td></tr>';
        } else {
            // determine the next pending installment index (first with outstanding > 0 and not paid)
            const nextPayIndex = installments.findIndex(it => (parseFloat((it.amount || 0) - (it.paid_amount || 0)) > 0) && it.status !== 'paid');
            installments.forEach((it, idx) => {
                const tr = document.createElement('tr');
                const due = it.due_date ? (new Date(it.due_date)).toISOString().slice(0,10) : '-';
                const scheduled = parseFloat(it.amount||0).toFixed(2);
                const paid = parseFloat(it.paid_amount||0).toFixed(2);
                const outstanding = Math.max(0, parseFloat((it.amount || 0) - (it.paid_amount || 0)));
                // Only allow paying the next pending installment
                const canPay = (outstanding > 0) && (it.status !== 'paid') && (idx === nextPayIndex);
                tr.innerHTML = `<td>${it.installment_number || it.installment || it.id}</td>` +
                    `<td>${scheduled}</td>` +
                    `<td class="text-end">${paid}${it.paid_at ? '<div class="small text-muted">at '+(new Date(it.paid_at)).toISOString().slice(0,10)+'</div>' : ''}</td>` +
                    `<td>${due}</td>` +
                    `<td>${it.status||'pending'}</td>` +
                    `<td style="min-width:300px;">` +
                        `<div style="display:flex;gap:8px;align-items:center;">` +
                            `${ canPay ? '<input type="number" step="0.01" class="form-control form-control-sm inst-pay-amount" value="'+outstanding.toFixed(2)+'" style="width:120px;">' : '' }` +
                            `${ canPay ? '<select class="form-select form-select-sm inst-payment-type" style="width:120px;"><option value="cash" selected>Cash</option><option value="card">Card</option><option value="bank">Bank Transfer</option></select>' : '' }` +
                            `${ canPay ? '<button class="btn btn-sm btn-primary btn-inst-pay" data-invoice="'+invoiceId+'" data-installment="'+it.id+'">Pay</button>' : (it.status === 'paid' ? '<small class="text-success">Paid</small>' : '<small class="text-muted">Pay later</small>') }` +
                        `</div>` +
                    `</td>`;
                instTableBody.appendChild(tr);
            });
        }
        instModal.style.display = 'block';
        // attach handlers for current buttons
        attachInstPayHandlers();
        
        // Click outside installment modal to close and refresh
        instModal.addEventListener('click', function(e) {
            if (e.target === instModal) {
                instModal.style.display = 'none';
                window.location.reload(); // Refresh the page when modal is closed
            }
        });
    }
    document.getElementById('instCloseBtn')?.addEventListener('click', function(){ 
        document.getElementById('installmentModal').style.display='none'; 
        window.location.reload(); // Refresh the page when modal is closed
    });
    document.getElementById('instCancelBtn')?.addEventListener('click', function(){ 
        document.getElementById('installmentModal').style.display='none'; 
        window.location.reload(); // Refresh the page when modal is closed
    });
    document.getElementById('instPrintBtn')?.addEventListener('click', function(){ 
        printInstallmentReceipt(); // Print the receipt without closing modal
    });
});
</script>
@endpush
