<?php
// Otomatik şüpheli aktivite tespit sistemi
require_once '../config.php';

header('Content-Type: application/json; charset=utf-8');

try {
    // Son 24 saat içindeki kullanıcı aktivitelerini analiz et
    $analysis_query = "
        SELECT 
            k.id as user_id,
            k.username,
            k.email,
            COUNT(DISTINCT DATE(t.created_at)) as active_days,
            SUM(CASE WHEN t.type = 'deposit' THEN t.amount ELSE 0 END) as total_deposits,
            SUM(CASE WHEN t.type = 'withdrawal' THEN t.amount ELSE 0 END) as total_withdrawals,
            COUNT(CASE WHEN t.type = 'bet' THEN 1 END) as bet_count,
            SUM(CASE WHEN t.type = 'bet' THEN t.amount ELSE 0 END) as total_bets,
            MAX(t.created_at) as last_activity
        FROM kullanicilar k
        LEFT JOIN transactions t ON k.id = t.user_id 
        WHERE t.created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
        GROUP BY k.id, k.username, k.email
        HAVING total_deposits > 0 OR total_withdrawals > 0 OR bet_count > 0
    ";
    
    $users = $db->query($analysis_query)->fetchAll(PDO::FETCH_ASSOC);
    
    // Şüpheli aktivite kurallarını al
    $rules_query = "SELECT * FROM suspicious_activity_rules ORDER BY risk_score DESC";
    $rules = $db->query($rules_query)->fetchAll(PDO::FETCH_ASSOC);
    
    $detected_activities = [];
    $new_detections = 0;
    
    foreach ($users as $user) {
        foreach ($rules as $rule) {
            $is_suspicious = false;
            $details = [];
            
            switch ($rule['rule_name']) {
                case 'Yüksek Miktarlı Para Yatırma':
                    if ($user['total_deposits'] > 5000) {
                        $is_suspicious = true;
                        $details = [
                            'total_deposits' => $user['total_deposits'],
                            'threshold' => 5000
                        ];
                    }
                    break;
                    
                case 'Hızlı Para Çekme':
                    if ($user['total_withdrawals'] > 3000) {
                        $is_suspicious = true;
                        $details = [
                            'total_withdrawals' => $user['total_withdrawals'],
                            'threshold' => 3000
                        ];
                    }
                    break;
                    
                case 'Anormal Bahis Paterni':
                    if ($user['bet_count'] > 50 || $user['total_bets'] > 10000) {
                        $is_suspicious = true;
                        $details = [
                            'bet_count' => $user['bet_count'],
                            'total_bets' => $user['total_bets'],
                            'bet_threshold' => 50,
                            'amount_threshold' => 10000
                        ];
                    }
                    break;
                    
                case 'Gece Saatlerinde Aktivite':
                    $hour = date('H', strtotime($user['last_activity']));
                    if ($hour >= 2 && $hour <= 6) {
                        $is_suspicious = true;
                        $details = [
                            'activity_hour' => $hour,
                            'last_activity' => $user['last_activity']
                        ];
                    }
                    break;
            }
            
            if ($is_suspicious) {
                // Bu aktivite daha önce tespit edilmiş mi kontrol et
                $existing_check = "
                    SELECT id FROM detected_suspicious_activities 
                    WHERE user_id = ? AND rule_id = ? AND DATE(detected_at) = CURDATE()
                ";
                $stmt = $db->prepare($existing_check);
                $stmt->execute([$user['user_id'], $rule['id']]);
                
                if (!$stmt->fetch()) {
                    // Yeni şüpheli aktivite kaydet
                    $insert_query = "
                        INSERT INTO detected_suspicious_activities 
                        (user_id, rule_id, risk_score, risk_level, details, status, detected_at) 
                        VALUES (?, ?, ?, ?, ?, 'pending', NOW())
                    ";
                    $stmt = $db->prepare($insert_query);
                    $stmt->execute([
                        $user['user_id'],
                        $rule['id'],
                        $rule['risk_score'],
                        $rule['risk_level'],
                        json_encode($details)
                    ]);
                    
                    $detected_activities[] = [
                        'user_id' => $user['user_id'],
                        'username' => $user['username'],
                        'rule_name' => $rule['rule_name'],
                        'risk_level' => $rule['risk_level'],
                        'risk_score' => $rule['risk_score'],
                        'details' => $details
                    ];
                    
                    $new_detections++;
                }
            }
        }
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Şüpheli aktivite taraması tamamlandı',
        'new_detections' => $new_detections,
        'total_users_analyzed' => count($users),
        'detected_activities' => $detected_activities
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>