<?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);
    
    $request_id = $input['request_id'] ?? 0;
    $inspector_id = $input['inspector_id'] ?? 0;
    $checkpoints = $input['checkpoints'] ?? [];
    $notes = $input['notes'] ?? '';
    
    if (!$request_id || !$inspector_id || empty($checkpoints)) {
        throw new Exception("البيانات غير مكتملة");
    }
    
    $db->beginTransaction();
    
    // حذف نقاط التفتيش القديمة
    $deleteQuery = "DELETE FROM inspection_checkpoints WHERE request_id = :request_id";
    $deleteStmt = $db->prepare($deleteQuery);
    $deleteStmt->execute(['request_id' => $request_id]);
    
    // إضافة نقاط التفتيش الجديدة
    $insertQuery = "INSERT INTO inspection_checkpoints (request_id, checkpoint_name, status, notes, created_at) 
                    VALUES (:request_id, :name, :status, :notes, NOW())";
    $insertStmt = $db->prepare($insertQuery);
    
    foreach ($checkpoints as $cp) {
        $insertStmt->execute([
            'request_id' => $request_id,
            'name' => $cp['name'],
            'status' => $cp['status'],
            'notes' => $cp['notes'] ?? ''
        ]);
    }
    
    // تحديث حالة الطلب
    $updateQuery = "UPDATE inspection_requests SET status = 'reviewed', notes = CONCAT(notes, '\n', :notes) WHERE id = :request_id";
    $updateStmt = $db->prepare($updateQuery);
    $updateStmt->execute([
        'request_id' => $request_id,
        'notes' => "[" . date('Y-m-d H:i:s') . "] تم إضافة نتائج الفحص" . ($notes ? " - $notes" : "")
    ]);
    
    // إضافة إلى الجدول الزمني
    $timelineQuery = "INSERT INTO request_timeline (request_id, status, notes, created_at) 
                      VALUES (:request_id, 'reviewed', :notes, NOW())";
    $timelineStmt = $db->prepare($timelineQuery);
    $timelineStmt->execute([
        'request_id' => $request_id,
        'notes' => "تم إضافة نتائج الفحص" . ($notes ? " - $notes" : "")
    ]);
    
    // إرسال إشعار للمشرف
    $adminNotif = "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($adminNotif);
    $notifStmt->execute([
        'message' => 'تم إضافة نتائج الفحص للطلب رقم ' . $request_id,
        'data' => json_encode(['request_id' => $request_id])
    ]);
    
    $db->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'تم إضافة نتائج الفحص بنجاح'
    ]);
    
} catch (Exception $e) {
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>