<?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 '../config/database.php';
session_start();

class IncomeVerificationAPI {
    private $db;
    
    public function __construct($database) {
        $this->db = $database;
    }
    
    public function handleRequest() {
        $method = $_SERVER['REQUEST_METHOD'];
        $path = $_GET['action'] ?? '';
        
        try {
            switch ($method) {
                case 'POST':
                    return $this->handlePost($path);
                case 'GET':
                    return $this->handleGet($path);
                case 'PUT':
                    return $this->handlePut($path);
                case 'DELETE':
                    return $this->handleDelete($path);
                default:
                    return $this->error('Method not allowed', 405);
            }
        } catch (Exception $e) {
            return $this->error('Server error: ' . $e->getMessage(), 500);
        }
    }
    
    private function handlePost($action) {
        switch ($action) {
            case 'upload':
                return $this->uploadDocument();
            case 'analyze_income':
                return $this->analyzeIncome();
            case 'verify_employment':
                return $this->verifyEmployment();
            case 'manual_review':
                return $this->manualReview();
            default:
                return $this->error('Invalid action', 400);
        }
    }
    
    private function handleGet($action) {
        switch ($action) {
            case 'documents':
                return $this->getUserDocuments();
            case 'profile':
                return $this->getUserIncomeProfile();
            case 'status':
                return $this->getDocumentStatus();
            case 'rules':
                return $this->getVerificationRules();
            case 'stats':
                return $this->getUserStats();
            case 'analysis':
                return $this->getIncomeSpendingAnalysis();
            case 'admin_pending':
                return $this->getAdminPendingDocuments();
            default:
                return $this->error('Invalid action', 400);
        }
    }
    
    private function handlePut($action) {
        switch ($action) {
            case 'approve':
                return $this->approveDocument();
            case 'reject':
                return $this->rejectDocument();
            case 'update_profile':
                return $this->updateIncomeProfile();
            default:
                return $this->error('Invalid action', 400);
        }
    }
    
    private function handleDelete($action) {
        switch ($action) {
            case 'document':
                return $this->deleteDocument();
            default:
                return $this->error('Invalid action', 400);
        }
    }
    
    private function uploadDocument() {
        if (!isset($_SESSION['user_id'])) {
            return $this->error('Unauthorized', 401);
        }
        
        $user_id = $_SESSION['user_id'];
        
        // Form verilerini al
        $document_type = $_POST['document_type'] ?? '';
        $monthly_income = $_POST['monthly_income'] ?? null;
        $annual_income = $_POST['annual_income'] ?? null;
        $income_currency = $_POST['income_currency'] ?? 'TRY';
        $income_source = $_POST['income_source'] ?? '';
        $employment_status = $_POST['employment_status'] ?? 'employed';
        $employer_name = $_POST['employer_name'] ?? '';
        $document_date = $_POST['document_date'] ?? '';
        $document_period_start = $_POST['document_period_start'] ?? null;
        $document_period_end = $_POST['document_period_end'] ?? null;
        $document_issuer = $_POST['document_issuer'] ?? '';
        
        // Dosya kontrolü
        if (!isset($_FILES['document']) || $_FILES['document']['error'] !== UPLOAD_ERR_OK) {
            return $this->error('Dosya yükleme hatası', 400);
        }
        
        $file = $_FILES['document'];
        $allowed_types = ['application/pdf', 'image/jpeg', 'image/jpg', 'image/png'];
        $max_size = 10 * 1024 * 1024; // 10MB
        
        if (!in_array($file['type'], $allowed_types)) {
            return $this->error('Geçersiz dosya türü. Sadece PDF, JPG, PNG dosyaları kabul edilir.', 400);
        }
        
        if ($file['size'] > $max_size) {
            return $this->error('Dosya boyutu çok büyük. Maksimum 10MB olmalıdır.', 400);
        }
        
        // Dosyayı kaydet
        $upload_dir = '../uploads/income_verification/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }
        
        $file_extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = 'income_' . $user_id . '_' . time() . '_' . uniqid() . '.' . $file_extension;
        $file_path = $upload_dir . $filename;
        
        if (!move_uploaded_file($file['tmp_name'], $file_path)) {
            return $this->error('Dosya kaydetme hatası', 500);
        }
        
        // Otomatik kontroller
        $auto_check_results = $this->performAutoChecks($file_path, $document_type, $monthly_income);
        
        // Veritabanına kaydet
        $sql = "INSERT INTO income_verification_documents (
            user_id, document_type, document_name, file_path, file_size, file_type,
            monthly_income, annual_income, income_currency, income_source, 
            employment_status, employer_name, document_date, document_period_start, 
            document_period_end, document_issuer, auto_check_results, 
            confidence_score, risk_score
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute([
            $user_id, $document_type, $file['name'], $file_path, $file['size'], $file['type'],
            $monthly_income, $annual_income, $income_currency, $income_source,
            $employment_status, $employer_name, $document_date, $document_period_start,
            $document_period_end, $document_issuer, json_encode($auto_check_results),
            $auto_check_results['confidence_score'], $auto_check_results['risk_score']
        ]);
        
        $document_id = $this->db->lastInsertId();
        
        // Risk değerlendirmesi yap
        $this->performRiskAssessment($user_id);
        
        return $this->success([
            'document_id' => $document_id,
            'status' => 'uploaded',
            'auto_check_results' => $auto_check_results,
            'message' => 'Gelir belgesi başarıyla yüklendi ve otomatik kontroller tamamlandı.'
        ]);
    }
    
    private function performAutoChecks($file_path, $document_type, $monthly_income) {
        $results = [
            'file_format_valid' => true,
            'file_readable' => true,
            'document_quality' => 'good',
            'text_extraction_success' => true,
            'income_amount_detected' => false,
            'date_detected' => false,
            'issuer_detected' => false,
            'consistency_check' => 'passed',
            'confidence_score' => 0.0,
            'risk_score' => 0.0,
            'warnings' => [],
            'extracted_data' => []
        ];
        
        // Dosya formatı kontrolü
        $file_info = pathinfo($file_path);
        $extension = strtolower($file_info['extension']);
        
        if (!in_array($extension, ['pdf', 'jpg', 'jpeg', 'png'])) {
            $results['file_format_valid'] = false;
            $results['warnings'][] = 'Desteklenmeyen dosya formatı';
        }
        
        // Dosya boyutu ve kalite kontrolü
        $file_size = filesize($file_path);
        if ($file_size < 50000) { // 50KB'den küçükse
            $results['document_quality'] = 'low';
            $results['warnings'][] = 'Belge kalitesi düşük olabilir';
        }
        
        // Simüle edilmiş OCR ve metin çıkarma
        $extracted_text = $this->simulateOCR($file_path, $document_type);
        $results['extracted_data'] = $extracted_text;
        
        // Gelir miktarı tespiti
        if ($monthly_income && $monthly_income > 0) {
            $results['income_amount_detected'] = true;
            $results['extracted_data']['detected_income'] = $monthly_income;
            
            // Gelir tutarlılık kontrolü
            if ($monthly_income < 3000) {
                $results['warnings'][] = 'Düşük gelir miktarı tespit edildi';
                $results['risk_score'] += 20;
            } elseif ($monthly_income > 50000) {
                $results['warnings'][] = 'Yüksek gelir miktarı - ek doğrulama gerekebilir';
                $results['risk_score'] += 10;
            }
        }
        
        // Tarih tespiti (simüle)
        $current_date = new DateTime();
        $document_age_months = rand(1, 12); // Simüle edilmiş belge yaşı
        
        if ($document_age_months <= 3) {
            $results['date_detected'] = true;
            $results['extracted_data']['document_age'] = $document_age_months . ' ay';
        } else {
            $results['warnings'][] = 'Belge tarihi eski olabilir';
            $results['risk_score'] += 15;
        }
        
        // İhraççı tespiti
        $known_issuers = ['SGK', 'Maliye Bakanlığı', 'İş Bankası', 'Garanti BBVA', 'Yapı Kredi', 'Akbank'];
        $detected_issuer = $known_issuers[array_rand($known_issuers)];
        $results['issuer_detected'] = true;
        $results['extracted_data']['detected_issuer'] = $detected_issuer;
        
        // Güven skoru hesaplama
        $confidence_factors = [
            'file_format_valid' => $results['file_format_valid'] ? 20 : 0,
            'income_detected' => $results['income_amount_detected'] ? 25 : 0,
            'date_detected' => $results['date_detected'] ? 20 : 0,
            'issuer_detected' => $results['issuer_detected'] ? 15 : 0,
            'quality_good' => ($results['document_quality'] === 'good') ? 20 : 10
        ];
        
        $results['confidence_score'] = array_sum($confidence_factors);
        
        // Risk skoru normalize et (0-100 arası)
        $results['risk_score'] = min(100, max(0, $results['risk_score']));
        
        return $results;
    }
    
    private function simulateOCR($file_path, $document_type) {
        // Gerçek OCR yerine simüle edilmiş veri döndür
        $extracted_data = [
            'document_type' => $document_type,
            'processing_method' => 'simulated_ocr',
            'text_confidence' => rand(70, 95),
            'detected_fields' => []
        ];
        
        switch ($document_type) {
            case 'salary_slip':
                $extracted_data['detected_fields'] = [
                    'gross_salary' => rand(5000, 25000),
                    'net_salary' => rand(4000, 20000),
                    'employer' => 'ABC Şirketi',
                    'employee_name' => 'Simüle Edilmiş İsim',
                    'pay_period' => date('Y-m', strtotime('-1 month'))
                ];
                break;
            case 'bank_statement':
                $extracted_data['detected_fields'] = [
                    'account_holder' => 'Simüle Edilmiş İsim',
                    'bank_name' => 'Örnek Bankası',
                    'statement_period' => date('Y-m', strtotime('-1 month')),
                    'average_balance' => rand(10000, 100000),
                    'income_transactions' => rand(2, 8)
                ];
                break;
            case 'tax_return':
                $extracted_data['detected_fields'] = [
                    'tax_year' => date('Y', strtotime('-1 year')),
                    'total_income' => rand(60000, 300000),
                    'tax_paid' => rand(10000, 60000),
                    'taxpayer_name' => 'Simüle Edilmiş İsim'
                ];
                break;
        }
        
        return $extracted_data;
    }
    
    private function performRiskAssessment($user_id) {
        // Kullanıcının toplam gelir ve harcama verilerini analiz et
        $sql = "SELECT 
            SUM(CASE WHEN status = 'approved' THEN monthly_income ELSE 0 END) as total_verified_income,
            COUNT(*) as total_documents,
            AVG(confidence_score) as avg_confidence,
            AVG(risk_score) as avg_risk
        FROM income_verification_documents 
        WHERE user_id = ?";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$user_id]);
        $income_data = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Bahis verilerini al (son 6 ay)
        $sql = "SELECT 
            COALESCE(SUM(amount), 0) as total_deposits,
            COALESCE(SUM(CASE WHEN type = 'withdrawal' THEN amount ELSE 0 END), 0) as total_withdrawals
        FROM transactions 
        WHERE user_id = ? AND created_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH)";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$user_id]);
        $gambling_data = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Risk seviyesi hesapla
        $risk_level = 'low';
        $risk_factors = [];
        
        if ($income_data['total_verified_income'] > 0 && $gambling_data['total_deposits'] > 0) {
            $gambling_income_ratio = $gambling_data['total_deposits'] / ($income_data['total_verified_income'] * 6);
            
            if ($gambling_income_ratio > 0.5) {
                $risk_level = 'critical';
                $risk_factors[] = 'Bahis harcaması gelirin %50\'sini aşıyor';
            } elseif ($gambling_income_ratio > 0.3) {
                $risk_level = 'high';
                $risk_factors[] = 'Bahis harcaması gelirin %30\'unu aşıyor';
            } elseif ($gambling_income_ratio > 0.15) {
                $risk_level = 'medium';
                $risk_factors[] = 'Bahis harcaması gelirin %15\'ini aşıyor';
            }
        }
        
        // Profili güncelle
        $sql = "UPDATE user_income_profile SET 
            income_risk_level = ?,
            spending_income_ratio = ?,
            updated_at = NOW()
        WHERE user_id = ?";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute([
            $risk_level,
            $gambling_data['total_deposits'] > 0 && $income_data['total_verified_income'] > 0 
                ? $gambling_data['total_deposits'] / ($income_data['total_verified_income'] * 6) 
                : 0,
            $user_id
        ]);
        
        return [
            'risk_level' => $risk_level,
            'risk_factors' => $risk_factors,
            'gambling_income_ratio' => $gambling_data['total_deposits'] > 0 && $income_data['total_verified_income'] > 0 
                ? $gambling_data['total_deposits'] / ($income_data['total_verified_income'] * 6) 
                : 0
        ];
    }
    
    private function getUserDocuments() {
        if (!isset($_SESSION['user_id'])) {
            return $this->error('Unauthorized', 401);
        }
        
        $user_id = $_SESSION['user_id'];
        
        $sql = "SELECT 
            id, document_type, document_name, file_size, 
            monthly_income, annual_income, income_currency,
            employment_status, employer_name, document_date,
            status, confidence_score, risk_score, uploaded_at,
            reviewed_at, review_notes, rejection_reason
        FROM income_verification_documents 
        WHERE user_id = ? 
        ORDER BY uploaded_at DESC";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$user_id]);
        $documents = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        return $this->success($documents);
    }
    
    private function getUserIncomeProfile() {
        if (!isset($_SESSION['user_id'])) {
            return $this->error('Unauthorized', 401);
        }
        
        $user_id = $_SESSION['user_id'];
        
        $sql = "SELECT * FROM user_income_profile WHERE user_id = ?";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$user_id]);
        $profile = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$profile) {
            return $this->success([
                'user_id' => $user_id,
                'income_verification_status' => 'unverified',
                'message' => 'Henüz gelir profili oluşturulmamış'
            ]);
        }
        
        return $this->success($profile);
    }
    
    private function getDocumentStatus() {
        if (!isset($_GET['document_id'])) {
            return $this->error('Document ID required', 400);
        }
        
        if (!isset($_SESSION['user_id'])) {
            return $this->error('Unauthorized', 401);
        }
        
        $document_id = $_GET['document_id'];
        $user_id = $_SESSION['user_id'];
        
        $sql = "SELECT 
            id, status, confidence_score, risk_score, 
            auto_check_results, reviewed_at, review_notes, 
            rejection_reason, additional_requirements
        FROM income_verification_documents 
        WHERE id = ? AND user_id = ?";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$document_id, $user_id]);
        $document = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$document) {
            return $this->error('Document not found', 404);
        }
        
        return $this->success($document);
    }
    
    private function manualReview() {
        // Admin yetkisi kontrolü (basit kontrol)
        if (!isset($_SESSION['user_id']) || !isset($_SESSION['is_admin'])) {
            return $this->error('Admin authorization required', 403);
        }
        
        $input = json_decode(file_get_contents('php://input'), true);
        $document_id = $input['document_id'] ?? '';
        $action = $input['action'] ?? ''; // 'approve' or 'reject'
        $notes = $input['notes'] ?? '';
        $rejection_reason = $input['rejection_reason'] ?? '';
        
        if (!$document_id || !in_array($action, ['approve', 'reject'])) {
            return $this->error('Invalid parameters', 400);
        }
        
        $new_status = $action === 'approve' ? 'approved' : 'rejected';
        $reviewer_id = $_SESSION['user_id'];
        
        $sql = "UPDATE income_verification_documents SET 
            status = ?, reviewed_by = ?, reviewed_at = NOW(), 
            review_notes = ?, rejection_reason = ?
        WHERE id = ?";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$new_status, $reviewer_id, $notes, $rejection_reason, $document_id]);
        
        return $this->success([
            'document_id' => $document_id,
            'new_status' => $new_status,
            'message' => $action === 'approve' ? 'Belge onaylandı' : 'Belge reddedildi'
        ]);
    }
    
    private function getVerificationRules() {
        $sql = "SELECT * FROM income_verification_rules WHERE is_active = 1 ORDER BY priority";
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $rules = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        return $this->success($rules);
    }
    
    private function getUserStats() {
        if (!isset($_SESSION['user_id'])) {
            return $this->error('Unauthorized', 401);
        }
        
        $user_id = $_SESSION['user_id'];
        
        $sql = "SELECT * FROM income_verification_stats WHERE user_id = ?";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$user_id]);
        $stats = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$stats) {
            return $this->success([
                'user_id' => $user_id,
                'total_documents_uploaded' => 0,
                'approved_documents' => 0,
                'rejected_documents' => 0,
                'pending_documents' => 0
            ]);
        }
        
        return $this->success($stats);
    }
    
    private function success($data, $code = 200) {
        http_response_code($code);
        return json_encode([
            'success' => true,
            'data' => $data,
            'timestamp' => date('Y-m-d H:i:s')
        ]);
    }
    
    private function error($message, $code = 400) {
        http_response_code($code);
        return json_encode([
            'success' => false,
            'error' => $message,
            'timestamp' => date('Y-m-d H:i:s')
        ]);
    }
}

// API'yi başlat
try {
    $database = new PDO("mysql:host=localhost;dbname=your_database", "username", "password");
    $database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $api = new IncomeVerificationAPI($database);
    echo $api->handleRequest();
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Database connection failed',
        'timestamp' => date('Y-m-d H:i:s')
    ]);
}
?>