<?php
$pageTitle = 'آمار و تحلیل';

$stats = AdminDB::getStats();
$growthData = AdminDB::getUserGrowthData(30);
$cmdData = AdminDB::getCommandUsageData(30);
$hourlyData = AdminDB::getHourlyActivity();
$storageDist = AdminDB::getStorageDistribution();
$statusDist = AdminDB::getStatusDistribution();
$recentEvents = AdminDB::getRecentEvents(30);

// Active games count (wrapped in try/catch in case the game_sessions table
// doesn't exist yet on a partially-migrated install).
$__activeGamesCount = 0;
try {
    $__activeGamesCount = Database::getActiveGamesCount();
} catch (\Throwable $e) {}

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

<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" 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> آمار و تحلیل</h1>
    <span class="breadcrumb">خانه / آمار</span>
</div>

<div class="stats-grid">
    <div class="stat-card blue"><div class="stat-icon"><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></div><div class="stat-value"><?= number_format($stats['total_users']) ?></div><div class="stat-label">کل کاربران</div></div>
    <div class="stat-card green"><div class="stat-icon"><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="18" height="18" x="3" y="4" rx="2" ry="2"/><line x1="16" x2="16" y1="2" y2="6"/><line x1="8" x2="8" y1="2" y2="6"/><line x1="3" x2="21" y1="10" y2="10"/></svg></div><div class="stat-value"><?= number_format($stats['new_week']) ?></div><div class="stat-label">کاربران جدید (هفته)</div></div>
    <div class="stat-card pink"><div class="stat-icon"><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="18" height="18" x="3" y="4" rx="2" ry="2"/><line x1="16" x2="16" y1="2" y2="6"/><line x1="8" x2="8" y1="2" y2="6"/><line x1="3" x2="21" y1="10" y2="10"/></svg></div><div class="stat-value"><?= number_format($stats['new_month']) ?></div><div class="stat-label">کاربران جدید (ماه)</div></div>
    <div class="stat-card purple"><div class="stat-icon"><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></div><div class="stat-value"><?= number_format($__activeGamesCount) ?></div><div class="stat-label">بازی‌های در جریان</div></div>
    <div class="stat-card cyan"><div class="stat-icon"><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="22" x2="2" y1="12" y2="12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/><line x1="6" x2="6.01" y1="16" y2="16"/><line x1="10" x2="10.01" y1="16" y2="16"/></svg></div><div class="stat-value"><?= number_format($stats['total_storage']) ?></div><div class="stat-label">کل توکن بازی کاربران</div></div>
    <div class="stat-card orange"><div class="stat-icon"><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.5 4.27 9 5.15"/><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg></div><div class="stat-value"><?= number_format($stats['total_allocated_gb'] ?? 0) ?></div><div class="stat-label">حجم دریافتی (GB)</div></div>
    <div class="stat-card green"><div class="stat-icon"><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></div><div class="stat-value"><?= number_format($stats['total_subs']) ?></div><div class="stat-label">کل زیرمجموعه‌ها</div></div>
    <div class="stat-card red"><div class="stat-icon"><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></div><div class="stat-value"><?= number_format($stats['banned_users']) ?></div><div class="stat-label">مسدود شده</div></div>
    <div class="stat-card yellow"><div class="stat-icon"><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="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"/><path d="m9 12 2 2 4-4"/></svg></div><div class="stat-value"><?= number_format($stats['total_rate_limits']) ?></div><div class="stat-label">سابقه محدودیت</div></div>
    <div class="stat-card blue"><div class="stat-icon"><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></div><div class="stat-value"><?= number_format($stats['total_tickets'] ?? 0) ?></div><div class="stat-label">کل تیکت‌ها</div></div>
    <div class="stat-card green"><div class="stat-icon"><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></div><div class="stat-value"><?= number_format($stats['answered_tickets'] ?? 0) ?></div><div class="stat-label">تیکت‌های پاسخ‌داده‌شده</div></div>
    <div class="stat-card red"><div class="stat-icon"><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></div><div class="stat-value"><?= number_format($stats['open_tickets'] ?? 0) ?></div><div class="stat-label">تیکت‌های باز</div></div>
</div>

<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>
        <canvas id="growthChart"></canvas>
    </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>
        <canvas id="cmdChart"></canvas>
    </div>
</div>

<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;"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg> فعالیت ساعتی</div>
        <canvas id="hourlyChart"></canvas>
    </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;"><line x1="22" x2="2" y1="12" y2="12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/><line x1="6" x2="6.01" y1="16" y2="16"/><line x1="10" x2="10.01" y1="16" y2="16"/></svg> توزیع حجم کاربران</div>
        <canvas id="storageChart"></canvas>
    </div>
</div>

<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="M15 12h-5"/><path d="M15 8h-5"/><path d="M19 17V5a2 2 0 0 0-2-2H4"/><path d="M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3"/></svg> توزیع وضعیت کاربران</div>
        <canvas id="statusChart"></canvas>
    </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 class="table-container" style="max-height:300px;overflow-y:auto;">
            <table>
                <thead><tr><th>نوع</th><th>کاربر</th><th>زمان</th></tr></thead>
                <tbody>
                    <?php foreach ($recentEvents as $ev): ?>
                    <tr>
                        <td><span class="badge badge-admin"><?= e($ev['event_type']) ?></span></td>
                        <td><?= $ev['user_id'] ?? '-' ?></td>
                        <td style="font-size:12px;color:var(--text-muted);"><?= $ev['created_at'] ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // SECURITY: JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT escapes
    // angle brackets, ampersand and quotes so that user-controlled strings in
    // the JSON (e.g. event_type values that originate from Telegram
    // callback_data) cannot break out of this script block via a crafted
    // closing-script sequence. (NOTE: never write the literal closing tag in
    // a JS comment — the HTML parser ends the script block on it.)
    const growthData = <?= json_encode($growthData, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
    const cmdData = <?= json_encode($cmdData, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
    const hourlyData = <?= json_encode($hourlyData, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
    const storageDist = <?= json_encode($storageDist, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
    const statusDist = <?= json_encode($statusDist, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;

    new Chart(document.getElementById('growthChart'), {
        type: 'line',
        data: { labels: growthData.map(d => d.day), datasets: [{ label: 'کاربران', data: growthData.map(d => d.cnt), borderColor: '#4f8cff', backgroundColor: 'rgba(79,140,255,0.1)', fill: true, tension: 0.4 }] },
        options: { responsive: true, plugins: { legend: { display: false } }, scales: { x: { ticks: { color: '#64748b', maxTicksLimit: 10 } }, y: { ticks: { color: '#64748b' }, beginAtZero: true } } }
    });

    new Chart(document.getElementById('cmdChart'), {
        type: 'bar',
        data: { labels: cmdData.map(d => d.event_type), datasets: [{ label: 'تعداد', data: cmdData.map(d => d.cnt), backgroundColor: ['#4f8cff', '#a855f7', '#ec4899', '#22c55e', '#f97316', '#06b6d4'], borderRadius: 6 }] },
        options: { responsive: true, plugins: { legend: { display: false } }, scales: { x: { ticks: { color: '#64748b' } }, y: { ticks: { color: '#64748b' }, beginAtZero: true } } }
    });

    const hourMap = {};
    hourlyData.forEach(d => hourMap[d.hour] = d.cnt);
    const hourLabels = Array.from({length: 24}, (_, i) => i + ':00');

    new Chart(document.getElementById('hourlyChart'), {
        type: 'bar',
        data: { labels: hourLabels, datasets: [{ label: 'رویداد', data: hourLabels.map((_, i) => hourMap[i] || 0), backgroundColor: 'rgba(168,85,247,0.5)', borderRadius: 4 }] },
        options: { responsive: true, plugins: { legend: { display: false } }, scales: { x: { ticks: { color: '#64748b' } }, y: { ticks: { color: '#64748b' }, beginAtZero: true } } }
    });

    new Chart(document.getElementById('storageChart'), {
        type: 'doughnut',
        data: { labels: ['صفر', '۱-۳ GB', '۴-۱۰ GB', 'بیش از ۱۰'], datasets: [{ data: [storageDist.zero, storageDist.low, storageDist.medium, storageDist.high], backgroundColor: ['#64748b', '#4f8cff', '#a855f7', '#ec4899'] }] },
        options: { responsive: true, plugins: { legend: { position: 'bottom', labels: { color: '#94a3b8', font: { family: 'Vazirmatn' } } } } }
    });

    new Chart(document.getElementById('statusChart'), {
        type: 'pie',
        data: { labels: statusDist.map(d => d.status), datasets: [{ data: statusDist.map(d => d.cnt), backgroundColor: ['#4f8cff', '#22c55e', '#f97316', '#a855f7', '#ec4899', '#06b6d4'] }] },
        options: { responsive: true, plugins: { legend: { position: 'bottom', labels: { color: '#94a3b8', font: { family: 'Vazirmatn' } } } } }
    });
});
</script>

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