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

require_permission('loyalty_manage');
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sadakat Programı Yönetimi - BlackBet Admin</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%);
            color: white;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 1rem;
        }
        
        .level-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            font-size: 0.875rem;
            font-weight: bold;
        }
        
        .level-bronze { background: linear-gradient(45deg, #cd7f32, #ffa500); color: white; }
        .level-silver { background: linear-gradient(45deg, #c0c0c0, #e5e5e5); color: #333; }
        .level-gold { background: linear-gradient(45deg, #ffd700, #ffed4e); color: #333; }
        .level-platinum { background: linear-gradient(45deg, #e5e4e2, #b8b8b8); color: #333; }
        .level-diamond { background: linear-gradient(45deg, #b9f2ff, #00d4ff); color: #333; }
        .level-vip { background: linear-gradient(45deg, #ff6b6b, #ee5a24); color: white; }
        
        .user-row {
            border-bottom: 1px solid #e9ecef;
            padding: 1rem 0;
        }
        
        .user-row:hover {
            background-color: #f8f9fa;
        }
        
        .reward-card {
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        
        .reward-card.active {
            border-color: #28a745;
            background-color: rgba(40, 167, 69, 0.05);
        }
        
        .reward-card.inactive {
            border-color: #dc3545;
            background-color: rgba(220, 53, 69, 0.05);
        }
        
        .chart-container {
            position: relative;
            height: 300px;
            margin: 1rem 0;
        }
    </style>
</head>
<body>
    <?php include 'topbar.php'; ?>
    <div class="container-fluid">
        <div class="row">
            <?php include 'sidebar.php'; ?>
            <main class="col-md-10 ms-sm-auto col-lg-10 px-md-4">
                        <div class="page-header">
                            <h3 class="fw-bold mb-3">Sadakat Programı Yönetimi</h3>
                            <ul class="breadcrumbs mb-3">
                                <li class="nav-home">
                                    <a href="dashboard.php"><i class="icon-home"></i></a>
                                </li>
                                <li class="separator"><i class="icon-arrow-right"></i></li>
                                <li class="nav-item"><a href="#">Yönetim</a></li>
                                <li class="separator"><i class="icon-arrow-right"></i></li>
                                <li class="nav-item">Sadakat Programı</li>
                            </ul>
                        </div>
                        
                        <!-- İstatistik Kartları -->
                        <div class="row">
                            <div class="col-md-3">
                                <div class="stats-card text-center">
                                    <h3 id="totalUsers">0</h3>
                                    <p class="mb-0">Toplam Kullanıcı</p>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stats-card text-center">
                                    <h3 id="monthlyPoints">0</h3>
                                    <p class="mb-0">Bu Ay Verilen Puan</p>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stats-card text-center">
                                    <h3 id="pendingClaims">0</h3>
                                    <p class="mb-0">Bekleyen Talep</p>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stats-card text-center">
                                    <h3 id="activeRewards">0</h3>
                                    <p class="mb-0">Aktif Ödül</p>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Navigasyon -->
                        <ul class="nav nav-pills mb-4" id="loyaltyTabs" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="overview-tab" data-bs-toggle="pill" data-bs-target="#overview" type="button" role="tab">
                                    <i class="fas fa-chart-pie"></i> Genel Bakış
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="users-tab" data-bs-toggle="pill" data-bs-target="#users" type="button" role="tab">
                                    <i class="fas fa-users"></i> Kullanıcılar
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="rewards-tab" data-bs-toggle="pill" data-bs-target="#rewards" type="button" role="tab">
                                    <i class="fas fa-gift"></i> Ödül Yönetimi
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="claims-tab" data-bs-toggle="pill" data-bs-target="#claims" type="button" role="tab">
                                    <i class="fas fa-clipboard-list"></i> Ödül Talepleri
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="levels-tab" data-bs-toggle="pill" data-bs-target="#levels" type="button" role="tab">
                                    <i class="fas fa-layer-group"></i> Seviye Yönetimi
                                </button>
                            </li>
                        </ul>
                        
                        <!-- Tab İçerikleri -->
                        <div class="tab-content" id="loyaltyTabContent">
                            <!-- Genel Bakış -->
                            <div class="tab-pane fade show active" id="overview" role="tabpanel">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="card">
                                            <div class="card-header">
                                                <h5><i class="fas fa-chart-bar"></i> Seviye Dağılımı</h5>
                                            </div>
                                            <div class="card-body">
                                                <div id="levelDistribution">
                                                    <div class="text-center py-4">
                                                        <div class="spinner-border" role="status"></div>
                                                        <p class="mt-2">Yükleniyor...</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="card">
                                            <div class="card-header">
                                                <h5><i class="fas fa-chart-line"></i> Aylık Puan Trendi</h5>
                                            </div>
                                            <div class="card-body">
                                                <div class="chart-container">
                                                    <canvas id="pointsTrendChart"></canvas>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row mt-4">
                                    <div class="col-md-12">
                                        <div class="card">
                                            <div class="card-header">
                                                <h5><i class="fas fa-trophy"></i> En Aktif Kullanıcılar</h5>
                                            </div>
                                            <div class="card-body">
                                                <div id="topUsers">
                                                    <div class="text-center py-4">
                                                        <div class="spinner-border" role="status"></div>
                                                        <p class="mt-2">Yükleniyor...</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Kullanıcılar -->
                            <div class="tab-pane fade" id="users" role="tabpanel">
                                <div class="card">
                                    <div class="card-header d-flex justify-content-between align-items-center">
                                        <h5><i class="fas fa-users"></i> Kullanıcı Yönetimi</h5>
                                        <div class="d-flex gap-2">
                                            <input type="text" class="form-control form-control-sm" id="userSearch" placeholder="Kullanıcı ara...">
                                            <button class="btn btn-primary btn-sm" onclick="searchUsers()">
                                                <i class="fas fa-search"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="card-body">
                                        <div id="usersList">
                                            <div class="text-center py-4">
                                                <div class="spinner-border" role="status"></div>
                                                <p class="mt-2">Kullanıcılar yükleniyor...</p>
                                            </div>
                                        </div>
                                        <div id="usersPagination" class="mt-3"></div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Ödül Yönetimi -->
                            <div class="tab-pane fade" id="rewards" role="tabpanel">
                                <div class="row">
                                    <div class="col-md-8">
                                        <div class="card">
                                            <div class="card-header d-flex justify-content-between align-items-center">
                                                <h5><i class="fas fa-gift"></i> Mevcut Ödüller</h5>
                                                <button class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#addRewardModal">
                                                    <i class="fas fa-plus"></i> Yeni Ödül Ekle
                                                </button>
                                            </div>
                                            <div class="card-body">
                                                <div id="rewardsList">
                                                    <div class="text-center py-4">
                                                        <div class="spinner-border" role="status"></div>
                                                        <p class="mt-2">Ödüller yükleniyor...</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="card">
                                            <div class="card-header">
                                                <h5><i class="fas fa-user-plus"></i> Kullanıcıya Puan Ver</h5>
                                            </div>
                                            <div class="card-body">
                                                <form id="addPointsForm">
                                                    <div class="mb-3">
                                                        <label class="form-label">Kullanıcı ID</label>
                                                        <input type="number" class="form-control" id="targetUserId" required>
                                                    </div>
                                                    <div class="mb-3">
                                                        <label class="form-label">Puan Miktarı</label>
                                                        <input type="number" class="form-control" id="pointsAmount" required>
                                                        <small class="text-muted">Negatif değer için eksi (-) kullanın</small>
                                                    </div>
                                                    <div class="mb-3">
                                                        <label class="form-label">Açıklama</label>
                                                        <textarea class="form-control" id="pointsDescription" rows="3"></textarea>
                                                    </div>
                                                    <button type="submit" class="btn btn-primary w-100">
                                                        <i class="fas fa-plus"></i> Puan Ekle
                                                    </button>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Ödül Talepleri -->
                            <div class="tab-pane fade" id="claims" role="tabpanel">
                                <div class="card">
                                    <div class="card-header">
                                        <h5><i class="fas fa-clipboard-list"></i> Ödül Talepleri</h5>
                                    </div>
                                    <div class="card-body">
                                        <div id="claimsList">
                                            <div class="text-center py-4">
                                                <div class="spinner-border" role="status"></div>
                                                <p class="mt-2">Talepler yükleniyor...</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Seviye Yönetimi -->
                            <div class="tab-pane fade" id="levels" role="tabpanel">
                                <div class="card">
                                    <div class="card-header">
                                        <h5><i class="fas fa-layer-group"></i> Sadakat Seviyeleri</h5>
                                    </div>
                                    <div class="card-body">
                                        <div id="levelsList">
                                            <div class="text-center py-4">
                                                <div class="spinner-border" role="status"></div>
                                                <p class="mt-2">Seviyeler yükleniyor...</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
            </main>
        </div>
    </div>
    
    <!-- Yeni Ödül Ekleme Modal -->
    <div class="modal fade" id="addRewardModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Yeni Ödül Ekle</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addRewardForm">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Ödül Tipi</label>
                                    <select class="form-select" id="rewardType" required>
                                        <option value="">Seçiniz</option>
                                        <option value="bonus">Bonus</option>
                                        <option value="cashback">Cashback</option>
                                        <option value="free_spins">Bedava Spin</option>
                                        <option value="merchandise">Hediye</option>
                                        <option value="vip_access">VIP Erişim</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Ödül Adı</label>
                                    <input type="text" class="form-control" id="rewardName" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Açıklama</label>
                            <textarea class="form-control" id="rewardDescription" rows="3"></textarea>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">Gerekli Seviye</label>
                                    <input type="number" class="form-control" id="requiredLevel" min="1" max="6">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">Gerekli Puan</label>
                                    <input type="number" class="form-control" id="requiredPoints" min="0">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">Ödül Değeri</label>
                                    <input type="number" class="form-control" id="rewardValue" step="0.01" min="0">
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Ödül Verileri (JSON)</label>
                            <textarea class="form-control" id="rewardData" rows="3" placeholder='{"key": "value"}'>{}</textarea>
                            <small class="text-muted">Ödüle özel veriler JSON formatında</small>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                    <button type="button" class="btn btn-primary" onclick="addReward()">Ödül Ekle</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        let currentUsersPage = 1;
        
        // Sayfa yüklendiğinde
        document.addEventListener('DOMContentLoaded', function() {
            loadStatistics();
            loadUsers(1);
            loadRewards();
            loadLevels();
            
            // Form submit olayları
            document.getElementById('addPointsForm').addEventListener('submit', function(e) {
                e.preventDefault();
                addPointsToUser();
            });
        });
        
        // İstatistikleri yükle
        function loadStatistics() {
            fetch('../api/loyalty_system.php?action=admin_get_statistics')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const stats = data.data;
                        
                        document.getElementById('totalUsers').textContent = stats.total_users || 0;
                        document.getElementById('monthlyPoints').textContent = (stats.monthly_points || 0).toLocaleString();
                        document.getElementById('pendingClaims').textContent = stats.pending_claims || 0;
                        
                        // Seviye dağılımını göster
                        displayLevelDistribution(stats.level_distribution);
                    }
                })
                .catch(error => console.error('İstatistikler yüklenirken hata:', error));
        }
        
        // Seviye dağılımını göster
        function displayLevelDistribution(distribution) {
            const container = document.getElementById('levelDistribution');
            
            if (!distribution || distribution.length === 0) {
                container.innerHTML = '<p class="text-muted">Veri bulunamadı</p>';
                return;
            }
            
            let html = '';
            distribution.forEach(level => {
                const percentage = level.user_count > 0 ? ((level.user_count / distribution.reduce((sum, l) => sum + l.user_count, 0)) * 100).toFixed(1) : 0;
                const levelClass = 'level-' + level.level_name.toLowerCase();
                
                html += `
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <div>
                            <span class="level-badge ${levelClass}">${level.level_name}</span>
                        </div>
                        <div class="text-end">
                            <strong>${level.user_count}</strong> kullanıcı
                            <small class="text-muted">(${percentage}%)</small>
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }
        
        // Kullanıcıları yükle
        function loadUsers(page, search = '') {
            currentUsersPage = page;
            
            let url = `../api/loyalty_system.php?action=admin_get_all_users&page=${page}`;
            if (search) {
                url += `&search=${encodeURIComponent(search)}`;
            }
            
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const container = document.getElementById('usersList');
                        
                        if (data.data.length === 0) {
                            container.innerHTML = '<p class="text-muted">Kullanıcı bulunamadı</p>';
                            return;
                        }
                        
                        let html = '';
                        data.data.forEach(user => {
                            const levelClass = 'level-' + (user.level_name || 'bronze').toLowerCase();
                            
                            html += `
                                <div class="user-row">
                                    <div class="row align-items-center">
                                        <div class="col-md-3">
                                            <h6 class="mb-1">${user.kullanici_adi}</h6>
                                            <small class="text-muted">${user.email}</small>
                                        </div>
                                        <div class="col-md-2">
                                            <span class="level-badge ${levelClass}">${user.level_name || 'Bronz'}</span>
                                        </div>
                                        <div class="col-md-2">
                                            <strong>${user.total_points}</strong> puan
                                        </div>
                                        <div class="col-md-2">
                                            <small class="text-muted">Bu ay: ${user.current_month_points || 0}</small>
                                        </div>
                                        <div class="col-md-3 text-end">
                                            <button class="btn btn-sm btn-primary" onclick="showUserDetails(${user.user_id})">
                                                <i class="fas fa-eye"></i> Detay
                                            </button>
                                            <button class="btn btn-sm btn-success" onclick="quickAddPoints(${user.user_id}, '${user.kullanici_adi}')">
                                                <i class="fas fa-plus"></i> Puan
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            `;
                        });
                        
                        container.innerHTML = html;
                    }
                })
                .catch(error => console.error('Kullanıcılar yüklenirken hata:', error));
        }
        
        // Kullanıcı ara
        function searchUsers() {
            const search = document.getElementById('userSearch').value;
            loadUsers(1, search);
        }
        
        // Hızlı puan ekleme
        function quickAddPoints(userId, username) {
            Swal.fire({
                title: `${username} kullanıcısına puan ekle`,
                html: `
                    <input type="number" id="quickPoints" class="swal2-input" placeholder="Puan miktarı" required>
                    <textarea id="quickDescription" class="swal2-textarea" placeholder="Açıklama (opsiyonel)"></textarea>
                `,
                showCancelButton: true,
                confirmButtonText: 'Puan Ekle',
                cancelButtonText: 'İptal',
                preConfirm: () => {
                    const points = document.getElementById('quickPoints').value;
                    const description = document.getElementById('quickDescription').value;
                    
                    if (!points || points == 0) {
                        Swal.showValidationMessage('Puan miktarı gerekli');
                        return false;
                    }
                    
                    return { points: parseInt(points), description: description || 'Admin tarafından eklendi' };
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    const formData = new FormData();
                    formData.append('action', 'admin_add_points');
                    formData.append('user_id', userId);
                    formData.append('points', result.value.points);
                    formData.append('description', result.value.description);
                    
                    fetch('../api/loyalty_system.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire('Başarılı!', data.message, 'success');
                            loadUsers(currentUsersPage);
                            loadStatistics();
                        } else {
                            Swal.fire('Hata!', data.message, 'error');
                        }
                    })
                    .catch(error => {
                        console.error('Puan eklenirken hata:', error);
                        Swal.fire('Hata!', 'Bir hata oluştu', 'error');
                    });
                }
            });
        }
        
        // Kullanıcıya puan ekle
        function addPointsToUser() {
            const userId = document.getElementById('targetUserId').value;
            const points = document.getElementById('pointsAmount').value;
            const description = document.getElementById('pointsDescription').value;
            
            if (!userId || !points || points == 0) {
                Swal.fire('Hata!', 'Kullanıcı ID ve puan miktarı gerekli', 'error');
                return;
            }
            
            const formData = new FormData();
            formData.append('action', 'admin_add_points');
            formData.append('user_id', userId);
            formData.append('points', points);
            formData.append('description', description || 'Admin tarafından eklendi');
            
            fetch('../api/loyalty_system.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire('Başarılı!', data.message, 'success');
                    document.getElementById('addPointsForm').reset();
                    loadUsers(currentUsersPage);
                    loadStatistics();
                } else {
                    Swal.fire('Hata!', data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Puan eklenirken hata:', error);
                Swal.fire('Hata!', 'Bir hata oluştu', 'error');
            });
        }
        
        // Ödülleri yükle
        function loadRewards() {
            fetch('../api/loyalty_system.php?action=admin_get_rewards')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const container = document.getElementById('rewardsList');
                        
                        if (data.data.length === 0) {
                            container.innerHTML = '<p class="text-muted">Henüz ödül eklenmemiş</p>';
                            return;
                        }
                        
                        let html = '';
                        let activeCount = 0;
                        
                        data.data.forEach(reward => {
                            if (reward.is_active) activeCount++;
                            
                            const cardClass = reward.is_active ? 'reward-card active' : 'reward-card inactive';
                            const statusBadge = reward.is_active ? 
                                '<span class="badge bg-success">Aktif</span>' : 
                                '<span class="badge bg-danger">Pasif</span>';
                            
                            html += `
                                <div class="${cardClass}">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <h6>${reward.reward_name} ${statusBadge}</h6>
                                            <p class="text-muted mb-2">${reward.description || 'Açıklama yok'}</p>
                                            <small class="text-info">
                                                Tip: ${getRewardTypeName(reward.reward_type)} | 
                                                ${reward.required_points ? reward.required_points + ' puan' : 'Puan yok'} |
                                                ${reward.required_level ? 'Seviye ' + reward.required_level + '+' : 'Seviye yok'}
                                            </small>
                                        </div>
                                        <div class="text-end">
                                            <div class="badge bg-${getRewardTypeColor(reward.reward_type)} mb-2">
                                                ${reward.reward_value || 0}
                                            </div>
                                            <br>
                                            <button class="btn btn-sm btn-outline-primary" onclick="editReward(${reward.id})">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            `;
                        });
                        
                        container.innerHTML = html;
                        document.getElementById('activeRewards').textContent = activeCount;
                    }
                })
                .catch(error => console.error('Ödüller yüklenirken hata:', error));
        }
        
        // Yeni ödül ekle
        function addReward() {
            const rewardType = document.getElementById('rewardType').value;
            const rewardName = document.getElementById('rewardName').value;
            const description = document.getElementById('rewardDescription').value;
            const requiredLevel = document.getElementById('requiredLevel').value;
            const requiredPoints = document.getElementById('requiredPoints').value;
            const rewardValue = document.getElementById('rewardValue').value;
            const rewardData = document.getElementById('rewardData').value;
            
            if (!rewardType || !rewardName) {
                Swal.fire('Hata!', 'Ödül tipi ve adı gerekli', 'error');
                return;
            }
            
            // JSON validasyonu
            try {
                JSON.parse(rewardData);
            } catch (e) {
                Swal.fire('Hata!', 'Geçersiz JSON formatı', 'error');
                return;
            }
            
            const formData = new FormData();
            formData.append('action', 'admin_add_reward');
            formData.append('reward_type', rewardType);
            formData.append('reward_name', rewardName);
            formData.append('description', description);
            formData.append('required_level', requiredLevel);
            formData.append('required_points', requiredPoints);
            formData.append('reward_value', rewardValue);
            formData.append('reward_data', rewardData);
            
            fetch('../api/loyalty_system.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire('Başarılı!', data.message, 'success');
                    bootstrap.Modal.getInstance(document.getElementById('addRewardModal')).hide();
                    document.getElementById('addRewardForm').reset();
                    loadRewards();
                } else {
                    Swal.fire('Hata!', data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Ödül eklenirken hata:', error);
                Swal.fire('Hata!', 'Bir hata oluştu', 'error');
            });
        }
        
        // Seviyeleri yükle
        function loadLevels() {
            fetch('../api/loyalty_system.php?action=get_loyalty_levels')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const container = document.getElementById('levelsList');
                        
                        let html = '';
                        data.data.forEach(level => {
                            const levelClass = 'level-' + level.level_name.toLowerCase();
                            
                            html += `
                                <div class="card mb-3">
                                    <div class="card-body">
                                        <div class="d-flex align-items-center justify-content-between">
                                            <div class="d-flex align-items-center">
                                                <span class="level-badge ${levelClass} me-3">${level.level_name}</span>
                                                <div>
                                                    <h6 class="mb-0">Seviye ${level.level_number}</h6>
                                                    <small class="text-muted">${level.required_points} puan gerekli</small>
                                                </div>
                                            </div>
                                            <div class="text-end">
                                                <div class="mb-1">
                                                    <small>Çarpan: <strong>${level.multiplier}x</strong></small>
                                                </div>
                                                <div class="mb-1">
                                                    <small>Cashback: <strong>%${level.cashback_percentage}</strong></small>
                                                </div>
                                                ${level.monthly_bonus > 0 ? 
                                                    `<div><small>Aylık Bonus: <strong>${level.monthly_bonus}₺</strong></small></div>` : ''
                                                }
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            `;
                        });
                        
                        container.innerHTML = html;
                    }
                })
                .catch(error => console.error('Seviyeler yüklenirken hata:', error));
        }
        
        // Yardımcı fonksiyonlar
        function getRewardTypeColor(type) {
            const colors = {
                'bonus': 'primary',
                'cashback': 'success',
                'free_spins': 'warning',
                'merchandise': 'info',
                'vip_access': 'danger'
            };
            return colors[type] || 'secondary';
        }
        
        function getRewardTypeName(type) {
            const names = {
                'bonus': 'Bonus',
                'cashback': 'Cashback',
                'free_spins': 'Bedava Spin',
                'merchandise': 'Hediye',
                'vip_access': 'VIP Erişim'
            };
            return names[type] || type;
        }
        
        // Enter tuşu ile arama
        document.getElementById('userSearch').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchUsers();
            }
        });
    </script>
</body>
</html>