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

require_permission('content_manage');

// Admin session kontrolü için admin_id'yi ayarla
if (!isset($_SESSION['admin_id']) && isset($_SESSION['user_id'])) {
    $_SESSION['admin_id'] = $_SESSION['user_id'];
}

$page_title = "Bonus Yönetimi";

// İstatistikleri al
try {
    // Toplam bonus sayısı (hem personalized hem de talepler)
    $stmt = $pdo->query("SELECT 
        (SELECT COUNT(*) FROM personalized_bonuses) + 
        (SELECT COUNT(*) FROM bonus_talepleri) as total");
    $total_bonuses = $stmt->fetch()['total'];
    
    // Aktif/pending bonus sayısı
    $stmt = $pdo->query("SELECT 
        (SELECT COUNT(*) FROM personalized_bonuses WHERE status = 'active') + 
        (SELECT COUNT(*) FROM bonus_talepleri WHERE durum = 1) as active");
    $active_bonuses = $stmt->fetch()['active'];
    
    // Bu ay verilen bonus miktarı
    $stmt = $pdo->query("SELECT 
        COALESCE(
            (SELECT SUM(amount) FROM personalized_bonuses WHERE status = 'used' AND DATE_FORMAT(created_at, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')) +
            (SELECT SUM(miktar) FROM bonus_talepleri WHERE durum = 1 AND DATE_FORMAT(tarih, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')), 
            0
        ) as monthly_amount");
    $monthly_bonus_amount = $stmt->fetch()['monthly_amount'];
    
    // Kullanılan/onaylanan bonus sayısı
    $stmt = $pdo->query("SELECT 
        (SELECT COUNT(*) FROM personalized_bonuses WHERE status = 'used') + 
        (SELECT COUNT(*) FROM bonus_talepleri WHERE durum = 1) as used");
    $used_bonuses = $stmt->fetch()['used'];
    
    // Bekleyen bonus talepleri
    $stmt = $pdo->query("SELECT COUNT(*) as pending_requests FROM bonus_talepleri WHERE durum = 0");
    $pending_requests = $stmt->fetch()['pending_requests'];
    
} catch (PDOException $e) {
    $total_bonuses = $active_bonuses = $monthly_bonus_amount = $used_bonuses = $pending_requests = 0;
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?> - Admin Panel</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">
    <link href="styles.css" rel="stylesheet">
    <style>
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 15px;
            color: white;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .stats-card.warning {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }
        
        .stats-card.success {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }
        
        .stats-card.info {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        }
        
        .bonus-type-card {
            border: 1px solid #ddd;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            background: #f8f9fa;
        }
        
        .user-behavior-item {
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
        }
        
        .activity-badge {
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 0.8rem;
            font-weight: bold;
        }
        
        .activity-low { background: #d4edda; color: #155724; }
        .activity-medium { background: #fff3cd; color: #856404; }
        .activity-high { background: #f8d7da; color: #721c24; }
        
        .nav-pills .nav-link.active {
            background-color: #007bff;
        }
        
        .table-responsive {
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <?php include 'topbar.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <?php include 'sidebar.php'; ?>
            
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2"><i class="fas fa-gift me-2"></i><?php echo $page_title; ?></h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addBonusTypeModal">
                            <i class="fas fa-plus me-2"></i>Yeni Bonus Türü
                        </button>
                    </div>
                </div>
                
                <!-- İstatistik Kartları -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="stats-card">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h6>Toplam Bonus</h6>
                                    <h3><?php echo number_format($total_bonuses); ?></h3>
                                </div>
                                <div class="align-self-center">
                                    <i class="fas fa-gift fa-2x"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stats-card success">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h6>Aktif Bonus</h6>
                                    <h3><?php echo number_format($active_bonuses); ?></h3>
                                </div>
                                <div class="align-self-center">
                                    <i class="fas fa-check-circle fa-2x"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stats-card warning">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h6>Bu Ay Verilen</h6>
                                    <h3><?php echo number_format($monthly_bonus_amount); ?> ₺</h3>
                                </div>
                                <div class="align-self-center">
                                    <i class="fas fa-calendar-alt fa-2x"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stats-card info">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h6>Bekleyen Talepler</h6>
                                    <h3><?php echo number_format($pending_requests); ?></h3>
                                </div>
                                <div class="align-self-center">
                                    <i class="fas fa-clock fa-2x"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- İkinci satır istatistikler -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="stats-card">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h6>Kullanılan Bonus</h6>
                                    <h3><?php echo number_format($used_bonuses); ?></h3>
                                </div>
                                <div class="align-self-center">
                                    <i class="fas fa-calendar-alt fa-2x"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stats-card info">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h6>Kullanılan Bonus</h6>
                                    <h3><?php echo number_format($used_bonuses); ?></h3>
                                </div>
                                <div class="align-self-center">
                                    <i class="fas fa-hand-holding-usd fa-2x"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Sekmeler -->
                <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="pills-bonuses-tab" data-bs-toggle="pill" data-bs-target="#pills-bonuses" type="button" role="tab">
                            <i class="fas fa-list me-2"></i>Bonuslar
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="pills-requests-tab" data-bs-toggle="pill" data-bs-target="#pills-requests" type="button" role="tab">
                            <i class="fas fa-clipboard-list me-2"></i>Bonus Talepleri
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="pills-types-tab" data-bs-toggle="pill" data-bs-target="#pills-types" type="button" role="tab">
                            <i class="fas fa-tags me-2"></i>Bonus Türleri
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="pills-behavior-tab" data-bs-toggle="pill" data-bs-target="#pills-behavior" type="button" role="tab">
                            <i class="fas fa-chart-line me-2"></i>Kullanıcı Davranışları
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="pills-assign-tab" data-bs-toggle="pill" data-bs-target="#pills-assign" type="button" role="tab">
                            <i class="fas fa-user-plus me-2"></i>Bonus Ata
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="pills-campaigns-tab" data-bs-toggle="pill" data-bs-target="#pills-campaigns" type="button" role="tab">
                            <i class="fas fa-magic me-2"></i>Kampanyalar
                        </button>
                    </li>
                </ul>
                
                <div class="tab-content" id="pills-tabContent">
                    <!-- Bonuslar Sekmesi -->
                    <div class="tab-pane fade show active" id="pills-bonuses" role="tabpanel">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="mb-0">Tüm Bonuslar</h5>
                                <div>
                                    <select class="form-select form-select-sm" id="bonusStatusFilter">
                                        <option value="">Tüm Durumlar</option>
                                        <option value="pending">Bekliyor</option>
                                        <option value="active">Aktif</option>
                                        <option value="used">Kullanıldı</option>
                                        <option value="expired">Süresi Doldu</option>
                                        <option value="approved">Onaylandı</option>
                                        <option value="rejected">Reddedildi</option>
                                    </select>
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped" id="bonusesTable">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Kullanıcı</th>
                                                <th>Bonus Türü</th>
                                                <th>Miktar</th>
                                                <th>Durum</th>
                                                <th>Oluşturulma</th>
                                                <th>İşlemler</th>
                                            </tr>
                                        </thead>
                                        <tbody id="bonusesTableBody">
                                            <tr>
                                                <td colspan="7" class="text-center">
                                                    <i class="fas fa-spinner fa-spin"></i> Yükleniyor...
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Bonus Talepleri Sekmesi -->
                    <div class="tab-pane fade" id="pills-requests" role="tabpanel">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="mb-0">Kullanıcı Bonus Talepleri</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped" id="bonusRequestsTable">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Kullanıcı</th>
                                                <th>Bonus Türü</th>
                                                <th>Miktar</th>
                                                <th>Tarih</th>
                                                <th>Durum</th>
                                            </tr>
                                        </thead>
                                        <tbody id="bonusRequestsTableBody">
                                            <tr>
                                                <td colspan="6" class="text-center">
                                                    <i class="fas fa-spinner fa-spin"></i> Yükleniyor...
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Bonus Türleri Sekmesi -->
                    <div class="tab-pane fade" id="pills-types" role="tabpanel">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="mb-0">Bonus Türleri</h5>
                                    </div>
                                    <div class="card-body" id="bonusTypesContainer">
                                        <div class="text-center">
                                            <i class="fas fa-spinner fa-spin"></i> Yükleniyor...
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Kullanıcı Davranışları Sekmesi -->
                    <div class="tab-pane fade" id="pills-behavior" role="tabpanel">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0">Kullanıcı Davranış Analitiği</h5>
                            </div>
                            <div class="card-body">
                                <div class="row mb-3">
                                    <div class="col-md-4">
                                        <input type="text" class="form-control" id="userSearchInput" placeholder="Kullanıcı ara...">
                                    </div>
                                    <div class="col-md-3">
                                        <select class="form-select" id="riskLevelFilter">
                                            <option value="">Tüm Risk Seviyeleri</option>
                                            <option value="low">Düşük</option>
                                            <option value="medium">Orta</option>
                                            <option value="high">Yüksek</option>
                                        </select>
                                    </div>
                                    <div class="col-md-2">
                                        <button class="btn btn-primary" onclick="loadUserBehaviors()">
                                            <i class="fas fa-search"></i> Ara
                                        </button>
                                    </div>
                                </div>
                                <div id="userBehaviorsContainer">
                                    <div class="text-center">
                                        <i class="fas fa-spinner fa-spin"></i> Yükleniyor...
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Bonus Ata Sekmesi -->
                    <div class="tab-pane fade" id="pills-assign" role="tabpanel">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0">Kullanıcıya Bonus Ata</h5>
                            </div>
                            <div class="card-body">
                                <form id="assignBonusForm">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="assignUserId" class="form-label">Kullanıcı ID</label>
                                                <input type="number" class="form-control" id="assignUserId" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="assignBonusType" class="form-label">Bonus Türü</label>
                                                <select class="form-select" id="assignBonusType" required>
                                                    <option value="">Seçiniz...</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="assignAmount" class="form-label">Miktar (₺)</label>
                                                <input type="number" class="form-control" id="assignAmount" step="0.01" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="assignValidUntil" class="form-label">Geçerlilik Tarihi</label>
                                                <input type="datetime-local" class="form-control" id="assignValidUntil">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <label for="assignDescription" class="form-label">Açıklama</label>
                                        <textarea class="form-control" id="assignDescription" rows="3"></textarea>
                                    </div>
                                    <button type="submit" class="btn btn-success">
                                        <i class="fas fa-plus me-2"></i>Bonus Ata
                                    </button>
                                </form>
                                <hr>
                                <h5 class="mb-3">Kullanıcıya Free Spin Ata</h5>
                                <form id="assignFreeSpinsForm">
                                    <div class="row">
                                        <div class="col-md-4">
                                            <div class="mb-3">
                                                <label for="fsUserId" class="form-label">Kullanıcı ID</label>
                                                <input type="number" class="form-control" id="fsUserId" required>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="mb-3">
                                                <label for="fsCount" class="form-label">Spin Sayısı</label>
                                                <input type="number" class="form-control" id="fsCount" min="1" required>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="mb-3">
                                                <label for="fsProvider" class="form-label">Sağlayıcı (opsiyonel)</label>
                                                <input type="text" class="form-control" id="fsProvider" placeholder="Örn: Pragmatic">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="fsGameCode" class="form-label">Oyun Kodu (opsiyonel)</label>
                                                <input type="text" class="form-control" id="fsGameCode" placeholder="Örn: sweet-bonanza">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="fsExpires" class="form-label">Bitiş Tarihi</label>
                                                <input type="datetime-local" class="form-control" id="fsExpires">
                                            </div>
                                        </div>
                                    </div>
                                    <button type="submit" class="btn btn-warning">
                                        <i class="fas fa-star me-2"></i>Free Spin Ata
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Kampanyalar Sekmesi (bonuses.php birleşimi) -->
                <div class="tab-pane fade" id="pills-campaigns" role="tabpanel">
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">Kampanyalar</h5>
                        </div>
                        <div class="card-body">
                            <div class="row mb-4">
                                <div class="col-md-3">
                                    <div class="bonus-card">
                                        <h6><i class="fas fa-gift"></i> Aylık Bonus</h6>
                                        <h4>₺<?php echo number_format($monthly_bonus_amount ?? 0, 2); ?></h4>
                                        <small>Son 30 gün</small>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="bonus-card cashback">
                                        <h6><i class="fas fa-money-bill-wave"></i> Aylık Cashback</h6>
                                        <h4>₺<?php echo number_format(($campaign_stats['monthly_cashback'] ?? 0), 2); ?></h4>
                                        <small>Son 30 gün</small>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="bonus-card vip">
                                        <h6><i class="fas fa-crown"></i> VIP Üyeler</h6>
                                        <h4><?php echo number_format(($campaign_stats['vip_members'] ?? 0)); ?></h4>
                                        <small>Aktif VIP üyeler</small>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="bonus-card active-bonuses">
                                        <h6><i class="fas fa-star"></i> Aktif Bonuslar</h6>
                                        <h4><?php echo number_format(($campaign_stats['active_bonuses'] ?? 0)); ?></h4>
                                        <small>Çalışan kampanyalar</small>
                                    </div>
                                </div>
                            </div>

                            <div class="mb-4">
                                <h6>Free Spin Kampanya Oluştur</h6>
                                <form id="fsCampaignCreateForm" class="mb-3">
                                    <div class="row">
                                        <div class="col-md-3">
                                            <label class="form-label">Vendor</label>
                                            <input type="text" class="form-control" id="fsVendor" placeholder="pragmatic" value="pragmatic">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Kampanya Kodu</label>
                                            <input type="text" class="form-control" id="fsCampaignCode" placeholder="WELCOME100">
                                        </div>
                                    </div>
                                    <div class="row mt-2">
                                        <div class="col-md-3">
                                            <label class="form-label">Spin/ Oyuncu</label>
                                            <input type="number" class="form-control" id="fsPerPlayer" min="1" value="3">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Başlangıç</label>
                                            <input type="datetime-local" class="form-control" id="fsBeginsAt">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Bitiş</label>
                                            <input type="datetime-local" class="form-control" id="fsExpiresAt">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Para Birimi</label>
                                            <input type="text" class="form-control" id="fsCurrency" value="TRY">
                                        </div>
                                    </div>
                                    <div class="row mt-2">
                                        <div class="col-md-3">
                                            <label class="form-label">Game ID</label>
                                            <input type="number" class="form-control" id="fsGameId" value="23846">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Total Bet</label>
                                            <input type="number" class="form-control" id="fsTotalBet" value="1000">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Oyuncular (virgülle)</label>
                                            <input type="text" class="form-control" id="fsPlayers" placeholder="227,111,333">
                                        </div>
                                    </div>
                                    <button type="submit" class="btn btn-warning mt-2"><i class="fas fa-bullhorn me-2"></i>Kampanya Oluştur</button>
                                </form>
                                <div class="d-flex gap-2">
                                    <button class="btn btn-primary" id="fsCampaignsRefresh"><i class="fas fa-sync"></i> Kampanyaları Listele</button>
                                    <div class="input-group" style="max-width:420px;">
                                        <input type="text" class="form-control" id="fsCancelCode" placeholder="İptal edilecek kampanya kodu">
                                        <button class="btn btn-danger" id="fsCampaignCancel"><i class="fas fa-ban"></i> Kampanyayı İptal Et</button>
                                    </div>
                                </div>
                                <div id="fsCampaignsList" class="mt-3"></div>
                                <div class="input-group mt-2" style="max-width:520px;">
                                    <input type="text" class="form-control" id="fsUpdatePlayers" placeholder="Oyuncular (virgülle)">
                                    <input type="text" class="form-control" id="fsUpdateCode" placeholder="Kampanya kodu">
                                    <button class="btn btn-success" id="fsPlayersAdd">Ekle</button>
                                    <button class="btn btn-secondary" id="fsPlayersRemove">Çıkar</button>
                                </div>
                            </div>

                            <ul class="nav nav-tabs" id="campaignTabs" role="tablist">
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-dynamic" type="button" role="tab">
                                        <i class="fas fa-magic"></i> Dinamik Bonuslar
                                    </button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-cashback" type="button" role="tab">
                                        <i class="fas fa-money-bill-wave"></i> Cashback
                                    </button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-vip" type="button" role="tab">
                                        <i class="fas fa-crown"></i> VIP
                                    </button>
                                </li>
                            </ul>

                            <div class="tab-content mt-3">
                                <div class="tab-pane fade show active" id="tab-dynamic" role="tabpanel">
                                    <div class="table-responsive">
                                        <table class="table table-striped">
                                            <thead>
                                                <tr>
                                                    <th>Bonus Adı</th>
                                                    <th>Tür</th>
                                                    <th>Tetikleyici</th>
                                                    <th>Bonus Miktarı</th>
                                                    <th>Kullanım</th>
                                                    <th>Toplam Verilen</th>
                                                    <th>Durum</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                            <?php foreach (($dynamic_bonuses ?? []) as $bonus): ?>
                                                <tr>
                                                    <td>
                                                        <strong><?php echo htmlspecialchars($bonus['bonus_name'] ?? ''); ?></strong>
                                                        <br><small class="text-muted"><?php echo htmlspecialchars(substr($bonus['description'] ?? '', 0, 50)) . '...'; ?></small>
                                                    </td>
                                                    <td><span class="badge bg-primary"><?php echo strtoupper($bonus['bonus_type'] ?? ''); ?></span></td>
                                                    <td><?php echo htmlspecialchars($bonus['trigger_condition'] ?? ''); ?></td>
                                                    <td>
                                                        <?php if (($bonus['bonus_type'] ?? '') === 'percentage'): ?>
                                                            %<?php echo $bonus['bonus_amount'] ?? 0; ?>
                                                        <?php else: ?>
                                                            ₺<?php echo number_format($bonus['bonus_amount'] ?? 0, 2); ?>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td><?php echo $bonus['usage_count'] ?? 0; ?></td>
                                                    <td>₺<?php echo number_format($bonus['total_given'] ?? 0, 2); ?></td>
                                                    <td><span class="badge <?php echo ($bonus['is_active'] ?? 0) ? 'bg-success' : 'bg-secondary'; ?>"><?php echo ($bonus['is_active'] ?? 0) ? 'Aktif' : 'Pasif'; ?></span></td>
                                                </tr>
                                            <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>

                                <div class="tab-pane fade" id="tab-cashback" role="tabpanel">
                                    <?php foreach (($cashback_programs ?? []) as $program): ?>
                                    <div class="cashback-card">
                                        <div class="row">
                                            <div class="col-md-8">
                                                <h6><?php echo htmlspecialchars($program['program_name'] ?? ''); ?></h6>
                                                <p class="mb-2"><?php echo htmlspecialchars($program['description'] ?? ''); ?></p>
                                                <div class="d-flex gap-3">
                                                    <span class="badge bg-primary">%<?php echo $program['cashback_percentage'] ?? 0; ?> Cashback</span>
                                                    <span class="badge bg-info">Min: ₺<?php echo number_format($program['min_loss_amount'] ?? 0, 2); ?></span>
                                                    <span class="badge bg-warning">Max: ₺<?php echo number_format($program['max_cashback_amount'] ?? 0, 2); ?></span>
                                                </div>
                                            </div>
                                            <div class="col-md-4 text-end">
                                                <h6>Toplam Ödenen: ₺<?php echo number_format($program['total_cashback'] ?? 0, 2); ?></h6>
                                                <small class="text-muted"><?php echo $program['payment_count'] ?? 0; ?> ödeme</small>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>

                                <div class="tab-pane fade" id="tab-vip" role="tabpanel">
                                    <div class="row">
                                        <?php foreach (($vip_levels ?? []) as $level): ?>
                                        <div class="col-md-6 col-lg-4">
                                            <div class="vip-level-card">
                                                <div class="text-center mb-2">
                                                    <span class="vip-badge vip-<?php echo strtolower($level['level_name'] ?? ''); ?>"><?php echo htmlspecialchars($level['level_name'] ?? ''); ?></span>
                                                </div>
                                                <h6 class="text-center"><?php echo number_format($level['member_count'] ?? 0); ?> Üye</h6>
                                                <hr>
                                                <p><strong>Gerekli Puan:</strong> <?php echo number_format($level['required_points'] ?? 0); ?></p>
                                                <p><strong>Aylık Bonus:</strong> ₺<?php echo number_format($level['monthly_bonus'] ?? 0, 2); ?></p>
                                                <p><strong>Cashback Oranı:</strong> %<?php echo $level['cashback_percentage'] ?? 0; ?></p>
                                                <?php if (($level['free_spins_monthly'] ?? 0) > 0): ?>
                                                    <p><strong>Free Spin:</strong> <?php echo $level['free_spins_monthly']; ?>/ay</p>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <!-- Yeni Bonus Türü Modal -->
    <div class="modal fade" id="addBonusTypeModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Yeni Bonus Türü Ekle</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="addBonusTypeForm">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="bonusTypeName" class="form-label">Bonus Adı</label>
                            <input type="text" class="form-control" id="bonusTypeName" required>
                        </div>
                        <div class="mb-3">
                            <label for="bonusTypeDescription" class="form-label">Açıklama</label>
                            <textarea class="form-control" id="bonusTypeDescription" rows="3"></textarea>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="bonusTypeMinAmount" class="form-label">Min. Miktar (₺)</label>
                                    <input type="number" class="form-control" id="bonusTypeMinAmount" step="0.01">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="bonusTypeMaxAmount" class="form-label">Max. Miktar (₺)</label>
                                    <input type="number" class="form-control" id="bonusTypeMaxAmount" step="0.01">
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="bonusTypePercentage" class="form-label">Yüzde (%)</label>
                            <input type="number" class="form-control" id="bonusTypePercentage" step="0.01" min="0" max="100">
                        </div>
                        <div class="mb-3">
                            <label for="bonusTypeConditions" class="form-label">Koşullar (JSON)</label>
                            <textarea class="form-control" id="bonusTypeConditions" rows="3" placeholder='{"min_deposit": 100, "activity_score": 50}'></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="bonusTypeWager" class="form-label">Çevrim Şartı (kat)</label>
                            <input type="number" class="form-control" id="bonusTypeWager" step="0.1" min="0" placeholder="Örn: 20 (20x)">
                        </div>
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="bonusTypeNoWager">
                            <label class="form-check-label" for="bonusTypeNoWager">Çevrim Şartsız</label>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                        <button type="submit" class="btn btn-primary">Kaydet</button>
                    </div>
                </form>
            </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
        document.addEventListener('DOMContentLoaded', function() {
            loadBonuses();
            loadBonusTypes();
            loadUserBehaviors();
            loadBonusTypesForAssign();
            loadBonusRequests();
            bindFsCampaignHandlers();
        });
        
        // Bonusları yükle
        function loadBonuses() {
            const status = document.getElementById('bonusStatusFilter').value;
            
            console.log('Loading bonuses with status:', status);
            console.log('Current session user_id:', '<?php echo $_SESSION["user_id"] ?? "not_set"; ?>');
            console.log('Current session admin_id:', '<?php echo $_SESSION["admin_id"] ?? "not_set"; ?>');
            
            fetch(`../api/bonus_system.php?action=admin_get_bonuses&status=${status}`)
                .then(response => {
                    console.log('Response received:', response);
                    return response.json();
                })
                .then(data => {
                    console.log('Full data received:', JSON.stringify(data, null, 2));
                    if (data.success) {
                        console.log('Bonuses count:', data.bonuses.length);
                        console.log('Debug info:', data.debug);
                        if (data.bonuses.length > 0) {
                            console.log('First bonus:', data.bonuses[0]);
                        }
                        displayBonuses(data.bonuses);
                    } else {
                        console.log('Error message:', data.message);
                        document.getElementById('bonusesTableBody').innerHTML = 
                            '<tr><td colspan="7" class="text-center">Bonus bulunamadı</td></tr>';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('bonusesTableBody').innerHTML = 
                        '<tr><td colspan="7" class="text-center text-danger">Hata oluştu</td></tr>';
                });
        }
        
        // Bonusları göster
        function displayBonuses(bonuses) {
            const tbody = document.getElementById('bonusesTableBody');
            
            if (bonuses.length === 0) {
                tbody.innerHTML = '<tr><td colspan="7" class="text-center">Bonus bulunamadı</td></tr>';
                return;
            }
            
            let html = '';
            bonuses.forEach(bonus => {
                const statusBadges = {
                    'pending': 'bg-warning',
                    'active': 'bg-success',
                    'used': 'bg-secondary',
                    'expired': 'bg-danger',
                    'approved': 'bg-info',
                    'rejected': 'bg-dark'
                };
                
                const statusTexts = {
                    'pending': 'Bekliyor',
                    'active': 'Aktif',
                    'used': 'Kullanıldı',
                    'expired': 'Süresi Doldu',
                    'approved': 'Onaylandı',
                    'rejected': 'Reddedildi'
                };
                
                // Bonus tipi etiketi
                const sourceTypeBadges = {
                    'personalized': 'bg-primary',
                    'request': 'bg-secondary'
                };
                
                const sourceTypeTexts = {
                    'personalized': 'Kişiselleştirilmiş',
                    'request': 'Talep'
                };
                
                html += `
                    <tr>
                        <td>${bonus.id}</td>
                        <td>${bonus.username || bonus.user_id}</td>
                        <td>
                            ${bonus.bonus_name || bonus.bonus_type_id || 'Bilinmeyen Bonus'}
                            <br><small class="text-muted">${sourceTypeTexts[bonus.source_type] || 'Sistem'}</small>
                        </td>
                        <td>${bonus.amount} ₺</td>
                        <td>
                            <span class="badge ${statusBadges[bonus.status]}">${statusTexts[bonus.status]}</span>
                            ${bonus.source_type === 'request' ? `<span class="badge ${sourceTypeBadges[bonus.source_type]}">Talep</span>` : ''}
                        </td>
                        <td>${new Date(bonus.created_at).toLocaleDateString('tr-TR')}</td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary" onclick="viewBonusDetails(${bonus.id}, '${bonus.source_type}')">
                                <i class="fas fa-eye"></i>
                            </button>
                            ${bonus.status === 'pending' && bonus.source_type === 'personalized' ? `
                                <button class="btn btn-sm btn-outline-danger" onclick="cancelBonus(${bonus.id})">
                                    <i class="fas fa-times"></i>
                                </button>
                            ` : ''}
                            ${bonus.status === 'pending' && bonus.source_type === 'request' ? `
                                <button class="btn btn-sm btn-success" onclick="approveBonusRequest(${bonus.id})">
                                    <i class="fas fa-check"></i>
                                </button>
                                <button class="btn btn-sm btn-danger" onclick="rejectBonusRequest(${bonus.id})">
                                    <i class="fas fa-times"></i>
                                </button>
                            ` : ''}
                        </td>
                    </tr>
                `;
            });
            
            tbody.innerHTML = html;
        }

        // Bonus taleplerini yükle
        function loadBonusRequests() {
            fetch(`../api/bonus_system.php?action=admin_get_bonus_requests`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayBonusRequests(data.requests);
                    } else {
                        document.getElementById('bonusRequestsTableBody').innerHTML = 
                            '<tr><td colspan="6" class="text-center">Talep bulunamadı</td></tr>';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('bonusRequestsTableBody').innerHTML = 
                        '<tr><td colspan="6" class="text-center text-danger">Hata oluştu</td></tr>';
                });
        }

        // Bonus taleplerini göster
        function displayBonusRequests(requests) {
            const tbody = document.getElementById('bonusRequestsTableBody');
            if (!Array.isArray(requests) || requests.length === 0) {
                tbody.innerHTML = '<tr><td colspan="6" class="text-center">Talep bulunamadı</td></tr>';
                return;
            }

            const statusBadges = {
                0: 'bg-warning',   // Bekliyor
                1: 'bg-success',   // Verildi
                2: 'bg-danger'     // Reddedildi
            };
            const statusTexts = {
                0: 'Bekliyor',
                1: 'Verildi',
                2: 'Reddedildi'
            };

            let html = '';
            requests.forEach(req => {
                const badge = statusBadges[req.durum] || 'bg-secondary';
                const text = statusTexts[req.durum] || String(req.durum);
                html += `
                    <tr>
                        <td>${req.id}</td>
                        <td>${req.username || req.user_id}</td>
                        <td>${req.bonus_name}</td>
                        <td>${req.amount} ₺</td>
                        <td>${req.created_at}</td>
                        <td>
                            <span class="badge ${badge}">${text}</span>
                            ${req.durum === 0 ? `
                                <div class="mt-2">
                                    <button class="btn btn-sm btn-success me-1" onclick="approveBonusRequest(${req.id})">
                                        <i class="fas fa-check"></i>
                                    </button>
                                    <button class="btn btn-sm btn-danger" onclick="rejectBonusRequest(${req.id})">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                            ` : ''}
                        </td>
                    </tr>
                `;
            });
            tbody.innerHTML = html;
        }

        function approveBonusRequest(id) {
            const formData = new FormData();
            formData.append('request_id', id);
            fetch('../api/bonus_system.php?action=admin_approve_bonus_request', {
                method: 'POST',
                body: formData
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    Swal.fire('Onaylandı', data.message, 'success');
                    loadBonusRequests();
                } else {
                    Swal.fire('Hata', data.message, 'error');
                }
            })
            .catch(() => Swal.fire('Hata', 'Talep onaylanırken hata oluştu', 'error'));
        }

        function rejectBonusRequest(id) {
            const formData = new FormData();
            formData.append('request_id', id);
            fetch('../api/bonus_system.php?action=admin_reject_bonus_request', {
                method: 'POST',
                body: formData
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    Swal.fire('Reddedildi', data.message, 'success');
                    loadBonusRequests();
                } else {
                    Swal.fire('Hata', data.message, 'error');
                }
            })
            .catch(() => Swal.fire('Hata', 'Talep reddedilirken hata oluştu', 'error'));
        }
        
        // Bonus türlerini yükle
        function loadBonusTypes() {
            fetch('../api/bonus_system.php?action=admin_get_bonus_types')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayBonusTypes(data.types);
                    } else {
                        document.getElementById('bonusTypesContainer').innerHTML = 
                            '<div class="alert alert-warning">Bonus türü bulunamadı</div>';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('bonusTypesContainer').innerHTML = 
                        '<div class="alert alert-danger">Hata oluştu</div>';
                });
        }
        
        // Bonus türlerini göster
        function displayBonusTypes(types) {
            const container = document.getElementById('bonusTypesContainer');
            
            if (types.length === 0) {
                container.innerHTML = '<div class="alert alert-info">Bonus türü bulunamadı</div>';
                return;
            }
            
            let html = '';
            types.forEach(type => {
                html += `
                    <div class="bonus-type-card">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <h6 class="fw-bold">${type.name}</h6>
                                <p class="text-muted mb-2">${type.description || 'Açıklama yok'}</p>
                                <div class="row">
                                    <div class="col-md-3">
                                        <small class="text-muted">Min: ${type.min_amount || 0} ₺</small>
                                    </div>
                                    <div class="col-md-3">
                                        <small class="text-muted">Max: ${type.max_amount || 'Sınırsız'} ₺</small>
                                    </div>
                                    <div class="col-md-3">
                                        <small class="text-muted">Yüzde: %${type.percentage || 0}</small>
                                    </div>
                                    <div class="col-md-3">
                                        <small class="text-muted">Çevrim: ${type.wagering_requirement || 0}x</small>
                                    </div>
                                    <div class="col-md-3 mt-2">
                                        <span class="badge ${type.is_active ? 'bg-success' : 'bg-secondary'}">
                                            ${type.is_active ? 'Aktif' : 'Pasif'}
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div>
                                <button class="btn btn-sm btn-primary me-1" onclick="editBonusType(${type.id})">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-sm btn-${type.is_active ? 'warning' : 'success'}" 
                                        onclick="toggleBonusType(${type.id}, ${type.is_active})">
                                    <i class="fas fa-${type.is_active ? 'pause' : 'play'}"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }
        
        // Kullanıcı davranışlarını yükle
        function loadUserBehaviors() {
            const search = document.getElementById('userSearchInput').value;
            const riskLevel = document.getElementById('riskLevelFilter').value;
            
            fetch(`../api/bonus_system.php?action=admin_get_user_behaviors&search=${search}&risk_level=${riskLevel}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayUserBehaviors(data.behaviors);
                    } else {
                        document.getElementById('userBehaviorsContainer').innerHTML = 
                            '<div class="alert alert-warning">Kullanıcı davranışı bulunamadı</div>';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('userBehaviorsContainer').innerHTML = 
                        '<div class="alert alert-danger">Hata oluştu</div>';
                });
        }
        
        // Kullanıcı davranışlarını göster
        function displayUserBehaviors(behaviors) {
            const container = document.getElementById('userBehaviorsContainer');
            
            if (behaviors.length === 0) {
                container.innerHTML = '<div class="alert alert-info">Kullanıcı davranışı bulunamadı</div>';
                return;
            }
            
            let html = '';
            behaviors.forEach(behavior => {
                const riskClass = `activity-${behavior.risk_level}`;
                const riskText = {
                    'low': 'Düşük',
                    'medium': 'Orta',
                    'high': 'Yüksek'
                };
                
                html += `
                    <div class="user-behavior-item">
                        <div class="row align-items-center">
                            <div class="col-md-2">
                                <strong>${behavior.username || 'ID: ' + behavior.user_id}</strong>
                            </div>
                            <div class="col-md-2">
                                <span class="activity-badge ${riskClass}">
                                    ${riskText[behavior.risk_level]}
                                </span>
                            </div>
                            <div class="col-md-2">
                                <small>Aktivite: ${behavior.activity_score}/100</small>
                            </div>
                            <div class="col-md-2">
                                <small>Yatırım: ${behavior.total_deposits || 0} ₺</small>
                            </div>
                            <div class="col-md-2">
                                <small>Bahis: ${behavior.total_bets || 0} ₺</small>
                            </div>
                            <div class="col-md-2">
                                <button class="btn btn-sm btn-primary" onclick="suggestBonusForUser(${behavior.user_id})">
                                    <i class="fas fa-magic me-1"></i>Bonus Öner
                                </button>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }
        
        // Bonus atama için bonus türlerini yükle
        function loadBonusTypesForAssign() {
            fetch('../api/bonus_system.php?action=admin_get_bonus_types')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const select = document.getElementById('assignBonusType');
                        select.innerHTML = '<option value="">Seçiniz...</option>';
                        
                        data.types.forEach(type => {
                            if (type.is_active) {
                                select.innerHTML += `<option value="${type.id}">${type.name}</option>`;
                            }
                        });
                    }
                })
                .catch(error => console.error('Error:', error));
        }
        
        // Event listeners
        document.getElementById('bonusStatusFilter').addEventListener('change', loadBonuses);
        
        function bindFsCampaignHandlers(){
            const createForm = document.getElementById('fsCampaignCreateForm');
            if (createForm){
                createForm.addEventListener('submit', function(e){
                    e.preventDefault();
                    const begins = document.getElementById('fsBeginsAt').value;
                    const expires = document.getElementById('fsExpiresAt').value;
                    const beginsEpoch = begins ? Math.floor(new Date(begins).getTime()/1000) : 0;
                    const expiresEpoch = expires ? Math.floor(new Date(expires).getTime()/1000) : 0;
                    const fd = new FormData();
                    fd.append('vendor', document.getElementById('fsVendor').value);
                    fd.append('campaign_code', document.getElementById('fsCampaignCode').value);
                    fd.append('freespins_per_player', document.getElementById('fsPerPlayer').value);
                    fd.append('begins_at', beginsEpoch);
                    fd.append('expires_at', expiresEpoch);
                    fd.append('currency_code', document.getElementById('fsCurrency').value);
                    fd.append('game_id', document.getElementById('fsGameId').value);
                    fd.append('total_bet', document.getElementById('fsTotalBet').value);
                    fd.append('players', document.getElementById('fsPlayers').value);
                    fetch('../api/bonus_system.php?action=admin_fs_campaign_create', { method: 'POST', body: fd })
                        .then(r=>r.json())
                        .then(data=>{
                            if (data.success){
                                Swal.fire('Başarılı','Kampanya oluşturuldu','success');
                                document.getElementById('fsCampaignsRefresh').click();
                            } else {
                                Swal.fire('Hata', data.response?.message || data.message || 'Kampanya oluşturulamadı','error');
                            }
                        })
                        .catch(()=>Swal.fire('Hata','İstek başarısız','error'));
                });
            }
            const refreshBtn = document.getElementById('fsCampaignsRefresh');
            if (refreshBtn){
                refreshBtn.addEventListener('click', function(){
                    const fd = new FormData();
                    fetch('../api/bonus_system.php?action=admin_fs_campaign_list', { method: 'POST', body: fd })
                        .then(r=>r.json())
                        .then(data=>{
                            const listDiv = document.getElementById('fsCampaignsList');
                            if (!data.success){ listDiv.innerHTML = '<div class="alert alert-danger">Liste alınamadı</div>'; return; }
                            const arr = Array.isArray(data.campaigns) ? data.campaigns : [];
                            let html = '<table class="table table-striped"><thead><tr><th>Kod</th><th>Vendor</th><th>Durum</th><th>Başlangıç</th><th>Bitiş</th></tr></thead><tbody>';
                            arr.forEach(c=>{
                                html += `<tr><td>${c.campaign_code||''}</td><td>${c.vendor||''}</td><td>${c.status||''}</td><td>${c.begins_at||''}</td><td>${c.expires_at||''}</td></tr>`;
                            });
                            html += '</tbody></table>';
                            listDiv.innerHTML = html;
                        })
                        .catch(()=>{ document.getElementById('fsCampaignsList').innerHTML = '<div class="alert alert-danger">Hata oluştu</div>'; });
                });
            }
            const cancelBtn = document.getElementById('fsCampaignCancel');
            if (cancelBtn){
                cancelBtn.addEventListener('click', function(){
                    const fd = new FormData();
                    fd.append('campaign_code', document.getElementById('fsCancelCode').value);
                    fetch('../api/bonus_system.php?action=admin_fs_campaign_cancel', { method: 'POST', body: fd })
                        .then(r=>r.json())
                        .then(data=>{
                            if (data.success){ Swal.fire('İptal edildi','Kampanya iptal edildi','success'); refreshBtn && refreshBtn.click(); }
                            else { Swal.fire('Hata', data.response?.message || data.message || 'İptal başarısız','error'); }
                        })
                        .catch(()=>Swal.fire('Hata','İstek başarısız','error'));
                });
            }
            const addBtn = document.getElementById('fsPlayersAdd');
            if (addBtn){
                addBtn.addEventListener('click', function(){
                    const fd = new FormData();
                    fd.append('campaign_code', document.getElementById('fsUpdateCode').value);
                    fd.append('players', document.getElementById('fsUpdatePlayers').value);
                    fetch('../api/bonus_system.php?action=admin_fs_campaign_players_add', { method: 'POST', body: fd })
                        .then(r=>r.json())
                        .then(data=>{ if (data.success){ Swal.fire('Eklendi','Oyuncular kampanyaya eklendi','success'); } else { Swal.fire('Hata', data.response?.message || data.message || 'Ekleme başarısız','error'); } })
                        .catch(()=>Swal.fire('Hata','İstek başarısız','error'));
                });
            }
            const removeBtn = document.getElementById('fsPlayersRemove');
            if (removeBtn){
                removeBtn.addEventListener('click', function(){
                    const fd = new FormData();
                    fd.append('campaign_code', document.getElementById('fsUpdateCode').value);
                    fd.append('players', document.getElementById('fsUpdatePlayers').value);
                    fetch('../api/bonus_system.php?action=admin_fs_campaign_players_remove', { method: 'POST', body: fd })
                        .then(r=>r.json())
                        .then(data=>{ if (data.success){ Swal.fire('Çıkarıldı','Oyuncular kampanyadan çıkarıldı','success'); } else { Swal.fire('Hata', data.response?.message || data.message || 'Çıkarma başarısız','error'); } })
                        .catch(()=>Swal.fire('Hata','İstek başarısız','error'));
                });
            }
        }
        
        // Yeni bonus türü formu
        document.getElementById('addBonusTypeForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData();
            formData.append('name', document.getElementById('bonusTypeName').value);
            formData.append('description', document.getElementById('bonusTypeDescription').value);
            formData.append('min_amount', document.getElementById('bonusTypeMinAmount').value);
            formData.append('max_amount', document.getElementById('bonusTypeMaxAmount').value);
            formData.append('percentage', document.getElementById('bonusTypePercentage').value);
            formData.append('conditions', document.getElementById('bonusTypeConditions').value);
            formData.append('wagering_requirement', document.getElementById('bonusTypeWager').value || 0);
            formData.append('no_wagering', document.getElementById('bonusTypeNoWager').checked ? 1 : 0);
            
            fetch('../api/bonus_system.php?action=admin_add_bonus_type', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire('Başarılı!', 'Bonus türü eklendi', 'success');
                    bootstrap.Modal.getInstance(document.getElementById('addBonusTypeModal')).hide();
                    loadBonusTypes();
                    loadBonusTypesForAssign();
                    document.getElementById('addBonusTypeForm').reset();
                } else {
                    Swal.fire('Hata!', data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire('Hata!', 'Bonus türü eklenirken hata oluştu', 'error');
            });
        });
        
        // Bonus atama formu
        document.getElementById('assignBonusForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData();
            formData.append('user_id', document.getElementById('assignUserId').value);
            formData.append('bonus_type_id', document.getElementById('assignBonusType').value);
            formData.append('amount', document.getElementById('assignAmount').value);
            formData.append('valid_until', document.getElementById('assignValidUntil').value);
            formData.append('description', document.getElementById('assignDescription').value);
            
            fetch('../api/bonus_system.php?action=admin_assign_bonus', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire('Başarılı!', 'Bonus atandı', 'success');
                    document.getElementById('assignBonusForm').reset();
                    loadBonuses();
                } else {
                    Swal.fire('Hata!', data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire('Hata!', 'Bonus atanırken hata oluştu', 'error');
            });
        });

        // Free spin atama formu
        document.getElementById('assignFreeSpinsForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const fd = new FormData();
            fd.append('user_id', document.getElementById('fsUserId').value);
            fd.append('spins', document.getElementById('fsCount').value);
            fd.append('provider', document.getElementById('fsProvider').value);
            fd.append('game_code', document.getElementById('fsGameCode').value);
            fd.append('expires_at', document.getElementById('fsExpires').value);
            fetch('../api/bonus_system.php?action=admin_assign_free_spins', { method: 'POST', body: fd })
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        Swal.fire('Başarılı', 'Free spin atandı', 'success');
                        document.getElementById('assignFreeSpinsForm').reset();
                    } else {
                        Swal.fire('Hata', data.message || 'İşlem başarısız', 'error');
                    }
                })
                .catch(() => Swal.fire('Hata', 'İstek sırasında hata oluştu', 'error'));
        });

        function editBonusType(id) {
            fetch('../api/bonus_system.php?action=admin_get_bonus_types')
                .then(r => r.json())
                .then(data => {
                    if (!data.success) {
                        Swal.fire('Hata', 'Bonus türleri yüklenemedi', 'error');
                        return;
                    }
                    const type = data.types.find(t => t.id == id);
                    if (!type) {
                        Swal.fire('Hata', 'Bonus türü bulunamadı', 'error');
                        return;
                    }
                    const html = `
                        <div class="text-start">
                            <div class="mb-2">
                                <label class="form-label">Bonus Adı</label>
                                <input id="edit_name" class="form-control" value="${type.name || ''}">
                            </div>
                            <div class="mb-2">
                                <label class="form-label">Açıklama</label>
                                <textarea id="edit_description" class="form-control" rows="3">${type.description || ''}</textarea>
                            </div>
                            <div class="row">
                                <div class="col-md-4">
                                    <label class="form-label">Min (₺)</label>
                                    <input id="edit_min" type="number" step="0.01" class="form-control" value="${type.min_amount || ''}">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Max (₺)</label>
                                    <input id="edit_max" type="number" step="0.01" class="form-control" value="${type.max_amount || ''}">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Yüzde (%)</label>
                                    <input id="edit_percentage" type="number" step="0.01" min="0" max="100" class="form-control" value="${type.percentage || ''}">
                                </div>
                            </div>
                            <div class="mt-2">
                                <label class="form-label">Koşullar (JSON)</label>
                                <textarea id="edit_conditions" class="form-control" rows="3">${type.conditions || ''}</textarea>
                            </div>
                            <div class="mt-2">
                                <label class="form-label">Çevrim Şartı (kat)</label>
                                <input id="edit_wager" type="number" step="0.1" min="0" class="form-control" value="${type.wagering_requirement || 0}">
                            </div>
                            <div class="form-check mt-2">
                                <input id="edit_no_wager" class="form-check-input" type="checkbox" ${type.no_wagering ? 'checked' : ''}>
                                <label class="form-check-label" for="edit_no_wager">Çevrim Şartsız</label>
                            </div>
                        </div>`;
                    Swal.fire({
                        title: 'Bonus Türünü Düzenle',
                        html,
                        showCancelButton: true,
                        confirmButtonText: 'Kaydet',
                        cancelButtonText: 'İptal',
                        background: '#000',
                        color: '#e6e6e6',
                        buttonsStyling: false,
                        customClass: { popup: 'swal-dark', confirmButton: 'btn btn-primary', cancelButton: 'btn btn-secondary' },
                        preConfirm: () => {
                            const payload = new FormData();
                            payload.append('id', id);
                            payload.append('name', document.getElementById('edit_name').value.trim());
                            payload.append('description', document.getElementById('edit_description').value.trim());
                            payload.append('min_amount', document.getElementById('edit_min').value);
                            payload.append('max_amount', document.getElementById('edit_max').value);
                            payload.append('percentage', document.getElementById('edit_percentage').value);
                            payload.append('conditions', document.getElementById('edit_conditions').value.trim());
                            payload.append('wagering_requirement', document.getElementById('edit_wager').value);
                            payload.append('no_wagering', document.getElementById('edit_no_wager').checked ? 1 : 0);
                            return fetch('../api/bonus_system.php?action=admin_update_bonus_type', { method: 'POST', body: payload })
                                .then(r => r.json());
                        }
                    }).then(res => {
                        if (res.isConfirmed) {
                            const data = res.value;
                            if (data && data.success) {
                                Swal.fire('Başarılı', 'Bonus türü güncellendi', 'success');
                                loadBonusTypes();
                                loadBonusTypesForAssign();
                            } else {
                                Swal.fire('Hata', (data && data.message) || 'Güncelleme başarısız', 'error');
                            }
                        }
                    });
                })
                .catch(() => Swal.fire('Hata', 'Düzenleme için veri alınamadı', 'error'));
        }

        function toggleBonusType(id, isActive) {
            const fd = new FormData();
            fd.append('id', id);
            fd.append('is_active', isActive ? 1 : 0);
            fetch('../api/bonus_system.php?action=admin_toggle_bonus_type', { method: 'POST', body: fd })
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        loadBonusTypes();
                        loadBonusTypesForAssign();
                    } else {
                        Swal.fire('Hata', data.message || 'İşlem başarısız', 'error');
                    }
                })
                .catch(() => Swal.fire('Hata', 'İşlem sırasında hata oluştu', 'error'));
        }
        
        // Bonus detaylarını göster
        function viewBonusDetails(bonusId, sourceType) {
            fetch(`../api/bonus_system.php?action=get_bonus_details&id=${bonusId}&source_type=${sourceType}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const bonus = data.bonus;
                        let detailsHtml = `
                            <div class="text-start">
                                <p><strong>Bonus ID:</strong> ${bonus.id}</p>
                                <p><strong>Kullanıcı:</strong> ${bonus.username || bonus.user_id}</p>
                                <p><strong>Bonus Türü:</strong> ${bonus.bonus_name || bonus.bonus_type_id || 'Bilinmeyen Bonus'}</p>
                                <p><strong>Miktar:</strong> ${bonus.amount} ₺</p>
                                <p><strong>Durum:</strong> <span class="badge bg-${bonus.status === 'active' ? 'success' : bonus.status === 'pending' ? 'warning' : 'secondary'}">${bonus.status}</span></p>
                                <p><strong>Kaynak:</strong> ${bonus.source_type === 'personalized' ? 'Kişiselleştirilmiş' : 'Kullanıcı Talebi'}</p>
                                <p><strong>Oluşturulma Tarihi:</strong> ${new Date(bonus.created_at).toLocaleDateString('tr-TR')}</p>
                                <hr>
                                <p><strong>Çevrim Şartı:</strong> ${bonus.wagering_required ?? 0} ₺ (kat: ${bonus.wagering_requirement ?? (bonus.wagering_required && bonus.amount ? (bonus.wagering_required/bonus.amount).toFixed(2) : 0)})</p>
                                <p><strong>Çevrim İlerlemesi:</strong> ${bonus.wagering_done ?? 0} ₺</p>
                                <p><strong>Şart Karşılandı mı?</strong> ${bonus.wagering_met ? 'Evet' : 'Hayır'}</p>
                            </div>
                        `;
                        
                        Swal.fire({
                            title: 'Bonus Detayları',
                            html: detailsHtml,
                            icon: 'info',
                            confirmButtonText: 'Kapat'
                        });
                    } else {
                        Swal.fire('Hata', data.message, 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    Swal.fire('Hata', 'Bonus detayları yüklenirken hata oluştu', 'error');
                });
        }
        
        // Bonus iptal et
        function cancelBonus(bonusId) {
            Swal.fire({
                title: 'Emin misiniz?',
                text: 'Bu bonusu iptal etmek istediğinizden emin misiniz?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Evet, İptal Et',
                cancelButtonText: 'Hayır'
            }).then((result) => {
                if (result.isConfirmed) {
                    const formData = new FormData();
                    formData.append('bonus_id', bonusId);
                    
                    fetch('../api/bonus_system.php?action=admin_cancel_bonus', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire('İptal Edildi!', 'Bonus iptal edildi', 'success');
                            loadBonuses();
                        } else {
                            Swal.fire('Hata!', data.message, 'error');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        Swal.fire('Hata!', 'Bonus iptal edilirken hata oluştu', 'error');
                    });
                }
            });
        }
        
        // Kullanıcı için bonus öner
        function suggestBonusForUser(userId) {
            fetch(`../api/bonus_system.php?action=calculate_personalized_bonus&user_id=${userId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.suggestions.length > 0) {
                        let message = 'Önerilen bonuslar:\n\n';
                        data.suggestions.forEach(suggestion => {
                            message += `• ${suggestion.title}: ${suggestion.amount || suggestion.percentage + '%'} ₺\n`;
                        });
                        
                        Swal.fire({
                            title: 'Bonus Önerileri',
                            text: message,
                            icon: 'info',
                            confirmButtonText: 'Tamam'
                        });
                    } else {
                        Swal.fire('Bilgi', 'Bu kullanıcı için önerilecek bonus bulunamadı', 'info');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    Swal.fire('Hata!', 'Bonus önerileri hesaplanırken hata oluştu', 'error');
                });
        }
    </script>
</body>
</html>