<!-- ===== Product Detail Modal ===== -->
<div id="productDetailModal" style="display:none;position:fixed;inset:0;z-index:9000;align-items:center;justify-content:center;background:rgba(15,23,42,0.55);">
    <div style="background:#fff;border-radius:10px;width:min(940px,96vw);max-height:90vh;display:flex;flex-direction:column;box-shadow:0 12px 48px rgba(0,0,0,0.25);">

        <!-- Header -->
        <div style="padding:14px 20px 12px;border-bottom:1px solid var(--border,#e2e8f0);display:flex;align-items:flex-start;gap:12px;flex-shrink:0;">
            <div style="flex:1;min-width:0;">
                <h3 id="pdProductName" style="margin:0;font-size:16px;font-weight:700;color:var(--text-primary,#1e293b);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">—</h3>
                <div id="pdProductMeta" style="margin-top:3px;font-size:12px;color:var(--text-muted,#94a3b8);"></div>
            </div>
            <button onclick="closePdModal()" style="background:none;border:none;cursor:pointer;font-size:20px;color:var(--text-muted,#94a3b8);padding:0 4px;line-height:1;flex-shrink:0;" title="Close">✕</button>
        </div>

        <!-- Summary strip — 5 stats -->
        <div style="display:flex;flex-shrink:0;border-bottom:1px solid var(--border,#e2e8f0);overflow-x:auto;">
            <div class="pd-stat-cell" style="border-right:1px solid var(--border,#e2e8f0);">
                <div class="pd-stat-label">Total Purchased</div>
                <div id="pdSumPurchased" class="pd-stat-val" style="color:var(--text-primary,#1e293b);">—</div>
            </div>
            <div class="pd-stat-cell" style="border-right:1px solid var(--border,#e2e8f0);">
                <div class="pd-stat-label">Total Sold</div>
                <div id="pdSumSold" class="pd-stat-val" style="color:var(--danger,#ef4444);">—</div>
            </div>
            <div class="pd-stat-cell" style="border-right:1px solid var(--border,#e2e8f0);">
                <div class="pd-stat-label">Available</div>
                <div id="pdSumAvail" class="pd-stat-val" style="color:var(--success,#16a34a);">—</div>
            </div>
            <div class="pd-stat-cell" style="border-right:1px solid var(--border,#e2e8f0);">
                <div class="pd-stat-label">Last Purchase Price<br><span style="font-weight:400;font-size:9px;">(incl. GST)</span></div>
                <div id="pdSumLastPur" class="pd-stat-val pd-stat-price" style="color:var(--primary,#2563eb);">—</div>
            </div>
            <div class="pd-stat-cell">
                <div class="pd-stat-label">Last Selling Price<br><span style="font-weight:400;font-size:9px;">(incl. GST)</span></div>
                <div id="pdSumLastSell" class="pd-stat-val pd-stat-price" style="color:#7c3aed;">—</div>
            </div>
        </div>

        <!-- Tabs -->
        <div style="display:flex;border-bottom:1px solid var(--border,#e2e8f0);padding:0 16px;flex-shrink:0;">
            <button id="pdTabBtnBatches" class="pd-tab-btn pd-tab-active" onclick="pdSwitchTab('batches')">
                <i class="fas fa-layer-group" style="margin-right:6px;font-size:12px;"></i>Stock Batches
            </button>
            <button id="pdTabBtnSales" class="pd-tab-btn" onclick="pdSwitchTab('sales')">
                <i class="fas fa-receipt" style="margin-right:6px;font-size:12px;"></i>Sales History
            </button>
        </div>

        <!-- Scrollable body -->
        <div style="flex:1;overflow:auto;min-height:0;">

            <!-- Batches pane -->
            <div id="pdPaneBatches">
                <table style="width:100%;border-collapse:collapse;font-size:12px;">
                    <thead>
                        <tr style="background:#f8fafc;">
                            <th class="pd-th" style="text-align:left;">Batch No</th>
                            <th class="pd-th" style="text-align:left;">Vendor</th>
                            <th class="pd-th" style="text-align:center;">Purchase Date</th>
                            <th class="pd-th" style="text-align:center;">Total Qty</th>
                            <th class="pd-th" style="text-align:center;">Available</th>
                            <th class="pd-th" style="text-align:right;">Purchase Price<br><span style="font-weight:400;font-size:10px;color:#94a3b8;">(incl. GST)</span></th>
                            <th class="pd-th" style="text-align:right;">MRP</th>
                            <th class="pd-th" style="text-align:center;">GST%</th>
                            <th class="pd-th" style="text-align:center;">Expiry</th>
                        </tr>
                    </thead>
                    <tbody id="pdBatchBody">
                        <tr><td colspan="9" class="pd-loading">Loading…</td></tr>
                    </tbody>
                </table>
            </div>

            <!-- Sales pane -->
            <div id="pdPaneSales" style="display:none;">
                <table style="width:100%;border-collapse:collapse;font-size:12px;">
                    <thead>
                        <tr style="background:#f8fafc;">
                            <th class="pd-th" style="text-align:left;">Date</th>
                            <th class="pd-th" style="text-align:left;">Invoice No</th>
                            <th class="pd-th" style="text-align:left;">Customer</th>
                            <th class="pd-th" style="text-align:center;">Qty Sold</th>
                            <th class="pd-th" style="text-align:right;">Selling Price<br><span style="font-weight:400;font-size:10px;color:#94a3b8;">(incl. GST)</span></th>
                            <th class="pd-th" style="text-align:right;">Line Total</th>
                        </tr>
                    </thead>
                    <tbody id="pdSalesBody">
                        <tr><td colspan="6" class="pd-loading">Loading…</td></tr>
                    </tbody>
                </table>
            </div>

        </div><!-- /body -->
    </div>
</div>


<!-- ===== Purchase Invoice Inner Modal ===== -->
<div id="poInvoiceModal" style="display:none;position:fixed;inset:0;z-index:9100;align-items:center;justify-content:center;background:rgba(15,23,42,0.45);">
    <div style="background:#fff;border-radius:10px;width:min(860px,95vw);max-height:88vh;display:flex;flex-direction:column;box-shadow:0 16px 56px rgba(0,0,0,0.3);">

        <div style="padding:14px 20px 12px;border-bottom:1px solid var(--border,#e2e8f0);display:flex;align-items:flex-start;gap:12px;flex-shrink:0;">
            <div style="flex:1;min-width:0;">
                <h3 style="margin:0;font-size:15px;font-weight:700;color:var(--text-primary,#1e293b);">
                    <i class="fas fa-file-invoice" style="color:var(--primary,#2563eb);margin-right:8px;font-size:13px;"></i>
                    Purchase Invoice — <span id="poiPoNo">…</span>
                </h3>
                <div id="poiMeta" style="margin-top:4px;font-size:12px;color:var(--text-muted,#94a3b8);"></div>
            </div>
            <button onclick="closePoInvoice()" style="background:none;border:none;cursor:pointer;font-size:20px;color:var(--text-muted,#94a3b8);padding:0 4px;line-height:1;flex-shrink:0;" title="Close">✕</button>
        </div>

        <div style="flex:1;overflow:auto;min-height:0;">
            <table style="width:100%;border-collapse:collapse;font-size:12px;">
                <thead>
                    <tr style="background:#f8fafc;">
                        <th class="pd-th" style="text-align:center;width:36px;">#</th>
                        <th class="pd-th" style="text-align:left;">Product</th>
                        <th class="pd-th" style="text-align:left;">Batch No</th>
                        <th class="pd-th" style="text-align:center;">Qty</th>
                        <th class="pd-th" style="text-align:center;">Available</th>
                        <th class="pd-th" style="text-align:right;">Rate<br><span style="font-weight:400;font-size:10px;color:#94a3b8;">(excl. GST)</span></th>
                        <th class="pd-th" style="text-align:center;">GST%</th>
                        <th class="pd-th" style="text-align:right;">Rate<br><span style="font-weight:400;font-size:10px;color:#94a3b8;">(incl. GST)</span></th>
                        <th class="pd-th" style="text-align:right;">Net Amount</th>
                        <th class="pd-th" style="text-align:right;">MRP</th>
                    </tr>
                </thead>
                <tbody id="poiItemBody">
                    <tr><td colspan="10" class="pd-loading">Loading…</td></tr>
                </tbody>
            </table>
        </div>

        <div id="poiTotals" style="border-top:1px solid var(--border,#e2e8f0);padding:10px 20px;display:flex;justify-content:flex-end;gap:28px;flex-shrink:0;background:#fafafa;border-radius:0 0 10px 10px;"></div>
    </div>
</div>


<!-- ===== Sales Invoice Inner Modal ===== -->
<div id="siInvoiceModal" style="display:none;position:fixed;inset:0;z-index:9100;align-items:center;justify-content:center;background:rgba(15,23,42,0.45);">
    <div style="background:#fff;border-radius:10px;width:min(860px,95vw);max-height:88vh;display:flex;flex-direction:column;box-shadow:0 16px 56px rgba(0,0,0,0.3);">

        <div style="padding:14px 20px 12px;border-bottom:1px solid var(--border,#e2e8f0);display:flex;align-items:flex-start;gap:12px;flex-shrink:0;">
            <div style="flex:1;min-width:0;">
                <h3 style="margin:0;font-size:15px;font-weight:700;color:var(--text-primary,#1e293b);">
                    <i class="fas fa-file-invoice-dollar" style="color:#7c3aed;margin-right:8px;font-size:13px;"></i>
                    Sales Invoice — <span id="siiInvNo">…</span>
                </h3>
                <div id="siiMeta" style="margin-top:4px;font-size:12px;color:var(--text-muted,#94a3b8);"></div>
            </div>
            <button onclick="closeSiInvoice()" style="background:none;border:none;cursor:pointer;font-size:20px;color:var(--text-muted,#94a3b8);padding:0 4px;line-height:1;flex-shrink:0;" title="Close">✕</button>
        </div>

        <div style="flex:1;overflow:auto;min-height:0;">
            <table style="width:100%;border-collapse:collapse;font-size:12px;">
                <thead>
                    <tr style="background:#f8fafc;">
                        <th class="pd-th" style="text-align:center;width:36px;">#</th>
                        <th class="pd-th" style="text-align:left;">Product</th>
                        <th class="pd-th" style="text-align:left;">Batch No</th>
                        <th class="pd-th" style="text-align:center;">Qty</th>
                        <th class="pd-th" style="text-align:right;">Rate<br><span style="font-weight:400;font-size:10px;color:#94a3b8;">(excl. GST)</span></th>
                        <th class="pd-th" style="text-align:center;">GST%</th>
                        <th class="pd-th" style="text-align:right;">Rate<br><span style="font-weight:400;font-size:10px;color:#94a3b8;">(incl. GST)</span></th>
                        <th class="pd-th" style="text-align:center;">Discount</th>
                        <th class="pd-th" style="text-align:right;">Line Total</th>
                    </tr>
                </thead>
                <tbody id="siiItemBody">
                    <tr><td colspan="9" class="pd-loading">Loading…</td></tr>
                </tbody>
            </table>
        </div>

        <div id="siiTotals" style="border-top:1px solid var(--border,#e2e8f0);padding:10px 20px;display:flex;justify-content:flex-end;gap:24px;align-items:center;flex-wrap:wrap;flex-shrink:0;background:#fafafa;border-radius:0 0 10px 10px;"></div>
    </div>
</div>


<style>
.pd-stat-cell {
    flex: 1;
    min-width: 100px;
    text-align: center;
    padding: 10px 8px;
}
.pd-stat-label {
    font-size: 10px;
    color: var(--text-muted, #94a3b8);
    text-transform: uppercase;
    letter-spacing: 0.06em;
    font-weight: 600;
    line-height: 1.3;
}
.pd-stat-val {
    font-size: 20px;
    font-weight: 700;
    margin-top: 3px;
    line-height: 1.1;
}
.pd-stat-price { font-size: 15px; }
.pd-tab-btn {
    padding: 10px 18px;
    font-size: 13px;
    font-weight: 500;
    color: var(--text-muted, #94a3b8);
    background: none;
    border: none;
    border-bottom: 2px solid transparent;
    cursor: pointer;
    margin-bottom: -1px;
    transition: color 0.15s;
}
.pd-tab-btn:hover { color: var(--primary, #2563eb); }
.pd-tab-active {
    color: var(--primary, #2563eb) !important;
    border-bottom-color: var(--primary, #2563eb) !important;
    font-weight: 600;
}
.pd-th {
    padding: 8px 12px;
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.04em;
    color: #64748b;
    border-bottom: 1px solid #e2e8f0;
    font-weight: 600;
    white-space: nowrap;
    position: sticky;
    top: 0;
    background: #f8fafc;
    z-index: 1;
}
.pd-loading {
    text-align: center;
    padding: 36px;
    color: #94a3b8;
    font-size: 13px;
}
.pd-tr { border-bottom: 1px solid #f1f5f9; }
.pd-tr:hover { background: #eef2ff !important; }
.pd-tr-soldout { opacity: 0.6; }
.pd-tr-soldout:hover { background: #fef2f2 !important; }
.pd-batch-link {
    cursor: pointer;
    font-family: monospace;
    font-weight: 700;
    color: #2563eb;
    text-decoration: underline;
    text-decoration-style: dotted;
    text-underline-offset: 2px;
}
.pd-batch-link:hover { color: #1d4ed8; text-decoration-style: solid; }
.pd-inv-link {
    cursor: pointer;
    font-family: monospace;
    font-size: 11px;
    font-weight: 700;
    color: #7c3aed;
    text-decoration: underline;
    text-decoration-style: dotted;
    text-underline-offset: 2px;
}
.pd-inv-link:hover { color: #6d28d9; text-decoration-style: solid; }
.pd-name-link {
    cursor: pointer;
    color: var(--text-primary, #1e293b);
    font-weight: 600;
}
.pd-name-link:hover {
    color: var(--primary, #2563eb);
    text-decoration: underline;
}
</style>


<script>
function openProductDetail(pid) {
    const modal = document.getElementById('productDetailModal');
    modal.style.display = 'flex';

    document.getElementById('pdProductName').textContent  = '…';
    document.getElementById('pdProductMeta').textContent  = '';
    document.getElementById('pdSumPurchased').textContent = '—';
    document.getElementById('pdSumSold').textContent      = '—';
    document.getElementById('pdSumAvail').textContent     = '—';
    document.getElementById('pdSumLastPur').textContent   = '—';
    document.getElementById('pdSumLastSell').textContent  = '—';
    document.getElementById('pdBatchBody').innerHTML      = '<tr><td colspan="9" class="pd-loading">Loading…</td></tr>';
    document.getElementById('pdSalesBody').innerHTML      = '<tr><td colspan="6" class="pd-loading">Loading…</td></tr>';
    pdSwitchTab('batches');

    fetch('../includes/product_detail_ajax.php?pid=' + pid)
        .then(r => r.json())
        .then(d => {
            if (d.error) { alert(d.error); closePdModal(); return; }

            /* Header */
            document.getElementById('pdProductName').textContent = d.product.name;
            const parts = [];
            if (d.product.category) parts.push(d.product.category);
            if (d.product.brand)    parts.push(d.product.brand);
            if (d.product.hsn_code) parts.push('HSN: ' + d.product.hsn_code);
            if (d.product.unit)     parts.push(d.product.unit);
            document.getElementById('pdProductMeta').textContent = parts.join(' • ');

            /* Summary */
            document.getElementById('pdSumPurchased').textContent = d.summary.total_purchased;
            document.getElementById('pdSumSold').textContent      = d.summary.total_sold;

            const avail   = d.summary.available;
            const availEl = document.getElementById('pdSumAvail');
            availEl.textContent = avail;
            availEl.style.color = avail === 0 ? 'var(--danger,#ef4444)'
                                : avail < 10   ? 'var(--warning,#f59e0b)'
                                :                'var(--success,#16a34a)';

            document.getElementById('pdSumLastPur').textContent  = d.summary.last_purchase_price_incl  !== null ? '₹ ' + parseFloat(d.summary.last_purchase_price_incl).toFixed(2)  : '—';
            document.getElementById('pdSumLastSell').textContent = d.summary.last_selling_price_incl   !== null ? '₹ ' + parseFloat(d.summary.last_selling_price_incl).toFixed(2)   : '—';

            /* Batches */
            if (d.batches.length === 0) {
                document.getElementById('pdBatchBody').innerHTML =
                    '<tr><td colspan="9" class="pd-loading"><i class="fas fa-box-open" style="display:block;font-size:22px;margin-bottom:6px;"></i>No purchase batches found</td></tr>';
            } else {
                document.getElementById('pdBatchBody').innerHTML = d.batches.map((b, i) => {
                    const soldOut   = parseInt(b.available_qty) === 0;
                    const rowClass  = soldOut ? 'pd-tr pd-tr-soldout' : 'pd-tr';
                    const stripeBg  = i % 2 !== 0 ? (soldOut ? 'background:#fef9f9;' : 'background:#f8fafc;') : '';
                    const availCell = soldOut
                        ? `<span style="font-size:10px;font-weight:700;padding:2px 6px;border-radius:10px;background:#fee2e2;color:#dc2626;">Sold Out</span>`
                        : `<span style="font-weight:700;color:#16a34a;">${b.available_qty}</span>`;
                    const batchLink = `<span class="pd-batch-link" onclick="openPoInvoice(${b.purchase_order_id})" title="View purchase invoice">${b.batch_no || '—'}</span>`;
                    return `<tr class="${rowClass}" style="${stripeBg}">
                        <td style="padding:7px 12px;">${batchLink}</td>
                        <td style="padding:7px 12px;">${b.vendor_name}</td>
                        <td style="padding:7px 12px;text-align:center;color:#64748b;">${b.purchase_date}</td>
                        <td style="padding:7px 12px;text-align:center;">${b.quantity}</td>
                        <td style="padding:7px 12px;text-align:center;">${availCell}</td>
                        <td style="padding:7px 12px;text-align:right;">&#8377; ${parseFloat(b.purchase_price_incl).toFixed(2)}</td>
                        <td style="padding:7px 12px;text-align:right;">&#8377; ${parseFloat(b.mrp).toFixed(2)}</td>
                        <td style="padding:7px 12px;text-align:center;">${parseFloat(b.gst_percent).toFixed(0)}%</td>
                        <td style="padding:7px 12px;text-align:center;color:#94a3b8;">${b.expiry_date || '—'}</td>
                    </tr>`;
                }).join('');
            }

            /* Sales */
            if (d.sales.length === 0) {
                document.getElementById('pdSalesBody').innerHTML =
                    '<tr><td colspan="6" class="pd-loading"><i class="fas fa-receipt" style="display:block;font-size:22px;margin-bottom:6px;"></i>No sales recorded</td></tr>';
            } else {
                document.getElementById('pdSalesBody').innerHTML = d.sales.map((s, i) => {
                    const bg = i % 2 !== 0 ? 'background:#f8fafc;' : '';
                    const invLink = `<span class="pd-inv-link" onclick="openSiInvoice(${s.sales_invoice_id})" title="View sales invoice">${s.invoice_no}</span>`;
                    return `<tr class="pd-tr" style="${bg}">
                        <td style="padding:7px 12px;color:#64748b;">${s.invoice_date}</td>
                        <td style="padding:7px 12px;">${invLink}</td>
                        <td style="padding:7px 12px;">${s.customer_name}</td>
                        <td style="padding:7px 12px;text-align:center;font-weight:700;">${s.sold_qty}</td>
                        <td style="padding:7px 12px;text-align:right;">&#8377; ${parseFloat(s.selling_price_incl).toFixed(2)}</td>
                        <td style="padding:7px 12px;text-align:right;font-weight:700;">&#8377; ${parseFloat(s.line_total).toFixed(2)}</td>
                    </tr>`;
                }).join('');
            }
        })
        .catch(() => {
            document.getElementById('pdBatchBody').innerHTML =
                '<tr><td colspan="9" class="pd-loading" style="color:#ef4444;">Failed to load data.</td></tr>';
        });
}

function closePdModal() {
    document.getElementById('productDetailModal').style.display = 'none';
    closePoInvoice();
    closeSiInvoice();
}

function pdSwitchTab(tab) {
    document.getElementById('pdPaneBatches').style.display  = tab === 'batches' ? '' : 'none';
    document.getElementById('pdPaneSales').style.display    = tab === 'sales'   ? '' : 'none';
    document.getElementById('pdTabBtnBatches').classList.toggle('pd-tab-active', tab === 'batches');
    document.getElementById('pdTabBtnSales').classList.toggle('pd-tab-active',   tab === 'sales');
}

/* ---- Purchase Invoice Inner Modal ---- */
function openPoInvoice(poId) {
    closeSiInvoice();
    const inner = document.getElementById('poInvoiceModal');
    inner.style.display = 'flex';
    document.getElementById('poiPoNo').textContent   = '…';
    document.getElementById('poiMeta').textContent   = '';
    document.getElementById('poiItemBody').innerHTML = '<tr><td colspan="10" class="pd-loading">Loading…</td></tr>';
    document.getElementById('poiTotals').innerHTML   = '';

    fetch('../includes/purchase_invoice_ajax.php?po_id=' + poId)
        .then(r => r.json())
        .then(d => {
            if (d.error) { alert(d.error); closePoInvoice(); return; }

            document.getElementById('poiPoNo').textContent = d.po.po_no;
            const metaParts = ['Date: ' + d.po.purchase_date, 'Vendor: ' + d.po.vendor_name];
            if (d.po.supplier_invoice_no && d.po.supplier_invoice_no !== '—') {
                metaParts.push('Supplier Inv: ' + d.po.supplier_invoice_no);
            }
            document.getElementById('poiMeta').textContent = metaParts.join('  •  ');

            document.getElementById('poiItemBody').innerHTML = d.items.map((item, i) => {
                const soldOut  = parseInt(item.available_qty) === 0;
                const bg       = i % 2 !== 0 ? 'background:#f8fafc;' : '';
                const availTxt = soldOut
                    ? `<span style="font-size:10px;font-weight:700;padding:2px 6px;border-radius:10px;background:#fee2e2;color:#dc2626;">Sold Out</span>`
                    : `<span style="font-weight:700;color:#16a34a;">${item.available_qty}</span>`;
                return `<tr class="pd-tr" style="${bg}${soldOut ? 'opacity:0.65;' : ''}">
                    <td style="padding:7px 10px;text-align:center;color:#94a3b8;">${i + 1}</td>
                    <td style="padding:7px 10px;font-weight:600;">${item.product_name}</td>
                    <td style="padding:7px 10px;font-family:monospace;font-size:11px;color:#2563eb;">${item.batch_no || '—'}</td>
                    <td style="padding:7px 10px;text-align:center;">${item.quantity}</td>
                    <td style="padding:7px 10px;text-align:center;">${availTxt}</td>
                    <td style="padding:7px 10px;text-align:right;">&#8377; ${parseFloat(item.purchase_price).toFixed(2)}</td>
                    <td style="padding:7px 10px;text-align:center;">${parseFloat(item.gst_percent).toFixed(0)}%</td>
                    <td style="padding:7px 10px;text-align:right;">&#8377; ${parseFloat(item.purchase_price_incl).toFixed(2)}</td>
                    <td style="padding:7px 10px;text-align:right;font-weight:600;">&#8377; ${parseFloat(item.net_amount).toFixed(2)}</td>
                    <td style="padding:7px 10px;text-align:right;">&#8377; ${parseFloat(item.mrp).toFixed(2)}</td>
                </tr>`;
            }).join('');

            document.getElementById('poiTotals').innerHTML = `
                <div style="font-size:12px;color:#64748b;">Taxable: <strong style="color:#1e293b;">&#8377; ${d.grand_taxable.toFixed(2)}</strong></div>
                <div style="font-size:12px;color:#64748b;">GST: <strong style="color:#1e293b;">&#8377; ${d.grand_gst.toFixed(2)}</strong></div>
                <div style="font-size:13px;font-weight:700;color:#1e293b;border-left:1px solid var(--border,#e2e8f0);padding-left:24px;">Net Total: &#8377; ${d.grand_net.toFixed(2)}</div>`;
        })
        .catch(() => {
            document.getElementById('poiItemBody').innerHTML =
                '<tr><td colspan="10" class="pd-loading" style="color:#ef4444;">Failed to load invoice.</td></tr>';
        });
}

function closePoInvoice() {
    document.getElementById('poInvoiceModal').style.display = 'none';
}

/* ---- Sales Invoice Inner Modal ---- */
function openSiInvoice(invId) {
    closePoInvoice();
    const inner = document.getElementById('siInvoiceModal');
    inner.style.display = 'flex';
    document.getElementById('siiInvNo').textContent   = '…';
    document.getElementById('siiMeta').textContent    = '';
    document.getElementById('siiItemBody').innerHTML  = '<tr><td colspan="9" class="pd-loading">Loading…</td></tr>';
    document.getElementById('siiTotals').innerHTML    = '';

    fetch('../includes/sales_invoice_ajax.php?inv_id=' + invId)
        .then(r => r.json())
        .then(d => {
            if (d.error) { alert(d.error); closeSiInvoice(); return; }

            document.getElementById('siiInvNo').textContent = d.invoice.invoice_no;
            const metaParts = ['Date: ' + d.invoice.invoice_date, 'Customer: ' + d.invoice.customer_name];
            if (d.invoice.customer_phone) metaParts.push(d.invoice.customer_phone);
            document.getElementById('siiMeta').textContent = metaParts.join('  •  ');

            document.getElementById('siiItemBody').innerHTML = d.items.map((item, i) => {
                const bg   = i % 2 !== 0 ? 'background:#f8fafc;' : '';
                const disc = (parseFloat(item.discount_value) > 0)
                    ? (item.discount_type === 'percent'
                        ? parseFloat(item.discount_value).toFixed(1) + '%'
                        : '&#8377; ' + parseFloat(item.discount_value).toFixed(2))
                    : '—';
                return `<tr class="pd-tr" style="${bg}">
                    <td style="padding:7px 10px;text-align:center;color:#94a3b8;">${i + 1}</td>
                    <td style="padding:7px 10px;font-weight:600;">${item.product_name}${item.description ? '<br><span style="font-weight:400;font-size:11px;color:#94a3b8;">' + item.description + '</span>' : ''}</td>
                    <td style="padding:7px 10px;font-family:monospace;font-size:11px;color:#2563eb;">${item.batch_no || '—'}</td>
                    <td style="padding:7px 10px;text-align:center;font-weight:700;">${item.sold_qty}</td>
                    <td style="padding:7px 10px;text-align:right;">&#8377; ${parseFloat(item.selling_price_excl).toFixed(2)}</td>
                    <td style="padding:7px 10px;text-align:center;">${parseFloat(item.gst_percent).toFixed(0)}%</td>
                    <td style="padding:7px 10px;text-align:right;">&#8377; ${parseFloat(item.selling_price_incl).toFixed(2)}</td>
                    <td style="padding:7px 10px;text-align:center;color:#64748b;">${disc}</td>
                    <td style="padding:7px 10px;text-align:right;font-weight:700;">&#8377; ${parseFloat(item.total_amount).toFixed(2)}</td>
                </tr>`;
            }).join('');

            /* Totals */
            const inv    = d.invoice;
            let totHtml  = '';
            totHtml += `<div style="font-size:12px;color:#64748b;">Gross: <strong style="color:#1e293b;">&#8377; ${inv.gross_total.toFixed(2)}</strong></div>`;
            if (inv.overall_discount_value > 0) {
                const discLabel = inv.overall_discount_type === 'percent'
                    ? inv.overall_discount_value.toFixed(1) + '% off'
                    : '&#8377; ' + inv.overall_discount_value.toFixed(2);
                totHtml += `<div style="font-size:12px;color:#dc2626;">Discount: <strong>${discLabel}</strong></div>`;
            }
            if (inv.total_gst > 0) {
                totHtml += `<div style="font-size:12px;color:#64748b;">GST: <strong style="color:#1e293b;">&#8377; ${inv.total_gst.toFixed(2)}</strong></div>`;
            }
            totHtml += `<div style="font-size:13px;font-weight:700;color:#1e293b;border-left:1px solid var(--border,#e2e8f0);padding-left:24px;">Net Total: &#8377; ${inv.net_total.toFixed(2)}</div>`;
            if (inv.balance_amount > 0) {
                totHtml += `<div style="font-size:12px;color:#dc2626;font-weight:600;">Balance Due: &#8377; ${inv.balance_amount.toFixed(2)}</div>`;
            }
            document.getElementById('siiTotals').innerHTML = totHtml;
        })
        .catch(() => {
            document.getElementById('siiItemBody').innerHTML =
                '<tr><td colspan="9" class="pd-loading" style="color:#ef4444;">Failed to load invoice.</td></tr>';
        });
}

function closeSiInvoice() {
    document.getElementById('siInvoiceModal').style.display = 'none';
}

/* Click outside to close — each modal independently */
document.getElementById('productDetailModal').addEventListener('click', function(e) {
    if (e.target === this) closePdModal();
});
document.getElementById('poInvoiceModal').addEventListener('click', function(e) {
    if (e.target === this) closePoInvoice();
});
document.getElementById('siInvoiceModal').addEventListener('click', function(e) {
    if (e.target === this) closeSiInvoice();
});

/* Escape: closes the topmost open modal first */
document.addEventListener('keydown', function(e) {
    if (e.key !== 'Escape') return;
    if (document.getElementById('siInvoiceModal').style.display  !== 'none') { closeSiInvoice();  return; }
    if (document.getElementById('poInvoiceModal').style.display  !== 'none') { closePoInvoice();  return; }
    if (document.getElementById('productDetailModal').style.display !== 'none') { closePdModal(); return; }
});
</script>
