<?php
$pageTitle = 'داشبورد';

// v2: dashboard stat cards updated to reflect the 3-currency game/airdrop bot.
// Removed: total_servers, total_allocated_gb. The old `total_storage` (SUM of
// users.storage) is now repurposed as "total game tokens" since users.storage
// holds game tokens in v2. Added: total_toman, total_ntx, pending_withdrawals,
// pending_satisfactions, active_games. Inline SQL is used for the new metrics
// because AdminDB::getStats() predates the v2 tables (withdrawals,
// satisfactions, game_sessions, ntx_records) and would 500 if it tried to
// query them directly.
$stats = AdminDB::getStats();

// ── v2 currency / pending-state metrics ────────────────────────────────
// All wrapped in try/catch because the new tables may not exist yet on a
// partially-migrated install — fail open with 0 rather than 500 the page.
$__db = Database::getConnection();
$__adminId = (int)($GLOBALS['config']['referral']['admin_chat_id'] ?? 0);
$__excl = "AND `user_id` != {$__adminId}";

$__totalToman = 0;
$__totalNtx   = 0;
$__pendingWithdrawals = 0;
$__pendingSatisfactions = 0;
$__activeGames = 0;

try {
    $__totalToman = (int)$__db->query("SELECT COALESCE(SUM(`toman`), 0) FROM `users` WHERE 1=1 {$__excl}")->fetchColumn();
} catch (\Throwable $e) { /* column might not exist yet */ }

try {
    $__totalNtx = (int)$__db->query("SELECT COALESCE(SUM(`ntx_balance`), 0) FROM `users` WHERE 1=1 {$__excl}")->fetchColumn();
} catch (\Throwable $e) { /* column might not exist yet */ }

try {
    $__stmt = $__db->query("SELECT COUNT(*) FROM `withdrawals` WHERE `status` NOT IN ('closed','rejected','approved')");
    $__pendingWithdrawals = (int)$__stmt->fetchColumn();
} catch (\Throwable $e) { /* table might not exist yet */ }

try {
    $__stmt = $__db->query("SELECT COUNT(*) FROM `satisfactions` WHERE `status` = 'pending'");
    $__pendingSatisfactions = (int)$__stmt->fetchColumn();
} catch (\Throwable $e) { /* table might not exist yet */ }

try {
    $__activeGames = Database::getActiveGamesCount();
} catch (\Throwable $e) { $__activeGames = 0; }

// total game tokens = SUM(users.storage) — already computed by AdminDB::getStats
// as `total_storage`. Aliased here for clarity inside the card array.
$__totalGameTokens = (int)($stats['total_storage'] ?? 0);

require __DIR__ . '/layout_top.php';
?>

<?php if ($flash): ?>
    <div class="alert alert-<?= e($flash['type']) ?>"><?= e($flash['msg']) ?></div>
<?php endif; ?>

<div class="page-header">
    <h1><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="7" height="9" x="3" y="3" rx="1"/><rect width="7" height="5" x="14" y="3" rx="1"/><rect width="7" height="9" x="14" y="12" rx="1"/><rect width="7" height="5" x="3" y="16" rx="1"/></svg> داشبورد</h1>
    <span class="breadcrumb">خانه / داشبورد</span>
</div>

<!-- Stat cards grid -->
<div class="stats-grid">
    <?php
    $__cards = [
        // Users
        ['blue', '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>', $stats['total_users'], 'کل کاربران'],
        ['green', '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><path d="m9 11 3 3L22 4"/></svg>', $stats['active_users'], 'کاربران فعال (۷ روز)'],
        ['pink', '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><line x1="19" x2="19" y1="8" y2="14"/><line x1="22" x2="16" y1="11" y2="11"/></svg>', $stats['new_today'], 'ثبت‌نام امروز'],

        // Currencies (3 totals)
        ['cyan', '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"/><path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"/><path d="M4 22h16"/><path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"/><path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"/><path d="M18 2H6v7a6 6 0 0 0 12 0V2Z"/></svg>', $__totalGameTokens, 'کل توکن بازی'],
        ['orange', '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="12" x="2" y="6" rx="2"/><circle cx="12" cy="12" r="2"/><path d="M6 12h.01M18 12h.01"/></svg>', $__totalToman, 'کل تومان (نقدی)'],
        ['purple', '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8"/><path d="M12 18V6"/></svg>', $__totalNtx, 'کل NTX'],

        // Referrals / channels / bans
        ['green', '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>', $stats['total_subs'], 'کل زیرمجموعه‌ها'],
        ['red', '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="m4.93 4.93 14.14 14.14"/></svg>', $stats['banned_users'], 'کاربران مسدود'],
        ['yellow', '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m3 11 18-5v12L3 14v-3z"/><path d="M11.6 16.8a3 3 0 1 1-5.8-1.6"/></svg>', $stats['total_channels'], 'کانال‌های فعال'],

        // Pending state (v2 systems)
        ['red', '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 1 1 1v4a1 1 0 0 1-1 1H5a2 2 0 0 1-2-2V5"/></svg>', $__pendingWithdrawals, 'برداشت‌های در انتظار'],
        ['orange', '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 10v12"/><path d="M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2h0a3.13 3.13 0 0 1 3 3.88Z"/></svg>', $__pendingSatisfactions, 'رضایت‌های در انتظار'],
        ['cyan', '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="6" x2="10" y1="11" y2="11"/><line x1="8" x2="8" y1="9" y2="13"/><line x1="15" x2="15.01" y1="12" y2="12"/><line x1="18" x2="18.01" y1="10" y2="10"/><path d="M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.544-.604-6.584-.685-7.258A4 4 0 0 0 17.32 5z"/></svg>', $__activeGames, 'بازی‌های در جریان'],

        // Support tickets (existing — kept as-is)
        ['blue', '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="m4.93 4.93 4.24 4.24"/><path d="m14.83 9.17 4.24-4.24"/><path d="m14.83 14.83 4.24 4.24"/><path d="m9.17 14.83-4.24 4.24"/><circle cx="12" cy="12" r="4"/></svg>', $stats['total_tickets'] ?? 0, 'کل تیکت‌ها'],
        ['green', '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><path d="m9 11 3 3L22 4"/></svg>', $stats['answered_tickets'] ?? 0, 'تیکت‌های پاسخ‌داده‌شده'],
        ['red', '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>', $stats['open_tickets'] ?? 0, 'تیکت‌های باز'],
    ];
    foreach ($__cards as $__c):
        [$__color, $__icon, $__val, $__label] = $__c;
    ?>
    <div class="stat-card <?= $__color ?>">
        <div class="stat-icon"><?= $__icon ?></div>
        <div class="stat-value"><?= number_format((int)$__val) ?></div>
        <div class="stat-label"><?= e($__label) ?></div>
    </div>
    <?php endforeach; ?>
</div>

<!-- v2: currency distribution card — 3 big numbers side-by-side -->
<div class="glass-card" style="margin-top:24px;margin-bottom:24px;">
    <div class="card-title" style="margin-bottom:16px;display:flex;align-items:center;gap:8px;">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8"/><path d="M12 18V6"/></svg>
        توزیع ارزهای ربات
    </div>
    <div class="grid-3" style="gap:16px;">
        <div style="text-align:center;padding:20px;border-radius:12px;background:rgba(34,211,238,0.08);border:1px solid rgba(34,211,238,0.18);">
            <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px;">توکن بازی</div>
            <div style="font-size:28px;font-weight:700;color:#22d3ee;"><?= number_format($__totalGameTokens) ?></div>
        </div>
        <div style="text-align:center;padding:20px;border-radius:12px;background:rgba(251,146,60,0.08);border:1px solid rgba(251,146,60,0.18);">
            <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px;">تومان</div>
            <div style="font-size:28px;font-weight:700;color:#fb923c;"><?= number_format($__totalToman) ?></div>
        </div>
        <div style="text-align:center;padding:20px;border-radius:12px;background:rgba(167,139,250,0.08);border:1px solid rgba(167,139,250,0.18);">
            <div style="font-size:11px;color:var(--text-muted);margin-bottom:6px;">توکن NTX</div>
            <div style="font-size:28px;font-weight:700;color:#a78bfa;"><?= number_format($__totalNtx) ?></div>
        </div>
    </div>
</div>

<!-- Charts row 1 -->
<div class="chart-grid">
    <div class="chart-card">
        <div class="chart-title"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-3px;margin-left:6px;"><polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/></svg> رشد کاربران (۳۰ روز اخیر)</div>
        <div style="height:260px;"><canvas id="growthChart"></canvas></div>
    </div>
    <div class="chart-card">
        <div class="chart-title"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-3px;margin-left:6px;"><rect width="7" height="9" x="3" y="3" rx="1"/><rect width="7" height="5" x="14" y="3" rx="1"/><rect width="7" height="9" x="14" y="12" rx="1"/><rect width="7" height="5" x="3" y="16" rx="1"/></svg> توزیع وضعیت کاربران</div>
        <div style="height:220px;"><canvas id="statusChart"></canvas></div>
        <div id="statusLegend" style="margin-top:8px;display:flex;flex-wrap:wrap;justify-content:center;gap:12px;"></div>
    </div>
</div>

<!-- Charts row 2 -->
<div class="chart-grid">
    <div class="chart-card">
        <div class="chart-title"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-3px;margin-left:6px;"><path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"/><path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"/><path d="M4 22h16"/><path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"/><path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"/><path d="M18 2H6v7a6 6 0 0 0 12 0V2Z"/></svg> برترین زیرمجموعه‌گیران</div>
        <div class="nx-table-wrap" style="border-radius:14px;border:1px solid rgba(34,211,238,0.06);">
            <table>
                <thead>
                    <tr><th>رتبه</th><th>شناسه کاربر</th><th>تعداد زیرمجموعه</th></tr>
                </thead>
                <tbody>
                    <?php foreach (AdminDB::getTopReferrers(10) as $i => $r): ?>
                    <tr>
                        <td style="font-weight:700;color:#22d3ee;">#<?= $i + 1 ?></td>
                        <td style="font-weight:600;color:#e6f0ff;"><a href="?page=user_detail&id=<?= e($r['user_id']) ?>" style="color:#22d3ee;text-decoration:none;"><?= e($r['user_id']) ?></a></td>
                        <td style="color:#9fb0c9;"><?= e($r['sub_count']) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <div class="chart-card">
        <div class="chart-title"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-3px;margin-left:6px;"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg> فعالیت ساعتی (۲۴ ساعت اخیر)</div>
        <div style="height:260px;"><canvas id="hourlyChart"></canvas></div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // SECURITY: JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT prevents
    // a user-controlled status/event string from breaking out of <script>.
    var growthData = <?= json_encode(AdminDB::getUserGrowthData(30), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
    var statusData = <?= json_encode(AdminDB::getStatusDistribution(), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
    var hourlyData = <?= json_encode(AdminDB::getHourlyActivity(), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
    Chart.defaults.color = '#5a6b85';
    Chart.defaults.font.family = 'Vazirmatn';

    var tt = {
        backgroundColor: 'rgba(8,10,24,0.92)', borderColor: 'rgba(34,211,238,0.2)',
        borderWidth: 1, titleColor: '#e6f0ff', bodyColor: '#22d3ee',
        titleFont: { family: 'Vazirmatn', size: 12 }, bodyFont: { family: 'Vazirmatn', size: 12 },
        padding: 10, cornerRadius: 10, displayColors: false
    };

    new Chart(document.getElementById('growthChart'), {
        type: 'line',
        data: {
            labels: growthData.map(function(d) { return d.day.slice(5); }),
            datasets: [{
                label: 'کاربران جدید', data: growthData.map(function(d) { return d.cnt; }),
                borderColor: '#22d3ee', backgroundColor: 'rgba(34,211,238,0.15)',
                fill: true, tension: 0.4, pointRadius: 3, pointBackgroundColor: '#22d3ee', borderWidth: 2.5
            }]
        },
        options: { responsive: true, maintainAspectRatio: false,
            plugins: { legend: { display: false }, tooltip: tt },
            scales: {
                x: { ticks: { color: '#5a6b85', font: { size: 10 }, maxTicksLimit: 8 }, grid: { display: false } },
                y: { ticks: { color: '#5a6b85', font: { size: 10 } }, beginAtZero: true, grid: { color: 'rgba(34,211,238,0.05)' } }
            }
        }
    });

    var statusColors = ['#22d3ee', '#a78bfa', '#f472b6', '#2dd4bf', '#fb923c', '#fbbf24'];
    new Chart(document.getElementById('statusChart'), {
        type: 'doughnut',
        data: {
            labels: statusData.map(function(d) { return d.status; }),
            datasets: [{
                data: statusData.map(function(d) { return d.cnt; }),
                backgroundColor: statusColors, borderColor: 'rgba(5,6,15,0.6)', borderWidth: 2
            }]
        },
        options: { responsive: true, maintainAspectRatio: false,
            plugins: { legend: { display: false }, tooltip: tt }, cutout: '60%'
        }
    });
    var legend = document.getElementById('statusLegend');
    statusData.forEach(function(d, i) {
        var s = document.createElement('span');
        s.style.cssText = 'display:flex;align-items:center;gap:6px;font-size:11px;color:#9fb0c9;';
        s.innerHTML = '<span style="width:10px;height:10px;border-radius:50%;background:' + statusColors[i % statusColors.length] + ';"></span>' + d.status;
        legend.appendChild(s);
    });

    var hourLabels = []; for (var i = 0; i < 24; i++) hourLabels.push(i + ':00');
    var hourMap = {}; hourlyData.forEach(function(d) { hourMap[d.hour] = d.cnt; });
    new Chart(document.getElementById('hourlyChart'), {
        type: 'bar',
        data: {
            labels: hourLabels,
            datasets: [{
                label: 'رویدادها', data: hourLabels.map(function(_, i) { return hourMap[i] || 0; }),
                backgroundColor: 'rgba(167,139,250,0.6)', borderRadius: 4, borderSkipped: false
            }]
        },
        options: { responsive: true, maintainAspectRatio: false,
            plugins: { legend: { display: false }, tooltip: tt },
            scales: {
                x: { ticks: { color: '#5a6b85', font: { size: 9 }, maxTicksLimit: 12 }, grid: { display: false } },
                y: { ticks: { color: '#5a6b85', font: { size: 10 } }, beginAtZero: true, grid: { color: 'rgba(34,211,238,0.05)' } }
            }
        }
    });
});
</script>

<?php require __DIR__ . '/layout_bottom.php'; ?>
