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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once '../inc/database.php';

class RiskBasedKYCAPI {
    private $db;
    
    public function __construct() {
        $this->db = new Database();
    }
    
    public function handleRequest() {
        $method = $_SERVER['REQUEST_METHOD'];
        $path = $_GET['action'] ?? '';
        
        try {
            switch ($method) {
                case 'GET':
                    $this->handleGet($path);
                    break;
                case 'POST':
                    $this->handlePost($path);
                    break;
                case 'PUT':
                    $this->handlePut($path);
                    break;
                default:
                    $this->sendResponse(['error' => 'Method not allowed'], 405);
            }
        } catch (Exception $e) {
            $this->sendResponse(['error' => $e->getMessage()], 500);
        }
    }
    
    private function handleGet($action) {
        switch ($action) {
            case 'user_risk_profile':
                $this->getUserRiskProfile();
                break;
            case 'risk_requirements':
                $this->getRiskRequirements();
                break;
            case 'risk_alerts':
                $this->getRiskAlerts();
                break;
            case 'compliance_status':
                $this->getComplianceStatus();
                break;
            case 'risk_statistics':
                $this->getRiskStatistics();
                break;
            case 'risk_history':
                $this->getRiskHistory();
                break;
            default:
                $this->sendResponse(['error' => 'Invalid action'], 400);
        }
    }
    
    private function handlePost($action) {
        switch ($action) {
            case 'assess_risk':
                $this->assessUserRisk();
                break;
            case 'create_alert':
                $this->createRiskAlert();
                break;
            case 'run_compliance_check':
                $this->runComplianceCheck();
                break;
            case 'manual_risk_override':
                $this->manualRiskOverride();
                break;
            default:
                $this->sendResponse(['error' => 'Invalid action'], 400);
        }
    }
    
    private function handlePut($action) {
        switch ($action) {
            case 'resolve_alert':
                $this->resolveAlert();
                break;
            case 'update_risk_factors':
                $this->updateRiskFactors();
                break;
            default:
                $this->sendResponse(['error' => 'Invalid action'], 400);
        }
    }
    
    // Kullanıcı risk profilini getir
    private function getUserRiskProfile() {
        $user_id = $_GET['user_id'] ?? null;
        
        if (!$user_id) {
            $this->sendResponse(['error' => 'User ID required'], 400);
            return;
        }
        
        $conn = $this->db->getConnection();
        
        // Risk profili bilgilerini getir
        $stmt = $conn->prepare("
            SELECT urp.*, 
                   COUNT(ra.id) as active_alerts,
                   (SELECT COUNT(*) FROM user_risk_history WHERE user_id = ? AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)) as recent_changes
            FROM user_risk_profiles urp
            LEFT JOIN risk_alerts ra ON urp.user_id = ra.user_id AND ra.status = 'open'
            WHERE urp.user_id = ?
            GROUP BY urp.id
        ");
        $stmt->execute([$user_id, $user_id]);
        $profile = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$profile) {
            // Eğer profil yoksa, yeni bir profil oluştur
            $this->createInitialRiskProfile($user_id);
            $stmt->execute([$user_id, $user_id]);
            $profile = $stmt->fetch(PDO::FETCH_ASSOC);
        }
        
        // Risk faktör skorlarını getir
        $stmt = $conn->prepare("
            SELECT rf.factor_name, rf.factor_category, rf.weight, 
                   urfs.score, urfs.calculated_at, urfs.data_source
            FROM user_risk_factor_scores urfs
            JOIN risk_factors rf ON urfs.risk_factor_id = rf.id
            WHERE urfs.user_id = ?
            ORDER BY urfs.calculated_at DESC
        ");
        $stmt->execute([$user_id]);
        $risk_factors = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $this->sendResponse([
            'success' => true,
            'profile' => $profile,
            'risk_factors' => $risk_factors
        ]);
    }
    
    // Risk gereksinimlerini getir
    private function getRiskRequirements() {
        $risk_level = $_GET['risk_level'] ?? 'medium';
        
        $conn = $this->db->getConnection();
        $stmt = $conn->prepare("
            SELECT * FROM risk_level_requirements 
            WHERE risk_level = ? 
            ORDER BY requirement_type, requirement_name
        ");
        $stmt->execute([$risk_level]);
        $requirements = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $this->sendResponse([
            'success' => true,
            'requirements' => $requirements,
            'risk_level' => $risk_level
        ]);
    }
    
    // Risk uyarılarını getir
    private function getRiskAlerts() {
        $user_id = $_GET['user_id'] ?? null;
        $status = $_GET['status'] ?? 'open';
        $limit = $_GET['limit'] ?? 50;
        
        $conn = $this->db->getConnection();
        
        $where_clause = "WHERE 1=1";
        $params = [];
        
        if ($user_id) {
            $where_clause .= " AND user_id = ?";
            $params[] = $user_id;
        }
        
        if ($status !== 'all') {
            $where_clause .= " AND status = ?";
            $params[] = $status;
        }
        
        $stmt = $conn->prepare("
            SELECT * FROM risk_alerts 
            $where_clause 
            ORDER BY created_at DESC 
            LIMIT ?
        ");
        $params[] = (int)$limit;
        $stmt->execute($params);
        $alerts = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $this->sendResponse([
            'success' => true,
            'alerts' => $alerts
        ]);
    }
    
    // Uygunluk durumunu getir
    private function getComplianceStatus() {
        $user_id = $_GET['user_id'] ?? null;
        
        if (!$user_id) {
            $this->sendResponse(['error' => 'User ID required'], 400);
            return;
        }
        
        $conn = $this->db->getConnection();
        
        // Son compliance kontrolleri
        $stmt = $conn->prepare("
            SELECT * FROM compliance_checks 
            WHERE user_id = ? 
            ORDER BY performed_at DESC 
            LIMIT 10
        ");
        $stmt->execute([$user_id]);
        $checks = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Genel uygunluk durumu
        $stmt = $conn->prepare("
            SELECT 
                COUNT(*) as total_checks,
                SUM(CASE WHEN check_result = 'pass' THEN 1 ELSE 0 END) as passed_checks,
                SUM(CASE WHEN check_result = 'fail' THEN 1 ELSE 0 END) as failed_checks,
                SUM(CASE WHEN check_result = 'pending' THEN 1 ELSE 0 END) as pending_checks,
                AVG(risk_impact) as avg_risk_impact
            FROM compliance_checks 
            WHERE user_id = ? AND performed_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
        ");
        $stmt->execute([$user_id]);
        $summary = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $this->sendResponse([
            'success' => true,
            'checks' => $checks,
            'summary' => $summary
        ]);
    }
    
    // Risk istatistiklerini getir
    private function getRiskStatistics() {
        $days = $_GET['days'] ?? 30;
        
        $conn = $this->db->getConnection();
        $stmt = $conn->prepare("
            SELECT * FROM risk_statistics 
            WHERE stat_date >= DATE_SUB(CURDATE(), INTERVAL ? DAY)
            ORDER BY stat_date DESC
        ");
        $stmt->execute([$days]);
        $stats = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Genel özet
        $stmt = $conn->prepare("
            SELECT 
                COUNT(*) as total_users,
                AVG(risk_score) as avg_risk_score,
                SUM(CASE WHEN risk_level = 'low' THEN 1 ELSE 0 END) as low_risk,
                SUM(CASE WHEN risk_level = 'medium' THEN 1 ELSE 0 END) as medium_risk,
                SUM(CASE WHEN risk_level = 'high' THEN 1 ELSE 0 END) as high_risk,
                SUM(CASE WHEN risk_level = 'critical' THEN 1 ELSE 0 END) as critical_risk
            FROM user_risk_profiles
        ");
        $stmt->execute();
        $summary = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $this->sendResponse([
            'success' => true,
            'statistics' => $stats,
            'summary' => $summary
        ]);
    }
    
    // Risk geçmişini getir
    private function getRiskHistory() {
        $user_id = $_GET['user_id'] ?? null;
        $limit = $_GET['limit'] ?? 20;
        
        if (!$user_id) {
            $this->sendResponse(['error' => 'User ID required'], 400);
            return;
        }
        
        $conn = $this->db->getConnection();
        $stmt = $conn->prepare("
            SELECT * FROM user_risk_history 
            WHERE user_id = ? 
            ORDER BY created_at DESC 
            LIMIT ?
        ");
        $stmt->execute([$user_id, (int)$limit]);
        $history = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $this->sendResponse([
            'success' => true,
            'history' => $history
        ]);
    }
    
    // Kullanıcı risk değerlendirmesi yap
    private function assessUserRisk() {
        $input = json_decode(file_get_contents('php://input'), true);
        $user_id = $input['user_id'] ?? null;
        $force_recalculate = $input['force_recalculate'] ?? false;
        
        if (!$user_id) {
            $this->sendResponse(['error' => 'User ID required'], 400);
            return;
        }
        
        $conn = $this->db->getConnection();
        
        // Risk faktörlerini hesapla
        $risk_score = $this->calculateRiskScore($user_id, $force_recalculate);
        $risk_level = $this->determineRiskLevel($risk_score);
        
        // Risk profilini güncelle veya oluştur
        $stmt = $conn->prepare("
            INSERT INTO user_risk_profiles (user_id, risk_level, risk_score, assessment_reason, auto_calculated)
            VALUES (?, ?, ?, ?, TRUE)
            ON DUPLICATE KEY UPDATE
                risk_level = VALUES(risk_level),
                risk_score = VALUES(risk_score),
                assessment_reason = VALUES(assessment_reason),
                last_assessment_date = CURRENT_TIMESTAMP
        ");
        
        $assessment_reason = "Otomatik risk değerlendirmesi - Skor: $risk_score";
        $stmt->execute([$user_id, $risk_level, $risk_score, $assessment_reason]);
        
        // Yüksek risk durumunda uyarı oluştur
        if (in_array($risk_level, ['high', 'critical'])) {
            $this->createAutoAlert($user_id, $risk_level, $risk_score);
        }
        
        $this->sendResponse([
            'success' => true,
            'user_id' => $user_id,
            'risk_level' => $risk_level,
            'risk_score' => $risk_score,
            'assessment_reason' => $assessment_reason
        ]);
    }
    
    // Risk uyarısı oluştur
    private function createRiskAlert() {
        $input = json_decode(file_get_contents('php://input'), true);
        
        $required_fields = ['user_id', 'alert_type', 'severity', 'title'];
        foreach ($required_fields as $field) {
            if (!isset($input[$field])) {
                $this->sendResponse(['error' => "Missing required field: $field"], 400);
                return;
            }
        }
        
        $conn = $this->db->getConnection();
        $stmt = $conn->prepare("
            INSERT INTO risk_alerts (user_id, alert_type, severity, title, description, triggered_by)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        
        $stmt->execute([
            $input['user_id'],
            $input['alert_type'],
            $input['severity'],
            $input['title'],
            $input['description'] ?? null,
            $input['triggered_by'] ?? 'manual'
        ]);
        
        $alert_id = $conn->lastInsertId();
        
        $this->sendResponse([
            'success' => true,
            'alert_id' => $alert_id,
            'message' => 'Risk uyarısı başarıyla oluşturuldu'
        ]);
    }
    
    // Uygunluk kontrolü çalıştır
    private function runComplianceCheck() {
        $input = json_decode(file_get_contents('php://input'), true);
        $user_id = $input['user_id'] ?? null;
        $check_type = $input['check_type'] ?? null;
        
        if (!$user_id || !$check_type) {
            $this->sendResponse(['error' => 'User ID and check type required'], 400);
            return;
        }
        
        $conn = $this->db->getConnection();
        
        // Compliance kontrolü simülasyonu
        $check_result = $this->performComplianceCheck($user_id, $check_type);
        
        $stmt = $conn->prepare("
            INSERT INTO compliance_checks (user_id, check_type, check_result, risk_impact, details)
            VALUES (?, ?, ?, ?, ?)
        ");
        
        $stmt->execute([
            $user_id,
            $check_type,
            $check_result['result'],
            $check_result['risk_impact'],
            json_encode($check_result['details'])
        ]);
        
        $this->sendResponse([
            'success' => true,
            'check_result' => $check_result,
            'message' => 'Uygunluk kontrolü tamamlandı'
        ]);
    }
    
    // Manuel risk geçersiz kılma
    private function manualRiskOverride() {
        $input = json_decode(file_get_contents('php://input'), true);
        
        $required_fields = ['user_id', 'new_risk_level', 'override_reason', 'admin_id'];
        foreach ($required_fields as $field) {
            if (!isset($input[$field])) {
                $this->sendResponse(['error' => "Missing required field: $field"], 400);
                return;
            }
        }
        
        $conn = $this->db->getConnection();
        
        // Mevcut risk profilini getir
        $stmt = $conn->prepare("SELECT * FROM user_risk_profiles WHERE user_id = ?");
        $stmt->execute([$input['user_id']]);
        $current_profile = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$current_profile) {
            $this->sendResponse(['error' => 'User risk profile not found'], 404);
            return;
        }
        
        // Risk profilini güncelle
        $stmt = $conn->prepare("
            UPDATE user_risk_profiles 
            SET risk_level = ?, 
                manual_override = TRUE, 
                override_reason = ?, 
                override_by = ?,
                assessment_reason = ?
            WHERE user_id = ?
        ");
        
        $assessment_reason = "Manuel geçersiz kılma: " . $input['override_reason'];
        $stmt->execute([
            $input['new_risk_level'],
            $input['override_reason'],
            $input['admin_id'],
            $assessment_reason,
            $input['user_id']
        ]);
        
        $this->sendResponse([
            'success' => true,
            'message' => 'Risk seviyesi manuel olarak güncellendi',
            'previous_level' => $current_profile['risk_level'],
            'new_level' => $input['new_risk_level']
        ]);
    }
    
    // Uyarıyı çöz
    private function resolveAlert() {
        $input = json_decode(file_get_contents('php://input'), true);
        
        $required_fields = ['alert_id', 'status', 'resolution_notes'];
        foreach ($required_fields as $field) {
            if (!isset($input[$field])) {
                $this->sendResponse(['error' => "Missing required field: $field"], 400);
                return;
            }
        }
        
        $conn = $this->db->getConnection();
        $stmt = $conn->prepare("
            UPDATE risk_alerts 
            SET status = ?, 
                resolution_notes = ?, 
                resolved_at = CURRENT_TIMESTAMP,
                assigned_to = ?
            WHERE id = ?
        ");
        
        $stmt->execute([
            $input['status'],
            $input['resolution_notes'],
            $input['assigned_to'] ?? null,
            $input['alert_id']
        ]);
        
        $this->sendResponse([
            'success' => true,
            'message' => 'Uyarı başarıyla çözüldü'
        ]);
    }
    
    // Yardımcı fonksiyonlar
    private function createInitialRiskProfile($user_id) {
        $conn = $this->db->getConnection();
        $stmt = $conn->prepare("
            INSERT INTO user_risk_profiles (user_id, risk_level, risk_score, assessment_reason)
            VALUES (?, 'medium', 50.00, 'İlk risk profili oluşturuldu')
        ");
        $stmt->execute([$user_id]);
    }
    
    private function calculateRiskScore($user_id, $force_recalculate = false) {
        $conn = $this->db->getConnection();
        
        // Risk faktörlerini getir
        $stmt = $conn->prepare("SELECT * FROM risk_factors WHERE is_active = TRUE");
        $stmt->execute();
        $risk_factors = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $total_score = 0;
        $factor_scores = [];
        
        foreach ($risk_factors as $factor) {
            $score = $this->calculateFactorScore($user_id, $factor);
            $weighted_score = $score * $factor['weight'];
            $total_score += $weighted_score;
            
            $factor_scores[] = [
                'factor_id' => $factor['id'],
                'score' => $score,
                'weighted_score' => $weighted_score
            ];
            
            // Faktör skorunu kaydet
            $stmt = $conn->prepare("
                INSERT INTO user_risk_factor_scores (user_id, risk_factor_id, score, data_source)
                VALUES (?, ?, ?, 'auto_calculation')
                ON DUPLICATE KEY UPDATE
                    score = VALUES(score),
                    calculated_at = CURRENT_TIMESTAMP
            ");
            $stmt->execute([$user_id, $factor['id'], $score]);
        }
        
        // Risk kurallarını kontrol et
        $rule_impact = $this->evaluateRiskRules($user_id);
        $total_score += $rule_impact;
        
        return min(100, max(0, $total_score)); // 0-100 arası sınırla
    }
    
    private function calculateFactorScore($user_id, $factor) {
        // Basit simülasyon - gerçek uygulamada karmaşık hesaplamalar olacak
        $base_scores = [
            'high_deposit_frequency' => rand(0, 20),
            'large_transaction_amounts' => rand(0, 25),
            'rapid_withdrawal_pattern' => rand(0, 15),
            'multiple_payment_methods' => rand(0, 10),
            'gambling_addiction_indicators' => rand(0, 30),
            'unusual_betting_patterns' => rand(0, 20),
            'account_sharing_signs' => rand(0, 25),
            'vpn_proxy_usage' => rand(0, 15),
            'multiple_device_access' => rand(0, 10),
            'high_risk_country' => rand(0, 25),
            'sanctions_list_match' => rand(0, 50),
            'age_verification_issues' => rand(0, 20),
            'income_inconsistency' => rand(0, 15),
            'document_authenticity_doubt' => rand(0, 25),
            'frequent_bonus_abuse' => rand(0, 20)
        ];
        
        return $base_scores[$factor['factor_name']] ?? rand(0, 10);
    }
    
    private function evaluateRiskRules($user_id) {
        // Risk kuralları değerlendirmesi simülasyonu
        return rand(0, 15);
    }
    
    private function determineRiskLevel($risk_score) {
        if ($risk_score >= 80) return 'critical';
        if ($risk_score >= 60) return 'high';
        if ($risk_score >= 30) return 'medium';
        return 'low';
    }
    
    private function createAutoAlert($user_id, $risk_level, $risk_score) {
        $conn = $this->db->getConnection();
        
        $severity = ($risk_level === 'critical') ? 'critical' : 'high';
        $title = "Yüksek Risk Seviyesi Tespit Edildi";
        $description = "Kullanıcı risk skoru $risk_score olarak hesaplandı ve $risk_level seviyesine yükseltildi.";
        
        $stmt = $conn->prepare("
            INSERT INTO risk_alerts (user_id, alert_type, severity, title, description, triggered_by)
            VALUES (?, 'risk_increase', ?, ?, ?, 'system')
        ");
        $stmt->execute([$user_id, $severity, $title, $description]);
    }
    
    private function performComplianceCheck($user_id, $check_type) {
        // Compliance kontrolü simülasyonu
        $results = [
            'identity_verification' => ['result' => 'pass', 'risk_impact' => 0],
            'document_authenticity' => ['result' => 'pass', 'risk_impact' => 0],
            'sanctions_screening' => ['result' => 'pass', 'risk_impact' => 0],
            'pep_screening' => ['result' => 'pass', 'risk_impact' => 0],
            'adverse_media' => ['result' => 'pass', 'risk_impact' => 0]
        ];
        
        $result = $results[$check_type] ?? ['result' => 'manual_review', 'risk_impact' => 5];
        
        return [
            'result' => $result['result'],
            'risk_impact' => $result['risk_impact'],
            'details' => [
                'check_type' => $check_type,
                'timestamp' => date('Y-m-d H:i:s'),
                'confidence' => rand(85, 99) / 100
            ]
        ];
    }
    
    private function sendResponse($data, $status_code = 200) {
        http_response_code($status_code);
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }
}

// API'yi başlat
$api = new RiskBasedKYCAPI();
$api->handleRequest();
?>