<?php
require_once __DIR__ . '/admin/includes/data_providers.php';
require_once __DIR__ . '/admin/includes/layout.php';

$pdo = admin_pdo();

$summary = admin_fetch_token_summary($pdo);
$topWallets = admin_fetch_top_token_users($pdo, 15);
$dailyStats = admin_fetch_token_daily_stats($pdo, 14);
$recentTransactions = admin_fetch_recent_token_activity($pdo, 15);
$packages = admin_fetch_token_packages($pdo);

admin_page_start('Token Economy Analytics', 'tokens');
?>

<section class="stats-grid">
    <article class="stat-card">
        <div class="stat-card__icon">&#128176;</div>
        <div class="stat-card__label">Circulating Balance</div>
        <div class="stat-card__value"><?= admin_format_number($summary['total_balance'], 2) ?></div>
        <div class="stat-card__meta">
            <span><?= admin_format_number($summary['total_earned'], 2) ?> earned</span>
            <span><?= admin_format_number($summary['total_spent'], 2) ?> spent</span>
        </div>
    </article>
    <article class="stat-card">
        <div class="stat-card__icon">&#128179;</div>
        <div class="stat-card__label">Completed Purchases</div>
        <div class="stat-card__value"><?= admin_format_number($summary['purchase_count']) ?></div>
        <div class="stat-card__meta">
            <span><?= admin_format_number($summary['purchase_volume'], 2) ?> USD volume</span>
        </div>
    </article>
    <article class="stat-card">
        <div class="stat-card__icon">&#9889;</div>
        <div class="stat-card__label">Activity Today</div>
        <div class="stat-card__value"><?= admin_format_number($summary['transactions_today']) ?></div>
        <div class="stat-card__meta">
            <span>Transactions recorded</span>
        </div>
    </article>
</section>

<div class="grid grid--two">
    <section class="card">
        <div class="card__header">
            <h2>Top Token Wallets</h2>
        </div>
        <?php if (empty($topWallets)): ?>
            <div class="empty-state">No token data available yet.</div>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th>User</th>
                        <th>Balance</th>
                        <th>Total Earned</th>
                        <th>Total Spent</th>
                        <th>Purchases</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($topWallets as $wallet): ?>
                        <tr>
                            <td>#<?= admin_escape((string) ($wallet['usr_id'] ?? $wallet['user_id'] ?? '')) ?> &middot; <?= admin_escape($wallet['usr_user'] ?? ($wallet['username'] ?? 'unknown')) ?></td>
                            <td><?= admin_format_number($wallet['token_balance'] ?? 0, 2) ?></td>
                            <td><?= admin_format_number($wallet['total_tokens_earned'] ?? 0, 2) ?></td>
                            <td><?= admin_format_number($wallet['total_tokens_spent'] ?? 0, 2) ?></td>
                            <td><?= admin_format_number($wallet['total_purchases'] ?? 0) ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </section>

    <section class="card">
        <div class="card__header">
            <h2>Recent Transactions</h2>
            <a class="admin-button admin-button--ghost" href="/f_modules/m_backend/token_customization.php">Adjust tokens</a>
        </div>
        <?php if (empty($recentTransactions)): ?>
            <div class="empty-state">No transactions recorded yet.</div>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>User</th>
                        <th>Amount</th>
                        <th>Type</th>
                        <th>Status</th>
                        <th>Created</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($recentTransactions as $txn): ?>
                        <tr>
                            <td>#<?= admin_escape((string) $txn['id']) ?></td>
                            <td>#<?= admin_escape((string) $txn['user_id']) ?></td>
                            <td><?= admin_format_number($txn['amount'] ?? 0, 2) ?></td>
                            <td><?= admin_escape(ucfirst($txn['transaction_type'] ?? '')) ?></td>
                            <td>
                                <?php $status = strtolower($txn['status'] ?? ''); ?>
                                <span class="badge <?= $status === 'completed' ? 'badge--success' : ($status === 'pending' ? 'badge--warning' : 'badge--danger') ?>">
                                    <?= admin_escape(ucfirst($status)) ?>
                                </span>
                            </td>
                            <td><?= admin_escape($txn['created_at'] ?? '') ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </section>
</div>

<section class="card">
    <div class="card__header">
        <h2>Daily Activity (Last 14 Days)</h2>
    </div>
    <?php if (empty($dailyStats)): ?>
        <div class="empty-state">No daily statistics captured.</div>
    <?php else: ?>
        <table>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Transactions</th>
                    <th>Tokens Purchased</th>
                    <?php if (isset($dailyStats[0]['tokens_donated'])): ?>
                        <th>Tokens Donated</th>
                    <?php endif; ?>
                    <th>Active Users</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($dailyStats as $row): ?>
                    <tr>
                        <td><?= admin_escape($row['date']) ?></td>
                        <td><?= admin_format_number($row['total_transactions'] ?? 0) ?></td>
                        <td><?= admin_format_number($row['tokens_purchased'] ?? 0, 2) ?></td>
                        <?php if (isset($row['tokens_donated'])): ?>
                            <td><?= admin_format_number($row['tokens_donated'] ?? 0, 2) ?></td>
                        <?php endif; ?>
                        <td><?= admin_format_number($row['active_users'] ?? 0) ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</section>

<section class="card">
    <div class="card__header">
        <h2>Token Packages</h2>
    </div>
    <?php if (empty($packages)): ?>
        <div class="empty-state">Token packages are not configured.</div>
    <?php else: ?>
        <div class="quick-actions">
            <?php foreach ($packages as $package): ?>
                <div class="quick-actions__item" style="cursor: default;">
                    <div class="quick-actions__icon">&#127873;</div>
                    <div class="quick-actions__content">
                        <div class="quick-actions__title"><?= admin_escape(ucwords(str_replace('_', ' ', $package['key']))) ?></div>
                        <div class="quick-actions__desc">
                            <?= admin_format_number($package['tokens'] ?? 0) ?> tokens &middot;
                            <?= admin_format_number($package['usd'] ?? 0, 2) ?> USD
                            <?php if (!empty($package['bonus'])): ?>
                                &middot; Bonus <?= admin_format_number($package['bonus'], 2) ?>
                            <?php endif; ?>
                            <?php if (!empty($package['popular'])): ?>
                                &middot; <strong>Popular</strong>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</section>

<section class="card">
    <div class="card__header">
        <h2>Operations</h2>
    </div>
    <div class="quick-actions">
        <a class="quick-actions__item" href="/f_modules/m_backend/token_customization.php">
            <div class="quick-actions__icon">&#128290;</div>
            <div class="quick-actions__content">
                <div class="quick-actions__title">Adjust Balances</div>
                <div class="quick-actions__desc">Credit or debit user balances and bonuses.</div>
            </div>
        </a>
        <a class="quick-actions__item" href="/f_modules/m_backend/token_customization.php?s=settings">
            <div class="quick-actions__icon">&#9881;</div>
            <div class="quick-actions__content">
                <div class="quick-actions__title">Exchange Rate</div>
                <div class="quick-actions__desc">Update purchase packages and conversion rate.</div>
            </div>
        </a>
        <a class="quick-actions__item" href="/f_modules/m_backend/members.php?s=balances">
            <div class="quick-actions__icon">&#128202;</div>
            <div class="quick-actions__content">
                <div class="quick-actions__title">Wallet Report</div>
                <div class="quick-actions__desc">Drill down into individual token activity.</div>
            </div>
        </a>
        <a class="quick-actions__item" href="/f_modules/m_backend/log_viewer.php">
            <div class="quick-actions__icon">&#128269;</div>
            <div class="quick-actions__content">
                <div class="quick-actions__title">Audit Trail</div>
                <div class="quick-actions__desc">Review token-related administrative changes.</div>
            </div>
        </a>
    </div>
</section>

<?php
admin_page_end();


