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

try {
    // Get latest location for each active bus
    $query = "
        SELECT b.id, b.bus_number, b.route_name, b.model, g.latitude, g.longitude, g.timestamp, g.battery_level
        FROM buses b
        LEFT JOIN (
            SELECT bus_id, latitude, longitude, timestamp, battery_level
            FROM gps_logs
            WHERE (bus_id, timestamp) IN (
                SELECT bus_id, MAX(timestamp)
                FROM gps_logs
                GROUP BY bus_id
            )
        ) g ON b.id = g.bus_id
        WHERE b.status = 'active'
    ";
    
    $stmt = $pdo->query($query);
    $locations = $stmt->fetchAll();

    echo json_encode(['success' => true, 'locations' => $locations]);

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