<?php
require 'config.php';
$ip = $_SERVER['REMOTE_ADDR'];
$endpoint = 'page.stats'; // ganti nama sesuai file
if (!checkRateLimitApi($pdo, $ip, $endpoint, 120, 60)) {
    http_response_code(429);
    die('<div style="text-align:center;padding:50px;"><h1>429 Too Many Requests</h1><p>Terlalu banyak permintaan. Silakan coba lagi setelah 1 menit.</p></div>');
}

// Tracking untuk admin (tidak akan tersimpan, hanya update last_activity jika perlu)
$userId = $_SESSION['user_id'] ?? null;
$sessionId = session_id();
$ip = $_SERVER['REMOTE_ADDR'];
$currentUrl = $_SERVER['REQUEST_URI'];
trackPageView($pdo, $userId, $currentUrl, $sessionId, $ip);

// Hanya admin yang bisa melihat statistik
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    header('Location: index.php');
    exit;
}

// ==================== AMBIL DATA DARI TABEL TRACKING (PAGE_VIEWS & USER_SESSIONS) ====================
$today = date('Y-m-d');

// Visitor hari ini (unique session dari page_views)
$stmt = $pdo->prepare("
    SELECT COUNT(DISTINCT session_id) as total 
    FROM page_views 
    WHERE DATE(visited_at) = ?
");
$stmt->execute([$today]);
$visitorsToday = $stmt->fetchColumn();

// Page view hari ini
$stmt = $pdo->prepare("
    SELECT COUNT(*) as total 
    FROM page_views 
    WHERE DATE(visited_at) = ?
");
$stmt->execute([$today]);
$pageviewsToday = $stmt->fetchColumn();

// User online (5 menit terakhir) - dari user_sessions, join users untuk dapat username
$stmt = $pdo->prepare("
    SELECT us.*, u.username 
    FROM user_sessions us
    LEFT JOIN users u ON us.user_id = u.id
    WHERE us.last_activity > DATE_SUB(NOW(), INTERVAL 5 MINUTE)
    ORDER BY us.last_activity DESC
");
$stmt->execute();
$usersOnline = $stmt->fetchAll();
$onlineCount = count($usersOnline);

// Page view per jam (hari ini)
$stmt = $pdo->prepare("
    SELECT HOUR(visited_at) as hour, COUNT(*) as views 
    FROM page_views 
    WHERE DATE(visited_at) = ? 
    GROUP BY hour 
    ORDER BY hour
");
$stmt->execute([$today]);
$hourlyViews = $stmt->fetchAll();

// Visitor per jam (unique session) hari ini
$stmt = $pdo->prepare("
    SELECT HOUR(visited_at) as hour, COUNT(DISTINCT session_id) as visitors 
    FROM page_views 
    WHERE DATE(visited_at) = ? 
    GROUP BY hour 
    ORDER BY hour
");
$stmt->execute([$today]);
$hourlyVisitors = $stmt->fetchAll();

// Statistik per hari (7 hari terakhir)
$stmt = $pdo->prepare("
    SELECT 
        DATE(visited_at) as date,
        COUNT(*) as views
    FROM page_views
    WHERE visited_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
    GROUP BY DATE(visited_at)
    ORDER BY date ASC
");
$stmt->execute();
$dailyViews = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

$stmt = $pdo->prepare("
    SELECT 
        DATE(visited_at) as date,
        COUNT(DISTINCT session_id) as visitors
    FROM page_views
    WHERE visited_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
    GROUP BY DATE(visited_at)
    ORDER BY date ASC
");
$stmt->execute();
$dailyVisitors = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

$last7Days = [];
for ($i = 6; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-$i days"));
    $last7Days[] = $date;
}
$dailyViewsData = [];
$dailyVisitorsData = [];
foreach ($last7Days as $date) {
    $dailyViewsData[] = isset($dailyViews[$date]) ? $dailyViews[$date] : 0;
    $dailyVisitorsData[] = isset($dailyVisitors[$date]) ? $dailyVisitors[$date] : 0;
}

// Statistik per bulan (6 bulan terakhir)
$stmt = $pdo->prepare("
    SELECT 
        DATE_FORMAT(visited_at, '%Y-%m') as month,
        COUNT(*) as views
    FROM page_views
    WHERE visited_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
    GROUP BY month
    ORDER BY month ASC
");
$stmt->execute();
$monthlyViews = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

$stmt = $pdo->prepare("
    SELECT 
        DATE_FORMAT(visited_at, '%Y-%m') as month,
        COUNT(DISTINCT session_id) as visitors
    FROM page_views
    WHERE visited_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
    GROUP BY month
    ORDER BY month ASC
");
$stmt->execute();
$monthlyVisitors = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

$last6Months = [];
for ($i = 5; $i >= 0; $i--) {
    $month = date('Y-m', strtotime("-$i months"));
    $last6Months[] = $month;
}
$monthlyViewsData = [];
$monthlyVisitorsData = [];
foreach ($last6Months as $month) {
    $monthlyViewsData[] = isset($monthlyViews[$month]) ? $monthlyViews[$month] : 0;
    $monthlyVisitorsData[] = isset($monthlyVisitors[$month]) ? $monthlyVisitors[$month] : 0;
}

// Top 10 halaman terpopuler hari ini
$stmt = $pdo->prepare("
    SELECT page_url, COUNT(*) as hits 
    FROM page_views 
    WHERE DATE(visited_at) = ? 
    GROUP BY page_url 
    ORDER BY hits DESC 
    LIMIT 10
");
$stmt->execute([$today]);
$topPages = $stmt->fetchAll();

// Total page view keseluruhan
$totalPageviews = $pdo->query("SELECT COUNT(*) FROM page_views")->fetchColumn();

// Total visitor keseluruhan (unique session)
$totalVisitors = $pdo->query("SELECT COUNT(DISTINCT session_id) FROM page_views")->fetchColumn();

// 10 user terakhir yang mendaftar
$stmt = $pdo->query("SELECT id, username, created_at, tickets, points FROM users ORDER BY created_at DESC LIMIT 10");
$recentUsers = $stmt->fetchAll();

// ==================== STATISTIK TAMBAHAN ====================
// Total kode tiket yang sudah diklaim (berhasil)
$stmt = $pdo->query("SELECT COUNT(*) as total FROM ticket_code_redemptions");
$totalTicketRedemptions = $stmt->fetchColumn();

// Total prediksi yang sudah dibuat (grup + knockout)
$stmt = $pdo->query("SELECT COUNT(*) as total FROM predictions");
$totalGroupPredictions = $stmt->fetchColumn();
$stmt = $pdo->query("SELECT COUNT(*) as total FROM knockout_predictions");
$totalKnockoutPredictions = $stmt->fetchColumn();
$totalPredictions = $totalGroupPredictions + $totalKnockoutPredictions;

// Total poin yang sudah ditukarkan (approved)
$stmt = $pdo->query("SELECT COALESCE(SUM(points_spent), 0) as total FROM point_redeems WHERE status = 'approved'");
$totalPointsRedeemed = $stmt->fetchColumn();

// ==================== STATISTIK BARU ====================
// User baru per hari (7 hari terakhir)
$stmt = $pdo->prepare("
    SELECT DATE(created_at) as date, COUNT(*) as total
    FROM users
    WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
    GROUP BY DATE(created_at)
");
$stmt->execute();
$newUsersPerDay = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

// Prediksi grup per hari (7 hari terakhir)
$stmt = $pdo->prepare("
    SELECT DATE(created_at) as date, COUNT(*) as total
    FROM predictions
    WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
    GROUP BY DATE(created_at)
");
$stmt->execute();
$groupPredictionsPerDay = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

// Prediksi knockout per hari (7 hari terakhir)
$stmt = $pdo->prepare("
    SELECT DATE(created_at) as date, COUNT(*) as total
    FROM knockout_predictions
    WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
    GROUP BY DATE(created_at)
");
$stmt->execute();
$knockoutPredictionsPerDay = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

// Claim kode tiket per hari (bukan daily claim gratis)
$stmt = $pdo->prepare("
    SELECT DATE(redeemed_at) as date, COUNT(*) as total
    FROM ticket_code_redemptions
    WHERE redeemed_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
    GROUP BY DATE(redeemed_at)
");
$stmt->execute();
$ticketCodeClaimsPerDay = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

// Siapkan array untuk 7 hari terakhir
$newUsersData = [];
$groupPredData = [];
$koPredData = [];
$ticketClaimsData = [];
foreach ($last7Days as $date) {
    $newUsersData[] = isset($newUsersPerDay[$date]) ? $newUsersPerDay[$date] : 0;
    $groupPredData[] = isset($groupPredictionsPerDay[$date]) ? $groupPredictionsPerDay[$date] : 0;
    $koPredData[] = isset($knockoutPredictionsPerDay[$date]) ? $knockoutPredictionsPerDay[$date] : 0;
    $ticketClaimsData[] = isset($ticketCodeClaimsPerDay[$date]) ? $ticketCodeClaimsPerDay[$date] : 0;
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes">
    <title>Statistik Pengunjung - FIFA World Cup 2026</title>
    <meta name="csrf-token" content="<?php echo $_SESSION['csrf_token']; ?>">
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap"
        rel="stylesheet">
    <style>
        body {
            background: #030610;
            font-family: 'Inter', sans-serif;
        }

        .glass-card {
            background: rgba(255, 255, 255, 0.02);
            backdrop-filter: blur(12px);
            border: 1px solid rgba(255, 255, 255, 0.05);
            border-radius: 2rem;
            transition: all 0.3s;
        }

        .glass-card:hover {
            background: rgba(255, 255, 255, 0.04);
            border-color: rgba(255, 255, 255, 0.1);
        }

        .stat-number {
            font-size: 2.5rem;
            font-weight: 800;
            background: linear-gradient(135deg, #f59e0b, #ffcc00);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th,
        td {
            padding: 12px 8px;
            text-align: left;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        th {
            color: #f59e0b;
            font-size: 0.7rem;
            text-transform: uppercase;
            letter-spacing: 0.1em;
        }

        .online-dot {
            width: 8px;
            height: 8px;
            background-color: #22c55e;
            border-radius: 50%;
            display: inline-block;
            margin-right: 8px;
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0% {
                opacity: 0.4;
                transform: scale(0.8);
            }

            70% {
                opacity: 1;
                transform: scale(1.2);
            }

            100% {
                opacity: 0.4;
                transform: scale(0.8);
            }
        }

        .refresh-btn {
            transition: all 0.2s;
        }

        .refresh-btn:hover {
            transform: rotate(180deg);
        }
    </style>
</head>

<body class="min-h-screen text-white">

    <nav class="sticky top-0 z-50 px-4 pt-4">
        <div class="max-w-7xl mx-auto glass-card rounded-[40px] px-5 sm:px-10 h-20 flex items-center justify-between">
            <div class="flex items-center gap-2 cursor-pointer" onclick="window.location.href='index.php'">
                <img src="fifa-world-cup-2026-logo-white.png" alt="Logo" class="h-10 w-auto">
                <span class="text-xs font-black text-white tracking-wider">WORLD CUP 2026</span>
            </div>
            <div class="flex items-center gap-4">
                <a href="admin_panel.php"
                    class="bg-white/10 px-4 py-2 rounded-full text-xs font-black hover:bg-white/20 transition">Admin
                    Panel</a>
                <a href="auth.php?action=logout"
                    class="bg-red-500/20 px-4 py-2 rounded-full text-xs font-black hover:bg-red-500/40">Logout</a>
            </div>
        </div>
    </nav>

    <main class="max-w-7xl mx-auto px-4 py-8">
        <div class="text-center mb-8">
            <h1 class="text-4xl md:text-6xl font-black uppercase tracking-tighter">Statistik <span
                    class="text-amber-500">Pengunjung & Aktivitas</span></h1>
            <p class="text-slate-400 text-sm mt-2">Pantau aktivitas user (non-admin) di website</p>
            <button onclick="window.location.reload()"
                class="mt-4 inline-flex items-center gap-2 bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 px-4 py-2 rounded-full text-xs font-black transition-all refresh-btn">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
                Refresh Data
            </button>
        </div>

        <!-- Ringkasan Cards Utama -->
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <div class="glass-card p-6 rounded-3xl text-center">
                <div class="text-slate-400 text-xs font-black uppercase tracking-wider mb-2">Visitor Hari Ini</div>
                <div class="stat-number text-5xl">
                    <?php echo number_format($visitorsToday); ?>
                </div>
                <div class="text-slate-500 text-[10px] mt-2">Unique session</div>
            </div>
            <div class="glass-card p-6 rounded-3xl text-center">
                <div class="text-slate-400 text-xs font-black uppercase tracking-wider mb-2">Page View Hari Ini</div>
                <div class="stat-number text-5xl">
                    <?php echo number_format($pageviewsToday); ?>
                </div>
                <div class="text-slate-500 text-[10px] mt-2">Total hits</div>
            </div>
            <div class="glass-card p-6 rounded-3xl text-center">
                <div class="text-slate-400 text-xs font-black uppercase tracking-wider mb-2">User Online</div>
                <div class="stat-number text-5xl">
                    <?php echo $onlineCount; ?>
                </div>
                <div class="text-slate-500 text-[10px] mt-2">Aktif 5 menit terakhir</div>
            </div>
            <div class="glass-card p-6 rounded-3xl text-center">
                <div class="text-slate-400 text-xs font-black uppercase tracking-wider mb-2">Total Page View</div>
                <div class="stat-number text-5xl">
                    <?php echo number_format($totalPageviews); ?>
                </div>
                <div class="text-slate-500 text-[10px] mt-2">Sejak tracker aktif</div>
            </div>
        </div>

        <!-- Cards Statistik Tambahan (Kode Tiket, Prediksi, Poin Ditukar) -->
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-6 mb-8">
            <div class="glass-card p-5 rounded-3xl text-center border border-amber-500/20">
                <div class="text-amber-400 text-sm font-black uppercase tracking-wider mb-1">🎫 Kode Tiket Diklaim</div>
                <div class="text-4xl font-black text-white">
                    <?php echo number_format($totalTicketRedemptions); ?>
                </div>
                <div class="text-slate-500 text-[10px] mt-2">Total berhasil redeem</div>
            </div>
            <div class="glass-card p-5 rounded-3xl text-center border border-amber-500/20">
                <div class="text-amber-400 text-sm font-black uppercase tracking-wider mb-1">📝 Prediksi Dibuat</div>
                <div class="text-4xl font-black text-white">
                    <?php echo number_format($totalPredictions); ?>
                </div>
                <div class="text-slate-500 text-[10px] mt-2">Grup:
                    <?php echo number_format($totalGroupPredictions); ?> | Knockout:
                    <?php echo number_format($totalKnockoutPredictions); ?>
                </div>
            </div>
            <div class="glass-card p-5 rounded-3xl text-center border border-amber-500/20">
                <div class="text-amber-400 text-sm font-black uppercase tracking-wider mb-1">💰 Poin Ditukarkan</div>
                <div class="text-4xl font-black text-white">
                    <?php echo number_format($totalPointsRedeemed); ?>
                </div>
                <div class="text-slate-500 text-[10px] mt-2">Total poin sudah di-redeem</div>
            </div>
        </div>

        <!-- Grafik Per Jam -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
            <div class="glass-card p-6 rounded-3xl">
                <h3 class="text-lg font-black text-white uppercase tracking-tight mb-4 flex items-center gap-2">
                    <svg class="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                    </svg>
                    Page View per Jam (Hari Ini)
                </h3>
                <canvas id="hourlyChart" width="400" height="200" style="max-height: 250px;"></canvas>
            </div>
            <div class="glass-card p-6 rounded-3xl">
                <h3 class="text-lg font-black text-white uppercase tracking-tight mb-4 flex items-center gap-2">
                    <svg class="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
                    </svg>
                    Visitor Unique per Jam (Hari Ini)
                </h3>
                <canvas id="visitorChart" width="400" height="200" style="max-height: 250px;"></canvas>
            </div>
        </div>

        <!-- Grafik 7 Hari & 6 Bulan -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
            <div class="glass-card p-6 rounded-3xl">
                <h3 class="text-lg font-black text-white uppercase tracking-tight mb-4 flex items-center gap-2">
                    <svg class="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                    </svg>
                    Page View per Hari (7 Hari Terakhir)
                </h3>
                <canvas id="dailyChart" width="400" height="200" style="max-height: 250px;"></canvas>
            </div>
            <div class="glass-card p-6 rounded-3xl">
                <h3 class="text-lg font-black text-white uppercase tracking-tight mb-4 flex items-center gap-2">
                    <svg class="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
                    </svg>
                    Visitor per Hari (7 Hari Terakhir)
                </h3>
                <canvas id="dailyVisitorChart" width="400" height="200" style="max-height: 250px;"></canvas>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
            <div class="glass-card p-6 rounded-3xl">
                <h3 class="text-lg font-black text-white uppercase tracking-tight mb-4 flex items-center gap-2">
                    <svg class="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                    </svg>
                    Page View per Bulan (6 Bulan Terakhir)
                </h3>
                <canvas id="monthlyChart" width="400" height="200" style="max-height: 250px;"></canvas>
            </div>
            <div class="glass-card p-6 rounded-3xl">
                <h3 class="text-lg font-black text-white uppercase tracking-tight mb-4 flex items-center gap-2">
                    <svg class="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z" />
                    </svg>
                    Visitor per Bulan (6 Bulan Terakhir)
                </h3>
                <canvas id="monthlyVisitorChart" width="400" height="200" style="max-height: 250px;"></canvas>
            </div>
        </div>

        <!-- Grafik User Baru & Prediksi per Hari (7 Hari Terakhir) -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
            <div class="glass-card p-6 rounded-3xl">
                <h3 class="text-lg font-black text-white uppercase tracking-tight mb-4 flex items-center gap-2">
                    <svg class="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z" />
                    </svg>
                    User Baru & Prediksi per Hari (7 Hari Terakhir)
                </h3>
                <canvas id="newUsersPredictionsChart" width="400" height="200" style="max-height: 250px;"></canvas>
            </div>
            <div class="glass-card p-6 rounded-3xl">
                <h3 class="text-lg font-black text-white uppercase tracking-tight mb-4 flex items-center gap-2">
                    <svg class="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    Claim Kode Tiket per Hari (7 Hari Terakhir)
                </h3>
                <canvas id="ticketClaimsChart" width="400" height="200" style="max-height: 250px;"></canvas>
            </div>
        </div>

        <!-- Tabel 10 User Terakhir Daftar -->
        <div class="glass-card p-6 rounded-3xl mb-8">
            <h3 class="text-lg font-black text-white uppercase tracking-tight mb-4 flex items-center gap-2">
                <svg class="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z" />
                </svg>
                10 User Terakhir Mendaftar
            </h3>
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr>
                            <th class="px-2 py-2">Username</th>
                            <th class="px-2 py-2">Tiket</th>
                            <th class="px-2 py-2">Poin</th>
                            <th class="px-2 py-2">Tanggal Daftar (WIB)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($recentUsers as $user): ?>
                            <tr class="border-b border-white/5">
                                <td class="px-2 py-2 font-medium">
                                    <?php echo htmlspecialchars($user['username']); ?>
                                </td>
                                <td class="px-2 py-2 text-center">
                                    <?php echo $user['tickets']; ?>
                                </td>
                                <td class="px-2 py-2 text-center">
                                    <?php echo $user['points']; ?>
                                </td>
                                <td class="px-2 py-2 text-xs">
                                    <?php echo utcToWib($user['created_at']); ?> WIB
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Top 10 Halaman Terpopuler -->
        <div class="glass-card p-6 rounded-3xl mb-8">
            <h3 class="text-lg font-black text-white uppercase tracking-tight mb-4 flex items-center gap-2">
                <svg class="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" />
                </svg>
                Halaman Terpopuler Hari Ini
            </h3>
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Halaman</th>
                            <th class="text-center">Dilihat</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($topPages) > 0):
                            $rank = 1;
                            foreach ($topPages as $page): ?>
                                <tr class="border-b border-white/5">
                                    <td class="px-2 py-2 font-mono font-bold">
                                        <?php echo $rank++; ?>
                                    </td>
                                    <td class="px-2 py-2 break-all">
                                        <?php echo htmlspecialchars($page['page_url']); ?>
                                    </td>
                                    <td class="px-2 py-2 text-center font-mono">
                                        <?php echo number_format($page['hits']); ?>
                                    </td>
                                </tr>
                            <?php endforeach; else: ?>
                            <tr>
                                <td colspan="3" class="text-center py-4 text-slate-400">Belum ada data halaman hari ini.
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Tabel User Online -->
        <div class="glass-card p-6 rounded-3xl">
            <h3 class="text-lg font-black text-white uppercase tracking-tight mb-4 flex items-center gap-2">
                <span class="online-dot"></span> User Online (Aktif 5 Menit Terakhir)
            </h3>
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr>
                            <th>Username</th>
                            <th>IP Address</th>
                            <th>Halaman Terakhir</th>
                            <th>Aktivitas Terakhir (WIB)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($usersOnline) > 0):
                            foreach ($usersOnline as $user): ?>
                                <tr class="border-b border-white/5">
                                    <td class="px-2 py-2 font-medium">
                                        <?php echo $user['username'] ?? 'Guest'; ?>
                                    </td>
                                    <td class="px-2 py-2 font-mono text-xs">
                                        <?php echo htmlspecialchars($user['ip_address']); ?>
                                    </td>
                                    <td class="px-2 py-2 break-all">
                                        <?php echo htmlspecialchars($user['page_url'] ?? '-'); ?>
                                    </td>
                                    <td class="px-2 py-2 text-xs whitespace-nowrap">
                                        <?php echo utcToWib($user['last_activity']); ?> WIB
                                    </td>
                                </tr>
                            <?php endforeach; else: ?>
                            <tr>
                                <td colspan="4" class="text-center py-4 text-slate-400">Tidak ada user online saat ini.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="mt-8 text-center text-slate-500 text-[10px]">
            <p>* Statistik hanya mencatat aktivitas user non-admin (termasuk pengunjung tidak login).</p>
            <p>Data diperbarui setiap kali halaman dimuat. User online dihitung berdasarkan aktivitas dalam 5 menit
                terakhir.</p>
            <p>Semua waktu ditampilkan dalam WIB (Asia/Jakarta).</p>
        </div>
    </main>

    <footer
        class="border-t border-white/10 mt-12 py-8 text-center text-slate-500 text-[9px] font-black uppercase tracking-wider">
        <p>FIFA World Cup 2026 © All Rights Reserved.</p>
    </footer>

    <script>
        // Data dari PHP untuk grafik
        const hourlyData = <?php echo json_encode($hourlyViews); ?>;
        const hours = Array.from({ length: 24 }, (_, i) => i.toString().padStart(2, '0') + ':00');
        const views = hours.map(hour => { const found = hourlyData.find(item => item.hour == parseInt(hour)); return found ? found.views : 0; });
        const visitorData = <?php echo json_encode($hourlyVisitors); ?>;
        const visitors = hours.map(hour => { const found = visitorData.find(item => item.hour == parseInt(hour)); return found ? found.visitors : 0; });

        new Chart(document.getElementById('hourlyChart'), {
            type: 'bar', data: { labels: hours, datasets: [{ label: 'Page Views', data: views, backgroundColor: 'rgba(245,158,11,0.6)', borderColor: '#f59e0b', borderWidth: 1, borderRadius: 6 }] },
            options: { responsive: true, maintainAspectRatio: true, scales: { y: { beginAtZero: true, grid: { color: 'rgba(255,255,255,0.05)' }, ticks: { color: '#94a3b8' } }, x: { grid: { display: false }, ticks: { color: '#94a3b8', maxRotation: 45, minRotation: 45 } } }, plugins: { legend: { labels: { color: '#f59e0b' } }, tooltip: { backgroundColor: '#0f172a', titleColor: '#f59e0b', bodyColor: '#fff' } } }
        });
        new Chart(document.getElementById('visitorChart'), {
            type: 'line', data: { labels: hours, datasets: [{ label: 'Unique Visitors', data: visitors, backgroundColor: 'rgba(0,223,130,0.1)', borderColor: '#00df82', borderWidth: 2, fill: true, tension: 0.3, pointBackgroundColor: '#f59e0b', pointBorderColor: '#fff', pointRadius: 3 }] },
            options: { responsive: true, maintainAspectRatio: true, scales: { y: { beginAtZero: true, grid: { color: 'rgba(255,255,255,0.05)' }, ticks: { color: '#94a3b8', stepSize: 1 } }, x: { grid: { display: false }, ticks: { color: '#94a3b8', maxRotation: 45, minRotation: 45 } } }, plugins: { legend: { labels: { color: '#00df82' } }, tooltip: { backgroundColor: '#0f172a', titleColor: '#00df82', bodyColor: '#fff' } } }
        });

        const dailyLabels = <?php echo json_encode($last7Days); ?>;
        const dailyViewsData = <?php echo json_encode($dailyViewsData); ?>;
        const dailyVisitorsData = <?php echo json_encode($dailyVisitorsData); ?>;
        new Chart(document.getElementById('dailyChart'), {
            type: 'bar', data: { labels: dailyLabels, datasets: [{ label: 'Page Views', data: dailyViewsData, backgroundColor: 'rgba(245,158,11,0.6)', borderColor: '#f59e0b', borderWidth: 1 }] },
            options: { responsive: true, maintainAspectRatio: true, scales: { y: { beginAtZero: true, grid: { color: 'rgba(255,255,255,0.05)' }, ticks: { color: '#94a3b8' } }, x: { ticks: { color: '#94a3b8', maxRotation: 45, minRotation: 45 } } }, plugins: { legend: { labels: { color: '#f59e0b' } } } }
        });
        new Chart(document.getElementById('dailyVisitorChart'), {
            type: 'line', data: { labels: dailyLabels, datasets: [{ label: 'Unique Visitors', data: dailyVisitorsData, backgroundColor: 'rgba(0,223,130,0.1)', borderColor: '#00df82', borderWidth: 2, fill: true, tension: 0.3, pointBackgroundColor: '#f59e0b', pointBorderColor: '#fff' }] },
            options: { responsive: true, maintainAspectRatio: true, scales: { y: { beginAtZero: true, grid: { color: 'rgba(255,255,255,0.05)' }, ticks: { color: '#94a3b8', stepSize: 1 } }, x: { ticks: { color: '#94a3b8', maxRotation: 45, minRotation: 45 } } }, plugins: { legend: { labels: { color: '#00df82' } } } }
        });

        const monthlyLabels = <?php echo json_encode($last6Months); ?>;
        const monthlyViewsData = <?php echo json_encode($monthlyViewsData); ?>;
        const monthlyVisitorsData = <?php echo json_encode($monthlyVisitorsData); ?>;
        new Chart(document.getElementById('monthlyChart'), {
            type: 'bar', data: { labels: monthlyLabels, datasets: [{ label: 'Page Views', data: monthlyViewsData, backgroundColor: 'rgba(245,158,11,0.6)', borderColor: '#f59e0b', borderWidth: 1 }] },
            options: { responsive: true, maintainAspectRatio: true, scales: { y: { beginAtZero: true, grid: { color: 'rgba(255,255,255,0.05)' }, ticks: { color: '#94a3b8' } }, x: { ticks: { color: '#94a3b8', maxRotation: 45, minRotation: 45 } } }, plugins: { legend: { labels: { color: '#f59e0b' } } } }
        });
        new Chart(document.getElementById('monthlyVisitorChart'), {
            type: 'line', data: { labels: monthlyLabels, datasets: [{ label: 'Unique Visitors', data: monthlyVisitorsData, backgroundColor: 'rgba(0,223,130,0.1)', borderColor: '#00df82', borderWidth: 2, fill: true, tension: 0.3, pointBackgroundColor: '#f59e0b', pointBorderColor: '#fff' }] },
            options: { responsive: true, maintainAspectRatio: true, scales: { y: { beginAtZero: true, grid: { color: 'rgba(255,255,255,0.05)' }, ticks: { color: '#94a3b8', stepSize: 1 } }, x: { ticks: { color: '#94a3b8', maxRotation: 45, minRotation: 45 } } }, plugins: { legend: { labels: { color: '#00df82' } } } }
        });

        // Grafik User Baru & Prediksi per Hari
        const newUsersData = <?php echo json_encode($newUsersData); ?>;
        const groupPredData = <?php echo json_encode($groupPredData); ?>;
        const koPredData = <?php echo json_encode($koPredData); ?>;

        new Chart(document.getElementById('newUsersPredictionsChart'), {
            type: 'bar',
            data: {
                labels: dailyLabels,
                datasets: [
                    { label: 'User Baru', data: newUsersData, backgroundColor: 'rgba(0,223,130,0.6)', borderColor: '#00df82', borderWidth: 1 },
                    { label: 'Prediksi Grup', data: groupPredData, backgroundColor: 'rgba(245,158,11,0.6)', borderColor: '#f59e0b', borderWidth: 1 },
                    { label: 'Prediksi Knockout', data: koPredData, backgroundColor: 'rgba(239,68,68,0.6)', borderColor: '#ef4444', borderWidth: 1 }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                scales: {
                    y: { beginAtZero: true, grid: { color: 'rgba(255,255,255,0.05)' }, ticks: { color: '#94a3b8', stepSize: 1 } },
                    x: { ticks: { color: '#94a3b8', maxRotation: 45, minRotation: 45 } }
                },
                plugins: { legend: { labels: { color: '#ffffff' } }, tooltip: { backgroundColor: '#0f172a', titleColor: '#f59e0b', bodyColor: '#fff' } }
            }
        });

        // Grafik Claim Kode Tiket per Hari
        const ticketClaimsData = <?php echo json_encode($ticketClaimsData); ?>;
        new Chart(document.getElementById('ticketClaimsChart'), {
            type: 'bar',
            data: {
                labels: dailyLabels,
                datasets: [{ label: 'Claim Kode Tiket', data: ticketClaimsData, backgroundColor: 'rgba(59,130,246,0.6)', borderColor: '#3b82f6', borderWidth: 1 }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                scales: {
                    y: { beginAtZero: true, grid: { color: 'rgba(255,255,255,0.05)' }, ticks: { color: '#94a3b8', stepSize: 1 } },
                    x: { ticks: { color: '#94a3b8', maxRotation: 45, minRotation: 45 } }
                },
                plugins: { legend: { labels: { color: '#ffffff' } }, tooltip: { backgroundColor: '#0f172a', titleColor: '#3b82f6', bodyColor: '#fff' } }
            }
        });
    </script>
</body>

</html>