<?= $this->extend('layouts/panel') ?>
<?= $this->section('sidebar') ?>
<?= $this->include('panel/_sidebar') ?>
<?= $this->endSection() ?>

<?= $this->section('content') ?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="mb-0">Payments &amp; Invoices</h5>
    <div class="d-flex gap-2">
        <select id="statusFilter" class="form-select form-select-sm" style="width:150px;">
            <option value="">All statuses</option>
            <option value="pending">Pending</option>
            <option value="success">Success</option>
            <option value="failed">Failed</option>
            <option value="refunded">Refunded</option>
        </select>
        <select id="gatewayFilter" class="form-select form-select-sm" style="width:160px;">
            <option value="">All gateways</option>
            <option value="bank_transfer">Bank Transfer</option>
            <option value="stripe">Stripe</option>
            <option value="paypal">PayPal</option>
            <option value="jazzcash">JazzCash</option>
            <option value="easypaisa">Easypaisa</option>
        </select>
    </div>
</div>

<div class="li-card mb-4">
    <div class="table-responsive">
        <table class="table li-table mb-0">
            <thead><tr><th>Agency</th><th>Invoice</th><th>Gateway</th><th>Purpose</th><th>Amount</th><th>Status</th><th>Date</th><th></th></tr></thead>
            <tbody id="paymentsTable"></tbody>
        </table>
    </div>
    <div id="paymentsEmpty" class="text-center text-muted py-5 d-none">No payments match your filters.</div>
</div>

<h5 class="mb-3">Pending Refund Requests</h5>
<div class="li-card">
    <div class="table-responsive">
        <table class="table li-table mb-0">
            <thead><tr><th>Payment</th><th>Requested By</th><th>Reason</th><th>Date</th><th></th></tr></thead>
            <tbody id="refundsTable"></tbody>
        </table>
    </div>
    <div id="refundsEmpty" class="text-center text-muted py-4 d-none">No pending refund requests.</div>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
function payStatusPill(s) {
    const map = { pending: 'yellow', success: 'green', failed: 'red', refunded: 'gray' };
    return `<span class="li-pill li-pill-${map[s] || 'gray'}">${s}</span>`;
}

async function loadPayments() {
    const params = new URLSearchParams();
    const status = document.getElementById('statusFilter').value;
    const gateway = document.getElementById('gatewayFilter').value;
    if (status) params.set('status', status);
    if (gateway) params.set('gateway', gateway);

    try {
        const res = await apiFetch(`/admin/payments?${params.toString()}`);
        const payments = res.data || [];
        const tbody = document.getElementById('paymentsTable');
        const empty = document.getElementById('paymentsEmpty');

        if (payments.length === 0) { tbody.innerHTML = ''; empty.classList.remove('d-none'); return; }
        empty.classList.add('d-none');

        tbody.innerHTML = payments.map(p => `
            <tr>
                <td>${escapeHtml(p.agency_name || '—')}</td>
                <td>${escapeHtml(p.invoice_number || '—')}</td>
                <td>${p.gateway.replace('_',' ')}</td>
                <td>${p.purpose.replace('_',' ')}</td>
                <td>${Number(p.amount).toLocaleString()} ${p.currency}</td>
                <td>${payStatusPill(p.status)}</td>
                <td class="text-muted small">${dateOnly(p.created_at)}</td>
                <td>${p.status === 'pending' ? `<button class="btn btn-li-primary btn-sm" onclick="verifyPayment(${p.id})">Mark Paid</button>` : ''}</td>
            </tr>
        `).join('');
    } catch (e) { showToast(e.message, true); }
}

async function verifyPayment(id) {
    if (!confirm('Confirm this payment was received and mark it as paid? This will activate the subscription/credits/wallet top-up immediately.')) return;
    try {
        await apiFetch(`/admin/payments/${id}/verify`, { method: 'POST' });
        showToast('Payment verified — effects applied.');
        loadPayments();
    } catch (e) { showToast(e.message, true); }
}

async function loadRefunds() {
    try {
        const res = await apiFetch('/admin/refund-requests');
        const list = res.data.refund_requests || [];
        const tbody = document.getElementById('refundsTable');
        const empty = document.getElementById('refundsEmpty');

        if (list.length === 0) { tbody.innerHTML = ''; empty.classList.remove('d-none'); return; }
        empty.classList.add('d-none');

        tbody.innerHTML = list.map(r => `
            <tr>
                <td>#${r.payment_id}</td>
                <td>User #${r.requested_by_user_id}</td>
                <td>${escapeHtml(r.reason)}</td>
                <td class="text-muted small">${dateOnly(r.created_at)}</td>
                <td class="d-flex gap-2">
                    <button class="btn btn-li-primary btn-sm" onclick="approveRefund(${r.id})">Approve</button>
                    <button class="btn btn-li-ghost btn-sm text-danger" onclick="rejectRefund(${r.id})">Reject</button>
                </td>
            </tr>
        `).join('');
    } catch (e) { showToast(e.message, true); }
}

async function approveRefund(id) {
    try {
        await apiFetch(`/admin/refund-requests/${id}/approve`, { method: 'POST' });
        showToast('Refund approved.');
        loadRefunds();
    } catch (e) { showToast(e.message, true); }
}
async function rejectRefund(id) {
    try {
        await apiFetch(`/admin/refund-requests/${id}/reject`, { method: 'POST' });
        showToast('Refund rejected.');
        loadRefunds();
    } catch (e) { showToast(e.message, true); }
}

document.getElementById('statusFilter').addEventListener('change', loadPayments);
document.getElementById('gatewayFilter').addEventListener('change', loadPayments);
loadPayments();
loadRefunds();
</script>
<?= $this->endSection() ?>
