<?php
header("Content-Type: text/html; charset=utf-8");
require_once "_serveur.php";
mysqli_set_charset($link, "utf8");

// Step 1: Get all teachers
$teachers = [];
$res = mysqli_query($link, "
    SELECT id, CONCAT(firstName, ' ', lastName) AS name 
    FROM users 
    WHERE type = 2 
    ORDER BY lastName, firstName
");
while ($row = mysqli_fetch_assoc($res)) {
    $teachers[$row['id']] = [
        'name' => $row['name'],
        'classes' => [],
        'subSubjects' => []
    ];
}

// Step 2: Get all classes & subjects
$res = mysqli_query($link, "
    SELECT ts.userID, c.className, s.name AS subjectName
    FROM teachersSubjects ts
    LEFT JOIN classes c ON ts.classID = c.id
    LEFT JOIN subjects s ON ts.subjectID = s.id
");
while ($row = mysqli_fetch_assoc($res)) {
    if (!isset($teachers[$row['userID']])) continue;
    $teachers[$row['userID']]['classes'][] = [
        'class' => $row['className'] ?? '(Aucune classe)',
        'subject' => $row['subjectName'] ?? '(Aucune matière)'
    ];
}

// Step 3: Get all sub-subjects
$res = mysqli_query($link, "
    SELECT tss.userID, ss.name AS subSubjectName
    FROM teachersSubsubjects tss
    LEFT JOIN subSubjects ss ON tss.subSubjectID = ss.id
");
while ($row = mysqli_fetch_assoc($res)) {
    if (!isset($teachers[$row['userID']])) continue;
    $teachers[$row['userID']]['subSubjects'][] = $row['subSubjectName'] ?? '(Aucune sous-matière)';
}

// Step 4: Display
echo "<h2>Liste des enseignants (type=2)</h2>";
foreach ($teachers as $id => $t) {
    echo "<h3>????? [$id] {$t['name']}</h3>";
    echo "<ul>";
    if (!empty($t['classes'])) {
        foreach ($t['classes'] as $c) {
            $subList = !empty($t['subSubjects']) 
                ? implode(', ', $t['subSubjects']) 
                : '(Aucune sous-matière)';
            echo "<li>{$c['class']} ? <b>{$c['subject']}</b> ? <i>$subList</i></li>";
        }
    } else {
        $subList = !empty($t['subSubjects']) 
            ? implode(', ', $t['subSubjects']) 
            : '(Aucune matière ni sous-matière)';
        echo "<li>$subList</li>";
    }
    echo "</ul>";
}
?>
