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

// Authenticate via API Key
$headers = getallheaders();
$apiKey = isset($headers['Authorization']) ? str_replace('Bearer ', '', $headers['Authorization']) : null;

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

try {
    // 1. Get driver and assigned bus
    $stmt = $pdo->prepare("SELECT d.*, b.bus_number FROM drivers d JOIN buses b ON d.bus_id = b.id 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'];

    // 2. Get students for this bus and their LATEST attendance log TODAY
    $stmt = $pdo->prepare("
        SELECT s.id, s.name, s.grade, s.nfc_id, bs.stop_name,
        (SELECT action FROM attendance_logs 
         WHERE student_id = s.id AND DATE(log_time) = CURDATE() 
         ORDER BY log_time DESC LIMIT 1) as current_status
        FROM students s
        LEFT JOIN bus_stops bs ON s.stop_id = bs.id
        WHERE s.bus_id = ?
        ORDER BY bs.stop_order ASC, s.name ASC
    ");
    $stmt->execute([$busId]);
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'success' => true,
        'bus_number' => $driver['bus_number'],
        'students' => $students
    ]);

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