<?php
// create_vehicle.php
header('Content-Type: application/json');

require_once __DIR__ . '/config/db.php';

// Получаем данные из тела запроса
$body = file_get_contents('php://input');
$data = json_decode($body, true);

// Проверяем JSON
if (!is_array($data)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Invalid JSON']);
    exit;
}

// Обязательные поля
$required = ['model', 'license_plate', 'capacity'];
foreach ($required as $field) {
    if (!isset($data[$field]) || $data[$field] === '') {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => "Missing field: $field"]);
        exit;
    }
}

$model        = trim($data['model']);
$licensePlate = trim($data['license_plate']);
$capacity     = (int) $data['capacity'];
$notes        = isset($data['notes']) ? trim($data['notes']) : null;

try {
    // Вставка нового автомобиля
    $stmt = $pdo->prepare(
        'INSERT INTO vehicles (model, license_plate, capacity, notes) 
         VALUES (:model, :license_plate, :capacity, :notes)'
    );
    $stmt->execute([
        ':model'         => $model,
        ':license_plate' => $licensePlate,
        ':capacity'      => $capacity,
        ':notes'         => $notes
    ]);

    $vehicleId = $pdo->lastInsertId();
    echo json_encode(['success' => true, 'vehicle_id' => $vehicleId]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
