<?php
$current_page = 'yem';
$yem_filters = $yem_filters ?? [
    'start_date' => null, 'end_date' => null, 'uid' => '', 'reason' => '', 'hash' => '',
    'status' => null, 'asset' => '', 'value_min' => null, 'value_max' => null,
];
$yem_filters_active = $yem_filters_active ?? false;
$yem_status_sel = ($yem_filters['status'] ?? null) ?: 'all';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>YEM / YEMChain - Admin App</title>
    <link rel="icon" href="/favicon.svg" type="image/svg+xml">
    <link rel="icon" href="/favicon.ico" sizes="any">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <?= view('admin/partials/admin_styles') ?>
    <style>
        .page-header { margin-bottom: 1.5rem; }
        .page-title { font-size: 1.5rem; color: #1e293b; font-weight: 700; }
        .breadcrumb { display: flex; align-items: center; gap: 0.5rem; color: #64748b; margin-top: 0.35rem; font-size: 0.9rem; }
        .breadcrumb a { color: #6366f1; text-decoration: none; font-weight: 500; }
        .yem-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        .yem-stat-card {
            background: #fff;
            padding: 1.25rem;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.06);
            border: 1px solid #e2e8f0;
        }
        .yem-stat-label { color: #64748b; font-size: 0.8rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 0.35rem; }
        .yem-stat-value { font-size: 1.5rem; font-weight: 700; color: #1e293b; }
        .yem-stat-card.price .yem-stat-value { color: #059669; }
        .yem-section {
            background: #fff;
            padding: 1.5rem;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.06);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        .yem-section h3 { font-size: 1.1rem; color: #1e293b; margin-bottom: 1rem; display: flex; align-items: center; gap: 0.5rem; }
        .yem-section h3 i { color: #6366f1; }
        .form-row { display: flex; gap: 1rem; flex-wrap: wrap; align-items: flex-end; margin-bottom: 1rem; }
        .form-group { flex: 1; min-width: 180px; }
        .form-group label { display: block; margin-bottom: 0.35rem; font-weight: 600; color: #374151; font-size: 0.9rem; }
        .form-group input, .form-group select { width: 100%; padding: 0.6rem 0.85rem; border: 2px solid #e2e8f0; border-radius: 8px; font-size: 0.9rem; background: #fff; }
        .form-group input:focus, .form-group select:focus { outline: none; border-color: #6366f1; }
        .yem-filters { margin-bottom: 1.25rem; padding-bottom: 1.25rem; border-bottom: 1px solid #e2e8f0; }
        .yem-filters .filter-actions { display: flex; gap: 0.75rem; flex-wrap: wrap; align-items: center; margin-top: 0.5rem; }
        .yem-filters .btn-secondary { padding: 0.6rem 1.25rem; border-radius: 8px; font-size: 0.9rem; font-weight: 600; }
        .btn {
            padding: 0.6rem 1.25rem;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 0.9rem;
            font-weight: 600;
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            color: white;
        }
        .btn:hover { opacity: 0.95; transform: translateY(-1px); }
        .btn-secondary { background: #64748b; color: white; text-decoration: none; display: inline-block; }
        .balances-result { margin-top: 1rem; }
        .balances-table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
        .balances-table th, .balances-table td { padding: 0.75rem; text-align: left; border-bottom: 1px solid #e2e8f0; }
        .balances-table th { background: #f8fafc; font-weight: 600; color: #475569; }
        .balances-table .amount { font-weight: 700; color: #059669; }
        .not-configured {
            background: #fef3c7;
            border: 1px solid #f59e0b;
            color: #92400e;
            padding: 1.5rem;
            border-radius: 12px;
            margin-bottom: 1.5rem;
        }
        .not-configured p { margin: 0.5rem 0 0 0; }
        .not-configured a { color: #b45309; font-weight: 600; }
        .error-msg { background: #fee2e2; color: #991b1b; padding: 0.75rem; border-radius: 8px; margin-top: 0.5rem; font-size: 0.9rem; }
        .api-info { font-size: 0.85rem; color: #64748b; margin-top: 1rem; }
        .tx-table { width: 100%; border-collapse: collapse; font-size: 0.85rem; }
        .tx-table th, .tx-table td { padding: 0.6rem 0.75rem; text-align: left; border-bottom: 1px solid #e2e8f0; }
        .tx-table th { background: #f8fafc; font-weight: 600; color: #475569; }
        .tx-table .hash { font-family: monospace; font-size: 0.8rem; max-width: 200px; overflow: hidden; text-overflow: ellipsis; }
        .tx-table .status { font-weight: 600; }
        .tx-table .status.confirmed { color: #059669; }
        .tx-table .status.failed { color: #dc2626; }
        .tx-table .status.not_found { color: #64748b; }
        .tx-table .status.pending { color: #d97706; }
        .tx-table .status.unknown { color: #94a3b8; }
        .tx-table .value { font-weight: 700; color: #059669; }
        .tx-section-actions { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 0.75rem; margin-bottom: 1rem; }
        .pagination-wrapper { padding: 1rem 0; margin-top: 1rem; border-top: 1px solid #e2e8f0; }
        .pagination-wrapper .pagination { display: flex; flex-wrap: wrap; gap: 0.35rem; list-style: none; margin: 0; padding: 0; justify-content: center; }
        .pagination-wrapper .pagination li a { display: inline-block; padding: 0.5rem 0.85rem; border-radius: 8px; background: #fff; border: 1px solid #e2e8f0; color: #6366f1; text-decoration: none; font-weight: 600; font-size: 0.9rem; }
        .pagination-wrapper .pagination li a:hover { background: #eef2ff; border-color: #c7d2fe; }
        .pagination-wrapper .pagination li.active a { background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%); border-color: transparent; color: #fff; }
        .flash-msg { background: #d1fae5; border: 1px solid #059669; color: #065f46; padding: 0.75rem 1rem; border-radius: 8px; margin-bottom: 1rem; font-size: 0.9rem; }
        .asset-stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 1rem; }
        .asset-stats-grid .yem-stat-card { margin: 0; }
        .tx-actions { white-space: nowrap; }
        .tx-actions .btn-sm { padding: 0.35rem 0.6rem; font-size: 0.8rem; margin-right: 0.25rem; }
        .tx-actions .btn-copy { background: #64748b; }
        .tx-details-modal { display: none; position: fixed; inset: 0; z-index: 1000; background: rgba(0,0,0,0.4); align-items: center; justify-content: center; padding: 1rem; }
        .tx-details-modal.show { display: flex; }
        .tx-details-box { background: #fff; border-radius: 12px; box-shadow: 0 10px 40px rgba(0,0,0,0.2); max-width: 560px; width: 100%; max-height: 90vh; overflow: hidden; display: flex; flex-direction: column; }
        .tx-details-box h4 { margin: 0; padding: 1rem 1.25rem; border-bottom: 1px solid #e2e8f0; font-size: 1rem; color: #1e293b; }
        .tx-details-box .body { padding: 1.25rem; overflow: auto; }
        .tx-details-dl { margin: 0; font-size: 0.9rem; }
        .tx-details-dl dt { font-weight: 600; color: #475569; margin-top: 0.75rem; margin-bottom: 0.2rem; }
        .tx-details-dl dt:first-child { margin-top: 0; }
        .tx-details-dl dd { margin: 0; color: #1e293b; word-break: break-all; font-family: monospace; font-size: 0.85rem; }
        .tx-details-dl dd.reason { font-family: inherit; word-break: break-word; }
        .tx-details-box .footer { padding: 0.75rem 1.25rem; border-top: 1px solid #e2e8f0; display: flex; justify-content: space-between; align-items: center; gap: 0.5rem; }
        .copy-feedback { font-size: 0.8rem; color: #059669; }
    </style>
</head>
<body>
<?= view('admin/partials/header_sidebar', ['current_page' => $current_page]) ?>

    <div class="page-header">
        <h1 class="page-title"><i class="fas fa-coins"></i> YEM / YEMChain</h1>
        <div class="breadcrumb">
            <a href="<?= site_url('admin/dashboard') ?>">Dashboard</a>
            <i class="fas fa-chevron-right"></i>
            <span>YEM</span>
        </div>
    </div>

    <?php if (!empty($configured) && $configured): ?>
        <div class="yem-stats">
            <?php if (!empty($globals)): ?>
                <div class="yem-stat-card">
                    <div class="yem-stat-label">Total accounts</div>
                    <div class="yem-stat-value"><?= esc(number_format((int)($globals['total_accs'] ?? 0))) ?></div>
                </div>
                <div class="yem-stat-card">
                    <div class="yem-stat-label">Total transactions</div>
                    <div class="yem-stat-value"><?= esc(number_format((int)($globals['total_txns'] ?? 0))) ?></div>
                </div>
            <?php endif; ?>
            <?php if (!empty($assetStats)): ?>
                <div class="yem-stat-card price">
                    <div class="yem-stat-label">YEM price</div>
                    <div class="yem-stat-value"><?= esc($assetStats['price'] ?? '—') ?></div>
                </div>
                <div class="yem-stat-card">
                    <div class="yem-stat-label">Wallets (YEM)</div>
                    <div class="yem-stat-value"><?= esc(number_format((int)($assetStats['wallets'] ?? 0))) ?></div>
                </div>
            <?php endif; ?>
            <?php if (!empty($volume)): ?>
                <div class="yem-stat-card">
                    <div class="yem-stat-label">Volume 1d</div>
                    <div class="yem-stat-value"><?= esc(number_format((float)($volume['volume_1d'] ?? 0), 2)) ?></div>
                </div>
                <div class="yem-stat-card">
                    <div class="yem-stat-label">Volume 7d</div>
                    <div class="yem-stat-value"><?= esc(number_format((float)($volume['volume_7d'] ?? 0), 2)) ?></div>
                </div>
            <?php endif; ?>
        </div>

        <div class="yem-section">
            <h3><i class="fas fa-chart-line"></i> Asset stats (YEM)</h3>
            <p class="api-info">From <code>getAssetStats</code> — price and wallet count for the YEM token.</p>
            <?php if (!empty($assetStats) && !empty($assetStats['success'])): ?>
                <div class="asset-stats-grid">
                    <div class="yem-stat-card price">
                        <div class="yem-stat-label">Price</div>
                        <div class="yem-stat-value"><?= esc($assetStats['price'] ?? '—') ?></div>
                    </div>
                    <div class="yem-stat-card">
                        <div class="yem-stat-label">Wallets</div>
                        <div class="yem-stat-value"><?= esc(number_format((int)($assetStats['wallets'] ?? 0))) ?></div>
                    </div>
                </div>
            <?php elseif (!empty($assetStats) && isset($assetStats['message'])): ?>
                <p class="error-msg"><?= esc($assetStats['message']) ?></p>
            <?php else: ?>
                <p class="api-info">Asset stats unavailable. Check YEMScan API configuration.</p>
            <?php endif; ?>
        </div>

        <div class="yem-section">
            <h3><i class="fas fa-wallet"></i> Look up balances</h3>
            <p class="api-info">Enter comma-separated UIDs to fetch YEM balances (max 100).</p>
            <div class="form-row">
                <div class="form-group">
                    <label for="balance-uids">UIDs</label>
                    <input type="text" id="balance-uids" placeholder="e.g. 123,456,789" value="">
                </div>
                <div class="form-group" style="max-width: 120px;">
                    <label for="balance-token">Asset</label>
                    <input type="text" id="balance-token" value="YEM" placeholder="YEM">
                </div>
                <div class="form-group" style="flex: 0 0 auto;">
                    <label>&nbsp;</label>
                    <button type="button" class="btn" id="btn-balances"><i class="fas fa-search"></i> Get balances</button>
                </div>
            </div>
            <div class="balances-result" id="balances-result"></div>
        </div>

        <?php if (session()->getFlashdata('yem_status_refreshed') !== null): ?>
            <div class="flash-msg">Statuses updated for <?= (int) session()->getFlashdata('yem_status_refreshed') ?> transaction(s).</div>
        <?php endif; ?>

        <div class="yem-section">
            <h3><i class="fas fa-list"></i> Recorded transactions</h3>
            <p class="api-info">Transactions created via the API are recorded here. Use "Refresh statuses" to fetch latest status from the chain.</p>

            <form method="get" action="<?= site_url('admin/yem') ?>" class="yem-filters">
                <div class="form-row">
                    <div class="form-group">
                        <label for="yem-start-date">Start date</label>
                        <input type="date" name="start_date" id="yem-start-date" value="<?= esc($yem_filters['start_date'] ?? '') ?>">
                    </div>
                    <div class="form-group">
                        <label for="yem-end-date">End date</label>
                        <input type="date" name="end_date" id="yem-end-date" value="<?= esc($yem_filters['end_date'] ?? '') ?>">
                    </div>
                    <div class="form-group">
                        <label for="yem-uid">UID</label>
                        <input type="text" name="uid" id="yem-uid" placeholder="From or to UID" value="<?= esc($yem_filters['uid'] ?? '') ?>"
                               autocomplete="off">
                    </div>
                    <div class="form-group">
                        <label for="yem-hash">Hash</label>
                        <input type="text" name="hash" id="yem-hash" placeholder="Partial hash" value="<?= esc($yem_filters['hash'] ?? '') ?>"
                               autocomplete="off">
                    </div>
                    <div class="form-group">
                        <label for="yem-reason">Reason</label>
                        <input type="text" name="reason" id="yem-reason" placeholder="Contains text" value="<?= esc($yem_filters['reason'] ?? '') ?>"
                               autocomplete="off">
                    </div>
                    <div class="form-group">
                        <label for="yem-status">Status</label>
                        <select name="status" id="yem-status">
                            <option value="all" <?= $yem_status_sel === 'all' ? 'selected' : '' ?>>All statuses</option>
                            <option value="pending" <?= $yem_status_sel === 'pending' ? 'selected' : '' ?>>pending</option>
                            <option value="confirmed" <?= $yem_status_sel === 'confirmed' ? 'selected' : '' ?>>confirmed</option>
                            <option value="failed" <?= $yem_status_sel === 'failed' ? 'selected' : '' ?>>failed</option>
                            <option value="not_found" <?= $yem_status_sel === 'not_found' ? 'selected' : '' ?>>not_found</option>
                            <option value="unknown" <?= $yem_status_sel === 'unknown' ? 'selected' : '' ?>>unknown</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="yem-asset">Asset</label>
                        <input type="text" name="asset" id="yem-asset" placeholder="e.g. YEM" value="<?= esc($yem_filters['asset'] ?? '') ?>"
                               autocomplete="off">
                    </div>
                    <div class="form-group" style="max-width: 120px;">
                        <label for="yem-value-min">Value min</label>
                        <input type="number" step="any" name="value_min" id="yem-value-min" placeholder="—" value="<?= esc($yem_filters['value_min'] ?? '') ?>">
                    </div>
                    <div class="form-group" style="max-width: 120px;">
                        <label for="yem-value-max">Value max</label>
                        <input type="number" step="any" name="value_max" id="yem-value-max" placeholder="—" value="<?= esc($yem_filters['value_max'] ?? '') ?>">
                    </div>
                </div>
                <div class="filter-actions">
                    <button type="submit" class="btn"><i class="fas fa-filter"></i> Apply filters</button>
                    <a href="<?= site_url('admin/yem') ?>" class="btn btn-secondary"><i class="fas fa-times"></i> Clear</a>
                </div>
            </form>

            <div class="tx-section-actions">
                <span class="api-info">
                    <?php
                    $yemPager = $yemPager ?? null;
                    if ($yemPager && $yemPager->getTotal() > 0) {
                        $start = ($yemPager->getCurrentPage() - 1) * $yemPager->getPerPage() + 1;
                        $end = min($yemPager->getCurrentPage() * $yemPager->getPerPage(), $yemPager->getTotal());
                        echo "Showing {$start}–{$end} of " . number_format($yemPager->getTotal()) . " recorded";
                    } else {
                        echo count($yemTransactions ?? []) . " recorded";
                    }
                    ?>
                </span>
                <form method="post" action="<?= site_url('admin/yem/refresh-status') ?>" style="display: inline;">
                    <?= csrf_field() ?>
                    <?php if (!empty($yemPager) && $yemPager->getCurrentPage() > 1): ?>
                    <input type="hidden" name="page" value="<?= (int) $yemPager->getCurrentPage() ?>">
                    <?php endif; ?>
                    <?php if (!empty($yem_filters['start_date'])): ?><input type="hidden" name="start_date" value="<?= esc($yem_filters['start_date']) ?>"><?php endif; ?>
                    <?php if (!empty($yem_filters['end_date'])): ?><input type="hidden" name="end_date" value="<?= esc($yem_filters['end_date']) ?>"><?php endif; ?>
                    <?php if (($yem_filters['uid'] ?? '') !== ''): ?><input type="hidden" name="uid" value="<?= esc($yem_filters['uid']) ?>"><?php endif; ?>
                    <?php if (($yem_filters['reason'] ?? '') !== ''): ?><input type="hidden" name="reason" value="<?= esc($yem_filters['reason']) ?>"><?php endif; ?>
                    <?php if (($yem_filters['hash'] ?? '') !== ''): ?><input type="hidden" name="hash" value="<?= esc($yem_filters['hash']) ?>"><?php endif; ?>
                    <?php if (!empty($yem_filters['status']) && $yem_filters['status'] !== 'all'): ?><input type="hidden" name="status" value="<?= esc($yem_filters['status']) ?>"><?php endif; ?>
                    <?php if (($yem_filters['asset'] ?? '') !== ''): ?><input type="hidden" name="asset" value="<?= esc($yem_filters['asset']) ?>"><?php endif; ?>
                    <?php if (($yem_filters['value_min'] ?? '') !== '' && $yem_filters['value_min'] !== null): ?><input type="hidden" name="value_min" value="<?= esc($yem_filters['value_min']) ?>"><?php endif; ?>
                    <?php if (($yem_filters['value_max'] ?? '') !== '' && $yem_filters['value_max'] !== null): ?><input type="hidden" name="value_max" value="<?= esc($yem_filters['value_max']) ?>"><?php endif; ?>
                    <button type="submit" class="btn btn-secondary"><i class="fas fa-sync-alt"></i> Refresh statuses</button>
                </form>
            </div>
            <?php if (!empty($yemTransactions ?? [])): ?>
                <div style="overflow-x: auto;">
                    <table class="tx-table balances-table">
                        <thead>
                            <tr>
                                <th>Hash</th>
                                <th>From UID</th>
                                <th>To UID</th>
                                <th>Value</th>
                                <th>Asset</th>
                                <th>Reason</th>
                                <th>Status</th>
                                <th>Created</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($yemTransactions as $tx): ?>
                                <?php
                                $hash = $tx['hash'] ?? '';
                                $reason = $tx['reason'] ?? '—';
                                ?>
                                <tr class="tx-row"
                                    data-hash="<?= esc($hash) ?>"
                                    data-from-uid="<?= esc($tx['from_uid'] ?? '') ?>"
                                    data-to-uid="<?= esc($tx['to_uid'] ?? '') ?>"
                                    data-value="<?= esc(number_format((float)($tx['value'] ?? 0), 2)) ?>"
                                    data-asset="<?= esc($tx['asset'] ?? 'YEM') ?>"
                                    data-reason="<?= esc($reason) ?>"
                                    data-from-curr="<?= esc($tx['from_curr'] ?? '') ?>"
                                    data-to-curr="<?= esc($tx['to_curr'] ?? '') ?>"
                                    data-status="<?= esc($tx['status'] ?? 'pending') ?>"
                                    data-created="<?= esc($tx['created_at'] ?? '') ?>"
                                    data-status-updated="<?= esc($tx['status_updated_at'] ?? '') ?>">
                                    <td class="hash" title="<?= esc($hash) ?>"><?= esc($hash ?: '—') ?></td>
                                    <td><?= esc($tx['from_uid'] ?? '—') ?></td>
                                    <td><?= esc($tx['to_uid'] ?? '—') ?></td>
                                    <td class="value"><?= esc(number_format((float)($tx['value'] ?? 0), 2)) ?></td>
                                    <td><?= esc($tx['asset'] ?? 'YEM') ?></td>
                                    <td title="<?= esc($reason) ?>"><?= esc(mb_strimwidth($reason, 0, 80, '…')) ?></td>
                                    <td class="status <?= esc($tx['status'] ?? 'pending') ?>"><?= esc($tx['status'] ?? 'pending') ?></td>
                                    <td><?= esc($tx['created_at'] ?? '—') ?></td>
                                    <td class="tx-actions">
                                        <button type="button" class="btn btn-sm btn-view-details" title="View full details"><i class="fas fa-eye"></i> Details</button>
                                        <button type="button" class="btn btn-sm btn-copy btn-copy-hash" title="Copy hash"><i class="fas fa-copy"></i> Copy hash</button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php if (!empty($yemPager) && $yemPager->getPageCount() > 1): ?>
                <div class="pagination-wrapper">
                    <?= $yemPager->links('default', 'default_full') ?>
                </div>
                <?php endif; ?>

                <div id="tx-details-modal" class="tx-details-modal" aria-hidden="true">
                    <div class="tx-details-box">
                        <h4><i class="fas fa-info-circle"></i> Transaction details</h4>
                        <div class="body">
                            <dl class="tx-details-dl" id="tx-details-content"></dl>
                        </div>
                        <div class="footer">
                            <button type="button" class="btn btn-sm btn-copy" id="tx-details-copy-hash"><i class="fas fa-copy"></i> Copy hash</button>
                            <span class="copy-feedback" id="tx-details-copy-feedback" style="display:none;">Copied!</span>
                            <button type="button" class="btn btn-secondary btn-sm" id="tx-details-close">Close</button>
                        </div>
                    </div>
                </div>
            <?php else: ?>
                <p class="api-info">
                    <?php if (!empty($yem_filters_active)): ?>
                        No transactions match your current filters. Try adjusting filters or <a href="<?= site_url('admin/yem') ?>">clear them</a>.
                    <?php else: ?>
                        No transactions recorded yet. Create transactions via the API to see them here.
                    <?php endif; ?>
                </p>
            <?php endif; ?>
        </div>

        <div class="yem-section">
            <h3><i class="fas fa-book"></i> API</h3>
            <p>Create transactions, get transaction details, and more via the simplified YEMScan API. No client auth required.</p>
            <a href="<?= site_url('api/docs') ?>" class="btn btn-secondary"><i class="fas fa-external-link-alt"></i> API documentation</a>
        </div>
    <?php else: ?>
        <div class="not-configured">
            <strong><i class="fas fa-exclamation-triangle"></i> YEMScan not configured</strong>
            <p>Set <code>yemscan.api_key</code>, <code>yemscan.custom_domain</code>, and <code>yemscan.uid</code> in your .env to use YEM features. See <a href="<?= site_url('api/docs') ?>">API docs</a> or <code>YEMSCAN_DEVELOPER_GUIDE.md</code> for details.</p>
        </div>
    <?php endif; ?>

    <script>
        (function() {
            const btn = document.getElementById('btn-balances');
            const resultEl = document.getElementById('balances-result');
            if (!btn || !resultEl) return;

            btn.addEventListener('click', function() {
                const uids = document.getElementById('balance-uids').value.trim();
                const token = document.getElementById('balance-token').value.trim() || 'YEM';
                if (!uids) {
                    resultEl.innerHTML = '<div class="error-msg">Enter at least one UID.</div>';
                    return;
                }
                resultEl.innerHTML = '<div class="api-info">Loading…</div>';
                const url = '<?= site_url('api/yemscan/balances') ?>?uids=' + encodeURIComponent(uids) + '&tokenSymbol=' + encodeURIComponent(token);
                fetch(url, { method: 'GET', headers: { 'Accept': 'application/json' } })
                    .then(function(r) { return r.json(); })
                    .then(function(data) {
                        if (data.success && data.balances && Object.keys(data.balances).length) {
                            let html = '<table class="balances-table"><thead><tr><th>UID</th><th>Balance</th></tr></thead><tbody>';
                            for (const [uid, balance] of Object.entries(data.balances)) {
                                html += '<tr><td>' + escapeHtml(uid) + '</td><td class="amount">' + escapeHtml(balance) + '</td></tr>';
                            }
                            html += '</tbody></table>';
                            resultEl.innerHTML = html;
                        } else if (data.success && data.balances && Object.keys(data.balances).length === 0) {
                            resultEl.innerHTML = '<div class="api-info">No balances returned.</div>';
                        } else {
                            resultEl.innerHTML = '<div class="error-msg">' + escapeHtml(data.message || 'Request failed') + '</div>';
                        }
                    })
                    .catch(function() {
                        resultEl.innerHTML = '<div class="error-msg">Network error.</div>';
                    });
            });

            function escapeHtml(s) {
                const div = document.createElement('div');
                div.textContent = s;
                return div.innerHTML;
            }
        })();

        (function() {
            const modal = document.getElementById('tx-details-modal');
            const content = document.getElementById('tx-details-content');
            const copyFeedback = document.getElementById('tx-details-copy-feedback');
            const closeBtn = document.getElementById('tx-details-close');
            const modalCopyBtn = document.getElementById('tx-details-copy-hash');
            if (!modal || !content) return;

            function escapeHtml(s) {
                if (s == null) return '';
                const div = document.createElement('div');
                div.textContent = s;
                return div.innerHTML;
            }

            let currentModalHash = '';

            function showDetails(row) {
                currentModalHash = row.getAttribute('data-hash') || '';
                content.innerHTML =
                    '<dt>Hash</dt><dd>' + escapeHtml(row.getAttribute('data-hash') || '') + '</dd>' +
                    '<dt>From UID</dt><dd>' + escapeHtml(row.getAttribute('data-from-uid') || '—') + '</dd>' +
                    '<dt>To UID</dt><dd>' + escapeHtml(row.getAttribute('data-to-uid') || '—') + '</dd>' +
                    '<dt>Value</dt><dd>' + escapeHtml(row.getAttribute('data-value') || '—') + '</dd>' +
                    '<dt>Asset</dt><dd>' + escapeHtml(row.getAttribute('data-asset') || '—') + '</dd>' +
                    '<dt>Reason</dt><dd class="reason">' + escapeHtml(row.getAttribute('data-reason') || '—') + '</dd>' +
                    '<dt>From curr</dt><dd>' + escapeHtml(row.getAttribute('data-from-curr') || '—') + '</dd>' +
                    '<dt>To curr</dt><dd>' + escapeHtml(row.getAttribute('data-to-curr') || '—') + '</dd>' +
                    '<dt>Status</dt><dd>' + escapeHtml(row.getAttribute('data-status') || '—') + '</dd>' +
                    '<dt>Created</dt><dd>' + escapeHtml(row.getAttribute('data-created') || '—') + '</dd>' +
                    '<dt>Status updated</dt><dd>' + escapeHtml(row.getAttribute('data-status-updated') || '—') + '</dd>';
                modal.classList.add('show');
                modal.setAttribute('aria-hidden', 'false');
            }

            function hideModal() {
                modal.classList.remove('show');
                modal.setAttribute('aria-hidden', 'true');
            }

            function copyHash(hash, feedbackEl) {
                if (!hash) return;
                navigator.clipboard.writeText(hash).then(function() {
                    if (feedbackEl) {
                        feedbackEl.style.display = 'inline';
                        setTimeout(function() { feedbackEl.style.display = 'none'; }, 2000);
                    }
                });
            }

            document.addEventListener('click', function(e) {
                const row = e.target.closest('.tx-row');
                if (e.target.closest('.btn-view-details') && row) {
                    e.preventDefault();
                    showDetails(row);
                } else if (e.target.closest('.btn-copy-hash') && row) {
                    e.preventDefault();
                    copyHash(row.getAttribute('data-hash'));
                }
            });

            if (closeBtn) closeBtn.addEventListener('click', hideModal);
            modal.addEventListener('click', function(e) {
                if (e.target === modal) hideModal();
            });
            if (modalCopyBtn) modalCopyBtn.addEventListener('click', function() {
                copyHash(currentModalHash, copyFeedback);
            });
        })();
    </script>
<?= view('admin/partials/footer') ?>
</body>
</html>
