<?php
// get_trip.php
header('Content-Type: application/json');
require_once __DIR__ . '/config/db.php';

// Получаем trip_id из GET
if (!isset($_GET['trip_id']) || !is_numeric($_GET['trip_id'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Missing or invalid trip_id']);
    exit;
}
$tripId = (int)$_GET['trip_id'];

try {
    // 1. Получаем данные поездки
    $stmt = $pdo->prepare(
        'SELECT id, client_id, driver_id, vehicle_id, pickup_lat, pickup_lng,
                scheduled_time, status, language_from, language_to, notes, created_at, updated_at
         FROM trips
         WHERE id = :trip_id'
    );
    $stmt->execute([':trip_id' => $tripId]);
    $trip = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$trip) {
        http_response_code(404);
        echo json_encode(['success' => false, 'error' => 'Trip not found']);
        exit;
    }

    // 2. Получаем последнюю позицию водителя
    $stmt = $pdo->prepare(
        'SELECT lat, lng, timestamp
         FROM positions
         WHERE trip_id = :trip_id
         ORDER BY timestamp DESC
         LIMIT 1'
    );
    $stmt->execute([':trip_id' => $tripId]);
    $position = $stmt->fetch(PDO::FETCH_ASSOC);

    echo json_encode([
        'success' => true,
        'trip'    => $trip,
        'position'=> $position ?: null
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
