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

$student_id = isset($_GET['student_id']) ? intval($_GET['student_id']) : 0;

if ($student_id === 0) {
    echo json_encode([]);
    exit;
}

// Get lesson count
$lessons_sql = "
    SELECT lg.label, COUNT(*) AS times_covered
    FROM DriveSchedule ds
    JOIN lesson_groups lg ON ds.lesson_group_id = lg.id
    WHERE ds.student_id = ?
    GROUP BY lg.label
";

$stmt1 = $conn->prepare($lessons_sql);
$stmt1->bind_param("i", $student_id);
$stmt1->execute();
$result1 = $stmt1->get_result();

$lessons = [];
while ($row = $result1->fetch_assoc()) {
    $lessons[] = [
        'label' => $row['label'],
        'times_covered' => $row['times_covered']
    ];
}
$stmt1->close();

// Get total BTW minutes
$btw_sql = "SELECT SUM(btw_minutes) AS total_btw FROM DriveSchedule WHERE student_id = ?";
$stmt2 = $conn->prepare($btw_sql);
$stmt2->bind_param("i", $student_id);
$stmt2->execute();
$result2 = $stmt2->get_result();
$row2 = $result2->fetch_assoc();
$total_btw = intval($row2['total_btw'] ?? 0);

echo json_encode([
    'lessons' => $lessons,
    'total_btw' => $total_btw
]);

