<?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 active route
    $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;
    }

    $activeRouteId = $driver['active_route_id'];

    // Check if driver has selected a route
    if (!$activeRouteId) {
        echo json_encode([
            'success' => true,
            'students' => [],
            'message' => 'Please select a route first'
        ]);
        exit;
    }

    // Get students for the active route
    $studentsStmt = $pdo->prepare("
        SELECT 
            s.id,
            s.name,
            s.grade,
            s.nfc_id,
            s.parent_phone,
            bs.name as stop_name,
            bs.latitude as stop_lat,
            bs.longitude as stop_lng
        FROM students s
        LEFT JOIN bus_stops bs ON s.stop_id = bs.id
        WHERE s.route_id = ?
        ORDER BY bs.sequence, s.name
    ");
    $studentsStmt->execute([$activeRouteId]);
    $students = $studentsStmt->fetchAll();

    // Get route info
    $routeStmt = $pdo->prepare("SELECT route_name, shift FROM routes WHERE id = ?");
    $routeStmt->execute([$activeRouteId]);
    $route = $routeStmt->fetch();

    echo json_encode([
        'success' => true,
        'students' => $students,
        'route_name' => $route['route_name'],
        'shift' => $route['shift'],
        'total_students' => count($students)
    ]);

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