<?php
session_start();
include '../config.php';

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

$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'] ?? '';

// Kullanıcı bilgilerini al
try {
    $stmt = $pdo->prepare("SELECT * FROM kullanicilar WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        session_destroy();
        header("Location: ../giris.php");
        exit;
    }
} catch (PDOException $e) {
    die("Veritabanı hatası: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bonuslarım - 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>
        body {
            background: #000;
            color: #fff;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .centerWrap.porfileWrap,
        .container-fluid,
        .profileRow {
            background: #000 !important;
        }
        
        .bonus-card {
            background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
            border: 2px solid #FFD700;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 3px 12px rgba(255, 215, 0, 0.3);
            transition: all 0.3s ease;
        }
        
        .bonus-card:hover {
            border-color: #FFA500;
            box-shadow: 0 5px 20px rgba(255, 165, 0, 0.4);
            transform: translateY(-2px);
        }
        
        .bonus-title {
            color: #FFD700;
            font-size: 1.4rem;
            font-weight: bold;
            margin-bottom: 10px;
        }
        
        .bonus-amount {
            color: #00FF00;
            font-size: 2rem;
            font-weight: bold;
        }
        
        .bonus-description {
            color: #ccc;
            margin: 10px 0;
        }
        
        .bonus-status {
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 0.9rem;
            font-weight: bold;
        }
        
        .status-pending {
            background: #FFA500;
            color: #000;
        }
        
        .status-active {
            background: #00FF00;
            color: #000;
        }
        
        .status-used {
            background: #666;
            color: #fff;
        }
        
        .status-expired {
            background: #FF4444;
            color: #fff;
        }
        
        .btn-claim {
            background: linear-gradient(45deg, #FFD700, #FFA500);
            border: none;
            color: #000;
            font-weight: bold;
            padding: 10px 25px;
            border-radius: 25px;
            transition: all 0.3s ease;
        }
        
        .btn-claim:hover {
            background: linear-gradient(45deg, #FFA500, #FFD700);
            transform: scale(1.05);
            color: #000;
        }
        
        .behavior-stats {
            background: linear-gradient(135deg, #2d2d2d 0%, #1a1a1a 100%);
            border: 1px solid #444;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 30px;
        }
        
        .stat-item {
            text-align: center;
            padding: 15px;
        }
        
        .stat-value {
            font-size: 1.8rem;
            font-weight: bold;
            color: #FFD700;
        }
        
        .stat-label {
            color: #ccc;
            font-size: 0.9rem;
        }
        
        .activity-score {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background: conic-gradient(#FFD700 0deg, #FFD700 var(--score-deg), #333 var(--score-deg), #333 360deg);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 10px;
            position: relative;
        }
        
        .activity-score::before {
            content: '';
            width: 80px;
            height: 80px;
            background: #1a1a1a;
            border-radius: 50%;
            position: absolute;
        }
        
        .activity-score span {
            position: relative;
            z-index: 1;
            font-weight: bold;
            color: #FFD700;
        }
        
        .nav-tabs .nav-link {
            background: #2d2d2d;
            border: 1px solid #444;
            color: #ccc;
        }
        
        .nav-tabs .nav-link.active {
            background: #FFD700;
            border-color: #FFD700;
            color: #000;
        }
        
        .tab-content {
            background: #1a1a1a;
            border: 1px solid #444;
            border-top: none;
            padding: 20px;
        }
    </style>
</head>
<body>
    <div class="centerWrap porfileWrap">
        <div class="container-fluid">
            <div class="row profileRow">
                <?php include 'sidebar.php'; ?>
                
                <div class="col-md-9">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-gift me-2"></i>Bonuslarım</h2>
                        <button class="btn btn-outline-warning" onclick="updateBehavior()">
                            <i class="fas fa-sync-alt me-2"></i>Verileri Güncelle
                        </button>
                    </div>
                    
                    <!-- Kullanıcı Davranış İstatistikleri -->
                    <div class="behavior-stats" id="behaviorStats">
                        <h5 class="text-warning mb-3"><i class="fas fa-chart-line me-2"></i>Aktivite Durumunuz</h5>
                        <div class="row">
                            <div class="col-md-2 stat-item">
                                <div class="activity-score" id="activityScore">
                                    <span id="scoreValue">0</span>
                                </div>
                                <div class="stat-label">Aktivite Skoru</div>
                            </div>
                            <div class="col-md-2 stat-item">
                                <div class="stat-value" id="totalDeposits">0 ₺</div>
                                <div class="stat-label">Toplam Yatırım</div>
                            </div>
                            <div class="col-md-2 stat-item">
                                <div class="stat-value" id="totalBets">0 ₺</div>
                                <div class="stat-label">Toplam Bahis</div>
                            </div>
                            <div class="col-md-2 stat-item">
                                <div class="stat-value" id="totalWins">0 ₺</div>
                                <div class="stat-label">Toplam Kazanç</div>
                            </div>
                            <div class="col-md-2 stat-item">
                                <div class="stat-value" id="riskLevel">Düşük</div>
                                <div class="stat-label">Risk Seviyesi</div>
                            </div>
                            <div class="col-md-2 stat-item">
                                <div class="stat-value" id="sessionCount">0</div>
                                <div class="stat-label">Oturum Sayısı</div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Bonus Sekmeleri -->
                    <ul class="nav nav-tabs" id="bonusTab" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="available-tab" data-bs-toggle="tab" data-bs-target="#available" type="button" role="tab">
                                <i class="fas fa-gift me-2"></i>Mevcut Bonuslar
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="suggestions-tab" data-bs-toggle="tab" data-bs-target="#suggestions" type="button" role="tab">
                                <i class="fas fa-magic me-2"></i>Önerilen Bonuslar
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="history-tab" data-bs-toggle="tab" data-bs-target="#history" type="button" role="tab">
                                <i class="fas fa-history me-2"></i>Bonus Geçmişi
                            </button>
                        </li>
                    </ul>
                    
                    <div class="tab-content" id="bonusTabContent">
                        <!-- Mevcut Bonuslar -->
                        <div class="tab-pane fade show active" id="available" role="tabpanel">
                            <div id="availableBonuses">
                                <div class="text-center py-4">
                                    <i class="fas fa-spinner fa-spin fa-2x text-warning"></i>
                                    <p class="mt-2">Bonuslar yükleniyor...</p>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Önerilen Bonuslar -->
                        <div class="tab-pane fade" id="suggestions" role="tabpanel">
                            <div id="suggestedBonuses">
                                <div class="text-center py-4">
                                    <button class="btn btn-warning" onclick="calculatePersonalizedBonuses()">
                                        <i class="fas fa-calculator me-2"></i>Kişisel Bonus Önerilerini Hesapla
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Bonus Geçmişi -->
                        <div class="tab-pane fade" id="history" role="tabpanel">
                            <div id="bonusHistory">
                                <div class="text-center py-4">
                                    <i class="fas fa-spinner fa-spin fa-2x text-warning"></i>
                                    <p class="mt-2">Geçmiş 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>
        // Sayfa yüklendiğinde verileri getir
        document.addEventListener('DOMContentLoaded', function() {
            loadAvailableBonuses();
            loadBonusHistory();
            updateBehavior();
        });
        
        // Mevcut bonusları yükle
        function loadAvailableBonuses() {
            fetch('../api/bonus_system.php?action=get_available_bonuses')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayAvailableBonuses(data.bonuses);
                    } else {
                        document.getElementById('availableBonuses').innerHTML = 
                            '<div class="alert alert-warning">Bonus bulunamadı</div>';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('availableBonuses').innerHTML = 
                        '<div class="alert alert-danger">Bonuslar yüklenirken hata oluştu</div>';
                });
        }
        
        // Mevcut bonusları göster
        function displayAvailableBonuses(bonuses) {
            const container = document.getElementById('availableBonuses');
            
            if (bonuses.length === 0) {
                container.innerHTML = '<div class="alert alert-info">Şu anda mevcut bonus bulunmuyor</div>';
                return;
            }
            
            let html = '';
            bonuses.forEach(bonus => {
                const statusClass = `status-${bonus.status}`;
                const statusText = {
                    'pending': 'Bekliyor',
                    'active': 'Aktif',
                    'used': 'Kullanıldı',
                    'expired': 'Süresi Doldu'
                };
                
                html += `
                    <div class="bonus-card">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <div class="bonus-title">${bonus.title}</div>
                                <div class="bonus-amount">${bonus.amount} ₺</div>
                                <div class="bonus-description">${bonus.description || ''}</div>
                                ${bonus.valid_until ? `<small class="text-muted">Geçerlilik: ${new Date(bonus.valid_until).toLocaleDateString('tr-TR')}</small>` : ''}
                            </div>
                            <div class="text-end">
                                <span class="bonus-status ${statusClass}">${statusText[bonus.status]}</span>
                                ${bonus.status === 'pending' ? `
                                    <div class="mt-2">
                                        <button class="btn btn-claim" onclick="claimBonus(${bonus.id})">
                                            <i class="fas fa-hand-holding-usd me-2"></i>Al
                                        </button>
                                    </div>
                                ` : ''}
                            </div>
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }
        
        // Bonus al
        function claimBonus(bonusId) {
            Swal.fire({
                title: 'Bonus Al',
                text: 'Bu bonusu almak istediğinizden emin misiniz?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Evet, Al',
                cancelButtonText: 'İptal',
                confirmButtonColor: '#FFD700',
                cancelButtonColor: '#666'
            }).then((result) => {
                if (result.isConfirmed) {
                    const formData = new FormData();
                    formData.append('bonus_id', bonusId);
                    
                    fetch('../api/bonus_system.php?action=claim_bonus', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire({
                                title: 'Başarılı!',
                                text: data.message,
                                icon: 'success',
                                confirmButtonColor: '#FFD700'
                            }).then(() => {
                                loadAvailableBonuses();
                                loadBonusHistory();
                            });
                        } else {
                            Swal.fire({
                                title: 'Hata!',
                                text: data.message,
                                icon: 'error',
                                confirmButtonColor: '#FFD700'
                            });
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        Swal.fire({
                            title: 'Hata!',
                            text: 'Bonus alınırken hata oluştu',
                            icon: 'error',
                            confirmButtonColor: '#FFD700'
                        });
                    });
                }
            });
        }
        
        // Kişiselleştirilmiş bonusları hesapla
        function calculatePersonalizedBonuses() {
            document.getElementById('suggestedBonuses').innerHTML = 
                '<div class="text-center py-4"><i class="fas fa-spinner fa-spin fa-2x text-warning"></i><p class="mt-2">Hesaplanıyor...</p></div>';
            
            fetch('../api/bonus_system.php?action=calculate_personalized_bonus')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displaySuggestedBonuses(data.suggestions);
                    } else {
                        document.getElementById('suggestedBonuses').innerHTML = 
                            '<div class="alert alert-warning">Önerilecek bonus bulunamadı</div>';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('suggestedBonuses').innerHTML = 
                        '<div class="alert alert-danger">Bonuslar hesaplanırken hata oluştu</div>';
                });
        }
        
        // Önerilen bonusları göster
        function displaySuggestedBonuses(suggestions) {
            const container = document.getElementById('suggestedBonuses');
            
            if (suggestions.length === 0) {
                container.innerHTML = '<div class="alert alert-info">Şu anda önerilecek bonus bulunmuyor</div>';
                return;
            }
            
            let html = '';
            suggestions.forEach(suggestion => {
                html += `
                    <div class="bonus-card">
                        <div class="bonus-title">${suggestion.title}</div>
                        <div class="bonus-amount">
                            ${suggestion.amount ? suggestion.amount + ' ₺' : '%' + suggestion.percentage}
                            ${suggestion.max_amount ? ` (Max: ${suggestion.max_amount} ₺)` : ''}
                        </div>
                        <div class="bonus-description">${suggestion.description}</div>
                        <div class="mt-3">
                            <span class="badge bg-info">Önerilen</span>
                            <small class="text-muted ms-2">Davranış analizinize göre önerildi</small>
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }
        
        // Bonus geçmişini yükle
        function loadBonusHistory() {
            fetch('../api/bonus_system.php?action=get_bonus_history')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayBonusHistory(data.history);
                    } else {
                        document.getElementById('bonusHistory').innerHTML = 
                            '<div class="alert alert-warning">Bonus geçmişi bulunamadı</div>';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('bonusHistory').innerHTML = 
                        '<div class="alert alert-danger">Geçmiş yüklenirken hata oluştu</div>';
                });
        }
        
        // Bonus geçmişini göster
        function displayBonusHistory(history) {
            const container = document.getElementById('bonusHistory');
            
            if (history.length === 0) {
                container.innerHTML = '<div class="alert alert-info">Bonus geçmişi bulunmuyor</div>';
                return;
            }
            
            let html = '<div class="table-responsive"><table class="table table-dark table-striped">';
            html += '<thead><tr><th>Bonus</th><th>Miktar</th><th>Durum</th><th>Tarih</th></tr></thead><tbody>';
            
            history.forEach(item => {
                const statusText = {
                    'pending': 'Bekliyor',
                    'active': 'Aktif',
                    'used': 'Kullanıldı',
                    'expired': 'Süresi Doldu'
                };
                
                html += `
                    <tr>
                        <td>${item.bonus_name || item.title}</td>
                        <td>${item.amount} ₺</td>
                        <td><span class="badge bg-secondary">${statusText[item.status]}</span></td>
                        <td>${new Date(item.created_at).toLocaleDateString('tr-TR')}</td>
                    </tr>
                `;
            });
            
            html += '</tbody></table></div>';
            container.innerHTML = html;
        }
        
        // Kullanıcı davranışını güncelle
        function updateBehavior() {
            fetch('../api/bonus_system.php?action=update_user_behavior', {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Davranış verilerini tekrar yükle
                    loadBehaviorStats();
                }
            })
            .catch(error => console.error('Error:', error));
        }
        
        // Davranış istatistiklerini yükle
        function loadBehaviorStats() {
            fetch('../api/bonus_system.php?action=calculate_personalized_bonus')
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.behavior) {
                        displayBehaviorStats(data.behavior);
                    }
                })
                .catch(error => console.error('Error:', error));
        }
        
        // Davranış istatistiklerini göster
        function displayBehaviorStats(behavior) {
            document.getElementById('scoreValue').textContent = behavior.activity_score || 0;
            document.getElementById('totalDeposits').textContent = (behavior.total_deposits || 0).toLocaleString('tr-TR') + ' ₺';
            document.getElementById('totalBets').textContent = (behavior.total_bets || 0).toLocaleString('tr-TR') + ' ₺';
            document.getElementById('totalWins').textContent = (behavior.total_wins || 0).toLocaleString('tr-TR') + ' ₺';
            document.getElementById('sessionCount').textContent = behavior.session_count || 0;
            
            const riskLevels = {
                'low': 'Düşük',
                'medium': 'Orta',
                'high': 'Yüksek'
            };
            document.getElementById('riskLevel').textContent = riskLevels[behavior.risk_level] || 'Düşük';
            
            // Aktivite skoru çemberini güncelle
            const score = behavior.activity_score || 0;
            const scoreDeg = (score / 100) * 360;
            document.getElementById('activityScore').style.setProperty('--score-deg', scoreDeg + 'deg');
        }
    </script>
</body>
</html>