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

require_once __DIR__ . '/../../database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception("فشل الاتصال بقاعدة البيانات");
    }
    
    $task_id = $_GET['id'] ?? 0;
    
    if (!$task_id) {
        throw new Exception("معرف المهمة مطلوب");
    }
    
    $query = "SELECT 
                ir.id,
                ir.request_number,
                ir.status,
                ir.created_at,
                ir.scheduled_date,
                ir.scheduled_time,
                ir.notes as request_notes,
                ir.total_price,
                CONCAT(u.first_name, ' ', u.last_name) as client_name,
                u.phone as client_phone,
                u.email as client_email,
                c.city,
                c.address as client_address,
                cc.brand,
                cc.model,
                cc.year,
                cc.plate_number,
                cc.chassis_number,
                cc.color,
                it.name as inspection_type,
                it.price,
                it.description,
                it.checkpoints as default_checkpoints,
                ic.name as center_name,
                ic.address as center_address,
                ic.phone as center_phone,
                ic.city as center_city
              FROM inspection_requests ir
              JOIN clients c ON ir.client_id = c.id
              JOIN users u ON c.user_id = u.id
              JOIN client_cars cc ON ir.car_id = cc.id
              JOIN inspection_types it ON ir.inspection_type_id = it.id
              LEFT JOIN inspection_centers ic ON ir.center_id = ic.id
              WHERE ir.id = :task_id";
    
    $stmt = $db->prepare($query);
    $stmt->execute(['task_id' => $task_id]);
    
    $task = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$task) {
        throw new Exception("المهمة غير موجودة");
    }
    
    // جلب نقاط التفتيش السابقة إذا وجدت
    $checkpointsQuery = "SELECT 
                            id,
                            checkpoint_name,
                            status,
                            notes,
                            image_urls,
                            created_at
                         FROM inspection_checkpoints
                         WHERE request_id = :task_id
                         ORDER BY id";
    $checkpointsStmt = $db->prepare($checkpointsQuery);
    $checkpointsStmt->execute(['task_id' => $task_id]);
    $checkpoints = $checkpointsStmt->fetchAll(PDO::FETCH_ASSOC);
    
    // إذا لم توجد نقاط تفتيش، نستخدم النقاط الافتراضية من نوع الفحص
    if (empty($checkpoints)) {
        $defaultCheckpoints = json_decode($task['default_checkpoints'], true) ?? [];
        foreach ($defaultCheckpoints as $index => $cp) {
            $checkpoints[] = [
                'id' => null,
                'checkpoint_name' => is_array($cp) ? $cp['name'] : $cp,
                'status' => 'pending',
                'notes' => '',
                'image_urls' => null,
                'created_at' => null
            ];
        }
    }
    
    $task['checkpoints'] = $checkpoints;
    
    echo json_encode([
        'success' => true,
        'data' => $task
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>