<?php
require_once 'includes/layout.php';
requireAdminLogin();

$payments = apiGet('/payments', ['limit'=>100])['payments'] ?? [];
$total    = count($payments);
$revenue  = array_sum(array_column(array_filter($payments, fn($p)=>$p['status']==='completed'),'amount'));
$completed= count(array_filter($payments, fn($p)=>$p['status']==='completed'));
$pending  = count(array_filter($payments, fn($p)=>$p['status']==='pending'));
$failed   = count(array_filter($payments, fn($p)=>$p['status']==='failed'));

ob_start();
?>
<div class="grid grid-4" style="margin-bottom:20px;">
    <div class="stat-card"><div class="stat-label">Total Revenue</div><div class="stat-value">K<?= number_format($revenue) ?></div><div class="stat-sub">Completed payments</div></div>
    <div class="stat-card"><div class="stat-label">Completed</div><div class="stat-value" style="color:var(--green);"><?= $completed ?></div></div>
    <div class="stat-card"><div class="stat-label">Pending</div><div class="stat-value" style="color:var(--orange);"><?= $pending ?></div></div>
    <div class="stat-card"><div class="stat-label">Failed</div><div class="stat-value" style="color:var(--red);"><?= $failed ?></div></div>
</div>

<div style="margin-bottom:16px;">
    <input type="text" placeholder="Search payments..." style="width:260px;" oninput="filterPayments(this.value)">
</div>

<div class="card">
    <div class="card-header">
        <span class="card-title">All Transactions (<?= $total ?>)</span>
        <a href="#" class="btn btn-surface" style="font-size:12px;padding:5px 10px;" onclick="exportCSV()">Export CSV</a>
    </div>
    <div class="table-wrap">
        <table id="paymentsTable">
            <thead><tr><th>Reference</th><th>User</th><th>Movie</th><th>Method</th><th>Amount</th><th>Status</th><th>Date</th></tr></thead>
            <tbody>
            <?php foreach ($payments as $p):
                $badge = match($p['status']??'') {
                    'completed' => 'badge-green',
                    'pending'   => 'badge-orange',
                    default     => 'badge-red',
                };
                $methodColor = match($p['method']??'') {
                    'airtel' => '#E8001C',
                    'tnm'    => '#00873E',
                    default  => '#1A1F71',
                };
            ?>
            <tr data-ref="<?= strtolower(htmlspecialchars($p['reference']??'')) ?>">
                <td style="font-family:monospace;font-size:11px;color:var(--text-muted);"><?= htmlspecialchars($p['reference']??'') ?></td>
                <td style="font-weight:600;font-size:13px;"><?= htmlspecialchars($p['user_name']??'—') ?></td>
                <td style="color:var(--text-sec);font-size:12px;"><?= htmlspecialchars($p['movie_title']??'—') ?></td>
                <td style="font-weight:600;font-size:12px;color:<?= $methodColor ?>;"><?= htmlspecialchars(strtoupper($p['method']??'')) ?></td>
                <td style="font-weight:700;color:var(--orange);">K<?= number_format((float)($p['amount']??0)) ?></td>
                <td><span class="badge <?= $badge ?>"><?= $p['status']??'—' ?></span></td>
                <td style="color:var(--text-muted);font-size:11px;"><?= isset($p['created_at']) ? date('d M Y H:i', strtotime($p['created_at'])) : '—' ?></td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($payments)): ?>
            <tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:30px;">No payments yet</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Method breakdown -->
<?php
$methods = ['airtel'=>['label'=>'Airtel Money','color'=>'#E8001C','total'=>0,'count'=>0],'tnm'=>['label'=>'TNM Mpamba','color'=>'#00873E','total'=>0,'count'=>0],'card'=>['label'=>'Card','color'=>'#1A1F71','total'=>0,'count'=>0]];
foreach ($payments as $p) {
    $m = $p['method']??'';
    if (isset($methods[$m]) && $p['status']==='completed') { $methods[$m]['total']+=$p['amount']; $methods[$m]['count']++; }
}
?>
<div class="grid grid-3" style="margin-top:16px;">
<?php foreach ($methods as $key => $m): ?>
<div class="card"><div class="card-body" style="display:flex;align-items:center;gap:14px;">
    <div style="width:44px;height:44px;border-radius:8px;background:<?= $m['color'] ?>;display:flex;align-items:center;justify-content:center;font-weight:900;color:#fff;font-size:13px;flex-shrink:0;"><?= strtoupper(substr($key,0,1)) ?></div>
    <div>
        <div style="font-size:13px;font-weight:600;"><?= $m['label'] ?></div>
        <div style="font-size:11px;color:var(--text-muted);"><?= $m['count'] ?> transactions</div>
        <div style="font-size:16px;font-weight:800;color:var(--orange);">K<?= number_format($m['total']) ?></div>
    </div>
</div></div>
<?php endforeach; ?>
</div>

<script>
function filterPayments(q) {
    q = q.toLowerCase();
    document.querySelectorAll('#paymentsTable tbody tr[data-ref]').forEach(r => {
        const text = r.textContent.toLowerCase();
        r.style.display = text.includes(q) ? '' : 'none';
    });
}
function exportCSV() { alert('In production: generate CSV from the Node.js API /payments?format=csv'); }
</script>
<?php
$content = ob_get_clean();
renderLayout('Payments', 'payments', $content);
