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

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception("فشل الاتصال بقاعدة البيانات");
    }
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    $task_id = $input['task_id'] ?? 0;
    $inspector_id = $input['inspector_id'] ?? 0;
    $checkpoints = $input['checkpoints'] ?? [];
    $notes = $input['notes'] ?? '';
    $status = $input['status'] ?? 'reviewed'; // reviewed or completed
    
    if (!$task_id || !$inspector_id || empty($checkpoints)) {
        throw new Exception("البيانات غير مكتملة");
    }
    
    $db->beginTransaction();
    
    // حذف نقاط التفتيش القديمة
    $deleteQuery = "DELETE FROM inspection_checkpoints WHERE request_id = :task_id";
    $deleteStmt = $db->prepare($deleteQuery);
    $deleteStmt->execute(['task_id' => $task_id]);
    
    // إضافة نقاط التفتيش الجديدة
    $insertQuery = "INSERT INTO inspection_checkpoints 
                    (request_id, checkpoint_name, status, notes, image_urls, created_at) 
                    VALUES (:request_id, :name, :status, :notes, :image_urls, NOW())";
    $insertStmt = $db->prepare($insertQuery);
    
    $passCount = 0;
    $failCount = 0;
    $warningCount = 0;
    
    foreach ($checkpoints as $cp) {
        $insertStmt->execute([
            'request_id' => $task_id,
            'name' => $cp['name'],
            'status' => $cp['status'],
            'notes' => $cp['notes'] ?? '',
            'image_urls' => isset($cp['images']) ? json_encode($cp['images']) : null
        ]);
        
        // حساب الإحصائيات
        if ($cp['status'] === 'pass') $passCount++;
        else if ($cp['status'] === 'fail') $failCount++;
        else if ($cp['status'] === 'warning') $warningCount++;
    }
    
    // تحديث حالة الطلب
    $updateQuery = "UPDATE inspection_requests 
                    SET status = :status,
                        completed_at = " . ($status === 'completed' ? 'NOW()' : 'NULL') . ",
                        notes = CONCAT(notes, '\n', :notes)
                    WHERE id = :task_id AND inspector_id = :inspector_id";
    $updateStmt = $db->prepare($updateQuery);
    $updateStmt->execute([
        'task_id' => $task_id,
        'inspector_id' => $inspector_id,
        'status' => $status,
        'notes' => "[" . date('Y-m-d H:i:s') . "] تم إضافة نتائج الفحص. ناجح: $passCount, راسب: $failCount, تحذير: $warningCount"
    ]);
    
    // إضافة إلى الجدول الزمني
    $timelineQuery = "INSERT INTO request_timeline (request_id, status, notes, created_at) 
                      VALUES (:task_id, :status, :timeline_notes, NOW())";
    $timelineStmt = $db->prepare($timelineQuery);
    $timelineStmt->execute([
        'task_id' => $task_id,
        'status' => $status,
        'timeline_notes' => "تم إضافة نتائج الفحص. ناجح: $passCount, راسب: $failCount, تحذير: $warningCount"
    ]);
    
    // إشعار للمشرف
    $notifQuery = "INSERT INTO notifications (user_id, type, title, message, data, created_at) 
                   SELECT id, 'inspection_complete', 'اكتمال الفحص', :message, :data, NOW()
                   FROM users WHERE role IN ('admin', 'supervisor')";
    $notifStmt = $db->prepare($notifQuery);
    $notifStmt->execute([
        'message' => 'تم إضافة نتائج الفحص للمهمة رقم ' . $task_id,
        'data' => json_encode([
            'task_id' => $task_id,
            'pass_count' => $passCount,
            'fail_count' => $failCount,
            'warning_count' => $warningCount
        ])
    ]);
    
    $db->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'تم حفظ نتائج الفحص بنجاح',
        'stats' => [
            'pass' => $passCount,
            'fail' => $failCount,
            'warning' => $warningCount
        ]
    ]);
    
} catch (Exception $e) {
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>