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

// Get driver API key from Authorization header
$headers = getallheaders();
$apiKey = isset($headers['Authorization']) ? str_replace('Bearer ', '', $headers['Authorization']) : null;

if (!$apiKey) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

try {
    // Verify driver and get bus_id
    $stmt = $pdo->prepare("SELECT d.* FROM drivers d WHERE d.api_key = ? AND d.status = 'active'");
    $stmt->execute([$apiKey]);
    $driver = $stmt->fetch();

    if (!$driver) {
        echo json_encode(['success' => false, 'error' => 'Invalid API key']);
        exit;
    }

    $busId = $driver['bus_id'];

    // Get all active routes for this bus with student count
    $routesStmt = $pdo->prepare("
        SELECT 
            r.id,
            r.route_name,
            r.shift,
            r.start_time,
            r.end_time,
            r.active,
            COUNT(s.id) as student_count
        FROM routes r
        LEFT JOIN students s ON r.id = s.route_id
        WHERE r.bus_id = ? AND r.active = 1
        GROUP BY r.id
        ORDER BY 
            FIELD(r.shift, 'morning', 'afternoon', 'evening'),
            r.route_name
    ");
    $routesStmt->execute([$busId]);
    $routes = $routesStmt->fetchAll();

    echo json_encode([
        'success' => true,
        'routes' => $routes,
        'current_route_id' => $driver['active_route_id']
    ]);

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