<?php
/**
 * Adres Doğrulama API
 * Fatura ve banka ekstresi kontrolü sistemi
 */

require_once '../inc/config.php';
require_once '../inc/functions.php';
require_once 'telegram.php';

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// CORS preflight request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

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

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

try {
    switch ($action) {
        case 'upload':
            handleDocumentUpload($user_id);
            break;
        case 'list':
            listUserDocuments($user_id);
            break;
        case 'status':
            getDocumentStatus($user_id);
            break;
        case 'delete':
            deleteDocument($user_id);
            break;
        case 'verify':
            verifyDocument($user_id);
            break;
        case 'rules':
            getVerificationRules();
            break;
        case 'stats':
            getUserStats($user_id);
            break;
        default:
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Geçersiz işlem']);
    }
} catch (Exception $e) {
    error_log("Address Verification API Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Sistem hatası oluştu']);
}

/**
 * Belge yükleme işlemi
 */
function handleDocumentUpload($user_id) {
    global $conn;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Sadece POST metodu desteklenir']);
        return;
    }
    
    // Form verilerini al
    $document_type = $_POST['document_type'] ?? '';
    $address_line1 = $_POST['address_line1'] ?? '';
    $address_line2 = $_POST['address_line2'] ?? '';
    $city = $_POST['city'] ?? '';
    $state_province = $_POST['state_province'] ?? '';
    $postal_code = $_POST['postal_code'] ?? '';
    $country = $_POST['country'] ?? 'Turkey';
    $document_date = $_POST['document_date'] ?? '';
    $document_issuer = $_POST['document_issuer'] ?? '';
    
    // Dosya kontrolü
    if (!isset($_FILES['document']) || $_FILES['document']['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['success' => false, 'message' => 'Dosya yükleme hatası']);
        return;
    }
    
    $file = $_FILES['document'];
    $allowed_types = ['application/pdf', 'image/jpeg', 'image/jpg', 'image/png'];
    $max_size = 10 * 1024 * 1024; // 10MB
    
    // Dosya türü kontrolü
    if (!in_array($file['type'], $allowed_types)) {
        echo json_encode(['success' => false, 'message' => 'Desteklenmeyen dosya türü. PDF, JPG, JPEG veya PNG dosyası yükleyiniz']);
        return;
    }
    
    // Dosya boyutu kontrolü
    if ($file['size'] > $max_size) {
        echo json_encode(['success' => false, 'message' => 'Dosya boyutu 10MB\'dan büyük olamaz']);
        return;
    }
    
    // Dosya adını güvenli hale getir
    $file_extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $safe_filename = 'address_' . $user_id . '_' . time() . '_' . uniqid() . '.' . $file_extension;
    
    // Upload dizini oluştur
    $upload_dir = '../uploads/address_verification/';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }
    
    $file_path = $upload_dir . $safe_filename;
    
    // Dosyayı kaydet
    if (!move_uploaded_file($file['tmp_name'], $file_path)) {
        echo json_encode(['success' => false, 'message' => 'Dosya kaydedilemedi']);
        return;
    }
    
    // Veritabanına kaydet
    $stmt = $conn->prepare("
        INSERT INTO address_verification_documents 
        (user_id, document_type, document_name, file_path, file_size, file_type, 
         address_line1, address_line2, city, state_province, postal_code, country, 
         document_date, document_issuer) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    
    $document_date_formatted = $document_date ? date('Y-m-d', strtotime($document_date)) : null;
    
    $stmt->bind_param("isssississssss", 
        $user_id, $document_type, $file['name'], $file_path, $file['size'], $file['type'],
        $address_line1, $address_line2, $city, $state_province, $postal_code, $country,
        $document_date_formatted, $document_issuer
    );
    
    if ($stmt->execute()) {
        $document_id = $conn->insert_id;
        
        // Otomatik kontrol başlat
        $auto_check_results = performAutoCheck($document_id, $file_path, $file['type']);
        
        // Sonuçları güncelle
        $stmt2 = $conn->prepare("UPDATE address_verification_documents SET auto_check_results = ?, confidence_score = ? WHERE id = ?");
        $auto_check_json = json_encode($auto_check_results);
        $confidence_score = $auto_check_results['overall_confidence'] ?? 0;
        $stmt2->bind_param("sdi", $auto_check_json, $confidence_score, $document_id);
        $stmt2->execute();
        
        // Kullanıcı bilgilerini al
        $user_stmt = $conn->prepare("SELECT username, email FROM kullanicilar WHERE id = ?");
        $user_stmt->bind_param("i", $user_id);
        $user_stmt->execute();
        $user_result = $user_stmt->get_result();
        $user_data = $user_result->fetch_assoc();
        
        // Telegram bildirimi gönder
        $chat = getenv('TELEGRAM_CHAT_ID') ?: '-1003194931942';
        $telegram_message = "🏠 <b>Yeni Adres Belgesi Yüklendi</b>\n\n";
        $telegram_message .= "👤 <b>Kullanıcı:</b> " . ($user_data['username'] ?? 'Bilinmiyor') . " (ID: {$user_id})\n";
        $telegram_message .= "📧 <b>E-posta:</b> " . ($user_data['email'] ?? 'Bilinmiyor') . "\n";
        $telegram_message .= "📄 <b>Belge Türü:</b> {$document_type}\n";
        $telegram_message .= "📍 <b>Adres:</b> {$address_line1}, {$city}, {$postal_code}\n";
        $telegram_message .= "🏢 <b>Belge Veren:</b> {$document_issuer}\n";
        $telegram_message .= "📅 <b>Belge Tarihi:</b> {$document_date}\n";
        $telegram_message .= "📊 <b>Güven Skoru:</b> {$confidence_score}%\n";
        $telegram_message .= "🔍 <b>Otomatik Kontrol:</b> " . ($confidence_score >= 70 ? "✅ Geçti" : "⚠️ Manuel İnceleme Gerekli") . "\n";
        $telegram_message .= "⏰ <b>Tarih:</b> " . date('d.m.Y H:i:s');
        
        // Telegram mesajını gönder (hata durumunda sessizce devam et)
        try {
            sendTelegramMessage($chat, $telegram_message, 'HTML');
        } catch (Exception $e) {
            error_log("Telegram notification failed for address verification: " . $e->getMessage());
        }
        
        echo json_encode([
            'success' => true, 
            'message' => 'Belge başarıyla yüklendi',
            'document_id' => $document_id,
            'auto_check_results' => $auto_check_results
        ]);
    } else {
        // Dosyayı sil
        unlink($file_path);
        echo json_encode(['success' => false, 'message' => 'Veritabanı hatası']);
    }
}

/**
 * Kullanıcının belgelerini listele
 */
function listUserDocuments($user_id) {
    global $conn;
    
    $stmt = $conn->prepare("
        SELECT id, document_type, document_name, status, verification_level, 
               confidence_score, uploaded_at, reviewed_at, review_notes,
               address_line1, city, postal_code, country
        FROM address_verification_documents 
        WHERE user_id = ? 
        ORDER BY uploaded_at DESC
    ");
    
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $documents = [];
    while ($row = $result->fetch_assoc()) {
        $documents[] = $row;
    }
    
    echo json_encode(['success' => true, 'documents' => $documents]);
}

/**
 * Belge durumunu getir
 */
function getDocumentStatus($user_id) {
    global $conn;
    
    $document_id = $_GET['document_id'] ?? 0;
    
    $stmt = $conn->prepare("
        SELECT id, status, verification_level, confidence_score, 
               reviewed_at, review_notes, rejection_reason, auto_check_results
        FROM address_verification_documents 
        WHERE id = ? AND user_id = ?
    ");
    
    $stmt->bind_param("ii", $document_id, $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        $row['auto_check_results'] = json_decode($row['auto_check_results'], true);
        echo json_encode(['success' => true, 'document' => $row]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Belge bulunamadı']);
    }
}

/**
 * Belge silme
 */
function deleteDocument($user_id) {
    global $conn;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'DELETE') {
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Sadece DELETE metodu desteklenir']);
        return;
    }
    
    $document_id = $_GET['document_id'] ?? 0;
    
    // Belgeyi getir
    $stmt = $conn->prepare("SELECT file_path, status FROM address_verification_documents WHERE id = ? AND user_id = ?");
    $stmt->bind_param("ii", $document_id, $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        // Onaylanmış belgeleri silmeye izin verme
        if ($row['status'] === 'approved') {
            echo json_encode(['success' => false, 'message' => 'Onaylanmış belgeler silinemez']);
            return;
        }
        
        // Dosyayı sil
        if (file_exists($row['file_path'])) {
            unlink($row['file_path']);
        }
        
        // Veritabanından sil
        $stmt2 = $conn->prepare("DELETE FROM address_verification_documents WHERE id = ? AND user_id = ?");
        $stmt2->bind_param("ii", $document_id, $user_id);
        
        if ($stmt2->execute()) {
            echo json_encode(['success' => true, 'message' => 'Belge başarıyla silindi']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Silme işlemi başarısız']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Belge bulunamadı']);
    }
}

/**
 * Manuel doğrulama (Admin)
 */
function verifyDocument($user_id) {
    global $conn;
    
    // Admin kontrolü
    if (!isAdmin($user_id)) {
        http_response_code(403);
        echo json_encode(['success' => false, 'message' => 'Yetkiniz bulunmuyor']);
        return;
    }
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Sadece POST metodu desteklenir']);
        return;
    }
    
    $document_id = $_POST['document_id'] ?? 0;
    $status = $_POST['status'] ?? '';
    $verification_level = $_POST['verification_level'] ?? 'basic';
    $review_notes = $_POST['review_notes'] ?? '';
    $rejection_reason = $_POST['rejection_reason'] ?? '';
    
    $stmt = $conn->prepare("
        UPDATE address_verification_documents 
        SET status = ?, verification_level = ?, reviewed_by = ?, reviewed_at = NOW(), 
            review_notes = ?, rejection_reason = ?
        WHERE id = ?
    ");
    
    $stmt->bind_param("ssissi", $status, $verification_level, $user_id, $review_notes, $rejection_reason, $document_id);
    
    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Doğrulama işlemi tamamlandı']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Güncelleme başarısız']);
    }
}

/**
 * Doğrulama kurallarını getir
 */
function getVerificationRules() {
    global $conn;
    
    $stmt = $conn->prepare("SELECT * FROM address_verification_rules WHERE is_active = 1 ORDER BY priority");
    $stmt->execute();
    $result = $stmt->get_result();
    
    $rules = [];
    while ($row = $result->fetch_assoc()) {
        $row['rule_config'] = json_decode($row['rule_config'], true);
        $rules[] = $row;
    }
    
    echo json_encode(['success' => true, 'rules' => $rules]);
}

/**
 * Kullanıcı istatistiklerini getir
 */
function getUserStats($user_id) {
    global $conn;
    
    $stmt = $conn->prepare("SELECT * FROM address_verification_stats WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        echo json_encode(['success' => true, 'stats' => $row]);
    } else {
        echo json_encode(['success' => true, 'stats' => [
            'total_documents_uploaded' => 0,
            'approved_documents' => 0,
            'rejected_documents' => 0,
            'pending_documents' => 0
        ]]);
    }
}

/**
 * Otomatik kontrol işlemleri
 */
function performAutoCheck($document_id, $file_path, $file_type) {
    $results = [
        'document_age_check' => false,
        'format_check' => true,
        'text_recognition' => false,
        'issuer_validation' => false,
        'overall_confidence' => 0
    ];
    
    // Format kontrolü
    $allowed_types = ['application/pdf', 'image/jpeg', 'image/jpg', 'image/png'];
    $results['format_check'] = in_array($file_type, $allowed_types);
    
    // Dosya boyutu kontrolü
    $file_size = filesize($file_path);
    $results['file_size_check'] = $file_size > 0 && $file_size <= (10 * 1024 * 1024);
    
    // Basit OCR simülasyonu (gerçek uygulamada Tesseract veya Google Vision API kullanılabilir)
    if (strpos($file_type, 'image') !== false) {
        $results['text_recognition'] = simulateOCR($file_path);
    }
    
    // Güven skoru hesaplama
    $confidence_factors = [
        $results['format_check'] ? 20 : 0,
        $results['file_size_check'] ? 20 : 0,
        $results['text_recognition'] ? 30 : 0,
        $results['issuer_validation'] ? 30 : 0
    ];
    
    $results['overall_confidence'] = array_sum($confidence_factors);
    
    return $results;
}

/**
 * OCR simülasyonu
 */
function simulateOCR($file_path) {
    // Gerçek uygulamada burada OCR kütüphanesi kullanılır
    // Şimdilik rastgele bir sonuç döndürüyoruz
    return rand(0, 1) === 1;
}

/**
 * Admin kontrolü
 */
function isAdmin($user_id) {
    global $conn;
    
    $stmt = $conn->prepare("SELECT role FROM kullanicilar WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        return $row['role'] === 'admin' || $row['role'] === 'moderator';
    }
    
    return false;
}
?>