<?php
session_start();
include("_serveur1.php");

// Get selected class and date from session
if (!isset($_SESSION['classeid'])) {
    die("Classe non sélectionnée. <a href='miseaniveau.php'>Retour</a>");
}
$currentClassID = $_SESSION['classeid'];
$currentClassName = $_SESSION['classe1'];
$date1 = $_SESSION['date1'];

// Handle form submission
$message = '';
if (isset($_POST['envoyer'])) {

    if (isset($_POST['plat']) && count($_POST['plat']) > 0) {
        $students = $_POST['plat'];

        if (isset($_POST['cla'])) {
            $newClassID = intval($_POST['cla']);

            foreach ($students as $s) {
                $parts = explode(";", $s);
                $studentID = intval($parts[1]);

                if ($newClassID === 0) {
                    // Delete student
                    mysqli_query($link, "DELETE FROM students WHERE id=$studentID");
                } else {
                    // Update student's class
                    mysqli_query($link, "UPDATE students SET classID=$newClassID WHERE id=$studentID");
                }
            }
            $message = "<p style='color:green;'>Opération terminée avec succès.</p>";

        } else {
            $message = "<p style='color:red;'>Veuillez sélectionner une classe ou Quitter.</p>";
        }

    } else {
        $message = "<p style='color:red;'>Veuillez sélectionner au moins un étudiant.</p>";
    }
}

// Fetch students of the current class ordered by student firstName, lastName
$studentsResult = mysqli_query($link, "
    SELECT students.id, students.classID, students.userID, 
           students.firstName AS studentFirst, students.lastName AS studentLast, 
           users.firstName AS fatherName
    FROM students
    JOIN users ON users.id = students.userID
    WHERE classID=$currentClassID
    ORDER BY students.firstName ASC, students.lastName ASC
");

// Fetch other classes for radio buttons
$classesResult = mysqli_query($link, "SELECT * FROM classes WHERE id!=$currentClassID ORDER BY name ASC");
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="w3.css">
<title>Mise à Niveau - <?= htmlspecialchars($currentClassName) ?></title>
<script>
// Toggle all student checkboxes
function toggleSelectAll(source) {
    let checkboxes = document.getElementsByName('plat[]');
    for (let i = 0; i < checkboxes.length; i++) checkboxes[i].checked = source.checked;
}

// Update "Sélectionner tout" checkbox
function updateSelectAll() {
    let checkboxes = document.getElementsByName('plat[]');
    let selectAll = document.getElementById('selectAll');
    let allChecked = true;
    for (let i = 0; i < checkboxes.length; i++) {
        if (!checkboxes[i].checked) { allChecked = false; break; }
    }
    selectAll.checked = allChecked;
}
</script>
</head>
<body class="w3-light-blue">
<?php include 'header.php'; ?>

<div class="w3-container w3-padding">
<h2 class="w3-text-white w3-padding w3-red w3-center"><?= htmlspecialchars($currentClassName) ?> — <?= htmlspecialchars($date1) ?></h2>

<?= $message ?>

<form method="post">
<table class="w3-table w3-bordered w3-white" style="width:95%">
<tr>
    <td colspan="2">
        <input type="checkbox" id="selectAll" onclick="toggleSelectAll(this)">
        <label for="selectAll"><b>Sélectionner tout</b></label>
    </td>
</tr>

<?php
$i=1; $num=1;
while ($data = mysqli_fetch_array($studentsResult)) {
    if($i==1) echo "<tr>";
    ?>
    <td width="50%">
        <input type="checkbox" name="plat[]" 
               value="<?= $i.";". $data['id'] . ";" . $data['studentFirst'] . ";" . $data['studentLast'] . ";" . $data['fatherName'] ?>" 
               onclick="updateSelectAll()">
        <?= $num . ". " . htmlspecialchars($data['studentFirst']." ".$data['studentLast']." ".$data['fatherName']) ?>
    </td>
    <?php
    $i++; $num++;
    if($i==3){ echo "</tr>"; $i=1; }
}
if($i!=1) echo "</tr>";
?>

<tr>
<td colspan="2">
<p><b>Classe de destination :</b></p>
<?php while($c = mysqli_fetch_array($classesResult)) { ?>
    <input class="w3-check" type="radio" name="cla" value="<?= $c['id'] ?>">
    <label><?= strtoupper(htmlspecialchars($c['name'])) ?></label>&emsp;
<?php } ?>
<input class="w3-check" type="radio" name="cla" value="0">
<label>Quitter</label>
</td>
</tr>
</table>

<br>
<input type="reset" class="w3-button w3-light-blue" value="Effacer" />
<input type="submit" name="envoyer" class="w3-button w3-green" value="Envoyer" />
</form>
</div>
</body>
</html>