<?php
require_once __DIR__ . '/../config/bootstrap.php';
$user = Auth::requireLogin();
$pageTitle = 'Credit History';
$activeNav = 'credit';
$showSearch = false;
require __DIR__ . '/../includes/partials/dashboard-head.php';
?>

<div class="page-header">
    <div class="page-header-left">
        <h4>Credit History</h4>
        <p>View all your purchase transactions and receipts</p>
    </div>
    <div class="page-header-actions">
        <a href="/dashboard/campaigns/add" class="btn-primary-custom">
            <i class="bi bi-plus"></i> New Campaign
        </a>
    </div>
</div>

<div class="content-wrapper">
    <div class="campaign-list-card">
        <div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
            <div style="display:grid;grid-template-columns:2fr 1fr 1fr 1fr;gap:12px;flex:1;min-width:300px;padding:0 14px">
                <span style="font-size:12px;color:var(--text-secondary);font-weight:500">Plan Details</span>
                <span style="font-size:12px;color:var(--text-secondary);font-weight:500">Amount</span>
                <span style="font-size:12px;color:var(--text-secondary);font-weight:500">Status</span>
                <span style="font-size:12px;color:var(--text-secondary);font-weight:500">Purchase Date</span>
            </div>
            <div class="pagination-custom">
                <span id="pageDisplay">01/01</span>
                <button class="page-btn" id="prevPage" disabled><i class="bi bi-chevron-left"></i></button>
                <button class="page-btn" id="nextPage" disabled><i class="bi bi-chevron-right"></i></button>
            </div>
        </div>

        <div id="historyList">
            <div class="text-center py-5 text-muted">
                <div class="spinner-border spinner-border-sm me-2"></div> Loading…
            </div>
        </div>
    </div>
</div>

<style>
.credit-history-row { border-bottom: 1px solid var(--card-border); }
.credit-history-row:last-child { border-bottom: none; }
.credit-row-header {
    display: flex; align-items: center; gap: 14px;
    padding: 14px; cursor: pointer; transition: background 0.15s;
}
.credit-row-header:hover { background: var(--bg-cream); }
.credit-star-icon {
    width: 38px; height: 38px; border-radius: 12px;
    background: linear-gradient(135deg,#1B7A43,#2D9B5A); color: white;
    display: flex; align-items: center; justify-content: center;
    flex-shrink: 0; font-size: 16px;
}
.credit-pkg-name { font-weight: 700; font-size: 14px; }
.credit-pkg-sub { font-size: 12px; color: var(--text-secondary); }
.credit-toggle-btn {
    width: 32px; height: 32px; border-radius: 50%;
    background: var(--bg-cream); border: 1px solid var(--card-border);
    display: flex; align-items: center; justify-content: center;
    color: var(--primary); cursor: pointer; margin-left: auto;
}
.credit-expanded-content {
    max-height: 0; overflow: hidden; transition: max-height 0.3s ease;
    background: var(--bg-cream);
}
.credit-expanded-content.open { max-height: 400px; padding: 16px 24px 20px; }
.credit-detail-grid {
    display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 16px;
}
.credit-detail-item { display: flex; gap: 10px; align-items: flex-start; }
.cd-icon { color: var(--primary); font-size: 16px; margin-top: 2px; }
.cd-label { font-size: 11px; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.5px; }
.cd-value { font-size: 13px; font-weight: 600; color: var(--text-primary); word-break: break-all; }
</style>

<script>
(function () {
    let currentPage = 1;

    function escapeHtml(s) {
        return String(s ?? '').replace(/[&<>"']/g, c =>
            ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c]));
    }

    function row(p) {
        return `
        <div class="credit-history-row">
            <div class="credit-row-header">
                <div class="credit-star-icon"><i class="bi bi-star-fill"></i></div>
                <div class="flex-grow-1">
                    <div class="d-flex align-items-center gap-4 flex-wrap">
                        <div>
                            <div class="credit-pkg-name">${escapeHtml(p.plan_name)} Package</div>
                            <div class="credit-pkg-sub">${escapeHtml(p.app_title || 'Plan purchase')}</div>
                        </div>
                        <div style="font-weight:700;color:var(--primary)">${p.currency_symbol}${p.total_amount.toFixed(2)}</div>
                        <div><span class="${escapeHtml(p.status_badge)}">${escapeHtml(p.status_label)}</span></div>
                        <div style="font-size:13px;color:var(--text-secondary)">${escapeHtml(p.created_at_human)}</div>
                    </div>
                </div>
                <button class="credit-toggle-btn"><i class="bi bi-arrow-down"></i></button>
            </div>
            <div class="credit-expanded-content">
                <div class="credit-detail-grid">
                    <div class="credit-detail-item">
                        <i class="bi bi-envelope-fill cd-icon"></i>
                        <div>
                            <div class="cd-label">Email</div>
                            <div class="cd-value">${escapeHtml(p.email)}</div>
                        </div>
                    </div>
                    <div class="credit-detail-item">
                        <i class="bi bi-credit-card-fill cd-icon"></i>
                        <div>
                            <div class="cd-label">Payment Method</div>
                            <div class="cd-value">${escapeHtml(p.gateway_label)} Gateway</div>
                        </div>
                    </div>
                    <div class="credit-detail-item">
                        <i class="bi bi-cash-stack cd-icon"></i>
                        <div>
                            <div class="cd-label">Subtotal</div>
                            <div class="cd-value">${p.currency_symbol}${p.subtotal.toFixed(2)}</div>
                        </div>
                    </div>
                    <div class="credit-detail-item">
                        <i class="bi bi-receipt cd-icon"></i>
                        <div>
                            <div class="cd-label">GST</div>
                            <div class="cd-value">${p.currency_symbol}${p.gst_amount.toFixed(2)}</div>
                        </div>
                    </div>
                    <div class="credit-detail-item">
                        <i class="bi bi-tag-fill cd-icon"></i>
                        <div>
                            <div class="cd-label">Order ID</div>
                            <div class="cd-value">${escapeHtml(p.order_id)}</div>
                        </div>
                    </div>
                    <div class="credit-detail-item">
                        <i class="bi bi-key-fill cd-icon"></i>
                        <div>
                            <div class="cd-label">Transaction ID</div>
                            <div class="cd-value">${escapeHtml(p.transaction_id)}</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>`;
    }

    function bindRowToggles() {
        document.querySelectorAll('.credit-row-header').forEach(h => {
            h.addEventListener('click', function () {
                const content = this.nextElementSibling;
                const icon = this.querySelector('.credit-toggle-btn i');
                document.querySelectorAll('.credit-expanded-content.open').forEach(c => {
                    if (c !== content) {
                        c.classList.remove('open');
                        const i = c.previousElementSibling.querySelector('.credit-toggle-btn i');
                        if (i) i.className = 'bi bi-arrow-down';
                    }
                });
                content.classList.toggle('open');
                if (icon) icon.className = content.classList.contains('open') ? 'bi bi-arrow-up' : 'bi bi-arrow-down';
            });
        });
    }

    async function load() {
        const list = document.getElementById('historyList');
        list.innerHTML = '<div class="text-center py-5 text-muted"><div class="spinner-border spinner-border-sm me-2"></div> Loading…</div>';
        try {
            const resp = await window.api('/api/credit/history?page=' + currentPage);
            if (resp.status !== 'success') throw new Error(resp.message);
            const d = resp.data;

            if (!d.payments.length) {
                list.innerHTML = `
                    <div class="text-center py-5">
                        <div style="font-size:48px">💳</div>
                        <p class="text-muted mt-2">No purchases yet. Buy a plan to publish your first campaign!</p>
                        <a href="/dashboard/campaigns/add" class="btn-primary-custom" style="display:inline-flex">
                            <i class="bi bi-plus"></i> Add Campaign
                        </a>
                    </div>`;
            } else {
                list.innerHTML = d.payments.map(row).join('');
                bindRowToggles();
                // open first
                const first = list.querySelector('.credit-row-header');
                if (first) first.click();
            }

            const pag = d.pagination;
            document.getElementById('pageDisplay').textContent =
                String(pag.page).padStart(2, '0') + '/' + String(pag.total_pages).padStart(2, '0');
            document.getElementById('prevPage').disabled = !pag.has_prev;
            document.getElementById('nextPage').disabled = !pag.has_next;
        } catch (err) {
            list.innerHTML = '<div class="text-center py-5 text-muted">Failed to load history.</div>';
            console.error(err);
        }
    }

    document.getElementById('prevPage').addEventListener('click', () => { currentPage--; load(); });
    document.getElementById('nextPage').addEventListener('click', () => { currentPage++; load(); });

    load();
})();
</script>

<?php require __DIR__ . '/../includes/partials/dashboard-foot.php'; ?>
