<?php
/*
 * Shared Payment Ledger Modal
 * Include from any page inside sales/ — AJAX paths resolve relative to the browser URL.
 * Pages must define page-specific callbacks BEFORE this include:
 *   window._pmAfterFinalize(data, id)      — called after Apply & Finalize succeeds
 *   window._pmAfterPaymentChange(rec, bal) — called after add/delete payment succeeds
 */
?>

<!-- ===== 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><span id="pm_invoice_date" style="color:var(--text-muted);font-weight:400;font-size:12px;margin-left:8px;"></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">

            <!-- Summary bar -->
            <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:var(--danger);">₹<span id="pm_balance_display">—</span></div>
                </div>
            </div>

            <!-- Payment History -->
            <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" style="font-size:13px;">
                    <div style="text-align:center;padding:12px;color:var(--text-muted);"><i class="fas fa-spinner fa-spin"></i></div>
                </div>
            </div>

            <!-- Fully Paid lock banner (shown when balance = 0) -->
            <div id="pm_lock_banner" style="display:none;background:#f0fdf4;border:1px solid #bbf7d0;border-radius:8px;padding:12px 14px;margin-bottom:14px;align-items:center;gap:10px;">
                <i class="fas fa-lock-open" style="color:#10b981;font-size:18px;flex-shrink:0;"></i>
                <div>
                    <div style="font-weight:600;font-size:13px;color:#065f46;">Invoice Fully Paid</div>
                    <div style="font-size:12px;color:#047857;margin-top:2px;">No further changes allowed. Delete a payment entry above to unlock.</div>
                </div>
            </div>

            <!-- Add Payment (hidden when fully paid) -->
            <div id="pm_add_section" 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="Cheque no., ref..." 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="addPayment()"><i class="fas fa-plus"></i> Add Payment</button>
            </div>

            <!-- Discount & Finalize (hidden when fully paid) -->
            <div id="pm_discount_section" 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%;" onchange="calcPayModal()">
                            <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%;" oninput="calcPayModal()">
                    </div>
                    <button type="button" class="btn btn-primary btn-sm" onclick="saveDiscount()" 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>

<script>
let _pmGross = 0, _pmRoundOff = 0, _pmRow = null;

function calcPayModal() {
    const discType = document.getElementById('pm_disc_type').value;
    const discVal  = parseFloat(document.getElementById('pm_disc_val').value || 0);
    let net = _pmGross;
    if (discType === 'percent') net -= _pmGross * discVal / 100;
    else if (discType === 'amount') net -= discVal;
    net = Math.max(0, net);
    net = Math.round((net + _pmRoundOff) * 100) / 100;
    document.getElementById('pm_net_display').textContent = net.toFixed(2);
}

function openPaymentModal(id, invoiceNo, invoiceDate, grossTotal, roundOff, discType, discVal) {
    _pmGross    = parseFloat(grossTotal);
    _pmRoundOff = parseFloat(roundOff);
    document.getElementById('pm_id').value                  = id;
    document.getElementById('pm_invoice_no').textContent    = invoiceNo;
    document.getElementById('pm_invoice_date').textContent  = invoiceDate ? '· ' + invoiceDate : '';
    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';
    _pmRow = document.querySelector(`tr[data-id="${id}"]`);
    // Reset lock state to unlocked while history loads
    _pmSetLock(false);
    calcPayModal();
    document.getElementById('paymentModal').style.display = 'flex';
    loadPaymentHistory(id);
    document.getElementById('pm_new_amount').focus();
}

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

function _pmSetLock(locked) {
    document.getElementById('pm_lock_banner').style.display     = locked ? 'flex'  : 'none';
    document.getElementById('pm_add_section').style.display     = locked ? 'none'  : 'block';
    document.getElementById('pm_discount_section').style.display = locked ? 'none'  : 'block';
}

function loadPaymentHistory(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('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; }
        updateSummary(data.net_total, data.received_amount, data.balance_amount);
        renderHistory(data.payments, id);
    })
    .catch(() => { document.getElementById('pm_history').innerHTML = '<div style="color:var(--danger);font-size:13px;">Failed to load.</div>'; });
}

function updateSummary(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 ? 'var(--danger)' : 'var(--success)';
    bb.style.background = parseFloat(balance) > 0 ? ''              : '#f0fdf4';
    _pmSetLock(parseFloat(balance) <= 0);
}

function renderHistory(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;
    }
    const modeIcon = {Cash:'💵',UPI:'📱',Card:'💳',Bank:'🏦'};
    let html = '<table style="width:100%;border-collapse:collapse;font-size:12px;">';
    html += '<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;">${modeIcon[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="deletePayment(${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 addPayment() {
    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('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   = '';
        updateSummary(data.net_total, data.received_amount, data.balance_amount);
        if (typeof window._pmAfterPaymentChange === 'function')
            window._pmAfterPaymentChange(data.received_amount, data.balance_amount);
        loadPaymentHistory(id);
    })
    .catch(() => { errEl.textContent = 'Server error. Try again.'; errEl.style.display = 'block'; });
}

function deletePayment(payId, invId) {
    if (!confirm('Delete this payment entry?')) return;
    fetch('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; }
        updateSummary(data.net_total, data.received_amount, data.balance_amount);
        if (typeof window._pmAfterPaymentChange === 'function')
            window._pmAfterPaymentChange(data.received_amount, data.balance_amount);
        loadPaymentHistory(invId);
    })
    .catch(() => alert('Server error.'));
}

function saveDiscount() {
    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('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; }
        updateSummary(data.net_total, data.received_amount, data.balance_amount);
        if (typeof window._pmAfterFinalize === 'function')
            window._pmAfterFinalize(data, id);
        loadPaymentHistory(id);
    })
    .catch(() => { errEl.textContent = 'Server error.'; errEl.style.display = 'block'; });
}
</script>
