{% extends "base.html" %}
{% set active = "home" %}

{% block title %}Riwayat Transaksi{% endblock %}
{% block page_title %}Riwayat Token{% endblock %}

{% block extra_head %}
<style>
    .transaction-table { width: 100%; border-collapse: collapse; }
    .transaction-table th, .transaction-table td { padding: 10px; border-bottom: 1px solid var(--border2); text-align: left; }
    .amount-positive { color: var(--success); }
    .amount-negative { color: var(--danger); }
    .badge-topup { background: rgba(63,185,80,.15); color: var(--success); }
    .badge-transcription { background: rgba(88,166,255,.15); color: var(--accent); }
    .badge-ba { background: rgba(212,160,23,.15); color: var(--gold); }
</style>
{% endblock %}

{% block content %}
<div class="card">
    <div class="card-header">
        <span class="card-title">📜 Riwayat Transaksi</span>
        <span class="badge">🪙 Token saat ini: {{ "{:,}".format(user.balance) }} Token</span>
    </div>
    <div class="table-wrap">
        <table class="transaction-table">
            <thead>
                <tr><th>Tanggal</th><th>Jenis</th><th>Jumlah (Token)</th><th>Deskripsi</th></tr>
            </thead>
            <tbody id="transactions-tbody">
                <tr><td colspan="4">Memuat...</td></tr>
            </tbody>
        </table>
    </div>
    <div class="pagination" id="pagination"></div>
</div>
{% endblock %}

{% block scripts %}
<script>
    let currentPage = 1;
    let totalPages = 1;

    async function loadTransactions(page = 1) {
        const tbody = document.getElementById('transactions-tbody');
        tbody.innerHTML = '<tr><td colspan="4">Memuat...</td></tr>';
        try {
            const res = await fetch(`/api/auth/transactions?limit=20&offset=${(page-1)*20}`);
            if (!res.ok) throw new Error('Gagal');
            const data = await res.json();
            const transactions = data.transactions;
            totalPages = Math.ceil(data.total / 20);
            if (transactions.length === 0) {
                tbody.innerHTML = '<tr><td colspan="4">Belum ada transaksi.</td></tr>';
            } else {
                tbody.innerHTML = transactions.map(t => {
                    let typeClass = '';
                    let typeText = '';
                    if (t.service_type === 'topup') { typeClass = 'badge-topup'; typeText = 'Top Up'; }
                    else if (t.service_type === 'transcription') { typeClass = 'badge-transcription'; typeText = 'Transkripsi'; }
                    else if (t.service_type === 'ba') { typeClass = 'badge-ba'; typeText = 'Berita Acara'; }
                    const amountClass = t.amount > 0 ? 'amount-positive' : 'amount-negative';
                    const amountFormatted = Math.abs(t.amount).toLocaleString('id-ID');
                    return `
                        <tr>
                            <td>${new Date(t.created_at).toLocaleString('id-ID')}</td>
                            <td><span class="badge ${typeClass}">${typeText}</span></td>
                            <td class="${amountClass}">${t.amount > 0 ? '+' : '-'} ${amountFormatted} Token</td>
                            <td>${t.description || '-'}</td>
                        </tr>
                    `;
                }).join('');
            }
            renderPagination();
        } catch(e) {
            tbody.innerHTML = '<tr><td colspan="4">Gagal memuat data.</td></tr>';
        }
    }

    function renderPagination() {
        const container = document.getElementById('pagination');
        if (totalPages <= 1) { container.innerHTML = ''; return; }
        let html = '';
        for (let i = 1; i <= totalPages; i++) {
            html += `<button class="page-btn ${i === currentPage ? 'active' : ''}" onclick="loadTransactions(${i}); currentPage=${i}">${i}</button>`;
        }
        container.innerHTML = html;
    }

    loadTransactions();
</script>
{% endblock %}