<?php
/**
 * ajax_semesters.php
 * Returns semesters that have grades for a given classID — as JSON.
 * Called from the JS updateSemesters() function in the stat pages.
 *
 * FIX: _serveur.php may output whitespace, a BOM, session headers, or HTML
 * which corrupts the JSON body and causes JSON.parse() to fail in the browser
 * (showing "Erreur" or an empty <select>).
 * Solution: buffer all output from _serveur.php and discard it, then send
 * the Content-Type header and JSON cleanly.
 */

// 1. Buffer EVERYTHING so _serveur.php cannot pollute the response body.
ob_start();
include '_serveur.php';
ob_end_clean();          // discard any stray output (BOM, whitespace, HTML…)

// 2. Now it is safe to send headers and JSON.
header('Content-Type: application/json; charset=utf-8');

$classID = isset($_GET['classID']) ? (int)$_GET['classID'] : 0;

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

$sql = 'SELECT DISTINCT s.id, s.name
        FROM semesters s
        JOIN classesSemesters cs ON s.id = cs.semesterID
        JOIN grades g            ON g.semesterID = s.id AND g.classID = cs.classID
        WHERE cs.classID = ' . $classID . '
        ORDER BY s.id ASC';

$result = mysqli_query($link, $sql);
$rows = [];
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $rows[] = ['id' => (int)$row['id'], 'name' => $row['name']];
    }
}
echo json_encode($rows);
