<?php
/**
 * طلب فحص جديد من الفاحص
 * endpoint: POST /api/inspector/request_inspection.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);

// التحقق من البيانات المطلوبة
$required = ['inspection_type', 'plate_number', 'client_name', 'car_brand', 'car_model'];
foreach ($required as $field) {
    if (empty($data[$field])) {
        http_response_code(400);
        echo json_encode(['error' => "حقل $field مطلوب"]);
        exit();
    }
}

try {
    $database = new Database();
    $db = $database->getConnection();
    $db->beginTransaction();
    
    // البحث عن العميل أو إنشائه
    $stmt = $db->prepare("SELECT id FROM clients WHERE phone = :phone");
    $stmt->execute([':phone' => $data['client_phone']]);
    $client = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$client) {
        $stmt = $db->prepare("
            INSERT INTO clients (name, phone, email, created_at) 
            VALUES (:name, :phone, :email, NOW())
        ");
        $stmt->execute([
            ':name' => $data['client_name'],
            ':phone' => $data['client_phone'],
            ':email' => $data['client_email'] ?? null
        ]);
        $clientId = $db->lastInsertId();
    } else {
        $clientId = $client['id'];
    }
    
    // إضافة السيارة
    $stmt = $db->prepare("
        INSERT INTO client_cars (client_id, brand, model, year, plate_number, color) 
        VALUES (:client_id, :brand, :model, :year, :plate_number, :color)
    ");
    $stmt->execute([
        ':client_id' => $clientId,
        ':brand' => $data['car_brand'],
        ':model' => $data['car_model'],
        ':year' => $data['car_year'] ?? null,
        ':plate_number' => $data['plate_number'],
        ':color' => $data['car_color'] ?? null
    ]);
    $carId = $db->lastInsertId();
    
    // إنشاء طلب الفحص
    $requestNumber = 'INV-' . date('Ymd') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
    
    $stmt = $db->prepare("
        INSERT INTO inspection_requests (
            request_number, inspector_id, client_id, car_id, inspection_type, 
            notes, status, created_at
        ) VALUES (
            :request_number, :inspector_id, :client_id, :car_id, :inspection_type,
            :notes, 'pending_approval', NOW()
        )
    ");
    $stmt->execute([
        ':request_number' => $requestNumber,
        ':inspector_id' => $inspectorId,
        ':client_id' => $clientId,
        ':car_id' => $carId,
        ':inspection_type' => $data['inspection_type'],
        ':notes' => $data['notes'] ?? null
    ]);
    $requestId = $db->lastInsertId();
    
    // إضافة إشعار للمشرف
    $stmt = $db->prepare("
        INSERT INTO notifications (user_id, type, title, message, related_id, created_at) 
        SELECT supervisor_id, 'new_request', 'طلب فحص جديد', 
        CONCAT('طلب فحص جديد من الفاحص للسيارة ', :plate_number),
        :request_id, NOW()
        FROM supervisor_inspectors
        WHERE inspector_id = :inspector_id
    ");
    $stmt->execute([
        ':plate_number' => $data['plate_number'],
        ':request_id' => $requestId,
        ':inspector_id' => $inspectorId
    ]);
    
    $db->commit();
    
    echo json_encode([
        'success' => true,
        'request_id' => $requestId,
        'request_number' => $requestNumber,
        'message' => 'تم إرسال طلب الفحص بنجاح'
    ]);
    
} catch (PDOException $e) {
    $db->rollBack();
    http_response_code(500);
    echo json_encode(['error' => 'خطأ في قاعدة البيانات: ' . $e->getMessage()]);
}
?>