<?php
require_once 'includes/auth.php';
require_once 'includes/db.php';
requireRole(['owner', 'finance executive']);
requireModule('invoices');

$currency = $_SESSION['company_currency'] ?? '$';
$company_id = $_SESSION['company_id'] ?? 0;

// Fetch company profile details
$company_profile = fetch("SELECT name, email, phone, website, address, logo FROM companies WHERE id = ?", [$company_id]) ?: [];

// Fetch active buyers for the creation form dropdown
$active_buyers = fetchAll("SELECT * FROM buyers WHERE company_id = ? AND status = 'Active' ORDER BY name ASC", [$company_id]);
// Fetch active products for the creation form dropdown
$active_products = fetchAll("SELECT * FROM products WHERE company_id = ? AND is_active = 1 ORDER BY name ASC", [$company_id]);
?>

<!-- ================================================================
     INVOICE LIST VIEW
     ================================================================ -->
<div id="invoiceListView" style="display: flex; flex-direction: column; gap: 1.5rem; min-height: 100%;">

    <!-- Top Stats / Metrics Cards -->
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 1.5rem;">

        <!-- Card 1: Total Invoiced -->
        <div class="metric-card" style="background: var(--bg-card); border: 1px solid var(--border); border-radius: 24px; padding: 1.5rem; display: flex; align-items: center; gap: 1.25rem; box-shadow: var(--shadow-sm); transition: all 0.3s ease;">
            <div style="width: 56px; height: 56px; border-radius: 16px; background: rgba(99, 102, 241, 0.1); color: var(--primary); display: flex; align-items: center; justify-content: center; font-size: 1.5rem; flex-shrink: 0;">
                <i class="fas fa-file-invoice-dollar"></i>
            </div>
            <div>
                <span style="font-size: 0.85rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px; display: block;">Total Invoiced (<span class="card-currency-label"><?php echo $currency; ?></span>)</span>
                <h3 id="stat-total-invoiced" style="font-size: 1.625rem; font-weight: 800; color: var(--text-main); margin: 0.25rem 0 0 0;">0.00</h3>
            </div>
        </div>

        <!-- Card 2: Total Paid -->
        <div class="metric-card" style="background: var(--bg-card); border: 1px solid var(--border); border-radius: 24px; padding: 1.5rem; display: flex; align-items: center; gap: 1.25rem; box-shadow: var(--shadow-sm); transition: all 0.3s ease;">
            <div style="width: 56px; height: 56px; border-radius: 16px; background: rgba(34, 197, 94, 0.1); color: var(--success); display: flex; align-items: center; justify-content: center; font-size: 1.5rem; flex-shrink: 0;">
                <i class="fas fa-money-bill-trend-up"></i>
            </div>
            <div>
                <span style="font-size: 0.85rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px; display: block;">Total Paid (<span class="card-currency-label"><?php echo $currency; ?></span>)</span>
                <h3 id="stat-total-paid" style="font-size: 1.625rem; font-weight: 800; color: var(--text-main); margin: 0.25rem 0 0 0;">0.00</h3>
            </div>
        </div>

        <!-- Card 3: Total Pending -->
        <div class="metric-card" style="background: var(--bg-card); border: 1px solid var(--border); border-radius: 24px; padding: 1.5rem; display: flex; align-items: center; gap: 1.25rem; box-shadow: var(--shadow-sm); transition: all 0.3s ease;">
            <div style="width: 56px; height: 56px; border-radius: 16px; background: rgba(245, 158, 11, 0.1); color: var(--warning); display: flex; align-items: center; justify-content: center; font-size: 1.5rem; flex-shrink: 0;">
                <i class="fas fa-clock"></i>
            </div>
            <div>
                <span style="font-size: 0.85rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px; display: block;">Total Pending (<span class="card-currency-label"><?php echo $currency; ?></span>)</span>
                <h3 id="stat-total-pending" style="font-size: 1.625rem; font-weight: 800; color: var(--text-main); margin: 0.25rem 0 0 0;">0.00</h3>
            </div>
        </div>

        <!-- Card 4: Total Invoices -->
        <div class="metric-card" style="background: var(--bg-card); border: 1px solid var(--border); border-radius: 24px; padding: 1.5rem; display: flex; align-items: center; gap: 1.25rem; box-shadow: var(--shadow-sm); transition: all 0.3s ease;">
            <div style="width: 56px; height: 56px; border-radius: 16px; background: rgba(168, 85, 247, 0.1); color: #a855f7; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; flex-shrink: 0;">
                <i class="fas fa-list-check"></i>
            </div>
            <div>
                <span style="font-size: 0.85rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px; display: block;">Total Invoices</span>
                <h3 id="stat-total-count" style="font-size: 1.625rem; font-weight: 800; color: var(--text-main); margin: 0.25rem 0 0 0;">0</h3>
            </div>
        </div>
    </div>

    <!-- Search & Filter Controls -->
    <div style="background: var(--bg-card); border: 1px solid var(--border); border-radius: 24px; padding: 1.25rem 1.5rem; display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 1.25rem; box-shadow: var(--shadow-sm);">
        <div style="display: flex; flex: 1; min-width: 300px; gap: 1rem; align-items: center;">
            <div style="position: relative; flex: 1; max-width: 400px;">
                <i class="fas fa-search" style="position: absolute; left: 1.25rem; top: 50%; transform: translateY(-50%); color: var(--text-muted); opacity: 0.5;"></i>
                <input type="text" id="invoiceSearch" class="form-control" placeholder="Search by Invoice #, Buyer, Product, PO..." style="padding-left: 3rem; border-radius: 50px; background: var(--bg-dark); border: 1px solid var(--border); height: 48px; width: 100%;">
            </div>
            <div style="width: 180px;">
                <select id="statusFilter" class="form-control" style="border-radius: 50px; background: var(--bg-dark); border: 1px solid var(--border); height: 48px;">
                    <option value="">All Statuses</option>
                    <option value="Pending">Pending</option>
                    <option value="Issued">Issued</option>
                    <option value="Partially Paid">Partially Paid</option>
                    <option value="Paid">Paid</option>
                    <option value="Past Due">Past Due</option>
                    <option value="Cancelled">Cancelled</option>
                </select>
            </div>
        </div>
        <div>
            <button onclick="showCreateView()" style="display: inline-flex; align-items: center; gap: 0.6rem; padding: 0.7rem 1.5rem; background: linear-gradient(135deg, var(--primary), var(--primary-light)); border: none; border-radius: 14px; cursor: pointer; font-size: 0.9rem; font-weight: 700; color: #fff; box-shadow: 0 4px 14px var(--primary-glow); transition: all 0.2s; white-space: nowrap;">
                <i class="fas fa-plus"></i> Create Invoice
            </button>
        </div>
    </div>

    <!-- Invoices Table -->
    <div style="background: var(--bg-card); border-radius: 28px; border: 1px solid var(--border); overflow: hidden; box-shadow: var(--shadow-md); display: flex; flex-direction: column; position: relative; min-height: 350px;">
        <div id="table-loader" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: rgba(255,255,255,0.7); display: none; align-items: center; justify-content: center; z-index: 10; backdrop-filter: blur(2px);">
            <div class="loader-spinner"></div>
        </div>
        <div style="overflow-x: auto; flex: 1;">
            <table class="admin-table" style="width: 100%; border-collapse: collapse;">
                <thead>
                    <tr>
                        <th style="padding: 1.25rem 1rem; text-align: left; font-size: 0.75rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase;">Invoice Number</th>
                        <th style="text-align: left; font-size: 0.75rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase;">Date</th>
                        <th style="text-align: left; font-size: 0.75rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase;">Buyer</th>
                        <th style="text-align: right; font-size: 0.75rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase;">Subtotal</th>
                        <th style="text-align: right; font-size: 0.75rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase;">Adjustments</th>
                        <th style="text-align: right; font-size: 0.75rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase;">Grand Total</th>
                        <th style="text-align: center; font-size: 0.75rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase;">Status</th>
                        <th style="text-align: right; padding-right: 1.75rem; font-size: 0.75rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase;">Actions</th>
                    </tr>
                </thead>
                <tbody id="invoiceTableBody">
                    <!-- Dynamic rows injected here -->
                </tbody>
            </table>
        </div>

        <!-- Pagination Footer -->
        <div style="padding: 1.25rem 1.75rem; border-top: 1px solid var(--border); background: var(--bg-dark); display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 1rem;">
            <div style="font-size: 0.85rem; color: var(--text-muted);">
                Showing <span id="pag-start" style="color: var(--text-main); font-weight: 700;">0</span> - <span id="pag-end" style="color: var(--text-main); font-weight: 700;">0</span> of <span id="pag-total" style="color: var(--text-main); font-weight: 700;">0</span> records
            </div>
            <div style="display: flex; gap: 0.5rem; align-items: center;">
                <button id="btn-prev" class="btn btn-sm" style="padding: 0.5rem 1rem; background: var(--bg-card); border: 1px solid var(--border);" onclick="changePage(-1)">
                    <i class="fas fa-chevron-left"></i> Previous
                </button>
                <div id="page-numbers" style="display: flex; gap: 0.25rem; align-items: center;"></div>
                <button id="btn-next" class="btn btn-sm" style="padding: 0.5rem 1rem; background: var(--bg-card); border: 1px solid var(--border);" onclick="changePage(1)">
                    Next <i class="fas fa-chevron-right"></i>
                </button>
            </div>
        </div>
    </div>

</div><!-- end #invoiceListView -->


<!-- ================================================================
     INVOICE DETAIL / EDIT VIEW  (inline workspace replacement)
     ================================================================ -->
<div id="invoiceDetailView" style="display: none; flex-direction: column; gap: 0; width: 100%;">

    <!-- Breadcrumb / Back Bar -->
    <div style="background: var(--bg-card); border: 1px solid var(--border); border-radius: 20px; padding: 1rem 1.5rem; display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.25rem;">
        <div style="display: flex; align-items: center; gap: 1rem;">
            <button onclick="showListView()" style="display: inline-flex; align-items: center; gap: 0.5rem; padding: 0.5rem 1.1rem; background: var(--bg-dark); border: 1px solid var(--border); border-radius: 10px; cursor: pointer; font-size: 0.875rem; font-weight: 700; color: var(--text-main); transition: all 0.2s;">
                <i class="fas fa-arrow-left"></i> Back to Invoices
            </button>
            <div style="width: 1px; height: 24px; background: var(--border);"></div>
            <span id="detail-invoice-title" style="font-size: 1.1rem; font-weight: 800; color: var(--text-main);">Invoice Details</span>
            <div id="invoiceDetailTabs" style="display: none; align-items: center; gap: 0.4rem; background: var(--bg-dark); padding: 0.3rem 0.4rem; border-radius: 12px; border: 1px solid var(--border); margin-left: 0.75rem; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                <button type="button" onclick="switchDetailTab('details')" id="tabBtnDetails" style="display: inline-flex; align-items: center; gap: 0.4rem; padding: 0.5rem 1.1rem; border-radius: 9px; border: none; font-size: 0.875rem; font-weight: 700; cursor: pointer; transition: all 0.2s; background: var(--primary); color: #fff;">
                    <i class="fas fa-file-invoice"></i> Invoice Details
                </button>
                <button type="button" onclick="switchDetailTab('payments')" id="tabBtnPayments" style="display: inline-flex; align-items: center; gap: 0.4rem; padding: 0.5rem 1.1rem; border-radius: 9px; border: none; font-size: 0.875rem; font-weight: 700; cursor: pointer; transition: all 0.2s; background: transparent; color: var(--text-muted);">
                    <i class="fas fa-credit-card"></i> Payments
                    <span id="paymentsTabBadge" style="display: none; background: var(--primary); color: #fff; font-size: 0.65rem; line-height: 1; padding: 0.15rem 0.45rem; border-radius: 10px; font-weight: 800; min-width: 18px; text-align: center;"></span>
                </button>
            </div>
        </div>
        <div style="display: flex; gap: 0.75rem;">
            <button onclick="openEmailModal()" style="display: inline-flex; align-items: center; gap: 0.5rem; padding: 0.5rem 1.25rem; background: var(--bg-dark); border: 1px solid var(--border); border-radius: 10px; cursor: pointer; font-size: 0.875rem; font-weight: 700; color: var(--text-main); transition: all 0.2s;" id="emailInvoiceBtn">
                <i class="fas fa-envelope" style="color: var(--primary);"></i> Email Invoice
            </button>
            <button onclick="printReceipt()" style="display: inline-flex; align-items: center; gap: 0.5rem; padding: 0.5rem 1.25rem; background: linear-gradient(135deg, var(--primary), var(--primary-light)); border: none; border-radius: 10px; cursor: pointer; font-size: 0.875rem; font-weight: 700; color: #fff; box-shadow: 0 4px 12px var(--primary-glow); transition: all 0.2s;" id="printInvoiceBtn">
                <i class="fas fa-print"></i> Print Invoice
            </button>
        </div>
    </div>

    <!-- Main Split Panel -->
    <div id="invoiceDetailGrid" style="display: grid; grid-template-columns: 1.4fr 1fr; gap: 1.25rem; align-items: start;">

        <!-- LEFT: Live Receipt Preview -->
        <div id="print-receipt-section" style="background: var(--bg-card); border: 1px solid var(--border); border-radius: 24px; padding: 2rem; display: flex; flex-direction: column; gap: 1.5rem; box-shadow: var(--shadow-sm);">

            <!-- Invoice Header -->
            <div style="display: flex; justify-content: space-between; align-items: flex-start;">
                <div>
                    <h2 style="font-size: 1.4rem; font-weight: 900; color: var(--primary); margin: 0; display: flex; align-items: center; gap: 0.75rem;">
                        <span id="receipt-logo-container" style="display: inline-flex; align-items: center; height: 38px;">
                            <?php if (!empty($company_profile['logo'])): ?>
                                <img src="<?php echo htmlspecialchars($company_profile['logo']); ?>" alt="Logo" style="max-height: 38px; max-width: 120px; object-fit: contain; border-radius: 6px;">
                            <?php else: ?>
                                <i class="fas fa-layer-group" id="receipt-default-logo"></i>
                            <?php endif; ?>
                        </span>
                        <span id="receipt-company-name">Company Name</span>
                    </h2>
                    <p style="font-size: 0.8rem; color: var(--text-muted); margin: 0.25rem 0 0 0;">NexCore Apparel ERP System</p>
                    <div id="receipt-company-address" style="font-size: 0.725rem; color: var(--text-muted); margin: 0.35rem 0 0 0; text-transform: lowercase; line-height: 1.4;"></div>
                    <div id="receipt-company-contacts" style="font-size: 0.725rem; color: var(--text-muted); margin: 0.15rem 0 0 0; text-transform: lowercase; line-height: 1.4;"></div>
                </div>
                <div style="text-align: right;">
                    <div style="font-size: 1.75rem; font-weight: 900; letter-spacing: 1px; color: var(--text-main); text-transform: uppercase;">INVOICE</div>
                    <div id="receipt-invoice-number" style="font-family: monospace; font-size: 0.95rem; font-weight: 700; color: var(--accent); margin-top: 0.25rem;">INV-XXXXXXXXXX</div>
                </div>
            </div>

            <hr style="border: 0; border-top: 1px dashed var(--border); margin: 0;">

            <!-- Billing Details -->
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem;">
                <div>
                    <span style="font-size: 0.7rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px;">Billed To</span>
                    <div id="receipt-buyer-details" style="font-size: 0.85rem; color: var(--text-main); font-weight: 600; line-height: 1.6; margin-top: 0.5rem; white-space: pre-line;">—</div>
                </div>
                <div>
                    <span style="font-size: 0.7rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px;">Invoice Dates</span>
                    <div style="font-size: 0.85rem; color: var(--text-main); line-height: 1.7; margin-top: 0.5rem;">
                        <div><strong>Date Generated:</strong> <span id="receipt-created-at">—</span></div>
                        <div><strong>Payment Due Date:</strong> <span id="receipt-due-date">—</span></div>
                        <div><strong>PO Reference:</strong> <span id="receipt-po-reference">—</span></div>
                        <div><strong>Payment Terms:</strong> <span id="receipt-payment-terms">—</span></div>
                    </div>
                </div>
            </div>

            <!-- Product Line Items Table -->
            <div style="background: var(--bg-dark); border-radius: 12px; border: 1px solid var(--border); overflow: hidden;">
                <table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">
                    <thead>
                        <tr style="background: rgba(0,0,0,0.04); border-bottom: 1px solid var(--border);">
                            <th style="padding: 0.75rem 1rem; text-align: left; color: var(--text-muted); font-weight: 800;">Product Details</th>
                            <th style="padding: 0.75rem 1rem; text-align: right; color: var(--text-muted); font-weight: 800; width: 90px;">Qty</th>
                            <th style="padding: 0.75rem 1rem; text-align: right; color: var(--text-muted); font-weight: 800; width: 110px;">Unit Price (<span class="invoice-currency-label"><?php echo htmlspecialchars($currency); ?></span>)</th>
                            <th style="padding: 0.75rem 1rem; text-align: right; color: var(--text-muted); font-weight: 800; width: 110px;">Total (<span class="invoice-currency-label"><?php echo htmlspecialchars($currency); ?></span>)</th>
                        </tr>
                    </thead>
                    <tbody id="receipt-product-rows">
                    </tbody>
                </table>
            </div>

            <!-- Grand Total Breakdown -->
            <div style="display: flex; justify-content: flex-end;">
                <div style="width: 290px; display: flex; flex-direction: column; gap: 0.5rem; font-size: 0.85rem;">
                    <div style="display: flex; justify-content: space-between;">
                        <span style="color: var(--text-muted);">Subtotal:</span>
                        <span id="receipt-breakdown-subtotal" style="font-weight: 600; color: var(--text-main);">$0.00</span>
                    </div>
                    <div style="display: flex; justify-content: space-between;">
                        <span style="color: var(--text-muted);">Taxes / VAT (+):</span>
                        <span id="receipt-breakdown-taxes" style="font-weight: 600; color: var(--text-main);">$0.00</span>
                    </div>
                    <div style="display: flex; justify-content: space-between;">
                        <span style="color: var(--text-muted);">Shipping Charges (+):</span>
                        <span id="receipt-breakdown-shipping" style="font-weight: 600; color: var(--text-main);">$0.00</span>
                    </div>
                    <div style="display: flex; justify-content: space-between;">
                        <span style="color: var(--text-muted);">Discounts (-):</span>
                        <span id="receipt-breakdown-discounts" style="font-weight: 600; color: var(--danger);">$0.00</span>
                    </div>
                    <hr style="border: 0; border-top: 2px solid var(--border); margin: 0.25rem 0;">
                    <div style="display: flex; justify-content: space-between; font-size: 1rem; font-weight: 800;">
                        <span style="color: var(--text-main);">Grand Total:</span>
                        <span id="receipt-breakdown-grandtotal" style="color: var(--primary);">$0.00</span>
                    </div>
                    <div id="receipt-payments-row" style="display: none; flex-direction: column; gap: 0.4rem; margin-top: 0.4rem;">
                        <div style="display: flex; justify-content: space-between; font-size: 0.85rem; font-weight: 600;">
                            <span style="color: var(--text-muted);">Total Paid:</span>
                            <span id="receipt-breakdown-totalpaid" style="color: var(--success);">$0.00</span>
                        </div>
                        <div style="display: flex; justify-content: space-between; font-size: 0.85rem; font-weight: 700; border-top: 1px solid var(--border); padding-top: 0.25rem; margin-top: 0.1rem;">
                            <span style="color: var(--text-main);">Balance Due:</span>
                            <span id="receipt-breakdown-balancedue" style="color: var(--accent); font-size: 0.9rem;">$0.00</span>
                        </div>
                    </div>
                </div>
            </div>

        </div><!-- end left panel -->

        <!-- RIGHT: Edit Form / Tabs Panel -->
        <div id="invoiceDetailRightPanel" style="background: var(--bg-card); border: 1px solid var(--border); border-radius: 24px; padding: 2rem; display: flex; flex-direction: column; gap: 1.5rem; box-shadow: var(--shadow-sm); min-height: 500px;">
            <div id="invoiceDetailsTabPanel" style="display: flex; flex-direction: column; gap: 1.5rem;">

            <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid var(--border); padding-bottom: 0.75rem;">
                <div style="display: flex; align-items: center; gap: 0.5rem;">
                    <i class="fas fa-pen-to-square" style="color: var(--primary);"></i>
                    <h3 style="font-size: 1rem; font-weight: 800; color: var(--text-main); margin: 0;">Edit Adjustments &amp; Status</h3>
                </div>
                <div id="invoiceEditIconContainer" style="display: none;">
                    <button type="button" onclick="setFormReadOnly(false)" style="background: var(--bg-dark); color: var(--primary); border: 1px solid var(--border); border-radius: 8px; display: inline-flex; align-items: center; gap: 0.35rem; font-size: 0.8rem; font-weight: 700; cursor: pointer; padding: 0.35rem 0.75rem; transition: all 0.2s;" onmouseover="this.style.background='rgba(124,58,237,0.08)'; this.style.borderColor='var(--primary-light)';" onmouseout="this.style.background='var(--bg-dark)'; this.style.borderColor='var(--border)';" title="Unlock Invoice to Edit">
                        <i class="fas fa-edit"></i> Edit
                    </button>
                </div>
            </div>

            <form id="invoiceEditForm" onsubmit="saveInvoice(event)" style="display: flex; flex-direction: column; gap: 1.25rem;">
                <input type="hidden" id="edit-invoice-id" name="id">

                <!-- Buyer Information Section -->
                <div id="buyer-info-section" style="display: flex; flex-direction: column; gap: 1rem; border-bottom: 1px dashed var(--border); padding-bottom: 1.25rem;">
                    <div style="font-size: 0.78rem; font-weight: 800; color: var(--primary); text-transform: uppercase; letter-spacing: 0.5px;">Buyer Information</div>
                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.875rem;">
                        <div class="form-group" style="margin: 0; position: relative;">
                            <label class="form-label" style="font-weight: 700;">Buyer Name <span style="color: var(--danger);">*</span></label>
                            <input type="text" id="edit-buyer-name" name="buyer_name" class="form-control" required placeholder="e.g. Zara" oninput="updateLiveReceipt()" autocomplete="off">
                            <div id="buyer_suggestions" style="display: none; position: absolute; top: 100%; left: 0; right: 0; background: var(--bg-card); border: 1px solid var(--border); border-radius: 10px; max-height: 180px; overflow-y: auto; z-index: 1050; margin-top: 5px; box-shadow: 0 4px 20px rgba(0,0,0,0.15);"></div>
                        </div>
                        <div class="form-group" style="margin: 0;">
                            <label class="form-label" style="font-weight: 700;">Brand</label>
                            <input type="text" id="edit-buyer-brand" name="buyer_brand" class="form-control" placeholder="e.g. Zara Man" oninput="updateLiveReceipt()">
                        </div>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.875rem;">
                        <div class="form-group" style="margin: 0;">
                            <label class="form-label" style="font-weight: 700;">Contact Person</label>
                            <input type="text" id="edit-buyer-contact" name="buyer_contact" class="form-control" placeholder="e.g. John Doe" oninput="updateLiveReceipt()">
                        </div>
                        <div class="form-group" style="margin: 0;">
                            <label class="form-label" style="font-weight: 700;">Country</label>
                            <select id="edit-buyer-country" name="buyer_country" class="form-control" onchange="updateLiveReceipt()">
                                <option value="">— Select Country —</option>
                                <option value="Sri Lanka">Sri Lanka</option>
                                <option value="Spain">Spain</option>
                                <option value="United States">United States</option>
                                <option value="United Kingdom">United Kingdom</option>
                                <option value="Bangladesh">Bangladesh</option>
                                <option value="India">India</option>
                                <option value="China">China</option>
                                <option value="Vietnam">Vietnam</option>
                                <option value="France">France</option>
                                <option value="Germany">Germany</option>
                                <option value="Italy">Italy</option>
                                <option value="Canada">Canada</option>
                                <option value="Australia">Australia</option>
                                <option value="Japan">Japan</option>
                                <option value="Netherlands">Netherlands</option>
                                <option value="Sweden">Sweden</option>
                                <option value="Turkey">Turkey</option>
                                <option value="Portugal">Portugal</option>
                                <option value="Brazil">Brazil</option>
                                <option value="Belgium">Belgium</option>
                                <option value="Denmark">Denmark</option>
                                <option value="Switzerland">Switzerland</option>
                                <option value="Singapore">Singapore</option>
                                <option value="Hong Kong">Hong Kong</option>
                                <option value="UAE">UAE</option>
                                <option value="South Africa">South Africa</option>
                                <option value="Mexico">Mexico</option>
                                <option value="New Zealand">New Zealand</option>
                            </select>
                        </div>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.875rem;">
                        <div class="form-group" style="margin: 0;">
                            <label class="form-label" style="font-weight: 700;">Email</label>
                            <input type="email" id="edit-buyer-email" name="buyer_email" class="form-control" placeholder="buyer@company.com" oninput="updateLiveReceipt()">
                        </div>
                        <div class="form-group" style="margin: 0;">
                            <label class="form-label" style="font-weight: 700;">Phone</label>
                            <input type="text" id="edit-buyer-phone" name="buyer_phone" class="form-control" placeholder="+34 123 456 789" oninput="updateLiveReceipt()">
                        </div>
                    </div>
                </div>

                <!-- Product Information Section -->
                <div style="display: flex; flex-direction: column; gap: 1rem; border-bottom: 1px dashed var(--border); padding-bottom: 1.25rem;">
                    <div style="display: flex; justify-content: space-between; align-items: center; gap: 1rem;">
                        <div style="font-size: 0.78rem; font-weight: 800; color: var(--primary); text-transform: uppercase; letter-spacing: 0.5px;">Product Information</div>
                        <button type="button" id="add-product-btn" onclick="addInvoiceProductRow()" class="btn-invoice-action" style="background: rgba(124, 58, 237, 0.1); color: #7c3aed; border: none; padding: 6px 12px; border-radius: 8px; font-size: 0.75rem; font-weight: 700; cursor: pointer; display: flex; align-items: center; gap: 6px; transition: all 0.2s;">
                            <i class="fas fa-plus"></i> Add Product
                        </button>
                    </div>

                    <div id="invoice-products-container" style="display: flex; flex-direction: column; gap: 1rem;">
                        <!-- Dynamic product list blocks will be generated here -->
                    </div>
                </div>


                <!-- Billing & Schedule Section -->
                <div style="display: flex; flex-direction: column; gap: 1rem;">
                    <div style="font-size: 0.78rem; font-weight: 800; color: var(--primary); text-transform: uppercase; letter-spacing: 0.5px;">Billing &amp; Schedule</div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.875rem;">
                        <div class="form-group" style="margin: 0;">
                            <label class="form-label" style="font-weight: 700;">PO Reference</label>
                            <input type="text" id="edit-po-reference" name="po_reference" class="form-control" placeholder="e.g. PO-12345" oninput="updateLiveReceipt()">
                        </div>
                        <div class="form-group" style="margin: 0;">
                            <label class="form-label" style="font-weight: 700;">Payment Terms <span style="color: var(--danger);">*</span></label>
                            <select id="edit-payment-terms-select" name="payment_term_id" class="form-control" required onchange="onPaymentTermChange()">
                                <option value="">— Loading payment terms... —</option>
                            </select>
                            <!-- Hidden field stores the label text for receipt display and API -->
                            <input type="hidden" id="edit-payment-terms" name="payment_terms">
                        </div>
                    </div>

                    <!-- Installment Scheduler (shown only when Installment Payment is selected) -->
                    <div id="installment-scheduler" style="display: none; flex-direction: column; gap: 0.875rem; background: rgba(124,58,237,0.04); border: 1px dashed rgba(124,58,237,0.3); border-radius: 14px; padding: 1.25rem;">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div style="font-size: 0.8rem; font-weight: 800; color: var(--primary); text-transform: uppercase; letter-spacing: 0.5px; display: flex; align-items: center; gap: 0.4rem;">
                                <i class="fas fa-calendar-alt"></i> Installment Schedule
                            </div>
                            <button type="button" onclick="addInstallmentRow()" style="display: inline-flex; align-items: center; gap: 0.4rem; padding: 0.35rem 0.85rem; background: var(--primary); border: none; border-radius: 8px; cursor: pointer; font-size: 0.78rem; font-weight: 700; color: #fff;">
                                <i class="fas fa-plus"></i> Add Installment
                            </button>
                        </div>
                        <div id="installment-rows" style="display: flex; flex-direction: column; gap: 0.625rem;">
                            <!-- Rows injected by JS -->
                        </div>
                        <div id="installment-summary" style="font-size: 0.8rem; color: var(--text-muted); text-align: right; padding-top: 0.25rem; border-top: 1px solid var(--border);"></div>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.875rem;">
                        <div class="form-group" style="margin: 0;">
                            <label class="form-label" style="font-weight: 700;">Payment Due Date <span style="color: var(--danger);">*</span></label>
                            <input type="date" id="edit-due-date" name="due_date" class="form-control" required onchange="updateLiveReceipt()">
                        </div>
                        <div class="form-group" style="margin: 0;">
                            <label class="form-label" style="font-weight: 700;">Payment Status <span style="color: var(--danger);">*</span></label>
                            <select id="edit-status" name="status" class="form-control" required>
                                <option value="Pending">Pending</option>
                                <option value="Issued">Issued</option>
                                <option value="Partially Paid">Partially Paid</option>
                                <option value="Paid">Paid</option>
                                <option value="Past Due">Past Due</option>
                                <option value="Cancelled">Cancelled</option>
                            </select>
                        </div>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.875rem;">
                        <div class="form-group" style="margin: 0;">
                            <label class="form-label" style="font-weight: 700;">Taxes / VAT (<?php echo $currency; ?>)</label>
                            <input type="number" id="edit-taxes-vat" name="taxes_vat" class="form-control" min="0" step="0.01" value="0.00" oninput="updateLiveReceipt()">
                        </div>
                        <div class="form-group" style="margin: 0;">
                            <label class="form-label" style="font-weight: 700;">Shipping Charges (<?php echo $currency; ?>)</label>
                            <input type="number" id="edit-shipping-charges" name="shipping_charges" class="form-control" min="0" step="0.01" value="0.00" oninput="updateLiveReceipt()">
                        </div>
                    </div>

                    <div class="form-group" style="margin: 0;">
                        <label class="form-label" style="font-weight: 700;">Discounts (<?php echo $currency; ?>)</label>
                        <input type="number" id="edit-discounts" name="discounts" class="form-control" min="0" step="0.01" value="0.00" oninput="updateLiveReceipt()">
                    </div>

                </div>

                <!-- Action Buttons -->
                <div style="display: flex; gap: 0.75rem; border-top: 1px solid var(--border); padding-top: 1.25rem; margin-top: 0.5rem;">
                    <button type="button" onclick="showListView()" style="flex: 1; display: inline-flex; align-items: center; justify-content: center; gap: 0.5rem; padding: 0.7rem 1rem; background: var(--bg-dark); border: 1px solid var(--border); border-radius: 10px; cursor: pointer; font-size: 0.9rem; font-weight: 700; color: var(--text-main);">
                        Cancel
                    </button>
                    <button type="button" onclick="triggerIssueInvoice()" style="flex: 1.2; display: inline-flex; align-items: center; justify-content: center; gap: 0.5rem; padding: 0.7rem 1rem; background: rgba(99,102,241,0.1); border: 1px solid rgba(99,102,241,0.3); border-radius: 10px; cursor: pointer; font-size: 0.9rem; font-weight: 700; color: var(--primary); transition: all 0.2s;" id="issueInvoiceBtn" onmouseover="this.style.background='rgba(99,102,241,0.18)'" onmouseout="this.style.background='rgba(99,102,241,0.1)'">
                        <i class="fas fa-paper-plane"></i> Issue
                    </button>
                    <button type="submit" style="flex: 1.5; display: inline-flex; align-items: center; justify-content: center; gap: 0.5rem; padding: 0.7rem 1rem; background: linear-gradient(135deg, var(--primary), var(--primary-light)); border: none; border-radius: 10px; cursor: pointer; font-size: 0.9rem; font-weight: 700; color: #fff; box-shadow: 0 4px 12px var(--primary-glow);" id="saveInvoiceBtn">
                        <i class="fas fa-save"></i> Save Invoice
                    </button>
                </div>
            </form>
            </div><!-- end Details Tab Panel -->

            <!-- Payments Tab Panel Container -->
            <div id="invoicePaymentsTabPanel" style="display: none; flex-direction: column; gap: 1.25rem;">

                <!-- Header (full width) -->
                <div style="display: flex; align-items: center; gap: 0.5rem; border-bottom: 1px solid var(--border); padding-bottom: 0.75rem;">
                    <i class="fas fa-credit-card" style="color: var(--primary);"></i>
                    <h3 style="font-size: 1rem; font-weight: 800; color: var(--text-main); margin: 0;">Collect &amp; Manage Payments</h3>
                </div>

                <!-- Summary Cards (full width) -->
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.75rem;">
                    <div style="background: var(--bg-dark); border: 1px solid var(--border); border-radius: 14px; padding: 0.85rem; text-align: center;">
                        <span style="font-size: 0.7rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase;">Grand Total</span>
                        <div id="payment-summary-grandtotal" style="font-size: 1.15rem; font-weight: 800; color: var(--text-main); margin-top: 0.25rem;">0.00</div>
                    </div>
                    <div style="background: var(--bg-dark); border: 1px solid var(--border); border-radius: 14px; padding: 0.85rem; text-align: center;">
                        <span style="font-size: 0.7rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase;">Total Paid</span>
                        <div id="payment-summary-totalpaid" style="font-size: 1.15rem; font-weight: 800; color: var(--success); margin-top: 0.25rem;">0.00</div>
                    </div>
                    <div style="background: var(--bg-dark); border: 1px solid var(--border); border-radius: 14px; padding: 0.85rem; text-align: center;">
                        <span style="font-size: 0.7rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase;">Balance Due</span>
                        <div id="payment-summary-balancedue" style="font-size: 1.15rem; font-weight: 800; color: var(--accent); margin-top: 0.25rem;">0.00</div>
                    </div>
                </div>

                <!-- Side-by-side: Left=Form, Right=History -->
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; align-items: start;">

                    <!-- LEFT COL: Fully Paid Banner + Record Payment Form -->
                    <div style="display: flex; flex-direction: column; gap: 1rem;">

                        <!-- Fully Paid Alert banner -->
                        <div id="fullyPaidMessage" style="display: none; background: rgba(34,197,94,0.1); border: 1px solid rgba(34,197,94,0.2); color: var(--success); border-radius: 16px; padding: 1rem; align-items: center; gap: 0.75rem;">
                            <i class="fas fa-check-circle" style="font-size: 1.25rem;"></i>
                            <div style="font-size: 0.85rem; font-weight: 700;">Invoice is fully paid. No further payments are required.</div>
                        </div>

                        <!-- Record New Payment Form Container -->
                        <div id="addPaymentFormContainer" style="background: rgba(124,58,237,0.02); border: 1px dashed var(--border); border-radius: 16px; padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
                            <div style="font-size: 0.8rem; font-weight: 800; color: var(--primary); text-transform: uppercase; letter-spacing: 0.5px;">Record New Payment</div>
                            <form id="recordPaymentForm" onsubmit="submitPayment(event)" style="display: flex; flex-direction: column; gap: 1rem;">
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem;">
                                    <div class="form-group" style="margin: 0;">
                                        <label class="form-label" style="font-weight: 700;">Amount Received <span style="color: var(--danger);">*</span></label>
                                        <input type="number" id="pay-amount" name="amount" class="form-control" min="0.01" step="0.01" required placeholder="0.00">
                                    </div>
                                    <div class="form-group" style="margin: 0;">
                                        <label class="form-label" style="font-weight: 700;">Payment Date <span style="color: var(--danger);">*</span></label>
                                        <input type="date" id="pay-date" name="payment_date" class="form-control" required>
                                    </div>
                                </div>
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem;">
                                    <div class="form-group" style="margin: 0;">
                                        <label class="form-label" style="font-weight: 700;">Payment Method <span style="color: var(--danger);">*</span></label>
                                        <select id="pay-method" name="payment_method" class="form-control" required>
                                            <option value="Cash">Cash</option>
                                            <option value="Bank Transfer">Bank Transfer</option>
                                            <option value="Credit Card">Credit Card</option>
                                            <option value="Cheque">Cheque</option>
                                            <option value="Other">Other</option>
                                        </select>
                                    </div>
                                    <div class="form-group" style="margin: 0;">
                                        <label class="form-label" style="font-weight: 700;">Reference No.</label>
                                        <input type="text" id="pay-reference" name="reference_no" class="form-control" placeholder="Slip / Cheque #">
                                    </div>
                                </div>
                                <div class="form-group" style="margin: 0;">
                                    <label class="form-label" style="font-weight: 700;">Notes</label>
                                    <textarea id="pay-notes" name="notes" class="form-control" rows="2" placeholder="Optional notes..."></textarea>
                                </div>
                                <div class="form-group" style="margin: 0;">
                                    <label class="form-label" style="font-weight: 700;">Payment Proof <span style="font-size: 0.75rem; color: var(--text-muted); font-weight: 400;">(Images, PDF, DOC &mdash; Multiple files allowed)</span></label>
                                    <div id="attachment-drop-zone" style="border: 2px dashed var(--border); border-radius: 12px; padding: 0.9rem 1rem; cursor: pointer; transition: border-color 0.2s, background 0.2s; background: var(--bg-dark);"
                                         onclick="document.getElementById('pay-attachments').click()"
                                         ondragover="event.preventDefault(); this.style.borderColor='var(--primary)'; this.style.background='rgba(124,58,237,0.05)';"
                                         ondragleave="this.style.borderColor='var(--border)'; this.style.background='var(--bg-dark)';"
                                         ondrop="handleAttachmentDrop(event)">
                                        <input type="file" id="pay-attachments" name="attachments[]" multiple accept="image/*,.pdf,.doc,.docx" style="display: none;" onchange="updateAttachmentPreview()">
                                        <div id="attachment-drop-hint" style="text-align: center; color: var(--text-muted); pointer-events: none;">
                                            <i class="fas fa-cloud-upload-alt" style="font-size: 1.5rem; display: block; margin-bottom: 0.35rem; opacity: 0.4;"></i>
                                            <span style="font-size: 0.8rem; font-weight: 600;">Click or drag &amp; drop files here</span>
                                            <div style="font-size: 0.72rem; margin-top: 0.15rem; opacity: 0.7;">PNG, JPG, PDF, DOC &mdash; Max 5MB per file</div>
                                        </div>
                                        <div id="attachment-preview" style="display: flex; flex-wrap: wrap; gap: 0.5rem;"></div>
                                    </div>
                                </div>
                                <div style="display: flex; justify-content: flex-end; gap: 0.5rem;">
                                    <button type="submit" class="btn" style="width: 100%; background: linear-gradient(135deg, var(--primary), var(--primary-light)); color: #fff; border: none; padding: 0.6rem 1.5rem; border-radius: 10px; font-size: 0.875rem; font-weight: 700; box-shadow: 0 4px 10px var(--primary-glow); cursor: pointer;" id="recordPaymentBtn">
                                        <i class="fas fa-check"></i> Record Payment
                                    </button>
                                </div>
                            </form>
                        </div>

                    </div><!-- end left col -->

                    <!-- RIGHT COL: Payment History -->
                    <div style="display: flex; flex-direction: column; gap: 0.75rem;">
                        <div style="display: flex; align-items: center; gap: 0.5rem; padding-bottom: 0.5rem; border-bottom: 1px solid var(--border);">
                            <i class="fas fa-history" style="color: var(--text-muted); font-size: 0.85rem;"></i>
                            <span style="font-size: 0.8rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px;">Payment History</span>
                            <span id="paymentsTabBadge2" style="margin-left: auto; background: rgba(124,58,237,0.1); color: var(--primary); font-size: 0.7rem; font-weight: 800; padding: 0.1rem 0.5rem; border-radius: 8px;"></span>
                        </div>
                        <div id="paymentsHistoryList" style="display: flex; flex-direction: column; gap: 0.75rem; max-height: 520px; overflow-y: auto; padding-right: 0.25rem;">
                            <!-- Payment rows injected dynamically -->
                        </div>
                    </div><!-- end right col -->

                </div><!-- end side-by-side grid -->

            </div><!-- end Payments Tab Panel -->

        </div><!-- end right panel -->

    </div><!-- end grid -->

</div><!-- end #invoiceDetailView -->


<!-- ================================================================
     EMAIL INVOICE MODAL
     ================================================================ -->
<div id="emailInvoiceModal" style="display: none; position: fixed; inset: 0; z-index: 9999; background: rgba(15, 23, 42, 0.6); backdrop-filter: blur(6px); align-items: center; justify-content: center;">
    <div style="background: var(--bg-card); border-radius: 24px; border: 1px solid var(--border); box-shadow: 0 25px 60px rgba(0,0,0,0.25); width: 100%; max-width: 480px; margin: 1rem; overflow: hidden; animation: emailModalIn 0.25s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;">

        <!-- Modal Header -->
        <div style="padding: 1.5rem 1.75rem; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; background: linear-gradient(135deg, rgba(124,58,237,0.06), rgba(99,102,241,0.04));">
            <div style="display: flex; align-items: center; gap: 0.75rem;">
                <div style="width: 40px; height: 40px; border-radius: 12px; background: rgba(124,58,237,0.12); display: flex; align-items: center; justify-content: center; color: var(--primary); font-size: 1.1rem;">
                    <i class="fas fa-envelope"></i>
                </div>
                <div>
                    <h3 style="margin: 0; font-size: 1rem; font-weight: 800; color: var(--text-main);">Email Invoice</h3>
                    <p style="margin: 0; font-size: 0.78rem; color: var(--text-muted);">Send invoice to a recipient by email</p>
                </div>
            </div>
            <button onclick="closeEmailModal()" style="width: 32px; height: 32px; border-radius: 8px; background: var(--bg-dark); border: 1px solid var(--border); cursor: pointer; display: flex; align-items: center; justify-content: center; color: var(--text-muted); font-size: 1rem; transition: all 0.2s;">
                <i class="fas fa-times"></i>
            </button>
        </div>

        <!-- Modal Body -->
        <div style="padding: 1.75rem;">

            <!-- Invoice summary chip -->
            <div id="email-invoice-chip" style="background: rgba(124,58,237,0.07); border: 1px solid rgba(124,58,237,0.15); border-radius: 12px; padding: 0.75rem 1rem; margin-bottom: 1.5rem; display: flex; align-items: center; gap: 0.75rem;">
                <i class="fas fa-file-invoice" style="color: var(--primary); font-size: 1.1rem;"></i>
                <div>
                    <div id="email-modal-invnum" style="font-weight: 800; font-size: 0.9rem; color: var(--primary); font-family: monospace;">INV-XXXXXXXXXX</div>
                    <div id="email-modal-buyer" style="font-size: 0.78rem; color: var(--text-muted); margin-top: 0.1rem;">—</div>
                </div>
            </div>

            <!-- Email input -->
            <div style="margin-bottom: 1.25rem;">
                <label style="display: block; font-size: 0.85rem; font-weight: 700; color: var(--text-muted); margin-bottom: 0.5rem;">
                    Recipient Email Address <span style="color: var(--danger);">*</span>
                </label>
                <div style="position: relative;">
                    <i class="fas fa-at" style="position: absolute; left: 1rem; top: 50%; transform: translateY(-50%); color: var(--text-muted); font-size: 0.9rem;"></i>
                    <input type="email" id="emailRecipient" placeholder="e.g. buyer@company.com" required
                        style="width: 100%; padding: 0.75rem 1rem 0.75rem 2.5rem; border-radius: 12px; border: 1px solid var(--border); background: var(--bg-dark); color: var(--text-main); font-size: 0.95rem; font-family: inherit; outline: none; transition: all 0.2s;"
                        onfocus="this.style.borderColor='var(--primary)'; this.style.boxShadow='0 0 0 3px rgba(124,58,237,0.1)';"
                        onblur="this.style.borderColor=''; this.style.boxShadow='';"
                        onkeydown="if(event.key==='Enter') confirmSendEmail();">
                </div>
            </div>

        </div>

        <!-- Modal Footer -->
        <div style="padding: 1.25rem 1.75rem; border-top: 1px solid var(--border); background: var(--bg-dark); display: flex; gap: 0.75rem; justify-content: flex-end;">
            <button onclick="closeEmailModal()" style="padding: 0.65rem 1.5rem; background: var(--bg-card); border: 1px solid var(--border); border-radius: 10px; cursor: pointer; font-size: 0.9rem; font-weight: 700; color: var(--text-muted); transition: all 0.2s;">
                Cancel
            </button>
            <button onclick="confirmSendEmail()" id="sendEmailBtn" style="display: inline-flex; align-items: center; gap: 0.5rem; padding: 0.65rem 1.75rem; background: linear-gradient(135deg, var(--primary), var(--primary-light)); border: none; border-radius: 10px; cursor: pointer; font-size: 0.9rem; font-weight: 700; color: #fff; box-shadow: 0 4px 12px var(--primary-glow); transition: all 0.2s;">
                <i class="fas fa-paper-plane"></i> Send Invoice
            </button>
        </div>
    </div>
</div>


<style>
    /* Override any global table defaults inside admin-table */
    .admin-table th {
        background: var(--bg-dark);
        padding: 1.25rem 1rem;
        border-bottom: 2px solid var(--border);
    }
    .admin-table td {
        padding: 1.15rem 1rem;
        border-bottom: 1px solid var(--border);
        font-size: 0.875rem;
        vertical-align: middle;
    }
    .admin-table tr:hover {
        background: rgba(124, 58, 237, 0.015);
    }
    .status-badge {
        padding: 0.35rem 0.85rem;
        border-radius: 50px;
        font-size: 0.725rem;
        font-weight: 800;
        text-transform: uppercase;
        display: inline-flex;
        align-items: center;
        gap: 0.35rem;
    }
    .status-dot {
        width: 6px;
        height: 6px;
        border-radius: 50%;
    }
    .loader-spinner {
        width: 45px;
        height: 45px;
        border: 4px solid var(--border);
        border-top: 4px solid var(--primary);
        border-radius: 50%;
        animation: spin 0.8s linear infinite;
    }
    .metric-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 12px 28px rgba(0,0,0,0.1);
        border-color: var(--primary-light);
    }
    .search-result-item:hover {
        background: rgba(124, 58, 237, 0.05) !important;
    }
    @keyframes spin {
        0%   { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    /* Email modal pop-in animation */
    @keyframes emailModalIn {
        from { opacity: 0; transform: scale(0.92) translateY(12px); }
        to   { opacity: 1; transform: scale(1) translateY(0); }
    }
    #emailInvoiceModal.active { display: flex !important; }

    /* Hover for Email button */
    #emailInvoiceBtn:hover {
        background: rgba(124,58,237,0.08) !important;
        border-color: var(--primary-light) !important;
        color: var(--primary) !important;
    }

    /* Responsive: stack on smaller screens */
    @media (max-width: 900px) {
        #invoiceDetailView > div:nth-child(2) {
            grid-template-columns: 1fr !important;
        }
    }

    /* Print rules: preserve layout and colors to match screen preview */
    @media print {
        /* Hide everything except the receipt panel */
        .sidebar,
        .top-header,
        #invoiceListView,
        #invoiceDetailView > div:first-child,
        #invoiceDetailView > div:nth-child(2) > div:last-child,
        #saveInvoiceBtn {
            display: none !important;
        }

        /* Reset page chrome */
        html, body {
            background: #fff !important;
            margin: 0 !important;
            padding: 0 !important;
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
            color-adjust: exact !important;
        }

        /* Make the detail view fill the page as a block */
        #invoiceDetailView {
            display: block !important;
            border: none !important;
            box-shadow: none !important;
            background: #fff !important;
            padding: 0 !important;
            margin: 0 !important;
            width: 100% !important;
        }

        /* The outer split grid – make it show only the receipt */
        #invoiceDetailView > div:nth-child(2) {
            display: block !important;
            width: 100% !important;
        }

        /* Receipt panel itself */
        #print-receipt-section {
            display: flex !important;
            flex-direction: column !important;
            gap: 1.25rem !important;
            width: 100% !important;
            background: #fff !important;
            border: none !important;
            box-shadow: none !important;
            padding: 1.5rem !important;
            border-radius: 0 !important;
        }

        /* ── Preserve brand colors ── */
        /* Company name (purple) */
        #print-receipt-section h2,
        #receipt-company-name {
            color: #7c3aed !important;
        }
        #receipt-company-address,
        #receipt-company-contacts {
            color: #64748b !important;
            font-size: 11px !important;
            text-transform: lowercase !important;
            line-height: 1.4 !important;
        }
        /* "INVOICE" heading */
        #print-receipt-section > div:first-child > div:last-child > div:first-child {
            color: #0f172a !important;
            font-weight: 900 !important;
        }
        /* Invoice number (fuchsia/accent) */
        #receipt-invoice-number {
            color: #d946ef !important;
        }
        /* Section labels (BILLED TO / INVOICE DATES) */
        #print-receipt-section span[style*="text-transform: uppercase"] {
            color: #64748b !important;
        }
        /* Grand total (purple) */
        #receipt-breakdown-grandtotal {
            color: #7c3aed !important;
        }
        /* Discounts (red) */
        #receipt-breakdown-discounts {
            color: #ef4444 !important;
        }
        /* Product SKU (fuchsia) */
        #receipt-product-sku {
            color: #d946ef !important;
        }

        /* ── Keep the two-column Billed To / Invoice Dates grid ── */
        #print-receipt-section > div[style*="grid-template-columns: 1fr 1fr"] {
            display: grid !important;
            grid-template-columns: 1fr 1fr !important;
            gap: 1.5rem !important;
        }

        /* ── Product table styling ── */
        #print-receipt-section .table-container,
        #print-receipt-section > div[style*="background: var(--bg-dark)"] {
            background: #f8fafc !important;
            border: 1px solid #e2e8f0 !important;
            border-radius: 8px !important;
            overflow: hidden !important;
        }
        #print-receipt-section table {
            border-collapse: collapse !important;
            width: 100% !important;
        }
        #print-receipt-section thead tr {
            background: #f1f5f9 !important;
        }
        #print-receipt-section th {
            background: #f1f5f9 !important;
            color: #64748b !important;
            font-weight: 800 !important;
            border-bottom: 1px solid #e2e8f0 !important;
            padding: 0.75rem 1rem !important;
        }
        #print-receipt-section td {
            border-bottom: 1px solid #e2e8f0 !important;
            padding: 0.75rem 1rem !important;
            color: #0f172a !important;
        }

        /* ── Financial breakdown ── */
        #print-receipt-section > div[style*="justify-content: flex-end"] {
            display: flex !important;
            justify-content: flex-end !important;
        }

        /* Dashed HR */
        #print-receipt-section hr {
            border: none !important;
            border-top: 1px dashed #e2e8f0 !important;
        }

        /* Page break settings */
        @page {
            margin: 15mm;
            size: A4;
        }
    }
</style>

<script>
const activeBuyers = <?php echo json_encode($active_buyers ?: []); ?>;
const activeProducts = <?php echo json_encode($active_products ?: []); ?>;
const companyProfile = <?php echo json_encode($company_profile ?: []); ?>;
let invoicesList = [];
let currentPage = 1;
let totalPages = 1;
let activeInvoice = null;
let paymentTermsCache = null; // Cache payment terms from DB

/* ── Helper Parsers ── */
function getBuyerName(details) {
    if (!details) return 'N/A';
    const m = details.match(/Name:\s*(.*)/i);
    return m ? m[1].trim() : (details.split('\n')[0] || 'N/A');
}

function getBuyerDetailValue(details, key) {
    if (!details) return '';
    const regex = new RegExp(key + ':\\s*(.*)', 'i');
    const match = details.match(regex);
    return match ? match[1].trim() : '';
}

function getProductName(details) {
    if (!details) return '';
    const m = details.match(/Name:\s*(.*)/i);
    return m ? m[1].trim() : (details.split('\n')[0] || '');
}

function getProductSku(details) {
    if (!details) return '';
    const m = details.match(/SKU:\s*(.*)/i);
    return m ? m[1].trim() : '';
}

function getProductDesc(details) {
    if (!details) return '';
    const m = details.match(/Description:\s*(.*)/i);
    if (m) return m[1].trim();
    const parts = details.split('\n');
    return parts.length > 2 ? parts.slice(2).join('\n') : '';
}

function parseProducts(details, qty = 0, unitPrice = 0) {
    if (!details) return [];
    if (details.trim().startsWith('[')) {
        try {
            return JSON.parse(details);
        } catch (e) {
            console.error("Failed to parse JSON product details", e);
        }
    }
    // Fallback to legacy format
    return [{
        name: getProductName(details),
        sku: getProductSku(details),
        description: getProductDesc(details),
        quantity: parseInt(qty) || 0,
        unit_price: parseFloat(unitPrice) || 0.0
    }];
}

function renderBuyerSuggestions(val) {
    const suggestionsDiv = document.getElementById('buyer_suggestions');
    if (!suggestionsDiv) return;

    if (!val.trim()) {
        suggestionsDiv.style.display = 'none';
        return;
    }

    const q = val.trim().toLowerCase();
    const filtered = activeBuyers.filter(buyer => {
        const name = (buyer.name || '').toLowerCase();
        const brand = (buyer.brand || '').toLowerCase();
        return name.includes(q) || brand.includes(q);
    });

    if (filtered.length === 0) {
        suggestionsDiv.innerHTML = '<div style="padding: 0.5rem 0.75rem; color: var(--text-muted); font-size: 0.78rem;">No buyers found</div>';
    } else {
        suggestionsDiv.innerHTML = filtered.map(buyer => `
            <div class="search-result-item" onclick="selectBuyer(${buyer.id})" style="padding: 0.5rem 0.75rem; cursor: pointer; border-bottom: 1px solid var(--border); transition: all 0.2s;">
                <div style="font-weight: 600; color: var(--text-main); font-size: 0.78rem;">${escapeHtml(buyer.name)}</div>
                ${buyer.brand ? `<div style="font-size: 0.68rem; color: var(--accent); font-weight: 700; margin-top: 0.1rem;">${escapeHtml(buyer.brand)}</div>` : ''}
            </div>
        `).join('');
    }
    suggestionsDiv.style.display = 'block';
}

function formatNumberOnly(amount) {
    const n = parseFloat(amount);
    return isNaN(n) ? '0.00' : n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function formatCurrency(amount) {
    const sym = (window.APP_CONFIG && window.APP_CONFIG.COMPANY_CURRENCY) ? window.APP_CONFIG.COMPANY_CURRENCY : '<?php echo addslashes($currency); ?>';
    return sym + ' ' + formatNumberOnly(amount);
}

function showLoader() {
    const el = document.getElementById('table-loader');
    if (el) el.style.display = 'flex';
}
function hideLoader() {
    const el = document.getElementById('table-loader');
    if (el) el.style.display = 'none';
}

/* ── Load Invoices List ── */
async function loadInvoices(page = 1) {
    currentPage = page;
    showLoader();
    try {
        const search = document.getElementById('invoiceSearch').value;
        const status = document.getElementById('statusFilter').value;
        const res = await apiCall('invoices', { action: 'list', search, status, page, limit: 10 });
        if (res.success) {
            invoicesList = res.data;
            totalPages   = res.pagination.pages;
            renderTable();
            renderPagination(res.pagination);
            renderMetrics(res.metrics);
        } else {
            notify(res.message || 'Failed to load invoices', 'error');
        }
    } catch (e) {
        console.error('loadInvoices error:', e);
        notify('Failed to load invoices', 'error');
    } finally {
        hideLoader();
    }
}

function renderMetrics(m) {
    const sym = (window.APP_CONFIG && window.APP_CONFIG.COMPANY_CURRENCY) ? window.APP_CONFIG.COMPANY_CURRENCY : '<?php echo addslashes($currency); ?>';
    document.querySelectorAll('.card-currency-label').forEach(el => {
        el.textContent = sym;
    });
    document.getElementById('stat-total-invoiced').innerText = formatNumberOnly(m.total_invoiced);
    document.getElementById('stat-total-paid').innerText     = formatNumberOnly(m.total_paid);
    document.getElementById('stat-total-pending').innerText  = formatNumberOnly(m.total_pending);
    document.getElementById('stat-total-count').innerText    = m.total_count;
}

function renderTable() {
    const body = document.getElementById('invoiceTableBody');
    if (!invoicesList || invoicesList.length === 0) {
        body.innerHTML = '<tr><td colspan="8" style="text-align:center;padding:4rem;color:var(--text-muted);"><i class="fas fa-file-invoice fa-3x" style="opacity:0.3;display:block;margin-bottom:1rem;"></i>No invoices found.</td></tr>';
        return;
    }
    body.innerHTML = invoicesList.map(item => {
        const buyerName   = getBuyerName(item.buyer_details);
        const subtotal    = parseFloat(item.total_amount) || 0;
        const adjustments = (parseFloat(item.taxes_vat) || 0) + (parseFloat(item.shipping_charges) || 0) - (parseFloat(item.discounts) || 0);
        const grandTotal  = subtotal + adjustments;
        const dateStr     = new Date(item.created_at).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
        let badgeStyle = 'background:rgba(245,158,11,0.1);color:var(--warning);';
        let dotStyle   = 'background:var(--warning);';
        if (item.status === 'Paid') {
            badgeStyle = 'background:rgba(34,197,94,0.1);color:var(--success);';
            dotStyle   = 'background:var(--success);';
        } else if (item.status === 'Issued') {
            badgeStyle = 'background:rgba(99,102,241,0.1);color:var(--primary);';
            dotStyle   = 'background:var(--primary);';
        } else if (item.status === 'Partially Paid') {
            badgeStyle = 'background:rgba(59,130,246,0.1);color:#3b82f6;';
            dotStyle   = 'background:#3b82f6;';
        } else if (item.status === 'Past Due') {
            badgeStyle = 'background:rgba(239,68,68,0.1);color:var(--danger);';
            dotStyle   = 'background:var(--danger);';
        } else if (item.status === 'Cancelled') {
            badgeStyle = 'background:rgba(239,68,68,0.1);color:var(--danger);';
            dotStyle   = 'background:var(--danger);';
        }

        let actionsHtml = '';
        if (item.status === 'Paid' || item.status === 'Cancelled') {
            actionsHtml += `
                <button class="btn-icon btn-sm" onclick="viewInvoiceDetails(${item.id})" style="background:rgba(34,197,94,0.1);color:var(--success);margin-left:0.25rem;" title="View Details">
                    <i class="fas fa-eye"></i>
                </button>
            `;
        } else {
            actionsHtml += `
                <button class="btn-icon btn-sm" onclick="viewInvoiceDetails(${item.id})" style="background:rgba(124,58,237,0.1);color:var(--primary);margin-left:0.25rem;" title="Edit Invoice">
                    <i class="fas fa-edit"></i>
                </button>
            `;
        }

        if (item.status !== 'Pending' && item.status !== 'Cancelled') {
            actionsHtml += `
                <button class="btn-icon btn-sm" onclick="viewInvoiceDetails(${item.id}, 'payments')" style="background:rgba(168,85,247,0.1);color:#a855f7;margin-left:0.25rem;" title="Manage Payments">
                    <i class="fas fa-credit-card"></i>
                </button>
            `;
        }

        if (item.status !== 'Paid' && item.status !== 'Cancelled') {
            actionsHtml += `
                <button class="btn-icon btn-sm" onclick="cancelInvoice(${item.id})" style="background:rgba(239,68,68,0.1);color:var(--danger);margin-left:0.25rem;" title="Cancel Invoice">
                    <i class="fas fa-ban"></i>
                </button>
            `;
        }

        return `
        <tr>
            <td style="font-weight:800;font-family:monospace;font-size:0.9rem;">
                <a href="javascript:void(0)" onclick="viewInvoiceDetails(${item.id})" style="color:var(--primary);text-decoration:none;transition:all 0.15s ease;" onmouseover="this.style.textDecoration='underline';this.style.opacity='0.8';" onmouseout="this.style.textDecoration='none';this.style.opacity='1';">${item.invoice_number}</a>
            </td>
            <td style="color:var(--text-muted);">${dateStr}</td>
            <td style="font-weight:700;color:var(--text-main);">${buyerName}</td>
            <td style="text-align:right;font-weight:600;">${formatCurrency(subtotal)}</td>
            <td style="text-align:right;font-weight:600;color:${adjustments < 0 ? 'var(--danger)' : 'var(--text-muted)'};">
                ${adjustments >= 0 ? '+' : ''}${formatCurrency(adjustments)}
            </td>
            <td style="text-align:right;font-weight:800;color:var(--primary);">${formatCurrency(grandTotal)}</td>
            <td style="text-align:center;">
                <span class="status-badge" style="${badgeStyle}">
                    <span class="status-dot" style="${dotStyle}"></span>${item.status}
                </span>
            </td>
            <td style="text-align:right;padding-right:1.75rem;white-space:nowrap;">
                ${actionsHtml}
            </td>
        </tr>`;
    }).join('');
}

function renderPagination(pag) {
    document.getElementById('pag-total').innerText = pag.total;
    const start = pag.total === 0 ? 0 : (pag.page - 1) * pag.limit + 1;
    const end   = Math.min(pag.page * pag.limit, pag.total);
    document.getElementById('pag-start').innerText = start;
    document.getElementById('pag-end').innerText   = end;

    const prevBtn = document.getElementById('btn-prev');
    const nextBtn = document.getElementById('btn-next');
    prevBtn.disabled     = pag.page <= 1;
    nextBtn.disabled     = pag.page >= pag.pages;
    prevBtn.style.opacity = prevBtn.disabled ? '0.5' : '1';
    nextBtn.style.opacity = nextBtn.disabled ? '0.5' : '1';

    let html = '';
    let sp = Math.max(1, pag.page - 2);
    let ep = Math.min(pag.pages, sp + 4);
    if (ep - sp < 4) sp = Math.max(1, ep - 4);
    for (let i = sp; i <= ep; i++) {
        html += `<button class="btn btn-sm" onclick="loadInvoices(${i})"
            style="min-width:36px;height:36px;padding:0;
            background:${i === pag.page ? 'var(--primary)' : 'var(--bg-card)'};
            color:${i === pag.page ? 'white' : 'var(--text-main)'};
            border:1px solid ${i === pag.page ? 'var(--primary)' : 'var(--border)'};">${i}</button>`;
    }
    document.getElementById('page-numbers').innerHTML = html;
}

function changePage(delta) {
    const next = currentPage + delta;
    if (next > 0 && next <= totalPages) loadInvoices(next);
}

/* ── View Invoice Details (workspace swap) ── */
async function viewInvoiceDetails(id, defaultTab = 'details') {
    try {
        // Fetch invoice + payment terms + existing installments in parallel
        const [invoiceRes, termsRes] = await Promise.all([
            apiCall('invoices', { action: 'get', id: id }),
            loadPaymentTerms(id)
        ]);

        if (!invoiceRes.success) {
            notify(invoiceRes.message || 'Invoice not found', 'error');
            return;
        }
        activeInvoice = invoiceRes.invoice;

        /* Show email & print action buttons */
        document.getElementById('emailInvoiceBtn').style.display = 'inline-flex';
        document.getElementById('printInvoiceBtn').style.display = 'inline-flex';

        /* Populate form fields */
        document.getElementById('edit-invoice-id').value        = activeInvoice.id || '';
        document.getElementById('edit-po-reference').value      = activeInvoice.po_reference || '';
        document.getElementById('edit-status').value            = activeInvoice.status || 'Pending';
        document.getElementById('edit-taxes-vat').value         = parseFloat(activeInvoice.taxes_vat || 0).toFixed(2);
        document.getElementById('edit-shipping-charges').value  = parseFloat(activeInvoice.shipping_charges || 0).toFixed(2);
        document.getElementById('edit-discounts').value         = parseFloat(activeInvoice.discounts || 0).toFixed(2);
        /* Populate product rows */
        const productsContainer = document.getElementById('invoice-products-container');
        if (productsContainer) {
            productsContainer.innerHTML = '';
            const products = parseProducts(activeInvoice.product_details, activeInvoice.units_completed, activeInvoice.unit_price);
            products.forEach(p => addInvoiceProductRow(p));
        }
        document.getElementById('edit-due-date').value          = activeInvoice.due_date || '';

        /* Populate buyer details */
        document.getElementById('edit-buyer-name').value    = getBuyerDetailValue(activeInvoice.buyer_details, 'Name');
        document.getElementById('edit-buyer-brand').value   = getBuyerDetailValue(activeInvoice.buyer_details, 'Brand');
        document.getElementById('edit-buyer-contact').value = getBuyerDetailValue(activeInvoice.buyer_details, 'Contact');
        document.getElementById('edit-buyer-email').value   = getBuyerDetailValue(activeInvoice.buyer_details, 'Email');
        document.getElementById('edit-buyer-phone').value   = getBuyerDetailValue(activeInvoice.buyer_details, 'Phone');
        const bCountry = getBuyerDetailValue(activeInvoice.buyer_details, 'Country');
        const countrySelect = document.getElementById('edit-buyer-country');
        if (bCountry) {
            let hasOption = false;
            for (let i = 0; i < countrySelect.options.length; i++) {
                if (countrySelect.options[i].value === bCountry) {
                    hasOption = true;
                    break;
                }
            }
            if (!hasOption) {
                const opt = document.createElement('option');
                opt.value = bCountry;
                opt.textContent = bCountry;
                countrySelect.appendChild(opt);
            }
        }
        countrySelect.value = bCountry;

        /* Hide suggestion lists */
        document.getElementById('buyer_suggestions').style.display = 'none';

        /* Set payment terms dropdown */
        const termId = activeInvoice.payment_term_id ? String(activeInvoice.payment_term_id) : '';
        const sel = document.getElementById('edit-payment-terms-select');
        if (sel && termId) {
            sel.value = termId;
            // If the option isn't found (stale cache), set to first
            if (!sel.value) sel.value = '';
        }
        // Sync the hidden text field and trigger installment display
        onPaymentTermChange();

        // Pre-load existing installments if Installment Payment term
        if (termsRes && termsRes.installments && termsRes.installments.length > 0) {
            const scheduler = document.getElementById('installment-scheduler');
            if (scheduler && scheduler.style.display !== 'none') {
                const installmentContainer = document.getElementById('installment-rows');
                installmentContainer.innerHTML = '';
                termsRes.installments.forEach(inst => {
                    addInstallmentRow(inst.due_date, inst.amount, inst.description);
                });
                updateInstallmentSummary();
            }
        }

        /* Set title */
        document.getElementById('detail-invoice-title').innerText = activeInvoice.invoice_number || 'Invoice Details';

        /* Show tabs only for Issued / Partially Paid / Paid / Past Due invoices */
        const tabsBar = document.getElementById('invoiceDetailTabs');
        const showPaymentsTab = ['Issued', 'Partially Paid', 'Paid', 'Past Due'].includes(activeInvoice.status);
        if (tabsBar) tabsBar.style.display = showPaymentsTab ? 'flex' : 'none';
        
        const activeTab = showPaymentsTab ? defaultTab : 'details';
        switchDetailTab(activeTab);

        /* Load payments in the background */
        window.activeInvoicePayments = [];
        loadPayments(id);

        /* Render live receipt immediately */
        updateLiveReceipt();

        /* Lock / Unlock form based on status */
        if (['Issued', 'Partially Paid', 'Paid', 'Past Due'].includes(activeInvoice.status)) {
            setFormReadOnly(true);
        } else {
            setFormReadOnly(false);
        }

        /* Swap views */
        document.getElementById('invoiceListView').style.display   = 'none';
        document.getElementById('invoiceDetailView').style.display = 'flex';

        /* Scroll to top of workspace */
        window.scrollTo({ top: 0, behavior: 'smooth' });

    } catch (e) {
        console.error('viewInvoiceDetails error:', e);
        notify('Failed to load invoice details', 'error');
    }
}

/* ── Show Create Invoice View ── */
async function showCreateView() {
    try {
        /* Reset form */
        document.getElementById('invoiceEditForm').reset();
        document.getElementById('edit-invoice-id').value = '';

        /* Hide email & print action buttons since invoice doesn't exist yet */
        document.getElementById('emailInvoiceBtn').style.display = 'none';
        document.getElementById('printInvoiceBtn').style.display = 'none';

        /* Hide suggestions and enable fields for create mode */
        document.getElementById('buyer_suggestions').style.display = 'none';
        document.getElementById('edit-buyer-name').disabled = false;
        document.getElementById('edit-buyer-brand').disabled = false;
        document.getElementById('edit-buyer-contact').disabled = false;
        document.getElementById('edit-buyer-email').disabled = false;
        document.getElementById('edit-buyer-phone').disabled = false;
        document.getElementById('edit-buyer-country').disabled = false;

        /* Reset activeInvoice object for live preview */
        activeInvoice = {
            id: '',
            invoice_number: 'INV-TEMP',
            buyer_details: '',
            created_at: new Date().toISOString().split('T')[0],
            due_date: '',
            po_reference: '',
            payment_terms: '',
            product_details: '',
            units_completed: 0,
            unit_price: 0,
            total_amount: 0,
            taxes_vat: 0,
            shipping_charges: 0,
            discounts: 0
        };

        /* Load payment terms */
        await loadPaymentTerms(0);

        /* Set default payment status to Pending */
        document.getElementById('edit-status').value = 'Pending';

        /* Reset products */
        const productsContainer = document.getElementById('invoice-products-container');
        if (productsContainer) productsContainer.innerHTML = '';
        addInvoiceProductRow();

        /* Reset installments */
        const scheduler = document.getElementById('installment-scheduler');
        if (scheduler) scheduler.style.display = 'none';
        const installmentContainer = document.getElementById('installment-rows');
        if (installmentContainer) installmentContainer.innerHTML = '';
        updateInstallmentSummary();

        /* Hide tabs and reset panel display */
        const tabsBar = document.getElementById('invoiceDetailTabs');
        if (tabsBar) tabsBar.style.display = 'none';
        switchDetailTab('details');
        window.activeInvoicePayments = [];

        /* Set title */
        document.getElementById('detail-invoice-title').innerText = 'Create Invoice';

        /* Render live receipt immediately */
        updateLiveReceipt();

        /* New invoices start editable */
        setFormReadOnly(false);

        /* Swap views */
        document.getElementById('invoiceListView').style.display   = 'none';
        document.getElementById('invoiceDetailView').style.display = 'flex';

        /* Scroll to top of workspace */
        window.scrollTo({ top: 0, behavior: 'smooth' });

    } catch (e) {
        console.error('showCreateView error:', e);
        notify('Failed to initialize create invoice form', 'error');
    }
}

/* ── Safe HTML Escaper ── */
function escapeHtml(str) {
    if (!str) return '';
    return str.replace(/&/g, '&amp;')
              .replace(/</g, '&lt;')
              .replace(/>/g, '&gt;')
              .replace(/"/g, '&quot;')
              .replace(/'/g, '&#039;');
}

/* ── Select Buyer Autocomplete Handler ── */
function selectBuyer(buyerId) {
    const buyer = activeBuyers.find(b => String(b.id) === String(buyerId));
    if (buyer) {
        document.getElementById('edit-buyer-name').value = buyer.name || '';
        document.getElementById('edit-buyer-brand').value = buyer.brand || '';
        document.getElementById('edit-buyer-contact').value = buyer.contact_person || '';
        document.getElementById('edit-buyer-email').value = buyer.email || '';
        document.getElementById('edit-buyer-phone').value = buyer.phone || '';
        const bCountry = buyer.country || '';
        const countrySelect = document.getElementById('edit-buyer-country');
        if (bCountry) {
            let hasOption = false;
            for (let i = 0; i < countrySelect.options.length; i++) {
                if (countrySelect.options[i].value === bCountry) {
                    hasOption = true;
                    break;
                }
            }
            if (!hasOption) {
                const opt = document.createElement('option');
                opt.value = bCountry;
                opt.textContent = bCountry;
                countrySelect.appendChild(opt);
            }
        }
        countrySelect.value = bCountry;
        updateLiveReceipt();
    }
    const suggestionsDiv = document.getElementById('buyer_suggestions');
    if (suggestionsDiv) suggestionsDiv.style.display = 'none';
}

/* ── Dynamic Product Item Row Manager ── */
function addInvoiceProductRow(productData = null) {
    const container = document.getElementById('invoice-products-container');
    if (!container) return;
    
    // Generate unique row ID
    const rowId = 'prod-row-' + Math.random().toString(36).substr(2, 9);
    
    const nameVal = productData ? escapeHtml(productData.name || '') : '';
    const skuVal = productData ? escapeHtml(productData.sku || '') : '';
    const descVal = productData ? escapeHtml(productData.description || '') : '';
    const qtyVal = productData ? parseInt(productData.quantity || 0) : '';
    const priceVal = productData ? parseFloat(productData.unit_price || 0).toFixed(2) : '';

    const rowHtml = `
        <div id="${rowId}" class="invoice-product-item-block" style="padding: 1.25rem; border: 1px solid var(--border); border-radius: 16px; background: rgba(255,255,255,0.015); display: flex; flex-direction: column; gap: 0.875rem; position: relative; backdrop-filter: blur(10px); transition: all 0.3s ease;">
            <button type="button" onclick="removeInvoiceProductRow('${rowId}')" class="btn-row-delete" style="position: absolute; top: 0.75rem; right: 0.75rem; background: rgba(239, 68, 68, 0.05); border: none; color: var(--danger); cursor: pointer; padding: 6px; border-radius: 8px; font-size: 0.8rem; display: flex; align-items: center; justify-content: center; width: 28px; height: 28px; transition: all 0.2s;" title="Remove Product">
                <i class="fas fa-trash-alt"></i>
            </button>
            <div class="product-row-title" style="font-size: 0.725rem; font-weight: 800; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px;">Product #1</div>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.875rem;">
                <div class="form-group" style="margin: 0; position: relative;">
                    <label class="form-label" style="font-weight: 700; font-size: 0.75rem;">Product Name <span style="color: var(--danger);">*</span></label>
                    <input type="text" class="form-control prod-name-input" required placeholder="Product name..." value="${nameVal}" oninput="onProductRowNameInput('${rowId}', this.value)" onfocus="onProductRowNameInput('${rowId}', this.value)" autocomplete="off" style="font-size: 0.825rem; height: 38px;">
                    <div class="prod-suggestions-box" style="display: none; position: absolute; top: 100%; left: 0; right: 0; background: var(--bg-card); border: 1px solid var(--border); border-radius: 12px; max-height: 180px; overflow-y: auto; z-index: 1050; margin-top: 5px; box-shadow: 0 8px 30px rgba(0,0,0,0.3); backdrop-filter: blur(20px);"></div>
                </div>
                <div class="form-group" style="margin: 0;">
                    <label class="form-label" style="font-weight: 700; font-size: 0.75rem;">Product SKU <span style="color: var(--danger);">*</span></label>
                    <input type="text" class="form-control prod-sku-input" required placeholder="SKU..." value="${skuVal}" oninput="updateLiveReceipt()" style="font-size: 0.825rem; height: 38px;">
                </div>
            </div>

            <div class="form-group" style="margin: 0;">
                <label class="form-label" style="font-weight: 700; font-size: 0.75rem;">Product Description</label>
                <textarea class="form-control prod-desc-input" placeholder="Description..." rows="2" oninput="updateLiveReceipt()" style="resize: vertical; font-family: inherit; font-size: 0.8rem; padding: 0.5rem 0.75rem;">${descVal}</textarea>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.875rem;">
                <div class="form-group" style="margin: 0;">
                    <label class="form-label" style="font-weight: 700; font-size: 0.75rem;">Quantity <span style="color: var(--danger);">*</span></label>
                    <input type="number" class="form-control prod-qty-input" min="0" step="1" required placeholder="0" value="${qtyVal}" oninput="updateLiveReceipt()" style="font-size: 0.825rem; height: 38px;">
                </div>
                <div class="form-group" style="margin: 0;">
                    <label class="form-label" style="font-weight: 700; font-size: 0.75rem;">Unit Price (<?php echo $currency; ?>) <span style="color: var(--danger);">*</span></label>
                    <input type="number" class="form-control prod-price-input" min="0" step="0.01" required placeholder="0.00" value="${priceVal}" oninput="updateLiveReceipt()" style="font-size: 0.825rem; height: 38px;">
                </div>
            </div>
        </div>
    `;

    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = rowHtml.trim();
    container.appendChild(tempDiv.firstChild);

    reindexInvoiceProductRows();
    updateLiveReceipt();
}

function removeInvoiceProductRow(rowId) {
    const row = document.getElementById(rowId);
    if (row) {
        row.remove();
        reindexInvoiceProductRows();
        updateLiveReceipt();
    }
}

function reindexInvoiceProductRows() {
    const container = document.getElementById('invoice-products-container');
    if (!container) return;
    
    const rows = container.querySelectorAll('.invoice-product-item-block');
    rows.forEach((row, i) => {
        const title = row.querySelector('.product-row-title');
        if (title) {
            title.textContent = `Product #${i + 1}`;
        }
        
        // Hide delete button if there is only 1 row (so user cannot delete the only product row)
        const delBtn = row.querySelector('.btn-row-delete');
        if (delBtn) {
            delBtn.style.display = (rows.length === 1) ? 'none' : 'flex';
        }
    });
}

function onProductRowNameInput(rowId, val) {
    const row = document.getElementById(rowId);
    if (!row) return;
    const suggestionsBox = row.querySelector('.prod-suggestions-box');
    if (!suggestionsBox) return;

    if (!val.trim()) {
        suggestionsBox.style.display = 'none';
        updateLiveReceipt();
        return;
    }

    const q = val.trim().toLowerCase();
    const filtered = activeProducts.filter(product => {
        const name = (product.name || '').toLowerCase();
        const sku = (product.sku || '').toLowerCase();
        return name.includes(q) || sku.includes(q);
    });

    if (filtered.length === 0) {
        suggestionsBox.innerHTML = '<div style="padding: 0.5rem 0.75rem; color: var(--text-muted); font-size: 0.78rem;">No products found</div>';
    } else {
        suggestionsBox.innerHTML = filtered.map(product => `
            <div class="search-result-item" onclick="selectProductForRow('${rowId}', ${product.id})" style="padding: 0.5rem 0.75rem; cursor: pointer; border-bottom: 1px solid var(--border); transition: all 0.2s;">
                <div style="font-weight: 600; color: var(--text-main); font-size: 0.78rem;">${escapeHtml(product.name)}</div>
                <div style="font-size: 0.68rem; color: var(--accent); font-weight: 700; margin-top: 0.1rem;">${escapeHtml(product.sku || 'No SKU')}</div>
            </div>
        `).join('');
    }
    suggestionsBox.style.display = 'block';
    updateLiveReceipt();
}

function selectProductForRow(rowId, productId) {
    const row = document.getElementById(rowId);
    if (!row) return;
    
    const product = activeProducts.find(p => String(p.id) === String(productId));
    if (product) {
        row.querySelector('.prod-name-input').value = product.name || '';
        row.querySelector('.prod-sku-input').value = product.sku || '';
        row.querySelector('.prod-desc-input').value = product.description || '';
        row.querySelector('.prod-price-input').value = parseFloat(product.base_price || 0).toFixed(2);
        
        // Default quantity to 1 if empty or 0
        const qtyInput = row.querySelector('.prod-qty-input');
        if (!qtyInput.value || parseInt(qtyInput.value) === 0) {
            qtyInput.value = 1;
        }
        
        updateLiveReceipt();
    }
    const suggestionsBox = row.querySelector('.prod-suggestions-box');
    if (suggestionsBox) suggestionsBox.style.display = 'none';
}


/* ── Live Receipt Renderer ── */
function updateLiveReceipt() {
    if (!activeInvoice) return;
    try {
        const sym = (window.APP_CONFIG && window.APP_CONFIG.COMPANY_CURRENCY) ? window.APP_CONFIG.COMPANY_CURRENCY : '<?php echo addslashes($currency); ?>';
        document.querySelectorAll('.invoice-currency-label').forEach(el => {
            el.textContent = sym;
        });

        const poRef    = document.getElementById('edit-po-reference').value || 'None';
        const taxes    = parseFloat(document.getElementById('edit-taxes-vat').value)        || 0;
        const shipping = parseFloat(document.getElementById('edit-shipping-charges').value) || 0;
        const discount = parseFloat(document.getElementById('edit-discounts').value)        || 0;
        const payTerms = document.getElementById('edit-payment-terms').value || 'Due on Receipt';

        // Retrieve all products from the form
        const productRows = document.querySelectorAll('.invoice-product-item-block');
        let subtotal = 0;
        let receiptRowsHtml = '';

        productRows.forEach(row => {
            const name = row.querySelector('.prod-name-input').value.trim() || 'Product Name';
            const sku = row.querySelector('.prod-sku-input').value.trim() || '';
            const desc = row.querySelector('.prod-desc-input').value.trim() || '';
            const qty = parseInt(row.querySelector('.prod-qty-input').value) || 0;
            const price = parseFloat(row.querySelector('.prod-price-input').value) || 0;
            const rowSubtotal = qty * price;
            subtotal += rowSubtotal;

            receiptRowsHtml += `
                <tr>
                    <td style="padding: 1rem;">
                        <div style="font-weight: 700; color: var(--text-main);">${escapeHtml(name)}</div>
                        ${sku ? `<div style="font-family: monospace; font-size: 0.75rem; color: var(--accent); margin-top: 0.15rem; font-weight: 700;">${escapeHtml(sku)}</div>` : ''}
                        ${desc ? `<div style="font-size: 0.75rem; color: var(--text-muted); margin-top: 0.25rem;">${escapeHtml(desc)}</div>` : ''}
                    </td>
                    <td style="padding: 1rem; text-align: right; font-weight: 600;">${qty}</td>
                    <td style="padding: 1rem; text-align: right; font-weight: 600;">${formatNumberOnly(price)}</td>
                    <td style="padding: 1rem; text-align: right; font-weight: 700; color: var(--text-main);">${formatNumberOnly(rowSubtotal)}</td>
                </tr>
            `;
        });

        const receiptTableBody = document.getElementById('receipt-product-rows');
        if (receiptTableBody) {
            receiptTableBody.innerHTML = receiptRowsHtml;
        }

        const grandTotal = subtotal + taxes + shipping - discount;

        /* Company + Invoice meta */
        document.getElementById('receipt-company-name').innerText = companyProfile.name || 'NexCore Apparel';
        document.getElementById('receipt-company-address').innerText = companyProfile.address || '';
        
        const logoContainer = document.getElementById('receipt-logo-container');
        if (logoContainer) {
            if (companyProfile.logo) {
                let logoSrc = companyProfile.logo;
                if (!logoSrc.startsWith('http') && !logoSrc.startsWith('/')) {
                    const basePath = window.APP_CONFIG ? window.APP_CONFIG.BASE_PATH : '/';
                    logoSrc = basePath + logoSrc;
                }
                logoContainer.innerHTML = `<img src="${logoSrc}" alt="Logo" style="max-height: 38px; max-width: 120px; object-fit: contain; border-radius: 6px;">`;
            } else {
                logoContainer.innerHTML = `<i class="fas fa-layer-group" id="receipt-default-logo"></i>`;
            }
        }
        
        const contacts = [];
        if (companyProfile.phone) contacts.push(companyProfile.phone);
        if (companyProfile.email) contacts.push(companyProfile.email);
        if (companyProfile.website) contacts.push(companyProfile.website);
        document.getElementById('receipt-company-contacts').innerText = contacts.join(' | ');

        document.getElementById('receipt-invoice-number').innerText = activeInvoice.invoice_number || '';

        /* Dates */
        try {
            const genDate = new Date(activeInvoice.created_at);
            document.getElementById('receipt-created-at').innerText = isNaN(genDate) ? activeInvoice.created_at : genDate.toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' });
        } catch(e) {
            document.getElementById('receipt-created-at').innerText = activeInvoice.created_at || '—';
        }

        const dueDateVal = document.getElementById('edit-due-date').value;
        if (dueDateVal) {
            try {
                const dueDate = new Date(dueDateVal + 'T00:00:00');
                document.getElementById('receipt-due-date').innerText = dueDate.toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' });
            } catch(e) {
                document.getElementById('receipt-due-date').innerText = dueDateVal;
            }
        } else {
            document.getElementById('receipt-due-date').innerText = 'N/A';
        }

        document.getElementById('receipt-po-reference').innerText    = poRef;
        document.getElementById('receipt-payment-terms').innerText   = payTerms;
        const bName = document.getElementById('edit-buyer-name').value || '';
        const bBrand = document.getElementById('edit-buyer-brand').value || '';
        const bContact = document.getElementById('edit-buyer-contact').value || '';
        const bEmail = document.getElementById('edit-buyer-email').value || '';
        const bPhone = document.getElementById('edit-buyer-phone').value || '';
        const bCountry = document.getElementById('edit-buyer-country').value || '';

        const buyerDetailsText = `Name: ${bName}\nBrand: ${bBrand}\nContact: ${bContact}\nEmail: ${bEmail}\nPhone: ${bPhone}\nCountry: ${bCountry}`;
        document.getElementById('receipt-buyer-details').innerText = bName ? buyerDetailsText : '—';

        /* Breakdown */
        document.getElementById('receipt-breakdown-subtotal').innerText   = formatCurrency(subtotal);
        document.getElementById('receipt-breakdown-taxes').innerText      = formatCurrency(taxes);
        document.getElementById('receipt-breakdown-shipping').innerText   = formatCurrency(shipping);
        document.getElementById('receipt-breakdown-discounts').innerText  = formatCurrency(discount);
        document.getElementById('receipt-breakdown-grandtotal').innerText = formatCurrency(grandTotal);

        const paymentsRow = document.getElementById('receipt-payments-row');
        if (paymentsRow) {
            if (activeInvoice && activeInvoice.id) {
                paymentsRow.style.display = 'flex';
                const totalPaid = (window.activeInvoicePayments || []).reduce((sum, p) => sum + parseFloat(p.amount), 0);
                const balanceDue = Math.max(0, grandTotal - totalPaid);
                document.getElementById('receipt-breakdown-totalpaid').innerText = formatCurrency(totalPaid);
                document.getElementById('receipt-breakdown-balancedue').innerText = formatCurrency(balanceDue);
            } else {
                paymentsRow.style.display = 'none';
            }
        }
    } catch(e) {
        console.error('updateLiveReceipt error:', e);
    }
}

/* ── Save Invoice ── */
async function saveInvoice(e) {
    if (e && e.preventDefault) e.preventDefault();
    const btn = document.getElementById('saveInvoiceBtn');
    const issueBtn = document.getElementById('issueInvoiceBtn');

    // Collect installments if scheduler is visible
    const installments = [];
    const scheduler = document.getElementById('installment-scheduler');
    if (scheduler && scheduler.style.display !== 'none') {
        scheduler.querySelectorAll('.installment-row').forEach(row => {
            const dt  = row.querySelector('.inst-date').value.trim();
            const amt = parseFloat(row.querySelector('.inst-amount').value) || 0;
            const dsc = row.querySelector('.inst-desc').value.trim();
            if (dt && amt > 0) installments.push({ due_date: dt, amount: amt, description: dsc });
        });
    }

    const isCreate = !document.getElementById('edit-invoice-id').value;

    const productRows = document.querySelectorAll('.invoice-product-item-block');
    const products = [];
    let totalQty = 0;
    let firstUnitPrice = 0;
    let totalSubtotal = 0;

    productRows.forEach((row, i) => {
        const name = row.querySelector('.prod-name-input').value.trim();
        const sku = row.querySelector('.prod-sku-input').value.trim();
        const desc = row.querySelector('.prod-desc-input').value.trim();
        const qty = parseInt(row.querySelector('.prod-qty-input').value) || 0;
        const price = parseFloat(row.querySelector('.prod-price-input').value) || 0;

        products.push({
            name: name,
            sku: sku,
            description: desc,
            quantity: qty,
            unit_price: price
        });

        totalQty += qty;
        totalSubtotal += qty * price;
        if (i === 0) {
            firstUnitPrice = price;
        }
    });

    const formData = {
        action:           isCreate ? 'create' : 'update',
        id:               document.getElementById('edit-invoice-id').value,
        po_reference:     document.getElementById('edit-po-reference').value,
        status:           document.getElementById('edit-status').value,
        taxes_vat:        document.getElementById('edit-taxes-vat').value,
        shipping_charges: document.getElementById('edit-shipping-charges').value,
        discounts:        document.getElementById('edit-discounts').value,
        payment_terms:    document.getElementById('edit-payment-terms').value,
        payment_term_id:  document.getElementById('edit-payment-terms-select').value || null,
        units_completed:  totalQty,
        unit_price:       firstUnitPrice,
        total_amount:     totalSubtotal,
        products:         products,
        due_date:         document.getElementById('edit-due-date').value,
        installments:     installments
    };

    formData.buyer_name    = document.getElementById('edit-buyer-name').value.trim();
    formData.buyer_brand   = document.getElementById('edit-buyer-brand').value.trim();
    formData.buyer_contact = document.getElementById('edit-buyer-contact').value.trim();
    formData.buyer_email   = document.getElementById('edit-buyer-email').value.trim();
    formData.buyer_phone   = document.getElementById('edit-buyer-phone').value.trim();
    formData.buyer_country = document.getElementById('edit-buyer-country').value.trim();

    if (btn) setLoading(btn, true);
    if (issueBtn) setLoading(issueBtn, true);
    try {
        const res = await apiCall('invoices', formData);
        if (res.success) {
            notify(res.message || 'Invoice saved successfully');
            showListView();
            loadInvoices(isCreate ? 1 : currentPage);
        } else {
            notify(res.message || 'Save failed', 'error');
        }
    } catch (err) {
        console.error('saveInvoice error:', err);
        notify('Save failed', 'error');
    } finally {
        if (btn) setLoading(btn, false);
        if (issueBtn) setLoading(issueBtn, false);
    }
}

/* ── Print ── */
function printReceipt() {
    window.print();
}

/* ── Lock/Unlock Form Fields ── */
function setFormReadOnly(readOnly) {
    const form = document.getElementById('invoiceEditForm');
    if (!form) return;

    const isLockedStatus = activeInvoice && (activeInvoice.status === 'Paid' || activeInvoice.status === 'Cancelled');
    if (isLockedStatus) {
        readOnly = true;
    }

    // Get all inputs, selects, textareas
    const elements = form.querySelectorAll('input, select, textarea');
    elements.forEach(el => {
        if (el.type !== 'hidden') {
            el.disabled = readOnly;
        }
    });

    // Disable buttons
    const formButtons = form.querySelectorAll('button');
    formButtons.forEach(btn => {
        const onclickAttr = btn.getAttribute('onclick') || '';
        if (onclickAttr.includes('showListView')) {
            btn.disabled = false;
        } else {
            btn.disabled = readOnly;
            if (btn.innerText.includes('Add Installment') || btn.querySelector('.fa-times')) {
                btn.style.display = readOnly ? 'none' : 'inline-flex';
            }
        }
    });

    // Hide/show product row deletion and "+ Add Product" button based on read-only
    const addProductBtn = document.getElementById('add-product-btn');
    if (addProductBtn) {
        addProductBtn.style.display = readOnly ? 'none' : 'inline-flex';
    }
    const delBtns = form.querySelectorAll('.btn-row-delete');
    delBtns.forEach(btn => {
        btn.style.display = readOnly ? 'none' : (form.querySelectorAll('.invoice-product-item-block').length === 1 ? 'none' : 'flex');
    });

    // Toggle edit pen icon container
    const editContainer = document.getElementById('invoiceEditIconContainer');
    if (editContainer) {
        editContainer.style.display = (readOnly && !isLockedStatus) ? 'block' : 'none';
    }

    // Toggle Save and Issue buttons visibility
    const saveBtn = document.getElementById('saveInvoiceBtn');
    const issueBtn = document.getElementById('issueInvoiceBtn');
    if (saveBtn) {
        saveBtn.style.display = readOnly ? 'none' : 'inline-flex';
    }
    if (issueBtn) {
        issueBtn.style.display = readOnly ? 'none' : 'inline-flex';
    }
}

/* ── Trigger Issue Invoice ── */
async function triggerIssueInvoice() {
    const confirmed = await confirmAction({
        title: 'Issue Invoice',
        message: 'Are you sure you want to issue this invoice? Once issued, the invoice will be set to "Issued" and locked as read-only. You can unlock it to edit using the edit icon in the form header.',
        confirmText: 'Issue'
    });
    if (confirmed) {
        document.getElementById('edit-status').value = 'Issued';
        await saveInvoice();
    }
}

/* ── Cancel Invoice Helper ── */
async function cancelInvoice(id) {
    const confirmed = await confirmAction({
        title: 'Cancel Invoice',
        message: 'Are you sure you want to cancel this invoice? Cancelled invoices cannot be edited or processed for payments.',
        confirmText: 'Cancel Invoice',
        confirmClass: 'var(--danger)'
    });
    if (confirmed) {
        try {
            const res = await apiCall('invoices', { action: 'cancel_invoice', id: id });
            if (res.success) {
                notify(res.message || 'Invoice cancelled successfully', 'success');
                loadInvoices(currentPage);
            } else {
                notify(res.message || 'Failed to cancel invoice', 'error');
            }
        } catch (err) {
            console.error('cancelInvoice error:', err);
            notify('Failed to cancel invoice', 'error');
        }
    }
}

/* ── Payments Tab & Collection Module handlers ── */
function switchDetailTab(tab) {
    const btnDetails  = document.getElementById('tabBtnDetails');
    const btnPayments = document.getElementById('tabBtnPayments');
    const panelDetails  = document.getElementById('invoiceDetailsTabPanel');
    const panelPayments = document.getElementById('invoicePaymentsTabPanel');
    const receiptSection = document.getElementById('print-receipt-section');
    const mainGrid    = document.getElementById('invoiceDetailGrid');

    if (tab === 'details') {
        if (btnDetails)  { btnDetails.style.background  = 'var(--primary)'; btnDetails.style.color  = '#fff'; }
        if (btnPayments) { btnPayments.style.background = 'transparent'; btnPayments.style.color = 'var(--text-muted)'; }
        if (panelDetails)  panelDetails.style.display  = 'flex';
        if (panelPayments) panelPayments.style.display = 'none';
        // Restore the receipt panel and two-column grid
        if (receiptSection) receiptSection.style.display = 'flex';
        if (mainGrid) mainGrid.style.gridTemplateColumns = '1.4fr 1fr';
    } else if (tab === 'payments') {
        if (btnDetails)  { btnDetails.style.background  = 'transparent'; btnDetails.style.color  = 'var(--text-muted)'; }
        if (btnPayments) { btnPayments.style.background = 'var(--primary)'; btnPayments.style.color = '#fff'; }
        if (panelDetails)  panelDetails.style.display  = 'none';
        if (panelPayments) panelPayments.style.display = 'flex';
        // Hide receipt, expand right panel to full width
        if (receiptSection) receiptSection.style.display = 'none';
        if (mainGrid) mainGrid.style.gridTemplateColumns = '1fr';
        // Focus amount input
        const payAmountInput = document.getElementById('pay-amount');
        if (payAmountInput && document.getElementById('addPaymentFormContainer') &&
            document.getElementById('addPaymentFormContainer').style.display !== 'none') {
            setTimeout(() => payAmountInput.focus(), 100);
        }
    }
}

async function loadPayments(invoiceId) {
    try {
        const res = await apiCall('invoices', { action: 'get_payments', invoice_id: invoiceId });
        if (res.success) {
            window.activeInvoicePayments = res.payments || [];
            
            // Calculate totals dynamically
            const productRows = document.querySelectorAll('.invoice-product-item-block');
            let subtotal = 0;
            productRows.forEach(row => {
                const qty = parseInt(row.querySelector('.prod-qty-input').value) || 0;
                const price = parseFloat(row.querySelector('.prod-price-input').value) || 0;
                subtotal += qty * price;
            });
            const taxes = parseFloat(document.getElementById('edit-taxes-vat').value) || 0;
            const shipping = parseFloat(document.getElementById('edit-shipping-charges').value) || 0;
            const discount = parseFloat(document.getElementById('edit-discounts').value) || 0;
            const grandTotal = subtotal + taxes + shipping - discount;
            
            const totalPaid = window.activeInvoicePayments.reduce((sum, p) => sum + parseFloat(p.amount), 0);
            const balanceDue = Math.max(0, grandTotal - totalPaid);
            
            // Update summary cards
            document.getElementById('payment-summary-grandtotal').innerText = formatCurrency(grandTotal);
            document.getElementById('payment-summary-totalpaid').innerText = formatCurrency(totalPaid);
            document.getElementById('payment-summary-balancedue').innerText = formatCurrency(balanceDue);
            
            // Update receipt preview
            updateLiveReceipt();

            // Update Payments tab badge count
            const tabBadge = document.getElementById('paymentsTabBadge');
            const tabBadge2 = document.getElementById('paymentsTabBadge2');
            const cnt = window.activeInvoicePayments.length;
            if (tabBadge) {
                tabBadge.style.display = cnt > 0 ? 'inline-block' : 'none';
                tabBadge.textContent = cnt;
            }
            if (tabBadge2) {
                tabBadge2.textContent = cnt > 0 ? cnt + ' record' + (cnt > 1 ? 's' : '') : 'No records yet';
            }
            
            // Toggle Record Payment Form vs Fully Paid Banner
            const formContainer = document.getElementById('addPaymentFormContainer');
            const fullyPaidBanner = document.getElementById('fullyPaidMessage');
            
            if (balanceDue <= 0.005) {
                if (formContainer) formContainer.style.display = 'none';
                if (fullyPaidBanner) fullyPaidBanner.style.display = 'flex';
            } else {
                if (formContainer) formContainer.style.display = 'flex';
                if (fullyPaidBanner) fullyPaidBanner.style.display = 'none';
                
                // Pre-fill fields
                const payAmount = document.getElementById('pay-amount');
                if (payAmount) {
                    payAmount.value = balanceDue.toFixed(2);
                    payAmount.max = balanceDue.toFixed(2);
                }
                const payDate = document.getElementById('pay-date');
                if (payDate) {
                    payDate.value = new Date().toISOString().split('T')[0];
                }
                const payRef = document.getElementById('pay-reference');
                if (payRef) payRef.value = '';
                const payNotes = document.getElementById('pay-notes');
                if (payNotes) payNotes.value = '';
            }
            
            // Render Payment History
            const historyList = document.getElementById('paymentsHistoryList');
            if (historyList) {
                if (window.activeInvoicePayments.length === 0) {
                    historyList.innerHTML = '<div style="text-align:center; padding:2rem; color:var(--text-muted); font-size:0.85rem;"><i class="fas fa-receipt fa-2x" style="opacity:0.3; display:block; margin-bottom:0.5rem;"></i>No payments recorded yet.</div>';
                } else {
                    historyList.innerHTML = window.activeInvoicePayments.map(p => {
                        const pDate = new Date(p.payment_date).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
                        const refText = p.reference_no ? `<span style="font-size:0.75rem; color:var(--text-muted); background:var(--bg-dark); padding:0.15rem 0.4rem; border-radius:4px; font-family:monospace; margin-left:0.5rem;">Ref: ${escapeHtml(p.reference_no)}</span>` : '';
                        const notesText = p.notes ? `<div style="font-size:0.75rem; color:var(--text-muted); margin-top:0.25rem; font-style:italic;">${escapeHtml(p.notes)}</div>` : '';
                        const attachmentsHtml = (p.attachments && p.attachments.length > 0) ? `
                            <div style="display:flex; flex-wrap:wrap; gap:0.35rem; margin-top:0.45rem;">
                                ${p.attachments.map(att => {
                                    const isPdf = att.file_type && att.file_type.includes('pdf');
                                    const isImg = att.file_type && att.file_type.startsWith('image/');
                                    const icon = isPdf ? 'fa-file-pdf' : isImg ? 'fa-file-image' : 'fa-file-alt';
                                    const dispName = att.original_name.length > 24 ? att.original_name.substring(0,24)+'…' : att.original_name;
                                    return `<a href="/api/invoices.php?action=get_attachment&id=${att.id}" target="_blank" style="display:inline-flex;align-items:center;gap:0.3rem;background:rgba(124,58,237,0.07);color:var(--primary);border:1px solid rgba(124,58,237,0.2);border-radius:6px;padding:0.2rem 0.55rem;font-size:0.72rem;font-weight:600;text-decoration:none;transition:all 0.15s;" title="${escapeHtml(att.original_name)}"><i class="fas ${icon}" style="font-size:0.7rem;"></i>${escapeHtml(dispName)}</a>`;
                                }).join('')}
                            </div>` : '';

                        return `
                            <div style="background:var(--bg-dark); border:1px solid var(--border); border-radius:12px; padding:0.85rem 1rem; display:flex; justify-content:space-between; align-items:flex-start; gap:1rem; transition:all 0.2s;">
                                <div style="flex:1; min-width:0;">
                                    <div style="display:flex; align-items:center; flex-wrap:wrap; gap:0.25rem;">
                                        <span style="font-weight:700; color:var(--text-main); font-size:0.85rem;">${p.payment_method}</span>
                                        ${refText}
                                        <span style="font-size:0.78rem; color:var(--text-muted); margin-left:auto;">${pDate}</span>
                                    </div>
                                    ${notesText}
                                    ${attachmentsHtml}
                                </div>
                                <div style="display:flex; align-items:center; gap:0.75rem; flex-shrink:0;">
                                    <span style="font-weight:800; color:var(--success); font-size:0.95rem;">${formatCurrency(p.amount)}</span>
                                    ${(activeInvoice && activeInvoice.status === 'Paid') ? '' : `
                                    <button type="button" class="btn-icon btn-sm" onclick="deletePayment(${p.id})" style="background:rgba(239,68,68,0.1); color:var(--danger); border:none; cursor:pointer; width:30px; height:30px; border-radius:6px; display:inline-flex; align-items:center; justify-content:center;" title="Delete Payment">
                                        <i class="fas fa-trash" style="font-size:0.78rem;"></i>
                                    </button>
                                    `}
                                </div>
                            </div>
                        `;
                    }).join('');
                }
            }
        } else {
            notify(res.message || 'Failed to load payments', 'error');
        }
    } catch (err) {
        console.error('loadPayments error:', err);
        notify('Failed to load payments', 'error');
    }
}

async function submitPayment(e) {
    if (e && e.preventDefault) e.preventDefault();
    if (!activeInvoice || !activeInvoice.id) return;

    const btn = document.getElementById('recordPaymentBtn');
    const amount = parseFloat(document.getElementById('pay-amount').value) || 0;
    const payment_date = document.getElementById('pay-date').value;
    const payment_method = document.getElementById('pay-method').value;
    const reference_no = document.getElementById('pay-reference').value.trim();
    const notes = document.getElementById('pay-notes').value.trim();

    if (amount <= 0) {
        notify('Please enter a valid amount greater than zero', 'error');
        return;
    }

    if (btn) setLoading(btn, true);
    try {
        // Use FormData to support file attachments
        const formData = new FormData();
        formData.append('action', 'add_payment');
        formData.append('invoice_id', activeInvoice.id);
        formData.append('amount', amount);
        formData.append('payment_date', payment_date);
        formData.append('payment_method', payment_method);
        formData.append('reference_no', reference_no);
        formData.append('notes', notes);

        const filesInput = document.getElementById('pay-attachments');
        if (filesInput && filesInput.files.length > 0) {
            Array.from(filesInput.files).forEach(file => formData.append('attachments[]', file));
        }

        const resp = await fetch('/api/invoices.php', { method: 'POST', body: formData, credentials: 'same-origin' });
        if (!resp.ok) throw new Error('HTTP ' + resp.status);
        const res = await resp.json();

        if (res.success) {
            notify(res.message || 'Payment recorded successfully', 'success');

            // Reset attachment input
            if (filesInput) { filesInput.value = ''; updateAttachmentPreview(); }

            // Sync status
            if (res.invoice_status) {
                activeInvoice.status = res.invoice_status;
                const statusSelect = document.getElementById('edit-status');
                if (statusSelect) statusSelect.value = res.invoice_status;

                // Re-evaluate Payments tab visibility
                updatePaymentsTabVisibility(res.invoice_status);

                // Lock the form details if Paid or Partially Paid
                if (res.invoice_status === 'Paid' || res.invoice_status === 'Partially Paid') {
                    setFormReadOnly(true);
                }
            }

            // Refresh
            await loadPayments(activeInvoice.id);
            loadInvoices(currentPage);
        } else {
            notify(res.message || 'Failed to record payment', 'error');
        }
    } catch (err) {
        console.error('submitPayment error:', err);
        notify('Failed to record payment', 'error');
    } finally {
        if (btn) setLoading(btn, false);
    }
}

async function deletePayment(paymentId) {
    if (!activeInvoice || !activeInvoice.id) return;
    
    const confirmed = await confirmAction({
        title: 'Delete Payment',
        message: 'Are you sure you want to delete this payment record? This will revert the paid amount and update the invoice status.',
        confirmText: 'Delete'
    });
    
    if (confirmed) {
        try {
            const res = await apiCall('invoices', {
                action: 'delete_payment',
                payment_id: paymentId,
                invoice_id: activeInvoice.id
            });
            
            if (res.success) {
                notify(res.message || 'Payment deleted successfully', 'success');
                
                // Sync status
                if (res.invoice_status) {
                    activeInvoice.status = res.invoice_status;
                    const statusSelect = document.getElementById('edit-status');
                    if (statusSelect) statusSelect.value = res.invoice_status;

                    // Re-evaluate Payments tab visibility
                    updatePaymentsTabVisibility(res.invoice_status);

                    // Re-evaluate form read-only lock based on new status
                    const isLocked = (res.invoice_status === 'Issued' || res.invoice_status === 'Partially Paid' || res.invoice_status === 'Paid' || res.invoice_status === 'Past Due');
                    setFormReadOnly(isLocked);
                }
                
                // Refresh
                await loadPayments(activeInvoice.id);
                loadInvoices(currentPage);
            } else {
                notify(res.message || 'Failed to delete payment', 'error');
            }
        } catch (err) {
            console.error('deletePayment error:', err);
            notify('Failed to delete payment', 'error');
        }
    }
}

/* ── Payments Tab Visibility Helper ── */
function updatePaymentsTabVisibility(status) {
    const tabsBar = document.getElementById('invoiceDetailTabs');
    if (!tabsBar) return;
    const showPayments = ['Issued', 'Partially Paid', 'Paid', 'Past Due'].includes(status);
    tabsBar.style.display = showPayments ? 'flex' : 'none';
    if (!showPayments) switchDetailTab('details');
}

/* ── Attachment File Preview ── */
function updateAttachmentPreview() {
    const filesInput = document.getElementById('pay-attachments');
    const preview = document.getElementById('attachment-preview');
    const hint = document.getElementById('attachment-drop-hint');
    if (!filesInput || !preview) return;
    const files = Array.from(filesInput.files);
    if (hint) hint.style.display = files.length > 0 ? 'none' : 'block';
    if (files.length === 0) { preview.innerHTML = ''; return; }
    preview.innerHTML = files.map(file => {
        const isPdf = file.type === 'application/pdf';
        const isImg = file.type.startsWith('image/');
        const icon = isPdf ? 'fa-file-pdf' : isImg ? 'fa-file-image' : 'fa-file-alt';
        const sz = file.size < 1024 ? file.size + 'B' : file.size < 1048576 ? (file.size / 1024).toFixed(0) + 'KB' : (file.size / 1048576).toFixed(1) + 'MB';
        const safeName = file.name.length > 18 ? file.name.substring(0, 18) + '…' : file.name;
        return `<div style="display:inline-flex;align-items:center;gap:0.3rem;background:var(--bg-card);border:1px solid var(--border);border-radius:8px;padding:0.3rem 0.6rem;font-size:0.74rem;max-width:175px;overflow:hidden;" title="${file.name}">
            <i class="fas ${icon}" style="color:var(--primary);flex-shrink:0;font-size:0.8rem;"></i>
            <span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;color:var(--text-main);">${safeName}</span>
            <span style="color:var(--text-muted);flex-shrink:0;white-space:nowrap;">${sz}</span>
        </div>`;
    }).join('');
}

function handleAttachmentDrop(event) {
    event.preventDefault();
    event.stopPropagation();
    const filesInput = document.getElementById('pay-attachments');
    if (!filesInput) return;
    const dt = event.dataTransfer;
    if (dt && dt.files.length > 0) {
        try {
            const dtNew = new DataTransfer();
            Array.from(filesInput.files).forEach(f => dtNew.items.add(f));
            Array.from(dt.files).forEach(f => dtNew.items.add(f));
            filesInput.files = dtNew.files;
        } catch (ex) {
            // Fallback: just use dropped files
            const dtNew = new DataTransfer();
            Array.from(dt.files).forEach(f => dtNew.items.add(f));
            filesInput.files = dtNew.files;
        }
    }
    updateAttachmentPreview();
    const zone = document.getElementById('attachment-drop-zone');
    if (zone) { zone.style.borderColor = 'var(--border)'; zone.style.background = 'var(--bg-dark)'; }
}

/* ── Back to List ── */
function showListView() {
    document.getElementById('invoiceDetailView').style.display = 'none';
    document.getElementById('invoiceListView').style.display   = 'flex';
    activeInvoice = null;
    paymentTermsCache = null; // Clear cache so fresh load next time (optional - keep cache for perf)
}

/* ── Payment Terms Dropdown ── */
async function loadPaymentTerms(invoiceId) {
    try {
        const res = await apiCall('invoices', { action: 'get_payment_terms', invoice_id: invoiceId || 0 });
        if (res.success) {
            paymentTermsCache = res.terms;
            populatePaymentTermsDropdown();
            return res;
        }
    } catch(e) {
        console.error('loadPaymentTerms error:', e);
    }
    return null;
}

function populatePaymentTermsDropdown() {
    const sel = document.getElementById('edit-payment-terms-select');
    if (!sel || !paymentTermsCache) return;
    const currentVal = sel.value; // preserve selection
    sel.innerHTML = '<option value="">— Select Payment Terms —</option>';
    paymentTermsCache.forEach(term => {
        const opt = document.createElement('option');
        opt.value = term.id;
        opt.textContent = term.name;
        opt.dataset.description = term.description || '';
        opt.dataset.requiresInstallment = term.requires_installment;
        sel.appendChild(opt);
    });
    // Restore selection
    if (currentVal) sel.value = currentVal;
}

function onPaymentTermChange() {
    const sel = document.getElementById('edit-payment-terms-select');
    const hidden = document.getElementById('edit-payment-terms');
    const scheduler = document.getElementById('installment-scheduler');
    if (!sel) return;

    const opt = sel.options[sel.selectedIndex];
    const termLabel = opt ? opt.textContent.trim() : '';
    const requiresInstallment = opt ? (opt.dataset.requiresInstallment == '1') : false;

    // Sync hidden field (used in receipt + API)
    if (hidden) hidden.value = termLabel === '— Select Payment Terms —' ? '' : termLabel;

    // Show/hide installment scheduler
    if (scheduler) {
        if (requiresInstallment) {
            scheduler.style.display = 'flex';
            // Add one row if empty
            const rows = document.getElementById('installment-rows');
            if (rows && rows.children.length === 0) addInstallmentRow();
        } else {
            scheduler.style.display = 'none';
        }
    }

    updateLiveReceipt();
}

let instRowCount = 0;
function addInstallmentRow(date = '', amount = '', desc = '') {
    const container = document.getElementById('installment-rows');
    if (!container) return;
    const rowId = 'inst-row-' + (++instRowCount);
    const row = document.createElement('div');
    row.className = 'installment-row';
    row.id = rowId;
    row.style.cssText = 'display: grid; grid-template-columns: 1fr 1fr 1.5fr auto; gap: 0.5rem; align-items: center;';
    row.innerHTML = `
        <input type="date" class="inst-date form-control" value="${date}" placeholder="Due Date"
            style="font-size:0.82rem; padding:0.5rem 0.7rem;" oninput="updateInstallmentSummary()">
        <input type="number" class="inst-amount form-control" value="${amount}" placeholder="Amount" min="0" step="0.01"
            style="font-size:0.82rem; padding:0.5rem 0.7rem;" oninput="updateInstallmentSummary()">
        <input type="text" class="inst-desc form-control" value="${desc}" placeholder="Note (optional)"
            style="font-size:0.82rem; padding:0.5rem 0.7rem;">
        <button type="button" onclick="document.getElementById('${rowId}').remove(); updateInstallmentSummary();"
            style="width:32px;height:32px;border-radius:8px;background:rgba(239,68,68,0.1);border:none;cursor:pointer;color:var(--danger);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
            <i class="fas fa-times" style="font-size:0.8rem;"></i>
        </button>
    `;
    container.appendChild(row);
    updateInstallmentSummary();
}

function updateInstallmentSummary() {
    const summary = document.getElementById('installment-summary');
    const rows = document.querySelectorAll('#installment-rows .installment-row');
    if (!summary) return;
    let total = 0;
    rows.forEach(r => {
        const amt = parseFloat(r.querySelector('.inst-amount').value) || 0;
        total += amt;
    });
    const sym = (window.APP_CONFIG && window.APP_CONFIG.COMPANY_CURRENCY) ? window.APP_CONFIG.COMPANY_CURRENCY : '<?php echo addslashes($currency); ?>';
    summary.innerText = `${rows.length} installment(s) — Total: ${sym} ${total.toLocaleString(undefined, {minimumFractionDigits:2,maximumFractionDigits:2})}`;
}

/* ── Email Invoice Modal ── */
function openEmailModal() {
    if (!activeInvoice) return;

    // Populate the chip summary inside the modal
    document.getElementById('email-modal-invnum').innerText = activeInvoice.invoice_number || 'N/A';
    document.getElementById('email-modal-buyer').innerText  = getBuyerName(activeInvoice.buyer_details);

    // Pre-fill email from buyer details if available
    const emailMatch = (activeInvoice.buyer_details || '').match(/Email:\s*(\S+)/i);
    document.getElementById('emailRecipient').value = emailMatch ? emailMatch[1].trim() : '';

    const modal = document.getElementById('emailInvoiceModal');
    modal.style.display = 'flex';
    // Focus the email input
    setTimeout(() => document.getElementById('emailRecipient').focus(), 80);
}

function closeEmailModal() {
    document.getElementById('emailInvoiceModal').style.display = 'none';
}

async function confirmSendEmail() {
    const emailInput = document.getElementById('emailRecipient');
    const email = emailInput.value.trim();
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        emailInput.style.borderColor = 'var(--danger)';
        emailInput.style.boxShadow   = '0 0 0 3px rgba(239,68,68,0.15)';
        emailInput.focus();
        notify('Please enter a valid email address', 'error');
        return;
    }
    // Reset validation style
    emailInput.style.borderColor = '';
    emailInput.style.boxShadow   = '';

    const btn     = document.getElementById('sendEmailBtn');
    setLoading(btn, true);

    try {
        const res = await apiCall('invoices', {
            action:     'send_email',
            id:         activeInvoice.id,
            email:      email
        });
        if (res.success) {
            closeEmailModal();
            notify('Invoice emailed successfully to ' + email, 'success');
        } else {
            notify(res.message || 'Failed to send email', 'error');
        }
    } catch(e) {
        console.error('confirmSendEmail error:', e);
        notify('Failed to send email', 'error');
    } finally {
        setLoading(btn, false);
    }
}

// Close email modal on backdrop click
document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('emailInvoiceModal').addEventListener('click', function(e) {
        if (e.target === this) closeEmailModal();
    });
});

/* ── Init ── */
document.addEventListener('DOMContentLoaded', () => {
    loadInvoices();

    // Autocomplete Input Listeners
    const buyerInput = document.getElementById('edit-buyer-name');

    if (buyerInput) {
        buyerInput.addEventListener('focus', () => {
            if (!buyerInput.disabled) {
                renderBuyerSuggestions(buyerInput.value);
            }
        });
        buyerInput.addEventListener('input', () => {
            if (!buyerInput.disabled) {
                renderBuyerSuggestions(buyerInput.value);
            }
        });
    }

    // Close suggestion boxes on document click outside
    document.addEventListener('click', (e) => {
        const buyerSuggestions = document.getElementById('buyer_suggestions');
        if (buyerInput && buyerSuggestions && !buyerInput.contains(e.target) && !buyerSuggestions.contains(e.target)) {
            buyerSuggestions.style.display = 'none';
        }
        
        // Close product row suggestions
        document.querySelectorAll('.invoice-product-item-block').forEach(row => {
            const suggestionsBox = row.querySelector('.prod-suggestions-box');
            const nameInput = row.querySelector('.prod-name-input');
            if (suggestionsBox && nameInput && !nameInput.contains(e.target) && !suggestionsBox.contains(e.target)) {
                suggestionsBox.style.display = 'none';
            }
        });
    });

    let searchTimer = null;
    document.getElementById('invoiceSearch').addEventListener('input', () => {
        clearTimeout(searchTimer);
        searchTimer = setTimeout(() => loadInvoices(1), 300);
    });
    document.getElementById('statusFilter').addEventListener('change', () => loadInvoices(1));
});
</script>
