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

<?= $this->section('content') ?>
<h5 class="mb-3">Billing</h5>

<div class="row g-3 mb-3">
    <div class="col-md-4">
        <div class="li-card">
            <div class="li-card-header">Current Plan</div>
            <div class="li-card-body">
                <div id="planInfo">Loading...</div>
                <button class="btn btn-li-outline btn-sm mt-2" data-bs-toggle="modal" data-bs-target="#plansModal">Change Plan</button>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="li-card">
            <div class="li-card-header">Credit Balance</div>
            <div class="li-card-body">
                <div class="li-stat-num" id="creditBalance">—</div>
                <div class="text-muted small mb-2">credits available</div>
                <button class="btn btn-li-outline btn-sm" data-bs-toggle="modal" data-bs-target="#creditsModal">Buy Credits</button>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="li-card">
            <div class="li-card-header">Wallet Balance</div>
            <div class="li-card-body">
                <div class="li-stat-num" id="walletBalance">—</div>
                <div class="text-muted small mb-2">PKR</div>
                <button class="btn btn-li-outline btn-sm" data-bs-toggle="modal" data-bs-target="#walletModal">Top Up</button>
            </div>
        </div>
    </div>
</div>

<div class="li-card">
    <div class="li-card-header">Invoices</div>
    <div class="table-responsive">
        <table class="table li-table mb-0">
            <thead><tr><th>Invoice #</th><th>Total</th><th>Status</th><th>Due</th><th></th></tr></thead>
            <tbody id="invoicesTable"></tbody>
        </table>
    </div>
</div>

<!-- Plans Modal -->
<div class="modal fade" id="plansModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header"><h6 class="modal-title">Choose a Plan</h6><button class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body"><div class="row g-2" id="plansList"></div></div>
        </div>
    </div>
</div>

<!-- Credits Modal -->
<div class="modal fade" id="creditsModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"><h6 class="modal-title">Buy Credits</h6><button class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <label class="form-label">Number of Credits</label>
                <input type="number" id="creditAmount" class="form-control mb-2" value="10" min="1">
                <label class="form-label">Payment Method</label>
                <select id="creditGateway" class="form-select">
                    <option value="wallet">Wallet Balance</option>
                    <option value="bank_transfer">Bank Transfer</option>
                    <option value="stripe">Card (Stripe)</option>
                </select>
            </div>
            <div class="modal-footer"><button class="btn btn-li-primary" onclick="buyCredits()">Purchase</button></div>
        </div>
    </div>
</div>

<!-- Wallet Modal -->
<div class="modal fade" id="walletModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"><h6 class="modal-title">Top Up Wallet</h6><button class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <label class="form-label">Amount (PKR)</label>
                <input type="number" id="topupAmount" class="form-control mb-2" value="1000">
                <label class="form-label">Payment Method</label>
                <select id="topupGateway" class="form-select">
                    <option value="bank_transfer">Bank Transfer</option>
                    <option value="stripe">Card (Stripe)</option>
                    <option value="jazzcash">JazzCash</option>
                    <option value="easypaisa">Easypaisa</option>
                </select>
            </div>
            <div class="modal-footer"><button class="btn btn-li-primary" onclick="topUpWallet()">Top Up</button></div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
async function loadBilling() {
    try {
        const sub = await apiFetch('/billing/subscription');
        document.getElementById('planInfo').innerHTML = `
            <span class="li-pill li-pill-blue">${escapeHtml(sub.data.plan.name)}</span>
            <div class="text-muted small mt-2">Status: ${sub.data.subscription.status}</div>
            <div class="text-muted small">Renews: ${sub.data.subscription.current_period_end}</div>
        `;
    } catch (e) { document.getElementById('planInfo').innerHTML = '<span class="text-muted">No active plan.</span>'; }

    try {
        const credits = await apiFetch('/billing/credits');
        document.getElementById('creditBalance').textContent = credits.data.balance;
    } catch (e) {}

    try {
        const wallet = await apiFetch('/billing/wallet');
        document.getElementById('walletBalance').textContent = Number(wallet.data.balance).toLocaleString();
    } catch (e) {}

    try {
        const plans = await apiFetch('/billing/plans');
        document.getElementById('plansList').innerHTML = (plans.data.plans || []).map(p => `
            <div class="col-md-6">
                <div class="li-card li-card-body">
                    <h6>${escapeHtml(p.name)}</h6>
                    <div class="li-stat-num" style="font-size:22px;">PKR ${Number(p.price_monthly).toLocaleString()}<span class="text-muted small">/mo</span></div>
                    <ul class="small text-muted mt-2">
                        <li>${p.job_posting_limit == -1 ? 'Unlimited' : p.job_posting_limit} job postings</li>
                        <li>${p.recruiter_limit == -1 ? 'Unlimited' : p.recruiter_limit} recruiters</li>
                        <li>${p.candidate_view_limit == -1 ? 'Unlimited' : p.candidate_view_limit} candidate views</li>
                    </ul>
                    <button class="btn btn-li-primary btn-sm w-100" onclick="subscribeToPlan('${p.slug}')">Request This Plan</button>
                </div>
            </div>
        `).join('');
    } catch (e) {}

    try {
        const inv = await apiFetch('/billing/invoices');
        document.getElementById('invoicesTable').innerHTML = (inv.data.invoices || []).map(i => `
            <tr>
                <td>${escapeHtml(i.invoice_number)}</td>
                <td>${Number(i.total).toLocaleString()} ${i.currency}</td>
                <td><span class="li-pill li-pill-${i.status === 'paid' ? 'green' : 'yellow'}">${i.status}</span></td>
                <td>${i.due_date || '—'}</td>
                <td><a href="${API_BASE}/billing/invoices/${i.id}/pdf" class="btn btn-li-ghost btn-sm">PDF</a></td>
            </tr>
        `).join('') || '<tr><td colspan="5" class="text-muted text-center py-3">No invoices yet.</td></tr>';
    } catch (e) {}
}

async function subscribeToPlan(slug) {
    try {
        await apiFetch('/billing/subscribe', { method: 'POST', body: JSON.stringify({ plan_slug: slug, billing_cycle: 'monthly' }) });
        showToast('Plan change requested — a Super Admin will review it shortly.');
        bootstrap.Modal.getInstance(document.getElementById('plansModal')).hide();
        loadBilling();
    } catch (e) { showToast(e.message, true); }
}

async function buyCredits() {
    const amount = document.getElementById('creditAmount').value;
    const gateway = document.getElementById('creditGateway').value;
    try {
        await apiFetch('/billing/credits/purchase', { method: 'POST', body: JSON.stringify({ credit_amount: parseInt(amount), gateway }) });
        showToast('Credit purchase initiated.');
        bootstrap.Modal.getInstance(document.getElementById('creditsModal')).hide();
        loadBilling();
    } catch (e) { showToast(e.message, true); }
}

async function topUpWallet() {
    const amount = document.getElementById('topupAmount').value;
    const gateway = document.getElementById('topupGateway').value;
    try {
        await apiFetch('/billing/wallet/topup', { method: 'POST', body: JSON.stringify({ amount: parseFloat(amount), gateway }) });
        showToast('Top-up initiated — complete payment via the gateway.');
        bootstrap.Modal.getInstance(document.getElementById('walletModal')).hide();
        loadBilling();
    } catch (e) { showToast(e.message, true); }
}

loadBilling();
</script>
<?= $this->endSection() ?>
