<?php
/*
 * Purchase Payment Ledger Modal
 * Include from pages inside purchases/ — AJAX paths resolve relative to browser URL.
 * Define before this include:
 *   window._ppmAfterPaymentChange(received, balance) — called after add/delete
 */
?>

<!-- ===== Purchase Payment Ledger Modal ===== -->
<div id="purchasePaymentModal" 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(--primary);margin-right:8px;"></i>
                Payment Ledger &nbsp;
                <span id="ppm_po_no" style="color:var(--text-muted);font-weight:500;font-size:13px;"></span>
                <span id="ppm_po_date" style="color:var(--text-muted);font-weight:400;font-size:12px;margin-left:8px;"></span>
            </h3>
            <button type="button" onclick="closePurchasePaymentModal()" 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="ppm_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);">&#8377;<span id="ppm_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);">&#8377;<span id="ppm_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="ppm_balance_box" style="font-weight:700;font-size:14px;color:var(--danger);">&#8377;<span id="ppm_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="ppm_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 -->
            <div id="ppm_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-check-circle" style="color:#10b981;font-size:18px;flex-shrink:0;"></i>
                <div>
                    <div style="font-weight:600;font-size:13px;color:#065f46;">Purchase Fully Paid</div>
                    <div style="font-size:12px;color:#047857;margin-top:2px;">Delete a payment entry above to make changes.</div>
                </div>
            </div>

            <!-- Add Payment (hidden when fully paid) -->
            <div id="ppm_add_section" style="background:#f8fafc;border-radius:8px;padding:12px 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 (&#8377;)</label>
                        <input type="number" step="0.01" id="ppm_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="ppm_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="ppm_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="ppm_new_note" placeholder="Cheque no., ref..." style="width:100%;">
                    </div>
                </div>
                <div id="ppm_add_error" style="color:var(--danger);font-size:12px;margin-bottom:6px;display:none;"></div>
                <button type="button" class="btn btn-primary btn-sm" onclick="ppmAddPayment()">
                    <i class="fas fa-plus"></i> Add Payment
                </button>
            </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="closePurchasePaymentModal()">Close</button>
        </div>
    </div>
</div>

<script>
let _ppmRow = null;

function openPurchasePaymentModal(id, poNo, poDate) {
    document.getElementById('ppm_id').value                = id;
    document.getElementById('ppm_po_no').textContent       = poNo;
    document.getElementById('ppm_po_date').textContent     = poDate ? '· ' + poDate : '';
    document.getElementById('ppm_new_date').value          = new Date().toISOString().slice(0,10);
    document.getElementById('ppm_new_amount').value        = '';
    document.getElementById('ppm_new_note').value          = '';
    document.getElementById('ppm_add_error').style.display = 'none';
    _ppmRow = document.querySelector(`tr[data-id="${id}"]`);
    _ppmSetLock(false);
    document.getElementById('purchasePaymentModal').style.display = 'flex';
    ppmLoadHistory(id);
    document.getElementById('ppm_new_amount').focus();
}

function closePurchasePaymentModal() {
    document.getElementById('purchasePaymentModal').style.display = 'none';
    _ppmRow = null;
}

function _ppmSetLock(locked) {
    document.getElementById('ppm_lock_banner').style.display = locked ? 'flex'  : 'none';
    document.getElementById('ppm_add_section').style.display = locked ? 'none'  : 'block';
}

function ppmUpdateSummary(net, paid, balance) {
    document.getElementById('ppm_net_display').textContent     = parseFloat(net).toFixed(2);
    document.getElementById('ppm_paid_display').textContent    = parseFloat(paid).toFixed(2);
    document.getElementById('ppm_balance_display').textContent = parseFloat(balance).toFixed(2);
    const bb = document.getElementById('ppm_balance_box');
    bb.style.color      = parseFloat(balance) > 0 ? 'var(--danger)' : 'var(--success)';
    bb.style.background = parseFloat(balance) > 0 ? ''              : '#f0fdf4';
    _ppmSetLock(parseFloat(balance) <= 0);
}

function ppmLoadHistory(id) {
    document.getElementById('ppm_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&purchase_order_id=' + id)
    .then(r => r.json())
    .then(data => {
        if (data.status !== 'ok') {
            document.getElementById('ppm_history').innerHTML = '<div style="color:var(--danger);font-size:13px;">' + data.msg + '</div>';
            return;
        }
        ppmUpdateSummary(data.net_amount, data.received_amount, data.balance_amount);
        ppmRenderHistory(data.payments, id);
    })
    .catch(() => {
        document.getElementById('ppm_history').innerHTML = '<div style="color:var(--danger);font-size:13px;">Failed to load.</div>';
    });
}

function ppmRenderHistory(payments, poId) {
    if (!payments.length) {
        document.getElementById('ppm_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);">&#8377;${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="ppmDeletePayment(${p.id},${poId})"
                        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('ppm_history').innerHTML = html;
}

function ppmAddPayment() {
    const id     = document.getElementById('ppm_id').value;
    const amount = parseFloat(document.getElementById('ppm_new_amount').value || 0);
    const mode   = document.getElementById('ppm_new_mode').value;
    const date   = document.getElementById('ppm_new_date').value;
    const note   = document.getElementById('ppm_new_note').value.trim();
    const errEl  = document.getElementById('ppm_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&purchase_order_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('ppm_new_amount').value = '';
        document.getElementById('ppm_new_note').value   = '';
        ppmUpdateSummary(data.net_amount, data.received_amount, data.balance_amount);
        if (typeof window._ppmAfterPaymentChange === 'function')
            window._ppmAfterPaymentChange(data.received_amount, data.balance_amount);
        ppmLoadHistory(id);
    })
    .catch(() => { errEl.textContent = 'Server error. Try again.'; errEl.style.display = 'block'; });
}

function ppmDeletePayment(payId, poId) {
    if (!confirm('Delete this payment entry?')) return;
    fetch('ajax_payment.php', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: `action=delete&purchase_order_id=${poId}&payment_id=${payId}`
    })
    .then(r => r.json())
    .then(data => {
        if (data.status !== 'ok') { alert(data.msg); return; }
        ppmUpdateSummary(data.net_amount, data.received_amount, data.balance_amount);
        if (typeof window._ppmAfterPaymentChange === 'function')
            window._ppmAfterPaymentChange(data.received_amount, data.balance_amount);
        ppmLoadHistory(poId);
    })
    .catch(() => alert('Server error.'));
}
</script>
