<?php
// create_trip.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 = ['client_id', 'driver_id', 'pickup_lat', 'pickup_lng', 'scheduled_time'];
foreach ($required as $field) {
    if (empty($data[$field])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => "Missing field: $field"]);
        exit;
    }
}

// Подготовка значений
$clientId      = (int) $data['client_id'];
$driverId      = (int) $data['driver_id'];
$pickupLat     = (float) $data['pickup_lat'];
$pickupLng     = (float) $data['pickup_lng'];
$scheduledTime = $data['scheduled_time']; // Должно быть в формате YYYY-MM-DDTHH:MM

// Приведение времени к формату MySQL DATETIME
$dt = date('Y-m-d H:i:s', strtotime($scheduledTime));

try {
    // Вставляем новую поездку
    $stmt = $pdo->prepare(
        'INSERT INTO trips (client_id, driver_id, pickup_lat, pickup_lng, scheduled_time) 
         VALUES (:client_id, :driver_id, :pickup_lat, :pickup_lng, :scheduled_time)'
    );
    $stmt->execute([
        ':client_id'      => $clientId,
        ':driver_id'      => $driverId,
        ':pickup_lat'     => $pickupLat,
        ':pickup_lng'     => $pickupLng,
        ':scheduled_time' => $dt
    ]);

    $tripId = $pdo->lastInsertId();

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