<?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;
    $center_id = $input['center_id'] ?? null;
    $notes = $input['notes'] ?? '';
    
    if (!$request_id || !$inspector_id) {
        throw new Exception("البيانات غير مكتملة");
    }
    
    $db->beginTransaction();
    
    // تحديث الطلب
    $query = "UPDATE inspection_requests 
              SET inspector_id = :inspector_id, 
                  center_id = :center_id, 
                  status = 'assigned',
                  notes = CONCAT(notes, '\n', :notes)
              WHERE id = :request_id";
    $stmt = $db->prepare($query);
    $stmt->execute([
        'request_id' => $request_id,
        'inspector_id' => $inspector_id,
        'center_id' => $center_id,
        'notes' => "[" . date('Y-m-d H:i:s') . "] تم تعيين الفاحص" . ($notes ? " - $notes" : "")
    ]);
    
    // تحديث حالة الفاحص
    $updateInspector = "UPDATE inspectors SET status = 'busy' WHERE id = :inspector_id";
    $inspectorStmt = $db->prepare($updateInspector);
    $inspectorStmt->execute(['inspector_id' => $inspector_id]);
    
    // إضافة إلى الجدول الزمني
    $timelineQuery = "INSERT INTO request_timeline (request_id, status, notes, created_at) 
                      VALUES (:request_id, 'assigned', :notes, NOW())";
    $timelineStmt = $db->prepare($timelineQuery);
    $timelineStmt->execute([
        'request_id' => $request_id,
        'notes' => "تم تعيين فاحص للطلب" . ($notes ? " - $notes" : "")
    ]);
    
    // إرسال إشعار للفاحص
    $inspectorNotif = "INSERT INTO notifications (user_id, type, title, message, data, created_at) 
                       SELECT i.user_id, 'new_task', 'طلب فحص جديد', :message, :data, NOW()
                       FROM inspectors i WHERE i.id = :inspector_id";
    $notifStmt = $db->prepare($inspectorNotif);
    $notifStmt->execute([
        'inspector_id' => $inspector_id,
        'message' => 'تم تعيينك لفحص جديد',
        '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()
    ]);
}
?>