<?php
/**
 * إرسال نتيجة الفحص
 * endpoint: POST /api/inspector/submit_inspection_result.php
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');

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

require_once '../config/database.php';
require_once 'includes/auth.php';

$user = validateToken();
$inspectorId = $user['inspector_id'];
$data = json_decode(file_get_contents('php://input'), true);

$taskId = $data['task_id'] ?? 0;
$results = $data['results'] ?? [];
$damages = $data['damages'] ?? [];
$accuracy = $data['accuracy'] ?? 0;
$duration = $data['duration_minutes'] ?? 0;

if (!$taskId) {
    http_response_code(400);
    echo json_encode(['error' => 'معرف المهمة مطلوب']);
    exit();
}

try {
    $database = new Database();
    $db = $database->getConnection();
    $db->beginTransaction();
    
    // التحقق من المهمة
    $stmt = $db->prepare("
        SELECT * FROM inspection_requests 
        WHERE id = :id AND inspector_id = :inspector_id AND status = 'in_progress'
    ");
    $stmt->execute([
        ':id' => $taskId,
        ':inspector_id' => $inspectorId
    ]);
    $task = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$task) {
        $db->rollBack();
        http_response_code(403);
        echo json_encode(['error' => 'لا يمكن إرسال نتيجة هذا الفحص']);
        exit();
    }
    
    // إنشاء هاش للبلوكشين
    $blockchainHash = '0x' . bin2hex(random_bytes(32));
    
    // حفظ نتيجة الفحص
    $stmt = $db->prepare("
        INSERT INTO inspection_records (
            request_id, inspector_id, inspection_data, accuracy, duration_minutes, 
            blockchain_hash, status, submitted_at
        ) VALUES (
            :request_id, :inspector_id, :inspection_data, :accuracy, :duration_minutes,
            :blockchain_hash, 'submitted', NOW()
        )
    ");
    $stmt->execute([
        ':request_id' => $taskId,
        ':inspector_id' => $inspectorId,
        ':inspection_data' => json_encode(['results' => $results, 'damages' => $damages]),
        ':accuracy' => $accuracy,
        ':duration_minutes' => $duration,
        ':blockchain_hash' => $blockchainHash
    ]);
    $recordId = $db->lastInsertId();
    
    // حفظ الأضرار
    if (!empty($damages)) {
        $stmt = $db->prepare("
            INSERT INTO detected_damages (
                inspection_record_id, title, location, severity, confidence, estimated_cost
            ) VALUES (
                :record_id, :title, :location, :severity, :confidence, :cost
            )
        ");
        foreach ($damages as $damage) {
            $stmt->execute([
                ':record_id' => $recordId,
                ':title' => $damage['title'] ?? '',
                ':location' => $damage['location'] ?? '',
                ':severity' => $damage['severity'] ?? 'low',
                ':confidence' => $damage['confidence'] ?? 0,
                ':cost' => $damage['cost'] ?? 0
            ]);
        }
    }
    
    // تحديث حالة طلب الفحص
    $stmt = $db->prepare("
        UPDATE inspection_requests 
        SET status = 'completed', completed_at = NOW(), accuracy = :accuracy, duration_minutes = :duration
        WHERE id = :id
    ");
    $stmt->execute([
        ':accuracy' => $accuracy,
        ':duration' => $duration,
        ':id' => $taskId
    ]);
    
    // تحديث نقاط XP للفاحص
    $xpGain = 10;
    if ($accuracy >= 95) $xpGain += 50;
    elseif ($accuracy >= 85) $xpGain += 30;
    if ($duration < 120) $xpGain += 20;
    
    $stmt = $db->prepare("
        UPDATE inspectors 
        SET experience_points = experience_points + :xp_gain 
        WHERE id = :inspector_id
    ");
    $stmt->execute([
        ':xp_gain' => $xpGain,
        ':inspector_id' => $inspectorId
    ]);
    
    // تحديث الرتبة
    $stmt = $db->prepare("
        SELECT experience_points FROM inspectors WHERE id = :inspector_id
    ");
    $stmt->execute([':inspector_id' => $inspectorId]);
    $newXP = $stmt->fetch(PDO::FETCH_ASSOC)['experience_points'];
    
    $newRank = 'مبتدئ';
    if ($newXP >= 1500) $newRank = 'خبير';
    elseif ($newXP >= 1000) $newRank = 'متقدم';
    elseif ($newXP >= 500) $newRank = 'محترف';
    elseif ($newXP >= 200) $newRank = 'متدرب';
    
    $stmt = $db->prepare("
        UPDATE inspectors SET rank = :rank WHERE id = :inspector_id
    ");
    $stmt->execute([
        ':rank' => $newRank,
        ':inspector_id' => $inspectorId
    ]);
    
    // إضافة إشعار للمشرف
    $stmt = $db->prepare("
        INSERT INTO notifications (user_id, type, title, message, related_id, created_at) 
        SELECT supervisor_id, 'inspection_completed', 'فحص مكتمل', 
        CONCAT('تم إكمال الفحص رقم ', :request_number),
        :request_id, NOW()
        FROM supervisor_inspectors
        WHERE inspector_id = :inspector_id
    ");
    $stmt->execute([
        ':request_number' => $task['request_number'],
        ':request_id' => $taskId,
        ':inspector_id' => $inspectorId
    ]);
    
    $db->commit();
    
    echo json_encode([
        'success' => true,
        'blockchain_hash' => $blockchainHash,
        'xp_gain' => $xpGain,
        'new_rank' => $newRank,
        'message' => 'تم إرسال نتيجة الفحص وتوثيقها على البلوكشين'
    ]);
    
} catch (PDOException $e) {
    $db->rollBack();
    http_response_code(500);
    echo json_encode(['error' => 'خطأ في قاعدة البيانات: ' . $e->getMessage()]);
}
?>