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

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

$studentId = $_GET['student_id'];

try {
    // Get student pickup location and bus ID
    $stmt = $pdo->prepare("SELECT s.latitude as student_lat, s.longitude as student_lon, s.bus_id, b.bus_number 
                           FROM students s 
                           LEFT JOIN buses b ON s.bus_id = b.id 
                           WHERE s.id = ?");
    $stmt->execute([$studentId]);
    $student = $stmt->fetch();

    if (!$student || !$student['bus_id']) {
        echo json_encode(['success' => false, 'error' => 'Student or Bus not found']);
        exit;
    }

    if (!$student['student_lat'] || !$student['student_lon']) {
        echo json_encode(['success' => false, 'error' => 'Student pickup location not set']);
        exit;
    }

    // Get latest bus location
    $stmt = $pdo->prepare("SELECT latitude, longitude, timestamp FROM gps_logs WHERE bus_id = ? ORDER BY timestamp DESC LIMIT 1");
    $stmt->execute([$student['bus_id']]);
    $gps = $stmt->fetch();

    if (!$gps) {
        echo json_encode(['success' => false, 'error' => 'Bus location not available']);
        exit;
    }

    // Simple Distance Calculation (Haversine)
    function getDistance($lat1, $lon1, $lat2, $lon2) {
        $earth_radius = 6371;
        $dLat = deg2rad($lat2 - $lat1);
        $dLon = deg2rad($lon2 - $lon1);
        $a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon/2) * sin($dLon/2);
        $c = 2 * atan2(sqrt($a), sqrt(1-$a));
        return $earth_radius * $c;
    }

    $distance = getDistance($gps['latitude'], $gps['longitude'], $student['student_lat'], $student['student_lon']);
    
    // Assume average speed 20km/h
    $speed = 20; 
    $hours = $distance / $speed;
    $minutes = ($hours * 60) + 2; // +2 mins for stops/etc

    // Get full bus route stops
    $stmt = $pdo->prepare("SELECT stop_name, latitude, longitude, stop_order FROM bus_stops WHERE bus_id = ? ORDER BY stop_order ASC");
    $stmt->execute([$student['bus_id']]);
    $route_stops = $stmt->fetchAll();

    echo json_encode([
        'success' => true,
        'bus_number' => $student['bus_number'],
        'distance_km' => round($distance, 2),
        'eta_minutes' => round($minutes),
        'last_update' => $gps['timestamp'],
        'bus_lat' => (float)$gps['latitude'],
        'bus_lon' => (float)$gps['longitude'],
        'student_lat' => (float)$student['student_lat'],
        'student_lon' => (float)$student['student_lon'],
        'route_stops' => $route_stops
    ]);

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