<?php
session_start();
require_once '../header.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sadakat Programı - BlackBet</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .loyalty-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 15px;
            color: white;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .level-progress {
            background: rgba(255,255,255,0.2);
            border-radius: 10px;
            height: 10px;
            overflow: hidden;
            margin: 1rem 0;
        }
        
        .level-progress-bar {
            background: linear-gradient(90deg, #00d4ff, #090979);
            height: 100%;
            border-radius: 10px;
            transition: width 0.3s ease;
        }
        
        .level-badge {
            display: inline-block;
            padding: 0.5rem 1rem;
            border-radius: 25px;
            font-weight: bold;
            margin: 0.25rem;
        }
        
        .level-bronze { background: linear-gradient(45deg, #cd7f32, #ffa500); }
        .level-silver { background: linear-gradient(45deg, #c0c0c0, #e5e5e5); }
        .level-gold { background: linear-gradient(45deg, #ffd700, #ffed4e); }
        .level-platinum { background: linear-gradient(45deg, #e5e4e2, #b8b8b8); }
        .level-diamond { background: linear-gradient(45deg, #b9f2ff, #00d4ff); }
        .level-vip { background: linear-gradient(45deg, #ff6b6b, #ee5a24); }
        
        .reward-card {
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
        }
        
        .reward-card:hover {
            border-color: #007bff;
            box-shadow: 0 4px 15px rgba(0,123,255,0.1);
        }
        
        .reward-card.claimable {
            border-color: #28a745;
            background: rgba(40,167,69,0.05);
        }
        
        .reward-card.claimed {
            border-color: #6c757d;
            background: rgba(108,117,125,0.05);
            opacity: 0.7;
        }
        
        .points-history-item {
            border-left: 4px solid #007bff;
            padding: 1rem;
            margin-bottom: 1rem;
            background: #f8f9fa;
            border-radius: 0 8px 8px 0;
        }
        
        .points-positive {
            border-left-color: #28a745;
        }
        
        .points-negative {
            border-left-color: #dc3545;
        }
        
        .leaderboard-item {
            display: flex;
            align-items: center;
            padding: 1rem;
            border-bottom: 1px solid #e9ecef;
        }
        
        .leaderboard-rank {
            font-size: 1.5rem;
            font-weight: bold;
            margin-right: 1rem;
            min-width: 50px;
        }
        
        .rank-1 { color: #ffd700; }
        .rank-2 { color: #c0c0c0; }
        .rank-3 { color: #cd7f32; }
        
        .stats-card {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            border-radius: 10px;
            padding: 1.5rem;
            text-align: center;
        }
        
        .nav-pills .nav-link.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-3">
                <?php include 'sidebar.php'; ?>
            </div>
            <div class="col-md-9">
                <div class="main-content p-4">
                    <h2><i class="fas fa-trophy"></i> Sadakat Programı</h2>
                    
                    <!-- Sadakat Kartı -->
                    <div class="loyalty-card" id="loyaltyCard">
                        <div class="row">
                            <div class="col-md-8">
                                <h3 id="currentLevel">Yükleniyor...</h3>
                                <p class="mb-2">Toplam Puanınız: <strong id="totalPoints">0</strong></p>
                                <p class="mb-2">Bu Ay Kazandığınız: <strong id="monthlyPoints">0</strong> puan</p>
                                <div class="level-progress">
                                    <div class="level-progress-bar" id="levelProgressBar" style="width: 0%"></div>
                                </div>
                                <p class="mb-0">Bir sonraki seviyeye: <strong id="pointsToNext">0</strong> puan</p>
                            </div>
                            <div class="col-md-4 text-end">
                                <div id="levelBadge" class="level-badge">
                                    <i class="fas fa-medal"></i> Seviye
                                </div>
                                <div class="mt-3">
                                    <small>Çarpan: <strong id="multiplier">1.0x</strong></small><br>
                                    <small>Cashback: <strong id="cashback">0%</strong></small>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Navigasyon -->
                    <ul class="nav nav-pills mb-4" id="loyaltyTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="overview-tab" data-bs-toggle="pill" data-bs-target="#overview" type="button" role="tab">
                                <i class="fas fa-chart-line"></i> Genel Bakış
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="rewards-tab" data-bs-toggle="pill" data-bs-target="#rewards" type="button" role="tab">
                                <i class="fas fa-gift"></i> Ödüller
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="history-tab" data-bs-toggle="pill" data-bs-target="#history" type="button" role="tab">
                                <i class="fas fa-history"></i> Puan Geçmişi
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="leaderboard-tab" data-bs-toggle="pill" data-bs-target="#leaderboard" type="button" role="tab">
                                <i class="fas fa-crown"></i> Lider Tablosu
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="levels-tab" data-bs-toggle="pill" data-bs-target="#levels" type="button" role="tab">
                                <i class="fas fa-layer-group"></i> Seviyeler
                            </button>
                        </li>
                    </ul>
                    
                    <!-- Tab İçerikleri -->
                    <div class="tab-content" id="loyaltyTabContent">
                        <!-- Genel Bakış -->
                        <div class="tab-pane fade show active" id="overview" role="tabpanel">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="stats-card">
                                        <h4 id="lifetimePoints">0</h4>
                                        <p class="mb-0">Toplam Kazanılan</p>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="stats-card">
                                        <h4 id="weeklyPoints">0</h4>
                                        <p class="mb-0">Bu Hafta</p>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="stats-card">
                                        <h4 id="rewardsClaimed">0</h4>
                                        <p class="mb-0">Alınan Ödül</p>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="stats-card">
                                        <h4 id="currentRank">-</h4>
                                        <p class="mb-0">Sıralama</p>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row mt-4">
                                <div class="col-md-6">
                                    <div class="card">
                                        <div class="card-header">
                                            <h5><i class="fas fa-star"></i> Puan Kazanma Yolları</h5>
                                        </div>
                                        <div class="card-body">
                                            <ul class="list-unstyled">
                                                <li><i class="fas fa-coins text-warning"></i> Para yatırma: Her 1₺ = 1 puan</li>
                                                <li><i class="fas fa-dice text-primary"></i> Bahis yapma: Her 1₺ = 1 puan</li>
                                                <li><i class="fas fa-calendar-day text-success"></i> Günlük giriş: 10 puan</li>
                                                <li><i class="fas fa-users text-info"></i> Arkadaş davet: 500 puan</li>
                                                <li><i class="fas fa-gamepad text-danger"></i> Oyun oynama: 5 puan</li>
                                                <li><i class="fas fa-trophy text-warning"></i> Turnuva katılımı: 50 puan</li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="card">
                                        <div class="card-header">
                                            <h5><i class="fas fa-chart-bar"></i> Bu Ay Aktiviteleriniz</h5>
                                        </div>
                                        <div class="card-body" id="monthlyActivities">
                                            <p class="text-muted">Yükleniyor...</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Ödüller -->
                        <div class="tab-pane fade" id="rewards" role="tabpanel">
                            <div class="row">
                                <div class="col-md-8">
                                    <h5><i class="fas fa-gift"></i> Mevcut Ödüller</h5>
                                    <div id="availableRewards">
                                        <div class="text-center py-4">
                                            <div class="spinner-border" role="status"></div>
                                            <p class="mt-2">Ödüller yükleniyor...</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <h5><i class="fas fa-history"></i> Ödül Geçmişi</h5>
                                    <div id="rewardHistory">
                                        <div class="text-center py-4">
                                            <div class="spinner-border spinner-border-sm" role="status"></div>
                                            <p class="mt-2">Yükleniyor...</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Puan Geçmişi -->
                        <div class="tab-pane fade" id="history" role="tabpanel">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h5><i class="fas fa-history"></i> Puan Geçmişi</h5>
                                <div>
                                    <button class="btn btn-sm btn-outline-primary" onclick="loadPointsHistory(1)">
                                        <i class="fas fa-sync-alt"></i> Yenile
                                    </button>
                                </div>
                            </div>
                            <div id="pointsHistory">
                                <div class="text-center py-4">
                                    <div class="spinner-border" role="status"></div>
                                    <p class="mt-2">Geçmiş yükleniyor...</p>
                                </div>
                            </div>
                            <div id="historyPagination" class="mt-3"></div>
                        </div>
                        
                        <!-- Lider Tablosu -->
                        <div class="tab-pane fade" id="leaderboard" role="tabpanel">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h5><i class="fas fa-crown"></i> Lider Tablosu</h5>
                                <div class="btn-group" role="group">
                                    <input type="radio" class="btn-check" name="leaderboardPeriod" id="allTime" value="all_time" checked>
                                    <label class="btn btn-outline-primary btn-sm" for="allTime">Tüm Zamanlar</label>
                                    
                                    <input type="radio" class="btn-check" name="leaderboardPeriod" id="monthly" value="monthly">
                                    <label class="btn btn-outline-primary btn-sm" for="monthly">Bu Ay</label>
                                    
                                    <input type="radio" class="btn-check" name="leaderboardPeriod" id="weekly" value="weekly">
                                    <label class="btn btn-outline-primary btn-sm" for="weekly">Bu Hafta</label>
                                </div>
                            </div>
                            <div id="leaderboardContent">
                                <div class="text-center py-4">
                                    <div class="spinner-border" role="status"></div>
                                    <p class="mt-2">Lider tablosu yükleniyor...</p>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Seviyeler -->
                        <div class="tab-pane fade" id="levels" role="tabpanel">
                            <h5><i class="fas fa-layer-group"></i> Sadakat Seviyeleri</h5>
                            <div id="loyaltyLevels">
                                <div class="text-center py-4">
                                    <div class="spinner-border" role="status"></div>
                                    <p class="mt-2">Seviyeler yükleniyor...</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        let currentPage = 1;
        
        // Sayfa yüklendiğinde
        document.addEventListener('DOMContentLoaded', function() {
            loadUserLoyalty();
            loadAvailableRewards();
            loadRewardHistory();
            loadPointsHistory(1);
            loadLeaderboard('all_time');
            loadLoyaltyLevels();
            loadLoyaltyStatistics();
            
            // Lider tablosu periyot değişikliği
            document.querySelectorAll('input[name="leaderboardPeriod"]').forEach(radio => {
                radio.addEventListener('change', function() {
                    loadLeaderboard(this.value);
                });
            });
        });
        
        // Kullanıcı sadakat bilgilerini yükle
        function loadUserLoyalty() {
            fetch('../api/loyalty_system.php?action=get_user_loyalty')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const loyalty = data.data;
                        
                        document.getElementById('currentLevel').textContent = loyalty.level_name || 'Bronz';
                        document.getElementById('totalPoints').textContent = loyalty.total_points || 0;
                        document.getElementById('monthlyPoints').textContent = loyalty.current_month_points || 0;
                        document.getElementById('pointsToNext').textContent = loyalty.points_to_next_level || 0;
                        document.getElementById('multiplier').textContent = (loyalty.multiplier || 1.0) + 'x';
                        document.getElementById('cashback').textContent = (loyalty.cashback_percentage || 0) + '%';
                        
                        // Seviye rozetini güncelle
                        const levelBadge = document.getElementById('levelBadge');
                        levelBadge.className = 'level-badge level-' + (loyalty.level_name || 'bronze').toLowerCase();
                        levelBadge.innerHTML = '<i class="fas fa-medal"></i> ' + (loyalty.level_name || 'Bronz');
                        
                        // İlerleme çubuğunu güncelle
                        const progressBar = document.getElementById('levelProgressBar');
                        progressBar.style.width = (loyalty.level_progress || 0) + '%';
                    }
                })
                .catch(error => console.error('Sadakat bilgileri yüklenirken hata:', error));
        }
        
        // Mevcut ödülleri yükle
        function loadAvailableRewards() {
            fetch('../api/loyalty_system.php?action=get_available_rewards')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const container = document.getElementById('availableRewards');
                        
                        if (data.data.length === 0) {
                            container.innerHTML = '<p class="text-muted">Henüz alabileceğiniz ödül bulunmuyor.</p>';
                            return;
                        }
                        
                        let html = '';
                        data.data.forEach(reward => {
                            const canClaim = reward.can_claim;
                            const cardClass = canClaim ? 'reward-card claimable' : 'reward-card';
                            
                            html += `
                                <div class="${cardClass}">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <h6>${reward.reward_name}</h6>
                                            <p class="text-muted mb-2">${reward.description}</p>
                                            <small class="text-info">
                                                ${reward.required_points ? reward.required_points + ' puan gerekli' : 'Puan gerektirmiyor'}
                                                ${reward.required_level ? ' | Seviye ' + reward.required_level + '+' : ''}
                                            </small>
                                        </div>
                                        <div class="text-end">
                                            <div class="badge bg-${getRewardTypeColor(reward.reward_type)} mb-2">
                                                ${getRewardTypeName(reward.reward_type)}
                                            </div>
                                            <br>
                                            ${canClaim ? 
                                                `<button class="btn btn-success btn-sm" onclick="claimReward(${reward.id})">
                                                    <i class="fas fa-gift"></i> Al
                                                </button>` :
                                                `<button class="btn btn-secondary btn-sm" disabled>
                                                    <i class="fas fa-lock"></i> Kilitli
                                                </button>`
                                            }
                                        </div>
                                    </div>
                                </div>
                            `;
                        });
                        
                        container.innerHTML = html;
                    }
                })
                .catch(error => console.error('Ödüller yüklenirken hata:', error));
        }
        
        // Ödül talep et
        function claimReward(rewardId) {
            Swal.fire({
                title: 'Ödülü almak istediğinizden emin misiniz?',
                text: 'Bu işlem geri alınamaz.',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Evet, Al',
                cancelButtonText: 'İptal'
            }).then((result) => {
                if (result.isConfirmed) {
                    const formData = new FormData();
                    formData.append('action', 'claim_reward');
                    formData.append('reward_id', rewardId);
                    
                    fetch('../api/loyalty_system.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire('Başarılı!', data.message, 'success');
                            loadUserLoyalty();
                            loadAvailableRewards();
                            loadRewardHistory();
                        } else {
                            Swal.fire('Hata!', data.message, 'error');
                        }
                    })
                    .catch(error => {
                        console.error('Ödül talep edilirken hata:', error);
                        Swal.fire('Hata!', 'Bir hata oluştu', 'error');
                    });
                }
            });
        }
        
        // Ödül geçmişini yükle
        function loadRewardHistory() {
            fetch('../api/loyalty_system.php?action=get_reward_claims')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const container = document.getElementById('rewardHistory');
                        
                        if (data.data.length === 0) {
                            container.innerHTML = '<p class="text-muted">Henüz ödül almamışsınız.</p>';
                            return;
                        }
                        
                        let html = '';
                        data.data.slice(0, 5).forEach(claim => {
                            const statusColor = getStatusColor(claim.status);
                            const statusText = getStatusText(claim.status);
                            
                            html += `
                                <div class="border-bottom pb-2 mb-2">
                                    <h6 class="mb-1">${claim.reward_name}</h6>
                                    <small class="text-muted">${formatDate(claim.created_at)}</small><br>
                                    <span class="badge bg-${statusColor}">${statusText}</span>
                                </div>
                            `;
                        });
                        
                        container.innerHTML = html;
                    }
                })
                .catch(error => console.error('Ödül geçmişi yüklenirken hata:', error));
        }
        
        // Puan geçmişini yükle
        function loadPointsHistory(page) {
            currentPage = page;
            
            fetch(`../api/loyalty_system.php?action=get_points_history&page=${page}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const container = document.getElementById('pointsHistory');
                        
                        if (data.data.length === 0) {
                            container.innerHTML = '<p class="text-muted">Henüz puan geçmişiniz bulunmuyor.</p>';
                            return;
                        }
                        
                        let html = '';
                        data.data.forEach(history => {
                            const isPositive = history.final_points > 0;
                            const pointsClass = isPositive ? 'points-positive' : 'points-negative';
                            const icon = isPositive ? 'fa-plus' : 'fa-minus';
                            const sign = isPositive ? '+' : '';
                            
                            html += `
                                <div class="points-history-item ${pointsClass}">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <h6 class="mb-1">
                                                <i class="fas ${icon} text-${isPositive ? 'success' : 'danger'}"></i>
                                                ${getActivityName(history.activity_type)}
                                            </h6>
                                            <p class="mb-1">${history.description || 'Açıklama yok'}</p>
                                            <small class="text-muted">${formatDate(history.created_at)}</small>
                                        </div>
                                        <div class="text-end">
                                            <h5 class="mb-0 text-${isPositive ? 'success' : 'danger'}">
                                                ${sign}${history.final_points}
                                            </h5>
                                            ${history.multiplier_applied > 1 ? 
                                                `<small class="text-info">${history.multiplier_applied}x çarpan</small>` : ''
                                            }
                                        </div>
                                    </div>
                                </div>
                            `;
                        });
                        
                        container.innerHTML = html;
                        
                        // Sayfalama
                        if (data.pagination && data.pagination.total_pages > 1) {
                            createPagination(data.pagination, 'historyPagination', loadPointsHistory);
                        }
                    }
                })
                .catch(error => console.error('Puan geçmişi yüklenirken hata:', error));
        }
        
        // Lider tablosunu yükle
        function loadLeaderboard(period) {
            fetch(`../api/loyalty_system.php?action=get_leaderboard&period=${period}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const container = document.getElementById('leaderboardContent');
                        
                        if (data.data.length === 0) {
                            container.innerHTML = '<p class="text-muted">Henüz lider tablosu verisi bulunmuyor.</p>';
                            return;
                        }
                        
                        let html = '<div class="card"><div class="card-body p-0">';
                        data.data.forEach((user, index) => {
                            const rankClass = index < 3 ? `rank-${index + 1}` : '';
                            const medal = index === 0 ? '🥇' : index === 1 ? '🥈' : index === 2 ? '🥉' : '';
                            
                            html += `
                                <div class="leaderboard-item">
                                    <div class="leaderboard-rank ${rankClass}">
                                        ${medal} ${user.rank_position}
                                    </div>
                                    <div class="flex-grow-1">
                                        <h6 class="mb-1">${user.kullanici_adi}</h6>
                                        <small class="text-muted">${user.level_name || 'Bronz'}</small>
                                    </div>
                                    <div class="text-end">
                                        <h6 class="mb-0">${user.total_points} puan</h6>
                                    </div>
                                </div>
                            `;
                        });
                        html += '</div></div>';
                        
                        container.innerHTML = html;
                    }
                })
                .catch(error => console.error('Lider tablosu yüklenirken hata:', error));
        }
        
        // Sadakat seviyelerini yükle
        function loadLoyaltyLevels() {
            fetch('../api/loyalty_system.php?action=get_loyalty_levels')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const container = document.getElementById('loyaltyLevels');
                        
                        let html = '';
                        data.data.forEach(level => {
                            const levelClass = 'level-' + level.level_name.toLowerCase();
                            
                            html += `
                                <div class="card mb-3">
                                    <div class="card-body">
                                        <div class="d-flex align-items-center mb-3">
                                            <div class="level-badge ${levelClass} me-3">
                                                <i class="fas fa-medal"></i> ${level.level_name}
                                            </div>
                                            <div>
                                                <h6 class="mb-0">Seviye ${level.level_number}</h6>
                                                <small class="text-muted">${level.required_points} puan gerekli</small>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <h6>Avantajlar:</h6>
                                                <ul class="list-unstyled">
                                                    <li><i class="fas fa-times text-success"></i> ${level.multiplier}x puan çarpanı</li>
                                                    <li><i class="fas fa-percent text-info"></i> %${level.cashback_percentage} cashback</li>
                                                    ${level.monthly_bonus > 0 ? 
                                                        `<li><i class="fas fa-gift text-warning"></i> Aylık ${level.monthly_bonus}₺ bonus</li>` : ''
                                                    }
                                                </ul>
                                            </div>
                                            <div class="col-md-6">
                                                <h6>Özel Haklar:</h6>
                                                <div id="benefits-${level.level_number}">
                                                    ${formatBenefits(level.benefits)}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            `;
                        });
                        
                        container.innerHTML = html;
                    }
                })
                .catch(error => console.error('Seviyeler yüklenirken hata:', error));
        }
        
        // İstatistikleri yükle
        function loadLoyaltyStatistics() {
            fetch('../api/loyalty_system.php?action=get_loyalty_statistics')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const stats = data.data;
                        
                        document.getElementById('lifetimePoints').textContent = stats.lifetime_points || 0;
                        document.getElementById('weeklyPoints').textContent = stats.weekly_points || 0;
                        
                        // Ödül sayısını al
                        fetch('../api/loyalty_system.php?action=get_reward_claims')
                            .then(response => response.json())
                            .then(rewardData => {
                                if (rewardData.success) {
                                    document.getElementById('rewardsClaimed').textContent = rewardData.data.length;
                                }
                            });
                    }
                })
                .catch(error => console.error('İstatistikler yüklenirken hata:', error));
        }
        
        // Yardımcı fonksiyonlar
        function getRewardTypeColor(type) {
            const colors = {
                'bonus': 'primary',
                'cashback': 'success',
                'free_spins': 'warning',
                'merchandise': 'info',
                'vip_access': 'danger'
            };
            return colors[type] || 'secondary';
        }
        
        function getRewardTypeName(type) {
            const names = {
                'bonus': 'Bonus',
                'cashback': 'Cashback',
                'free_spins': 'Bedava Spin',
                'merchandise': 'Hediye',
                'vip_access': 'VIP Erişim'
            };
            return names[type] || type;
        }
        
        function getStatusColor(status) {
            const colors = {
                'pending': 'warning',
                'approved': 'info',
                'delivered': 'success',
                'cancelled': 'danger'
            };
            return colors[status] || 'secondary';
        }
        
        function getStatusText(status) {
            const texts = {
                'pending': 'Beklemede',
                'approved': 'Onaylandı',
                'delivered': 'Teslim Edildi',
                'cancelled': 'İptal Edildi'
            };
            return texts[status] || status;
        }
        
        function getActivityName(type) {
            const names = {
                'deposit': 'Para Yatırma',
                'bet': 'Bahis Yapma',
                'login': 'Günlük Giriş',
                'referral': 'Arkadaş Davet',
                'kyc_complete': 'KYC Tamamlama',
                'first_deposit': 'İlk Para Yatırma',
                'game_play': 'Oyun Oynama',
                'tournament_join': 'Turnuva Katılımı',
                'social_share': 'Sosyal Medya Paylaşım',
                'feedback': 'Geri Bildirim',
                'admin_action': 'Admin İşlemi'
            };
            return names[type] || type;
        }
        
        function formatBenefits(benefits) {
            if (!benefits) return '<p class="text-muted">Özel hak bulunmuyor</p>';
            
            let html = '<ul class="list-unstyled">';
            Object.entries(benefits).forEach(([key, value]) => {
                if (typeof value === 'boolean' && value) {
                    html += `<li><i class="fas fa-check text-success"></i> ${formatBenefitKey(key)}</li>`;
                } else if (typeof value === 'string' || typeof value === 'number') {
                    html += `<li><i class="fas fa-star text-warning"></i> ${formatBenefitKey(key)}: ${value}</li>`;
                }
            });
            html += '</ul>';
            
            return html;
        }
        
        function formatBenefitKey(key) {
            const keys = {
                'welcome_bonus': 'Hoş geldin bonusu',
                'support_priority': 'Destek önceliği',
                'monthly_bonus': 'Aylık bonus',
                'faster_withdrawals': 'Hızlı çekim',
                'vip_support': 'VIP destek',
                'exclusive_bonuses': 'Özel bonuslar',
                'personal_manager': 'Kişisel müdür',
                'higher_limits': 'Yüksek limitler',
                'exclusive_events': 'Özel etkinlikler',
                'custom_bonuses': 'Özel bonuslar',
                'luxury_gifts': 'Lüks hediyeler',
                'unlimited_support': 'Sınırsız destek'
            };
            return keys[key] || key;
        }
        
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleDateString('tr-TR') + ' ' + date.toLocaleTimeString('tr-TR', {hour: '2-digit', minute: '2-digit'});
        }
        
        function createPagination(pagination, containerId, callback) {
            const container = document.getElementById(containerId);
            let html = '<nav><ul class="pagination justify-content-center">';
            
            // Önceki sayfa
            if (pagination.current_page > 1) {
                html += `<li class="page-item"><a class="page-link" href="#" onclick="${callback.name}(${pagination.current_page - 1})">Önceki</a></li>`;
            }
            
            // Sayfa numaraları
            for (let i = Math.max(1, pagination.current_page - 2); i <= Math.min(pagination.total_pages, pagination.current_page + 2); i++) {
                const active = i === pagination.current_page ? 'active' : '';
                html += `<li class="page-item ${active}"><a class="page-link" href="#" onclick="${callback.name}(${i})">${i}</a></li>`;
            }
            
            // Sonraki sayfa
            if (pagination.current_page < pagination.total_pages) {
                html += `<li class="page-item"><a class="page-link" href="#" onclick="${callback.name}(${pagination.current_page + 1})">Sonraki</a></li>`;
            }
            
            html += '</ul></nav>';
            container.innerHTML = html;
        }
    </script>
</body>
</html>