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

// Admin kontrolü
if (!isset($_SESSION['admin_logged_in']) || !has_permission('bonuses_manage')) {
    header('Location: index.php');
    exit;
}

$page_title = "Bonus Yönetimi";

// Dinamik bonuslar
try {
    $stmt = $pdo->query("
        SELECT db.*, 
               COUNT(ubh.id) as usage_count,
               SUM(ubh.bonus_amount) as total_given
        FROM dynamic_bonuses db
        LEFT JOIN user_bonus_history ubh ON db.id = ubh.bonus_id
        GROUP BY db.id
        ORDER BY db.created_at DESC
        LIMIT 20
    ");
    $dynamic_bonuses = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $dynamic_bonuses = [];
}

// Cashback programları
try {
    $stmt = $pdo->query("
        SELECT cp.*, 
               COUNT(cpp.id) as payment_count,
               SUM(cpp.cashback_amount) as total_cashback
        FROM cashback_programs cp
        LEFT JOIN cashback_payments cpp ON cp.id = cpp.program_id
        GROUP BY cp.id
        ORDER BY cp.created_at DESC
        LIMIT 20
    ");
    $cashback_programs = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $cashback_programs = [];
}

// VIP seviyeleri
try {
    $stmt = $pdo->query("
        SELECT vl.*, 
               COUNT(uvs.user_id) as member_count
        FROM vip_levels vl
        LEFT JOIN user_vip_status uvs ON vl.id = uvs.vip_level_id
        GROUP BY vl.id
        ORDER BY vl.required_points ASC
    ");
    $vip_levels = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $vip_levels = [];
}

// İstatistikler
try {
    $stats = [];
    
    // Toplam bonus dağıtımı
    $stmt = $pdo->query("SELECT SUM(bonus_amount) as total FROM user_bonus_history WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)");
    $stats['monthly_bonus'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
    
    // Toplam cashback
    $stmt = $pdo->query("SELECT SUM(cashback_amount) as total FROM cashback_payments WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)");
    $stats['monthly_cashback'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
    
    // Aktif VIP üyeler
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM user_vip_status WHERE status = 'active'");
    $stats['vip_members'] = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    // Aktif bonus kampanyaları
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM dynamic_bonuses WHERE is_active = 1");
    $stats['active_bonuses'] = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
} catch (Exception $e) {
    $stats = ['monthly_bonus' => 0, 'monthly_cashback' => 0, 'vip_members' => 0, 'active_bonuses' => 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="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">
    <style>
        .bonus-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
            transition: transform 0.3s ease;
        }
        
        .bonus-card:hover {
            transform: translateY(-5px);
        }
        
        .bonus-card.cashback {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
        }
        
        .bonus-card.vip {
            background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
            color: #333;
        }
        
        .bonus-card.active-bonuses {
            background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
            color: #333;
        }
        
        .vip-badge {
            padding: 0.5rem 1rem;
            border-radius: 25px;
            font-weight: bold;
            text-transform: uppercase;
            font-size: 0.8rem;
        }
        
        .vip-bronze { background: #cd7f32; color: white; }
        .vip-silver { background: #c0c0c0; color: #333; }
        .vip-gold { background: #ffd700; color: #333; }
        .vip-platinum { background: #e5e4e2; color: #333; }
        .vip-diamond { background: #b9f2ff; color: #333; }
        
        .bonus-type-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 50px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .type-deposit { background: #28a745; color: white; }
        .type-loss { background: #dc3545; color: white; }
        .type-activity { background: #17a2b8; color: white; }
        .type-birthday { background: #ffc107; color: #333; }
        .type-milestone { background: #6f42c1; color: white; }
        
        .cashback-card {
            border-left: 4px solid #28a745;
            background: #f8f9fa;
            padding: 1rem;
            margin-bottom: 1rem;
            border-radius: 0 8px 8px 0;
        }
        
        .vip-level-card {
            border: 2px solid #ddd;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
        }
        
        .vip-level-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .benefit-list {
            list-style: none;
            padding: 0;
        }
        
        .benefit-list li {
            padding: 0.25rem 0;
            border-bottom: 1px solid #eee;
        }
        
        .benefit-list li:last-child {
            border-bottom: none;
        }
        
        .benefit-list i {
            color: #28a745;
            margin-right: 0.5rem;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <?php include 'sidebar.php'; ?>
            
            <div class="col-md-10 p-4">
                <?php include 'topbar.php'; ?>
                
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h1><i class="fas fa-gift"></i> <?php echo $page_title; ?></h1>
                    <div>
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#newBonusModal">
                            <i class="fas fa-plus"></i> Yeni Bonus
                        </button>
                        <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#newCashbackModal">
                            <i class="fas fa-money-bill-wave"></i> Yeni Cashback
                        </button>
                        <button class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#newVipLevelModal">
                            <i class="fas fa-crown"></i> VIP Seviye
                        </button>
                    </div>
                </div>

                <!-- İstatistik Kartları -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="bonus-card">
                            <h5><i class="fas fa-gift"></i> Aylık Bonus</h5>
                            <h2>₺<?php echo number_format($stats['monthly_bonus'], 2); ?></h2>
                            <small>Son 30 gün</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="bonus-card cashback">
                            <h5><i class="fas fa-money-bill-wave"></i> Aylık Cashback</h5>
                            <h2>₺<?php echo number_format($stats['monthly_cashback'], 2); ?></h2>
                            <small>Son 30 gün</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="bonus-card vip">
                            <h5><i class="fas fa-crown"></i> VIP Üyeler</h5>
                            <h2><?php echo number_format($stats['vip_members']); ?></h2>
                            <small>Aktif VIP üyeler</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="bonus-card active-bonuses">
                            <h5><i class="fas fa-star"></i> Aktif Bonuslar</h5>
                            <h2><?php echo number_format($stats['active_bonuses']); ?></h2>
                            <small>Çalışan kampanyalar</small>
                        </div>
                    </div>
                </div>

                <!-- Tabs -->
                <ul class="nav nav-tabs" id="bonusTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="dynamic-bonuses-tab" data-bs-toggle="tab" data-bs-target="#dynamic-bonuses" type="button" role="tab">
                            <i class="fas fa-magic"></i> Dinamik Bonuslar
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="cashback-tab" data-bs-toggle="tab" data-bs-target="#cashback" type="button" role="tab">
                            <i class="fas fa-money-bill-wave"></i> Cashback Programları
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="vip-tab" data-bs-toggle="tab" data-bs-target="#vip" type="button" role="tab">
                            <i class="fas fa-crown"></i> VIP Seviyeleri
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="birthday-tab" data-bs-toggle="tab" data-bs-target="#birthday" type="button" role="tab">
                            <i class="fas fa-birthday-cake"></i> Doğum Günü Bonusları
                        </button>
                    </li>
                </ul>

                <div class="tab-content" id="bonusTabsContent">
                    <!-- Dinamik Bonuslar -->
                    <div class="tab-pane fade show active" id="dynamic-bonuses" role="tabpanel">
                        <div class="card mt-3">
                            <div class="card-header">
                                <h5><i class="fas fa-magic"></i> Dinamik Bonus Kampanyaları</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped" id="bonusesTable">
                                        <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>
                                                <th>İşlemler</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="bonus-type-badge type-<?php echo $bonus['bonus_type']; ?>">
                                                        <?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']; ?>
                                                    <?php else: ?>
                                                        ₺<?php echo number_format($bonus['bonus_amount'], 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'] ? 'bg-success' : 'bg-secondary'; ?>">
                                                        <?php echo $bonus['is_active'] ? 'Aktif' : 'Pasif'; ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <div class="btn-group btn-group-sm">
                                                        <button class="btn btn-outline-primary" onclick="viewBonus(<?php echo $bonus['id']; ?>)">
                                                            <i class="fas fa-eye"></i>
                                                        </button>
                                                        <button class="btn btn-outline-warning" onclick="editBonus(<?php echo $bonus['id']; ?>)">
                                                            <i class="fas fa-edit"></i>
                                                        </button>
                                                        <button class="btn btn-outline-<?php echo $bonus['is_active'] ? 'secondary' : 'success'; ?>" 
                                                                onclick="toggleBonus(<?php echo $bonus['id']; ?>, <?php echo $bonus['is_active'] ? 'false' : 'true'; ?>)">
                                                            <i class="fas fa-<?php echo $bonus['is_active'] ? 'pause' : 'play'; ?>"></i>
                                                        </button>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Cashback Programları -->
                    <div class="tab-pane fade" id="cashback" role="tabpanel">
                        <div class="card mt-3">
                            <div class="card-header">
                                <h5><i class="fas fa-money-bill-wave"></i> Cashback Programları</h5>
                            </div>
                            <div class="card-body">
                                <?php foreach ($cashback_programs as $program): ?>
                                <div class="cashback-card">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <h5><?php echo htmlspecialchars($program['program_name']); ?></h5>
                                            <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']; ?> Cashback
                                                </span>
                                                <span class="badge bg-info">
                                                    Min: ₺<?php echo number_format($program['min_loss_amount'], 2); ?>
                                                </span>
                                                <span class="badge bg-warning">
                                                    Max: ₺<?php echo number_format($program['max_cashback_amount'], 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>
                                            <br>
                                            <div class="btn-group btn-group-sm mt-2">
                                                <button class="btn btn-outline-warning" onclick="editCashback(<?php echo $program['id']; ?>)">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button class="btn btn-outline-<?php echo $program['is_active'] ? 'secondary' : 'success'; ?>" 
                                                        onclick="toggleCashback(<?php echo $program['id']; ?>, <?php echo $program['is_active'] ? 'false' : 'true'; ?>)">
                                                    <i class="fas fa-<?php echo $program['is_active'] ? 'pause' : 'play'; ?>"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>

                    <!-- VIP Seviyeleri -->
                    <div class="tab-pane fade" id="vip" role="tabpanel">
                        <div class="card mt-3">
                            <div class="card-header">
                                <h5><i class="fas fa-crown"></i> VIP Seviyeleri</h5>
                            </div>
                            <div class="card-body">
                                <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-3">
                                                <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 $level['member_count']; ?> Üye</h6>
                                            <hr>
                                            <p><strong>Gerekli Puan:</strong> <?php echo number_format($level['required_points']); ?></p>
                                            <p><strong>Aylık Bonus:</strong> ₺<?php echo number_format($level['monthly_bonus'], 2); ?></p>
                                            <p><strong>Cashback Oranı:</strong> %<?php echo $level['cashback_percentage']; ?></p>
                                            
                                            <h6>Ayrıcalıklar:</h6>
                                            <ul class="benefit-list">
                                                <?php if ($level['free_spins_monthly'] > 0): ?>
                                                <li><i class="fas fa-check"></i> <?php echo $level['free_spins_monthly']; ?> Aylık Free Spin</li>
                                                <?php endif; ?>
                                                <?php if ($level['withdrawal_limit_multiplier'] > 1): ?>
                                                <li><i class="fas fa-check"></i> <?php echo $level['withdrawal_limit_multiplier']; ?>x Çekim Limiti</li>
                                                <?php endif; ?>
                                                <?php if ($level['priority_support']): ?>
                                                <li><i class="fas fa-check"></i> Öncelikli Destek</li>
                                                <?php endif; ?>
                                                <?php if ($level['personal_manager']): ?>
                                                <li><i class="fas fa-check"></i> Kişisel Hesap Yöneticisi</li>
                                                <?php endif; ?>
                                            </ul>
                                            
                                            <div class="text-center mt-3">
                                                <button class="btn btn-outline-warning btn-sm" onclick="editVipLevel(<?php echo $level['id']; ?>)">
                                                    <i class="fas fa-edit"></i> Düzenle
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Doğum Günü Bonusları -->
                    <div class="tab-pane fade" id="birthday" role="tabpanel">
                        <div class="card mt-3">
                            <div class="card-header">
                                <h5><i class="fas fa-birthday-cake"></i> Doğum Günü Bonus Sistemi</h5>
                            </div>
                            <div class="card-body">
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle"></i>
                                    Doğum günü bonusları otomatik olarak kullanıcıların doğum günlerinde verilir.
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <h6>Bonus Ayarları</h6>
                                        <form id="birthdayBonusSettings">
                                            <div class="mb-3">
                                                <label class="form-label">Standart Bonus Miktarı (₺)</label>
                                                <input type="number" class="form-control" name="standard_amount" value="50" step="0.01">
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label">VIP Bonus Çarpanı</label>
                                                <input type="number" class="form-control" name="vip_multiplier" value="2" step="0.1">
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label">Free Spin Sayısı</label>
                                                <input type="number" class="form-control" name="free_spins" value="25">
                                            </div>
                                            <button type="button" class="btn btn-primary" onclick="updateBirthdaySettings()">
                                                Ayarları Güncelle
                                            </button>
                                        </form>
                                    </div>
                                    <div class="col-md-6">
                                        <h6>Bu Ay Doğum Günü Olanlar</h6>
                                        <div id="birthdayUsers">
                                            <!-- Doğum günü olan kullanıcılar buraya yüklenecek -->
                                            <p class="text-muted">Yükleniyor...</p>
                                        </div>
                                    </div>
                                </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://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
    
    <script>
        $(document).ready(function() {
            $('#bonusesTable').DataTable({
                "language": {
                    "url": "//cdn.datatables.net/plug-ins/1.11.5/i18n/tr.json"
                },
                "order": [[ 0, "asc" ]]
            });
        });

        function viewBonus(id) {
            alert('Bonus detayları: ' + id);
        }

        function editBonus(id) {
            alert('Bonus düzenleme: ' + id);
        }

        function toggleBonus(id, status) {
            alert('Bonus durumu değiştiriliyor: ' + id + ' -> ' + status);
        }

        function editCashback(id) {
            alert('Cashback düzenleme: ' + id);
        }

        function toggleCashback(id, status) {
            alert('Cashback durumu değiştiriliyor: ' + id + ' -> ' + status);
        }

        function editVipLevel(id) {
            alert('VIP seviye düzenleme: ' + id);
        }

        function updateBirthdaySettings() {
            alert('Doğum günü bonus ayarları güncelleniyor...');
        }
    </script>
</body>
</html>