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

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Oturum açmanız gerekiyor']);
    exit;
}

$user_id = $_SESSION['user_id'];
$action = $_POST['action'] ?? $_GET['action'] ?? '';

try {
    switch ($action) {
        case 'get_user_loyalty':
            getUserLoyalty($user_id);
            break;
        case 'get_loyalty_levels':
            getLoyaltyLevels();
            break;
        case 'get_available_rewards':
            getAvailableRewards($user_id);
            break;
        case 'claim_reward':
            claimReward($user_id);
            break;
        case 'get_points_history':
            getPointsHistory($user_id);
            break;
        case 'get_reward_claims':
            getRewardClaims($user_id);
            break;
        case 'add_points':
            addPoints($user_id);
            break;
        case 'get_leaderboard':
            getLeaderboard();
            break;
        case 'get_loyalty_statistics':
            getLoyaltyStatistics($user_id);
            break;
        // Admin endpoints
        case 'admin_get_all_users':
            adminGetAllUsers();
            break;
        case 'admin_add_points':
            adminAddPoints();
            break;
        case 'admin_get_rewards':
            adminGetRewards();
            break;
        case 'admin_add_reward':
            adminAddReward();
            break;
        case 'admin_process_claim':
            adminProcessClaim();
            break;
        case 'admin_get_statistics':
            adminGetStatistics();
            break;
        default:
            echo json_encode(['success' => false, 'message' => 'Geçersiz işlem']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Bir hata oluştu: ' . $e->getMessage()]);
}

function getUserLoyalty($user_id) {
    global $db;
    
    // Kullanıcı sadakat bilgilerini al veya oluştur
    $stmt = $db->prepare("
        SELECT ul.*, ll.level_name, ll.required_points, ll.benefits, ll.multiplier, 
               ll.monthly_bonus, ll.cashback_percentage,
               (SELECT required_points FROM loyalty_levels WHERE level_number = ul.current_level + 1) as next_level_points
        FROM user_loyalty ul
        LEFT JOIN loyalty_levels ll ON ul.current_level = ll.level_number
        WHERE ul.user_id = ?
    ");
    $stmt->execute([$user_id]);
    $loyalty = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$loyalty) {
        // İlk kez gelen kullanıcı için sadakat kaydı oluştur
        $stmt = $db->prepare("INSERT INTO user_loyalty (user_id) VALUES (?)");
        $stmt->execute([$user_id]);
        
        // Tekrar al
        $stmt = $db->prepare("
            SELECT ul.*, ll.level_name, ll.required_points, ll.benefits, ll.multiplier, 
                   ll.monthly_bonus, ll.cashback_percentage,
                   (SELECT required_points FROM loyalty_levels WHERE level_number = ul.current_level + 1) as next_level_points
            FROM user_loyalty ul
            LEFT JOIN loyalty_levels ll ON ul.current_level = ll.level_number
            WHERE ul.user_id = ?
        ");
        $stmt->execute([$user_id]);
        $loyalty = $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    // Bir sonraki seviyeye kadar gereken puanı hesapla
    if ($loyalty['next_level_points']) {
        $loyalty['points_to_next_level'] = $loyalty['next_level_points'] - $loyalty['total_points'];
    } else {
        $loyalty['points_to_next_level'] = 0; // Maksimum seviyede
    }
    
    // Seviye ilerlemesi yüzdesini hesapla
    if ($loyalty['next_level_points']) {
        $current_level_points = $loyalty['required_points'];
        $progress = (($loyalty['total_points'] - $current_level_points) / ($loyalty['next_level_points'] - $current_level_points)) * 100;
        $loyalty['level_progress'] = max(0, min(100, $progress));
    } else {
        $loyalty['level_progress'] = 100;
    }
    
    echo json_encode(['success' => true, 'data' => $loyalty]);
}

function getLoyaltyLevels() {
    global $db;
    
    $stmt = $db->prepare("SELECT * FROM loyalty_levels WHERE is_active = 1 ORDER BY level_number");
    $stmt->execute();
    $levels = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($levels as &$level) {
        $level['benefits'] = json_decode($level['benefits'], true);
    }
    
    echo json_encode(['success' => true, 'data' => $levels]);
}

function getAvailableRewards($user_id) {
    global $db;
    
    // Kullanıcının mevcut seviye ve puanlarını al
    $stmt = $db->prepare("SELECT current_level, total_points FROM user_loyalty WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $user_loyalty = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user_loyalty) {
        echo json_encode(['success' => false, 'message' => 'Sadakat bilgisi bulunamadı']);
        return;
    }
    
    // Kullanıcının alabileceği ödülleri getir
    $stmt = $db->prepare("
        SELECT * FROM loyalty_rewards 
        WHERE is_active = 1 AND is_claimable = 1
        AND (required_level IS NULL OR required_level <= ?)
        AND (required_points IS NULL OR required_points <= ?)
        AND (valid_until IS NULL OR valid_until > NOW())
        ORDER BY required_points ASC
    ");
    $stmt->execute([$user_loyalty['current_level'], $user_loyalty['total_points']]);
    $rewards = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($rewards as &$reward) {
        $reward['reward_data'] = json_decode($reward['reward_data'], true);
        $reward['can_claim'] = $user_loyalty['total_points'] >= ($reward['required_points'] ?? 0);
    }
    
    echo json_encode(['success' => true, 'data' => $rewards]);
}

function claimReward($user_id) {
    global $db;
    
    $reward_id = $_POST['reward_id'] ?? 0;
    
    if (!$reward_id) {
        echo json_encode(['success' => false, 'message' => 'Ödül ID gerekli']);
        return;
    }
    
    $db->beginTransaction();
    
    try {
        // Ödül bilgilerini al
        $stmt = $db->prepare("SELECT * FROM loyalty_rewards WHERE id = ? AND is_active = 1 AND is_claimable = 1");
        $stmt->execute([$reward_id]);
        $reward = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$reward) {
            throw new Exception('Ödül bulunamadı veya talep edilemez');
        }
        
        // Kullanıcı bilgilerini al
        $stmt = $db->prepare("SELECT * FROM user_loyalty WHERE user_id = ?");
        $stmt->execute([$user_id]);
        $user_loyalty = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user_loyalty) {
            throw new Exception('Kullanıcı sadakat bilgisi bulunamadı');
        }
        
        // Gerekli kontrolleri yap
        if ($reward['required_level'] && $user_loyalty['current_level'] < $reward['required_level']) {
            throw new Exception('Bu ödül için yeterli seviyeniz yok');
        }
        
        if ($reward['required_points'] && $user_loyalty['total_points'] < $reward['required_points']) {
            throw new Exception('Bu ödül için yeterli puanınız yok');
        }
        
        // Ödül talebini kaydet
        $stmt = $db->prepare("
            INSERT INTO loyalty_reward_claims (user_id, reward_id, points_spent, claim_data) 
            VALUES (?, ?, ?, ?)
        ");
        $points_spent = $reward['required_points'] ?? 0;
        $claim_data = json_encode(['claimed_at' => date('Y-m-d H:i:s')]);
        $stmt->execute([$user_id, $reward_id, $points_spent, $claim_data]);
        
        // Puanları düş (eğer puan gerektiriyorsa)
        if ($points_spent > 0) {
            $stmt = $db->prepare("
                UPDATE user_loyalty 
                SET total_points = total_points - ?, 
                    updated_at = CURRENT_TIMESTAMP 
                WHERE user_id = ?
            ");
            $stmt->execute([$points_spent, $user_id]);
        }
        
        // Ödül tipine göre işlem yap
        if ($reward['reward_type'] == 'bonus') {
            // Bonus hesabına ekle (bonus_system.php ile entegrasyon)
            $bonus_amount = $reward['reward_value'];
            $stmt = $db->prepare("UPDATE kullanicilar SET bonus = bonus + ? WHERE id = ?");
            $stmt->execute([$bonus_amount, $user_id]);
        }
        
        $db->commit();
        echo json_encode(['success' => true, 'message' => 'Ödül başarıyla talep edildi']);
        
    } catch (Exception $e) {
        $db->rollBack();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

function getPointsHistory($user_id) {
    global $db;
    
    $page = $_GET['page'] ?? 1;
    $limit = 20;
    $offset = ($page - 1) * $limit;
    
    $stmt = $db->prepare("
        SELECT * FROM loyalty_points_history 
        WHERE user_id = ? 
        ORDER BY created_at DESC 
        LIMIT ? OFFSET ?
    ");
    $stmt->execute([$user_id, $limit, $offset]);
    $history = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Toplam kayıt sayısını al
    $stmt = $db->prepare("SELECT COUNT(*) FROM loyalty_points_history WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $total = $stmt->fetchColumn();
    
    echo json_encode([
        'success' => true, 
        'data' => $history,
        'pagination' => [
            'current_page' => $page,
            'total_pages' => ceil($total / $limit),
            'total_records' => $total
        ]
    ]);
}

function getRewardClaims($user_id) {
    global $db;
    
    $stmt = $db->prepare("
        SELECT rc.*, r.reward_name, r.reward_type, r.description
        FROM loyalty_reward_claims rc
        JOIN loyalty_rewards r ON rc.reward_id = r.id
        WHERE rc.user_id = ?
        ORDER BY rc.created_at DESC
    ");
    $stmt->execute([$user_id]);
    $claims = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($claims as &$claim) {
        $claim['claim_data'] = json_decode($claim['claim_data'], true);
    }
    
    echo json_encode(['success' => true, 'data' => $claims]);
}

function addPoints($user_id) {
    global $db;
    
    $activity_type = $_POST['activity_type'] ?? '';
    $points = intval($_POST['points'] ?? 0);
    $description = $_POST['description'] ?? '';
    $reference_id = $_POST['reference_id'] ?? null;
    
    if (!$activity_type || $points <= 0) {
        echo json_encode(['success' => false, 'message' => 'Geçersiz parametreler']);
        return;
    }
    
    $db->beginTransaction();
    
    try {
        // Aktivite bilgilerini al
        $stmt = $db->prepare("SELECT * FROM loyalty_activities WHERE activity_type = ? AND is_active = 1");
        $stmt->execute([$activity_type]);
        $activity = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Kullanıcı sadakat bilgilerini al
        $stmt = $db->prepare("SELECT ul.*, ll.multiplier FROM user_loyalty ul LEFT JOIN loyalty_levels ll ON ul.current_level = ll.level_number WHERE ul.user_id = ?");
        $stmt->execute([$user_id]);
        $user_loyalty = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user_loyalty) {
            // İlk kez puan kazanan kullanıcı için kayıt oluştur
            $stmt = $db->prepare("INSERT INTO user_loyalty (user_id) VALUES (?)");
            $stmt->execute([$user_id]);
            
            $stmt = $db->prepare("SELECT ul.*, ll.multiplier FROM user_loyalty ul LEFT JOIN loyalty_levels ll ON ul.current_level = ll.level_number WHERE ul.user_id = ?");
            $stmt->execute([$user_id]);
            $user_loyalty = $stmt->fetch(PDO::FETCH_ASSOC);
        }
        
        // Çarpan uygula
        $multiplier = 1.00;
        if ($activity && $activity['multiplier_applicable'] && $user_loyalty['multiplier']) {
            $multiplier = $user_loyalty['multiplier'];
        }
        
        $final_points = intval($points * $multiplier);
        
        // Günlük/aylık limitleri kontrol et
        if ($activity) {
            if ($activity['max_daily_points']) {
                $stmt = $db->prepare("
                    SELECT COALESCE(SUM(final_points), 0) as daily_points 
                    FROM loyalty_points_history 
                    WHERE user_id = ? AND activity_type = ? AND DATE(created_at) = CURDATE()
                ");
                $stmt->execute([$user_id, $activity_type]);
                $daily_points = $stmt->fetchColumn();
                
                if ($daily_points + $final_points > $activity['max_daily_points']) {
                    throw new Exception('Günlük puan limitini aştınız');
                }
            }
            
            if ($activity['max_monthly_points']) {
                $stmt = $db->prepare("
                    SELECT COALESCE(SUM(final_points), 0) as monthly_points 
                    FROM loyalty_points_history 
                    WHERE user_id = ? AND activity_type = ? AND YEAR(created_at) = YEAR(CURDATE()) AND MONTH(created_at) = MONTH(CURDATE())
                ");
                $stmt->execute([$user_id, $activity_type]);
                $monthly_points = $stmt->fetchColumn();
                
                if ($monthly_points + $final_points > $activity['max_monthly_points']) {
                    throw new Exception('Aylık puan limitini aştınız');
                }
            }
        }
        
        // Puan geçmişine ekle
        $stmt = $db->prepare("
            INSERT INTO loyalty_points_history (user_id, activity_type, points_earned, multiplier_applied, final_points, description, reference_id) 
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([$user_id, $activity_type, $points, $multiplier, $final_points, $description, $reference_id]);
        
        // Kullanıcı puanlarını güncelle
        $stmt = $db->prepare("
            UPDATE user_loyalty 
            SET total_points = total_points + ?, 
                current_month_points = current_month_points + ?,
                lifetime_points = lifetime_points + ?,
                updated_at = CURRENT_TIMESTAMP 
            WHERE user_id = ?
        ");
        $stmt->execute([$final_points, $final_points, $final_points, $user_id]);
        
        // Seviye kontrolü yap
        checkLevelUp($user_id);
        
        $db->commit();
        echo json_encode(['success' => true, 'message' => 'Puan başarıyla eklendi', 'points_added' => $final_points]);
        
    } catch (Exception $e) {
        $db->rollBack();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

function checkLevelUp($user_id) {
    global $db;
    
    // Kullanıcının mevcut durumunu al
    $stmt = $db->prepare("SELECT * FROM user_loyalty WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $user_loyalty = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Bir sonraki seviyeyi kontrol et
    $stmt = $db->prepare("
        SELECT * FROM loyalty_levels 
        WHERE level_number > ? AND required_points <= ? AND is_active = 1
        ORDER BY level_number DESC 
        LIMIT 1
    ");
    $stmt->execute([$user_loyalty['current_level'], $user_loyalty['total_points']]);
    $next_level = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($next_level) {
        // Seviye atla
        $stmt = $db->prepare("
            UPDATE user_loyalty 
            SET current_level = ?, last_level_up = CURRENT_TIMESTAMP 
            WHERE user_id = ?
        ");
        $stmt->execute([$next_level['level_number'], $user_id]);
        
        // Seviye atlama bonusu ver (eğer varsa)
        if ($next_level['monthly_bonus'] > 0) {
            $stmt = $db->prepare("UPDATE kullanicilar SET bonus = bonus + ? WHERE id = ?");
            $stmt->execute([$next_level['monthly_bonus'], $user_id]);
        }
    }
}

function getLeaderboard() {
    global $db;
    
    $period = $_GET['period'] ?? 'all_time'; // all_time, monthly, weekly
    
    $where_clause = '';
    if ($period == 'monthly') {
        $where_clause = 'WHERE YEAR(ul.updated_at) = YEAR(CURDATE()) AND MONTH(ul.updated_at) = MONTH(CURDATE())';
    } elseif ($period == 'weekly') {
        $where_clause = 'WHERE YEARWEEK(ul.updated_at) = YEARWEEK(CURDATE())';
    }
    
    $stmt = $db->prepare("
        SELECT ul.user_id, k.kullanici_adi, ul.total_points, ul.current_level, ll.level_name,
               ROW_NUMBER() OVER (ORDER BY ul.total_points DESC) as rank_position
        FROM user_loyalty ul
        JOIN kullanicilar k ON ul.user_id = k.id
        LEFT JOIN loyalty_levels ll ON ul.current_level = ll.level_number
        $where_clause
        ORDER BY ul.total_points DESC
        LIMIT 50
    ");
    $stmt->execute();
    $leaderboard = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode(['success' => true, 'data' => $leaderboard]);
}

function getLoyaltyStatistics($user_id) {
    global $db;
    
    // Kullanıcı istatistiklerini al veya oluştur
    $stmt = $db->prepare("SELECT * FROM loyalty_statistics WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$stats) {
        // İlk kez için istatistik kaydı oluştur
        $stmt = $db->prepare("INSERT INTO loyalty_statistics (user_id) VALUES (?)");
        $stmt->execute([$user_id]);
        
        $stmt = $db->prepare("SELECT * FROM loyalty_statistics WHERE user_id = ?");
        $stmt->execute([$user_id]);
        $stats = $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    // Bu ay kazanılan puanları al
    $stmt = $db->prepare("
        SELECT COALESCE(SUM(final_points), 0) as monthly_points 
        FROM loyalty_points_history 
        WHERE user_id = ? AND YEAR(created_at) = YEAR(CURDATE()) AND MONTH(created_at) = MONTH(CURDATE())
    ");
    $stmt->execute([$user_id]);
    $stats['monthly_points'] = $stmt->fetchColumn();
    
    // Bu hafta kazanılan puanları al
    $stmt = $db->prepare("
        SELECT COALESCE(SUM(final_points), 0) as weekly_points 
        FROM loyalty_points_history 
        WHERE user_id = ? AND YEARWEEK(created_at) = YEARWEEK(CURDATE())
    ");
    $stmt->execute([$user_id]);
    $stats['weekly_points'] = $stmt->fetchColumn();
    
    echo json_encode(['success' => true, 'data' => $stats]);
}

// Admin fonksiyonları
function adminGetAllUsers() {
    global $db;
    
    // Admin kontrolü
    if (!isset($_SESSION['admin']) || $_SESSION['admin'] != 1) {
        echo json_encode(['success' => false, 'message' => 'Yetkisiz erişim']);
        return;
    }
    
    $page = $_GET['page'] ?? 1;
    $limit = 50;
    $offset = ($page - 1) * $limit;
    $search = $_GET['search'] ?? '';
    
    $where_clause = '';
    $params = [];
    
    if ($search) {
        $where_clause = 'WHERE k.kullanici_adi LIKE ? OR k.email LIKE ?';
        $params = ["%$search%", "%$search%"];
    }
    
    $stmt = $db->prepare("
        SELECT ul.*, k.kullanici_adi, k.email, ll.level_name
        FROM user_loyalty ul
        JOIN kullanicilar k ON ul.user_id = k.id
        LEFT JOIN loyalty_levels ll ON ul.current_level = ll.level_number
        $where_clause
        ORDER BY ul.total_points DESC
        LIMIT ? OFFSET ?
    ");
    $params[] = $limit;
    $params[] = $offset;
    $stmt->execute($params);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode(['success' => true, 'data' => $users]);
}

function adminAddPoints() {
    global $db;
    
    if (!isset($_SESSION['admin']) || $_SESSION['admin'] != 1) {
        echo json_encode(['success' => false, 'message' => 'Yetkisiz erişim']);
        return;
    }
    
    $target_user_id = $_POST['user_id'] ?? 0;
    $points = intval($_POST['points'] ?? 0);
    $description = $_POST['description'] ?? 'Admin tarafından eklendi';
    
    if (!$target_user_id || $points == 0) {
        echo json_encode(['success' => false, 'message' => 'Geçersiz parametreler']);
        return;
    }
    
    $db->beginTransaction();
    
    try {
        // Puan geçmişine ekle
        $stmt = $db->prepare("
            INSERT INTO loyalty_points_history (user_id, activity_type, points_earned, multiplier_applied, final_points, description) 
            VALUES (?, 'admin_action', ?, 1.00, ?, ?)
        ");
        $stmt->execute([$target_user_id, $points, $points, $description]);
        
        // Kullanıcı puanlarını güncelle
        if ($points > 0) {
            $stmt = $db->prepare("
                UPDATE user_loyalty 
                SET total_points = total_points + ?, 
                    lifetime_points = lifetime_points + ?,
                    updated_at = CURRENT_TIMESTAMP 
                WHERE user_id = ?
            ");
            $stmt->execute([$points, $points, $target_user_id]);
        } else {
            $stmt = $db->prepare("
                UPDATE user_loyalty 
                SET total_points = GREATEST(0, total_points + ?),
                    updated_at = CURRENT_TIMESTAMP 
                WHERE user_id = ?
            ");
            $stmt->execute([$points, $target_user_id]);
        }
        
        // Seviye kontrolü
        if ($points > 0) {
            checkLevelUp($target_user_id);
        }
        
        $db->commit();
        echo json_encode(['success' => true, 'message' => 'Puan başarıyla güncellendi']);
        
    } catch (Exception $e) {
        $db->rollBack();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}

function adminGetRewards() {
    global $db;
    
    if (!isset($_SESSION['admin']) || $_SESSION['admin'] != 1) {
        echo json_encode(['success' => false, 'message' => 'Yetkisiz erişim']);
        return;
    }
    
    $stmt = $db->prepare("SELECT * FROM loyalty_rewards ORDER BY required_points ASC");
    $stmt->execute();
    $rewards = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($rewards as &$reward) {
        $reward['reward_data'] = json_decode($reward['reward_data'], true);
    }
    
    echo json_encode(['success' => true, 'data' => $rewards]);
}

function adminAddReward() {
    global $db;
    
    if (!isset($_SESSION['admin']) || $_SESSION['admin'] != 1) {
        echo json_encode(['success' => false, 'message' => 'Yetkisiz erişim']);
        return;
    }
    
    $reward_type = $_POST['reward_type'] ?? '';
    $reward_name = $_POST['reward_name'] ?? '';
    $description = $_POST['description'] ?? '';
    $required_level = $_POST['required_level'] ?? null;
    $required_points = $_POST['required_points'] ?? null;
    $reward_value = $_POST['reward_value'] ?? 0;
    $reward_data = $_POST['reward_data'] ?? '{}';
    
    if (!$reward_type || !$reward_name) {
        echo json_encode(['success' => false, 'message' => 'Ödül tipi ve adı gerekli']);
        return;
    }
    
    $stmt = $db->prepare("
        INSERT INTO loyalty_rewards (reward_type, reward_name, description, required_level, required_points, reward_value, reward_data) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([$reward_type, $reward_name, $description, $required_level, $required_points, $reward_value, $reward_data]);
    
    echo json_encode(['success' => true, 'message' => 'Ödül başarıyla eklendi']);
}

function adminProcessClaim() {
    global $db;
    
    if (!isset($_SESSION['admin']) || $_SESSION['admin'] != 1) {
        echo json_encode(['success' => false, 'message' => 'Yetkisiz erişim']);
        return;
    }
    
    $claim_id = $_POST['claim_id'] ?? 0;
    $status = $_POST['status'] ?? '';
    $admin_id = $_SESSION['user_id'];
    
    if (!$claim_id || !in_array($status, ['approved', 'delivered', 'cancelled'])) {
        echo json_encode(['success' => false, 'message' => 'Geçersiz parametreler']);
        return;
    }
    
    $stmt = $db->prepare("
        UPDATE loyalty_reward_claims 
        SET status = ?, processed_by = ?, processed_at = CURRENT_TIMESTAMP 
        WHERE id = ?
    ");
    $stmt->execute([$status, $admin_id, $claim_id]);
    
    echo json_encode(['success' => true, 'message' => 'Talep durumu güncellendi']);
}

function adminGetStatistics() {
    global $db;
    
    if (!isset($_SESSION['admin']) || $_SESSION['admin'] != 1) {
        echo json_encode(['success' => false, 'message' => 'Yetkisiz erişim']);
        return;
    }
    
    // Genel istatistikler
    $stats = [];
    
    // Toplam kullanıcı sayısı
    $stmt = $db->prepare("SELECT COUNT(*) FROM user_loyalty");
    $stmt->execute();
    $stats['total_users'] = $stmt->fetchColumn();
    
    // Seviye dağılımı
    $stmt = $db->prepare("
        SELECT ll.level_name, COUNT(ul.user_id) as user_count
        FROM loyalty_levels ll
        LEFT JOIN user_loyalty ul ON ll.level_number = ul.current_level
        GROUP BY ll.level_number, ll.level_name
        ORDER BY ll.level_number
    ");
    $stmt->execute();
    $stats['level_distribution'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Bu ay verilen toplam puan
    $stmt = $db->prepare("
        SELECT COALESCE(SUM(final_points), 0) as monthly_points 
        FROM loyalty_points_history 
        WHERE YEAR(created_at) = YEAR(CURDATE()) AND MONTH(created_at) = MONTH(CURDATE())
    ");
    $stmt->execute();
    $stats['monthly_points'] = $stmt->fetchColumn();
    
    // Bekleyen ödül talepleri
    $stmt = $db->prepare("SELECT COUNT(*) FROM loyalty_reward_claims WHERE status = 'pending'");
    $stmt->execute();
    $stats['pending_claims'] = $stmt->fetchColumn();
    
    echo json_encode(['success' => true, 'data' => $stats]);
}
?>