<?php
session_start();
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// OPTIONS request için
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once '../woohdd/config.php'; // Woohdd config dosyasını kullan
require_once '../inc/SuspiciousActivityDetector.php';

// Kullanıcı giriş kontrolü
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

$user_id = $_SESSION['user_id'];

try {
    $detector = new SuspiciousActivityDetector($pdo, $user_id, session_id());
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $input = json_decode(file_get_contents('php://input'), true);
        $action = $input['action'] ?? '';
        
        switch ($action) {
            case 'check_login':
                $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
                $alerts = [];
                
                if ($detector->checkMultipleLoginAttempts($user_id, $ip_address)) {
                    $alerts[] = 'multiple_login_attempts';
                }
                
                if ($detector->checkMultipleLocations($user_id, $ip_address)) {
                    $alerts[] = 'multiple_locations';
                }
                
                $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
                if ($detector->checkDeviceChange($user_id, $user_agent)) {
                    $alerts[] = 'device_change';
                }
                
                echo json_encode([
                    'status' => 'success',
                    'alerts' => $alerts,
                    'message' => count($alerts) > 0 ? 'Şüpheli aktivite tespit edildi' : 'Normal aktivite'
                ]);
                break;
                
            case 'check_betting':
                $alerts = [];
                
                if ($detector->checkRapidBetting($user_id)) {
                    $alerts[] = 'rapid_betting';
                }
                
                if ($detector->checkUnusualWinnings($user_id)) {
                    $alerts[] = 'unusual_winnings';
                }
                
                echo json_encode([
                    'status' => 'success',
                    'alerts' => $alerts,
                    'message' => count($alerts) > 0 ? 'Şüpheli bahis aktivitesi tespit edildi' : 'Normal bahis aktivitesi'
                ]);
                break;
                
            case 'check_transaction':
                $amount = floatval($input['amount'] ?? 0);
                $type = $input['type'] ?? ''; // 'deposit' or 'withdrawal'
                
                $alerts = [];
                
                if ($type === 'deposit' && $detector->checkLargeDeposits($user_id, $amount)) {
                    $alerts[] = 'large_deposit';
                }
                
                if ($type === 'withdrawal' && $detector->checkLargeWithdrawals($user_id, $amount)) {
                    $alerts[] = 'large_withdrawal';
                }
                
                echo json_encode([
                    'status' => 'success',
                    'alerts' => $alerts,
                    'message' => count($alerts) > 0 ? 'Şüpheli işlem tespit edildi' : 'Normal işlem'
                ]);
                break;
                
            case 'run_all_checks':
                $context = $input['context'] ?? [];
                $alerts = $detector->runAllChecks($user_id, $context);
                
                echo json_encode([
                    'status' => 'success',
                    'alerts' => $alerts,
                    'alert_count' => count($alerts),
                    'message' => count($alerts) > 0 ? 'Şüpheli aktiviteler tespit edildi' : 'Tüm kontroller normal'
                ]);
                break;
                
            default:
                http_response_code(400);
                echo json_encode(['status' => 'error', 'message' => 'Geçersiz aksiyon']);
                break;
        }
        
    } elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
        // Kullanıcının son şüpheli aktivitelerini getir
        $stmt = $pdo->prepare("
            SELECT 
                dsa.*,
                ar.rule_name,
                ar.description as rule_description
            FROM detected_suspicious_activities dsa
            LEFT JOIN alert_rules ar ON dsa.rule_id = ar.id
            WHERE dsa.user_id = ?
            ORDER BY dsa.detected_at DESC
            LIMIT 10
        ");
        $stmt->execute([$user_id]);
        $activities = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // JSON verisini decode et
        foreach ($activities as &$activity) {
            $activity['activity_data'] = json_decode($activity['activity_data'], true);
        }
        
        echo json_encode([
            'status' => 'success',
            'activities' => $activities,
            'count' => count($activities)
        ]);
    }
    
} catch (Exception $e) {
    error_log("Suspicious activity API error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'status' => 'error',
        'message' => 'Sistem hatası oluştu'
    ]);
}
?>