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

if (!isset($_GET['bus_id'])) {
    echo json_encode(['success' => false, 'error' => 'Missing bus_id']);
    exit;
}

$busId = $_GET['bus_id'];

try {
    // Get latest location for the specified bus
    $query = "
        SELECT b.id, b.bus_number, b.model, g.latitude, g.longitude, g.timestamp, g.battery_level,
               d.name as driver_name, d.phone as driver_phone
        FROM buses b
        LEFT JOIN (
            SELECT bus_id, latitude, longitude, timestamp, battery_level
            FROM gps_logs
            WHERE bus_id = ?
            ORDER BY timestamp DESC
            LIMIT 1
        ) g ON b.id = g.bus_id
        LEFT JOIN drivers d ON b.id = d.bus_id
        WHERE b.id = ? AND b.status = 'active'
    ";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute([$busId, $busId]);
    $bus = $stmt->fetch();

    if ($bus) {
        echo json_encode([
            'success' => true,
            'bus' => $bus
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Bus not found']);
    }

} catch (PDOException $e) {
    echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}
?>
