<?php
require_once '../includes/auth.php';
require_once '../db.php';

requirePermission('master_sales', 'view', BASE_URL . '/dashboard.php');

require_once '../includes/header.php';
require_once '../includes/sidebar.php';

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) die('Invalid ID');

$master = $conn->query("
    SELECT mi.*, c.name AS client_name, c.phone AS client_phone, c.address AS client_address
    FROM master_invoices mi
    JOIN clients c ON c.id = mi.client_id
    WHERE mi.id = $id
")->fetch_assoc();
if (!$master) die('Master invoice not found.');

$totals = $conn->query("
    SELECT SUM(net_total) AS grand_total, SUM(received_amount) AS grand_received, SUM(balance_amount) AS grand_balance
    FROM sales_invoices WHERE master_invoice_id = $id
")->fetch_assoc();

// Load all split invoices linked to this master
$invoices = $conn->query("
    SELECT si.*, cm.company_name, cm.invoice_prefix
    FROM sales_invoices si
    JOIN company_master cm ON cm.id = si.company_id
    WHERE si.master_invoice_id = $id
    ORDER BY si.id ASC
");

$statusBadge = $master['status'] === 'final'
    ? '<span class="badge badge-success">Final</span>'
    : ($master['status'] === 'cancelled'
        ? '<span class="badge badge-gray">Cancelled</span>'
        : '<span class="badge badge-warning">Draft</span>');
?>

<div class="page-header">
    <h2><i class="fas fa-layer-group" style="color:var(--primary);margin-right:8px;"></i>Master Invoice</h2>
    <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
        <label style="display:flex;align-items:center;gap:6px;font-size:13px;font-weight:600;color:var(--text-secondary);">
            Template:
            <select id="printTemplate" class="btn btn-secondary btn-sm" style="padding:5px 8px;font-weight:500;">
                <option value="simple">Simple</option>
                <option value="tally">Tally</option>
                <option value="modern">Modern</option>
            </select>
        </label>
        <?php if ($master['status'] === 'draft'): ?>
        <a href="edit.php?id=<?= $id ?>" class="btn btn-primary">
            <i class="fas fa-edit"></i> Edit
        </a>
        <a href="cancel.php?id=<?= $id ?>" class="btn btn-danger"
           onclick="return confirm('Cancel this master invoice? All sub-invoices will also be cancelled.')">
            <i class="fas fa-ban"></i> Cancel Invoice
        </a>
        <a href="delete.php?id=<?= $id ?>" class="btn btn-danger"
           onclick="return confirm('Delete this draft master invoice and all its sub-invoices?')">
            <i class="fas fa-trash"></i> Delete
        </a>
        <?php endif; ?>
        <?php if ($master['status'] === 'cancelled'): ?>
        <a href="create.php?copy_from=<?= $id ?>" class="btn btn-primary no-print">
            <i class="fas fa-copy"></i> Copy Invoice
        </a>
        <?php endif; ?>
        <?php if ($master['status'] === 'final'): ?>
        <a href="../master_returns/create_master.php?master_id=<?= $id ?>" class="btn btn-secondary">
            <i class="fas fa-rotate-left"></i> Return
        </a>
        <?php endif; ?>
        <?php if ($master['status'] === 'final' && hasPermission('master_sales', 'revert')): ?>
        <a href="revert_to_draft.php?id=<?= $id ?>"
           onclick="return confirm('Revert this master invoice to Draft? Stock for all sub-invoices will be restored and they will become editable again.')"
           class="btn btn-secondary">
            <i class="fas fa-clock-rotate-left"></i> Revert to Draft
        </a>
        <?php endif; ?>
        <?php if (!empty($master['client_phone'])): ?>
        <button onclick="sendWhatsApp()" class="btn btn-success" style="background:#25d366;border-color:#25d366;">
            <i class="fab fa-whatsapp"></i> WhatsApp
        </button>
        <?php endif; ?>
        <a href="index.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
    </div>
</div>

<!-- Master Header -->
<div class="panel" style="margin-bottom:16px;">
    <div class="panel-body">
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:16px;">
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:4px;">Master Ref</div>
                <div style="font-size:16px;font-weight:700;"><?= htmlspecialchars($master['master_no']) ?></div>
            </div>
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:4px;">Date</div>
                <div style="font-size:15px;"><?= date('d M Y', strtotime($master['invoice_date'])) ?></div>
            </div>
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:4px;">Client</div>
                <div style="font-size:15px;font-weight:700;"><?= htmlspecialchars($master['client_name']) ?></div>
                <?php if ($master['client_phone']): ?><div style="font-size:12px;color:var(--text-muted);"><?= htmlspecialchars($master['client_phone']) ?></div><?php endif; ?>
            </div>
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:4px;">Status</div>
                <div><?= $statusBadge ?></div>
            </div>
        </div>
    </div>
</div>

<!-- Per-company invoices -->
<?php
$grandNetTotal = 0;
$invoiceRows = [];
while ($inv = $invoices->fetch_assoc()) $invoiceRows[] = $inv;
foreach ($invoiceRows as $inv):
    $grandNetTotal += $inv['net_total'];
    $items = $conn->query("
        SELECT si.*, p.name AS product_name, p.unit
        FROM sales_items si
        JOIN products p ON p.id = si.product_id
        WHERE si.sales_invoice_id = {$inv['id']}
    ");
?>
<div class="panel" style="margin-bottom:16px;border-left:4px solid var(--primary);">
    <div class="panel-header" style="flex-wrap:wrap;gap:8px;">
        <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
            <span class="panel-title" style="font-size:15px;"><?= htmlspecialchars($inv['company_name']) ?></span>
            <span style="font-size:13px;color:var(--text-secondary);"><?= htmlspecialchars($inv['invoice_no']) ?></span>
            <?php $s = $inv['status']; ?>
            <span class="badge <?= $s==='final'?'badge-success':($s==='cancelled'?'badge-gray':'badge-warning') ?>"><?= ucfirst($s) ?></span>
        </div>
        <div style="display:flex;gap:8px;margin-left:auto;flex-wrap:wrap;">
            <a href="../sales/view.php?id=<?= $inv['id'] ?>" class="btn btn-sm btn-outline" target="_blank">
                <i class="fas fa-eye"></i> View
            </a>
            <button type="button" onclick="printA4(<?= $inv['id'] ?>)" class="btn btn-sm btn-primary">
                <i class="fas fa-print"></i> Print A4
            </button>
            <button type="button" onclick="downloadPdf(<?= $inv['id'] ?>)" class="btn btn-sm btn-danger">
                <i class="fas fa-file-pdf"></i> PDF
            </button>
            <button type="button" onclick="printThermal(<?= $inv['id'] ?>)" class="btn btn-sm btn-secondary">
                <i class="fas fa-receipt"></i> Thermal
            </button>
            <button type="button" onclick="printThermalTransport(<?= $inv['id'] ?>)" class="btn btn-sm btn-secondary">
                <i class="fas fa-truck"></i> Transport Slip
            </button>
            <?php if (in_array($inv['status'], ['final','draft'])): ?>
            <button type="button" class="btn btn-sm btn-success"
                onclick="openPaymentModal(<?= $inv['id'] ?>, '<?= htmlspecialchars($inv['invoice_no'], ENT_QUOTES) ?>', <?= (float)$inv['gross_total'] ?>, <?= (float)$inv['round_off'] ?>, '<?= addslashes($inv['overall_discount_type'] ?? '') ?>', <?= (float)($inv['overall_discount_value'] ?? 0) ?>)">
                <i class="fas fa-receipt"></i> Ledger
            </button>
            <?php endif; ?>
        </div>
    </div>
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>Product</th>
                    <th>Batch</th>
                    <th style="text-align:right;">Qty</th>
                    <th style="text-align:right;">Rate (incl.)</th>
                    <th style="text-align:right;">Total</th>
                </tr>
            </thead>
            <tbody>
            <?php $i=1; while ($item = $items->fetch_assoc()): ?>
            <tr>
                <td style="color:var(--text-muted);"><?= $i++ ?></td>
                <td>
                    <strong><?= htmlspecialchars($item['product_name']) ?></strong>
                    <?php if ($item['unit']): ?><span style="font-size:11px;color:var(--text-muted);margin-left:4px;"><?= htmlspecialchars($item['unit']) ?></span><?php endif; ?>
                </td>
                <td style="font-size:12px;color:var(--text-secondary);"><?= htmlspecialchars($item['batch_no']) ?></td>
                <td style="text-align:right;"><?= number_format($item['sold_qty'], 0) ?></td>
                <td style="text-align:right;">&#8377; <?= number_format($item['selling_price_incl'],2) ?></td>
                <td style="text-align:right;font-weight:600;">&#8377; <?= number_format($item['total_amount'],2) ?></td>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    </div>
    <div style="display:flex;justify-content:flex-end;padding:12px 16px 4px;">
        <table id="inv-totals-<?= $inv['id'] ?>" style="width:240px;font-size:13px;border-collapse:collapse;">
            <tr><td style="color:var(--text-muted);padding:3px 8px;">Gross</td><td style="text-align:right;padding:3px 8px;">&#8377; <?= number_format($inv['gross_total'],2) ?></td></tr>
            <tr class="inv-disc-row-<?= $inv['id'] ?>" <?= $inv['overall_discount_value'] > 0 ? '' : 'style="display:none;"' ?>>
                <td style="color:var(--text-muted);padding:3px 8px;">Discount</td>
                <td class="inv-disc-val-<?= $inv['id'] ?>" style="text-align:right;padding:3px 8px;color:#ef4444;">- &#8377; <?= number_format($inv['overall_discount_value'],2) ?></td>
            </tr>
            <tr><td style="color:var(--text-muted);padding:3px 8px;">GST</td><td class="inv-gst-<?= $inv['id'] ?>" style="text-align:right;padding:3px 8px;">&#8377; <?= number_format($inv['total_gst'],2) ?></td></tr>
            <tr style="border-top:2px solid #e2e8f0;font-weight:700;">
                <td style="padding:6px 8px;">Net Total</td>
                <td class="inv-net-<?= $inv['id'] ?>" style="text-align:right;padding:6px 8px;">&#8377; <?= number_format($inv['net_total'],2) ?></td>
            </tr>
            <tr class="inv-recv-row-<?= $inv['id'] ?>">
                <td style="color:#10b981;padding:3px 8px;">Received</td>
                <td class="inv-recv-<?= $inv['id'] ?>" style="text-align:right;padding:3px 8px;color:#10b981;">&#8377; <?= number_format($inv['received_amount'],2) ?></td>
            </tr>
            <tr>
                <td class="inv-bal-lbl-<?= $inv['id'] ?>" style="color:<?= $inv['balance_amount']>0?'#ef4444':'#10b981' ?>;padding:3px 8px;">Balance</td>
                <td class="inv-bal-<?= $inv['id'] ?>" style="text-align:right;padding:3px 8px;color:<?= $inv['balance_amount']>0?'#ef4444':'#10b981' ?>;">&#8377; <?= number_format($inv['balance_amount'],2) ?></td>
            </tr>
        </table>
    </div>
</div>
<?php endforeach; ?>

<!-- Grand Total -->
<div style="display:flex;justify-content:flex-end;margin-bottom:24px;">
    <div class="totals-box" style="min-width:260px;">
        <div class="totals-row grand-total">
            <span>Master Grand Total</span>
            <span>&#8377; <?= number_format($grandNetTotal, 2) ?></span>
        </div>
    </div>
</div>

<script>
function printA4(id) {
    const template = document.getElementById('printTemplate').value;
    window.open('../sales/print_a4.php?id=' + id + '&template=' + template, '_blank', 'width=900,height=720,scrollbars=yes');
}
function downloadPdf(id) {
    const template = document.getElementById('printTemplate').value;
    window.location.href = '../sales/pdf_download.php?id=' + id + '&template=' + template;
}
function printThermal(id) {
    window.open('../sales/layout_loader_thermal.php?id=' + id + '&type=invoice', 'thermal_print', 'width=560,height=780,scrollbars=yes');
}
function printThermalTransport(id) {
    window.open('../sales/layout_loader_thermal.php?id=' + id + '&type=transport', 'thermal_transport', 'width=560,height=780,scrollbars=yes');
}

/* ---- Payment Ledger Modal ---- */
let _pmId = null, _pmModeIcon = {Cash:'💵',UPI:'📱',Card:'💳',Bank:'🏦'};

function openPaymentModal(id, invoiceNo, grossTotal, roundOff, discType, discVal) {
    _pmId = id;
    document.getElementById('pm_id').value               = id;
    document.getElementById('pm_invoice_no').textContent = invoiceNo;
    document.getElementById('pm_disc_type').value        = discType || '';
    document.getElementById('pm_disc_val').value         = parseFloat(discVal || 0).toFixed(2);
    document.getElementById('pm_new_date').value         = new Date().toISOString().slice(0,10);
    document.getElementById('pm_new_amount').value       = '';
    document.getElementById('pm_new_note').value         = '';
    document.getElementById('pm_add_error').style.display  = 'none';
    document.getElementById('pm_disc_error').style.display = 'none';
    document.getElementById('paymentModal').style.display  = 'flex';
    pmLoadHistory(id);
    document.getElementById('pm_new_amount').focus();
}

function closePaymentModal() {
    document.getElementById('paymentModal').style.display = 'none';
    _pmId = null;
}

function pmUpdateSummary(id, net, paid, balance) {
    document.getElementById('pm_net_display').textContent     = parseFloat(net).toFixed(2);
    document.getElementById('pm_paid_display').textContent    = parseFloat(paid).toFixed(2);
    document.getElementById('pm_balance_display').textContent = parseFloat(balance).toFixed(2);
    const bb = document.getElementById('pm_balance_box');
    bb.style.color      = parseFloat(balance) > 0 ? '#ef4444' : '#10b981';
    bb.style.background = parseFloat(balance) > 0 ? '' : '#f0fdf4';
    // Live update the inline totals table
    const recvEl   = document.querySelector('.inv-recv-'  + id);
    const balEl    = document.querySelector('.inv-bal-'   + id);
    const balLblEl = document.querySelector('.inv-bal-lbl-' + id);
    if (recvEl)   recvEl.textContent  = '₹' + parseFloat(paid).toFixed(2);
    if (balEl)    { balEl.textContent = '₹' + parseFloat(balance).toFixed(2); balEl.style.color = parseFloat(balance)>0?'#ef4444':'#10b981'; }
    if (balLblEl) balLblEl.style.color = parseFloat(balance)>0?'#ef4444':'#10b981';
}

function pmLoadHistory(id) {
    document.getElementById('pm_history').innerHTML =
        '<div style="text-align:center;padding:10px;color:var(--text-muted);"><i class="fas fa-spinner fa-spin"></i></div>';
    fetch('../sales/ajax_payment.php?action=list&sales_invoice_id='+id)
    .then(r=>r.json())
    .then(data=>{
        if(data.status!=='ok'){document.getElementById('pm_history').innerHTML='<div style="color:var(--danger);font-size:13px;">'+data.msg+'</div>';return;}
        pmUpdateSummary(id,data.net_total,data.received_amount,data.balance_amount);
        pmRenderHistory(data.payments,id);
    });
}

function pmRenderHistory(payments,invId) {
    if(!payments.length){document.getElementById('pm_history').innerHTML='<div style="color:var(--text-muted);font-size:13px;padding:6px 0;">No payments recorded yet.</div>';return;}
    let html='<table style="width:100%;border-collapse:collapse;font-size:12px;"><thead><tr style="background:#f8fafc;"><th style="padding:5px 8px;text-align:left;font-weight:600;">Date</th><th style="padding:5px 8px;text-align:left;font-weight:600;">Mode</th><th style="padding:5px 8px;text-align:right;font-weight:600;">Amount</th><th style="padding:5px 8px;text-align:left;font-weight:600;">Note</th><th style="padding:5px 4px;"></th></tr></thead><tbody>';
    payments.forEach(p=>{
        const d=p.payment_date.split('-');
        html+=`<tr style="border-bottom:1px solid #f1f5f9;">
            <td style="padding:5px 8px;">${d[2]+'-'+d[1]+'-'+d[0]}</td>
            <td style="padding:5px 8px;">${_pmModeIcon[p.payment_mode]||''} ${p.payment_mode}</td>
            <td style="padding:5px 8px;text-align:right;font-weight:600;color:var(--success);">₹${parseFloat(p.amount).toFixed(2)}</td>
            <td style="padding:5px 8px;color:var(--text-muted);">${p.note||'—'}</td>
            <td style="padding:5px 4px;text-align:center;"><button type="button" onclick="pmDeletePayment(${p.id},${invId})" style="background:none;border:none;color:var(--danger);cursor:pointer;font-size:13px;" title="Delete"><i class="fas fa-trash-alt"></i></button></td>
        </tr>`;
    });
    html+='</tbody></table>';
    document.getElementById('pm_history').innerHTML=html;
}

function pmAddPayment() {
    const id     = document.getElementById('pm_id').value;
    const amount = parseFloat(document.getElementById('pm_new_amount').value||0);
    const mode   = document.getElementById('pm_new_mode').value;
    const date   = document.getElementById('pm_new_date').value;
    const note   = document.getElementById('pm_new_note').value.trim();
    const errEl  = document.getElementById('pm_add_error');
    errEl.style.display='none';
    if(amount<=0){errEl.textContent='Enter a valid amount.';errEl.style.display='block';return;}
    if(!date){errEl.textContent='Select a payment date.';errEl.style.display='block';return;}
    fetch('../sales/ajax_payment.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:`action=add&sales_invoice_id=${id}&amount=${amount}&payment_mode=${encodeURIComponent(mode)}&payment_date=${date}&note=${encodeURIComponent(note)}`})
    .then(r=>r.json())
    .then(data=>{
        if(data.status!=='ok'){errEl.textContent=data.msg;errEl.style.display='block';return;}
        document.getElementById('pm_new_amount').value='';
        document.getElementById('pm_new_note').value='';
        pmUpdateSummary(id,data.net_total,data.received_amount,data.balance_amount);
        pmLoadHistory(id);
    })
    .catch(()=>{errEl.textContent='Server error.';errEl.style.display='block';});
}

function pmDeletePayment(payId,invId) {
    if(!confirm('Delete this payment entry?'))return;
    fetch('../sales/ajax_payment.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:`action=delete&sales_invoice_id=${invId}&payment_id=${payId}`})
    .then(r=>r.json())
    .then(data=>{
        if(data.status!=='ok'){alert(data.msg);return;}
        pmUpdateSummary(invId,data.net_total,data.received_amount,data.balance_amount);
        pmLoadHistory(invId);
    });
}

function pmSaveDiscount() {
    const id       = document.getElementById('pm_id').value;
    const discType = document.getElementById('pm_disc_type').value;
    const discVal  = parseFloat(document.getElementById('pm_disc_val').value||0);
    const errEl    = document.getElementById('pm_disc_error');
    errEl.style.display='none';
    fetch('../sales/ajax_update_payment.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:`id=${id}&overall_discount_type=${encodeURIComponent(discType)}&overall_discount_value=${discVal}`})
    .then(r=>r.json())
    .then(data=>{
        if(data.status!=='ok'){errEl.textContent=data.msg||'Error.';errEl.style.display='block';return;}
        // Update discount row in totals table
        const net=parseFloat(data.net_total),gst=parseFloat(data.total_gst),dt=data.discount_type,dv=parseFloat(data.discount_value);
        const discRow=document.querySelector('.inv-disc-row-'+id);
        const discValEl=document.querySelector('.inv-disc-val-'+id);
        if(discRow&&discValEl){
            if(dt==='percent'){discValEl.textContent='- '+dv+'%';discRow.style.display='';}
            else if(dt==='amount'){discValEl.textContent='- ₹'+dv.toFixed(2);discRow.style.display='';}
            else{discRow.style.display='none';}
        }
        const gstEl=document.querySelector('.inv-gst-'+id);
        const netEl=document.querySelector('.inv-net-'+id);
        if(gstEl)gstEl.textContent='₹'+gst.toFixed(2);
        if(netEl)netEl.textContent='₹'+net.toFixed(2);
        pmUpdateSummary(id,data.net_total,data.received_amount,data.balance_amount);
        pmLoadHistory(id);
    })
    .catch(()=>{errEl.textContent='Server error.';errEl.style.display='block';});
}

function sendWhatsApp() {
    let phone = '<?= preg_replace('/\D/', '', $master['client_phone'] ?? '') ?>';
    if (phone.length === 10) phone = '91' + phone;

    const balance = <?= (float)($totals['grand_balance'] ?? 0) ?>;
    const msg =
        `Dear <?= addslashes($master['client_name']) ?>,\n\n` +
        `Your invoice is ready.\n\n` +
        `📄 Master Ref : *<?= addslashes($master['master_no']) ?>*\n` +
        `📅 Date       : <?= date('d-m-Y', strtotime($master['invoice_date'])) ?>\n` +
        `💰 Amount     : ₹<?= number_format((float)($totals['grand_total'] ?? 0), 2) ?>\n` +
        `✅ Paid       : ₹<?= number_format((float)($totals['grand_received'] ?? 0), 2) ?>\n` +
        (balance > 0 ? `⚠️ Balance    : ₹<?= number_format((float)($totals['grand_balance'] ?? 0), 2) ?>\n` : '') +
        `\nThank you for your business! 🙏`;

    window.open('https://wa.me/' + phone + '?text=' + encodeURIComponent(msg), '_blank');
}
</script>

<!-- Payment Ledger Modal -->
<div id="paymentModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.45);z-index:2000;align-items:center;justify-content:center;">
    <div style="background:#fff;border-radius:10px;width:520px;max-width:97vw;max-height:90vh;display:flex;flex-direction:column;box-shadow:0 8px 40px rgba(0,0,0,.2);">
        <div style="padding:16px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;flex-shrink:0;">
            <h3 style="margin:0;font-size:15px;"><i class="fas fa-receipt" style="color:var(--success);margin-right:8px;"></i>Payment Ledger &nbsp;<span id="pm_invoice_no" style="color:var(--text-muted);font-weight:500;font-size:13px;"></span></h3>
            <button type="button" onclick="closePaymentModal()" style="background:none;border:none;font-size:20px;cursor:pointer;color:var(--text-muted);line-height:1;">&times;</button>
        </div>
        <div style="padding:14px 20px;overflow-y:auto;flex:1;">
            <input type="hidden" id="pm_id">
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;margin-bottom:14px;">
                <div style="background:#f0f9ff;border-radius:6px;padding:8px 12px;text-align:center;">
                    <div style="font-size:11px;color:var(--text-muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:2px;">Net Payable</div>
                    <div style="font-weight:700;font-size:14px;color:var(--primary);">₹<span id="pm_net_display">—</span></div>
                </div>
                <div style="background:#f0fdf4;border-radius:6px;padding:8px 12px;text-align:center;">
                    <div style="font-size:11px;color:var(--text-muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:2px;">Total Paid</div>
                    <div style="font-weight:700;font-size:14px;color:var(--success);">₹<span id="pm_paid_display">—</span></div>
                </div>
                <div style="background:#fef2f2;border-radius:6px;padding:8px 12px;text-align:center;">
                    <div style="font-size:11px;color:var(--text-muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:2px;">Balance</div>
                    <div id="pm_balance_box" style="font-weight:700;font-size:14px;color:#ef4444;">₹<span id="pm_balance_display">—</span></div>
                </div>
            </div>
            <div style="margin-bottom:14px;">
                <div style="font-size:12px;font-weight:600;text-transform:uppercase;letter-spacing:.5px;color:var(--text-muted);margin-bottom:6px;">Payment History</div>
                <div id="pm_history"><div style="text-align:center;padding:10px;color:var(--text-muted);"><i class="fas fa-spinner fa-spin"></i></div></div>
            </div>
            <div style="background:#f8fafc;border-radius:8px;padding:12px 14px;margin-bottom:14px;">
                <div style="font-size:12px;font-weight:600;text-transform:uppercase;letter-spacing:.5px;color:var(--text-muted);margin-bottom:10px;">Add Payment</div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:10px;">
                    <div class="form-group" style="margin:0;"><label style="font-size:12px;">Amount (₹)</label><input type="number" step="0.01" id="pm_new_amount" placeholder="0.00" style="width:100%;"></div>
                    <div class="form-group" style="margin:0;"><label style="font-size:12px;">Payment Mode</label>
                        <select id="pm_new_mode" style="width:100%;"><option value="Cash">Cash</option><option value="UPI">UPI</option><option value="Card">Card</option><option value="Bank">Bank Transfer</option></select>
                    </div>
                    <div class="form-group" style="margin:0;"><label style="font-size:12px;">Payment Date</label><input type="date" id="pm_new_date" style="width:100%;"></div>
                    <div class="form-group" style="margin:0;"><label style="font-size:12px;">Note (optional)</label><input type="text" id="pm_new_note" placeholder="Ref, cheque no..." style="width:100%;"></div>
                </div>
                <div id="pm_add_error" style="color:var(--danger);font-size:12px;margin-bottom:6px;display:none;"></div>
                <button type="button" class="btn btn-success btn-sm" onclick="pmAddPayment()"><i class="fas fa-plus"></i> Add Payment</button>
            </div>
            <div style="background:#fff7ed;border-radius:8px;padding:12px 14px;border:1px solid #fed7aa;">
                <div style="font-size:12px;font-weight:600;text-transform:uppercase;letter-spacing:.5px;color:#92400e;margin-bottom:10px;">Update Overall Discount &amp; Finalize</div>
                <div style="display:flex;gap:8px;align-items:flex-end;flex-wrap:wrap;">
                    <div class="form-group" style="margin:0;flex:0 0 110px;"><label style="font-size:12px;">Discount Type</label>
                        <select id="pm_disc_type" style="width:100%;"><option value="">None</option><option value="percent">Percent %</option><option value="amount">Amount ₹</option></select>
                    </div>
                    <div class="form-group" style="margin:0;flex:1;min-width:80px;"><label style="font-size:12px;">Value</label>
                        <input type="number" step="0.01" min="0" id="pm_disc_val" placeholder="0.00" style="width:100%;">
                    </div>
                    <button type="button" class="btn btn-primary btn-sm" onclick="pmSaveDiscount()" style="margin-bottom:1px;"><i class="fas fa-tag"></i> Apply &amp; Finalize</button>
                </div>
                <div id="pm_disc_error" style="color:var(--danger);font-size:12px;margin-top:6px;display:none;"></div>
            </div>
        </div>
        <div style="padding:12px 20px;border-top:1px solid var(--border);display:flex;justify-content:flex-end;flex-shrink:0;">
            <button type="button" class="btn btn-secondary" onclick="closePaymentModal()">Close</button>
        </div>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>
