<?php session_start(); ?>
<!DOCTYPE html>
<html lang="fr">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Écrire les absences</title>
<link rel="stylesheet" href="w3.css">
<style>
    .style1 { font-size: 18px; font-weight: bold; }
    body, td, th { color: #000033; }
    body { background-color: #FFF; }
</style>
<body>

<?php
include 'header.php';
include '_serveur.php';

$classeid = $subjectId = $coef = $ordre = 0;
$classeErr = $subSubjectErr = $coefErr = $ordreErr = "";

// Determine $classeid from POST or GET
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['classe'])) {
    $classeid = intval($_POST['classe']);
} elseif (isset($_GET['classeid'])) {
    $classeid = intval($_GET['classeid']);
} else {
    die("Classe ID is missing.");
}
?>

<form method="post" action="_ecrireabsence.php?classeid=<?php echo $classeid; ?>">
    <input name="classe" type="hidden" value="<?php echo $classeid; ?>">

    <?php
    // Semester selection dropdown
    $sql = 'SELECT DISTINCT semesters.id, semesters.name 
            FROM semesters 
            INNER JOIN classesSemesters ON semesters.id = classesSemesters.semesterID 
            WHERE classID = "' . $classeid . '" ORDER BY id ASC';

    $req = mysqli_query($link, $sql);
    if (!$req) {
        echo "ERROR: Could not execute $sql. " . mysqli_error($link);
    }

    echo '<label class="w3-text-teal">Contrôle:</label>
          <select name="ctr" class="w3-select w3-border w3-light-grey">';
    while ($data = mysqli_fetch_array($req)) {
        $semesterid = $data[0];
        $semester = $data[1];
        echo '<option value="' . $semesterid . ';' . $semester . '">' . $semester . '</option>';
    }
    echo '</select>';

    // Dates
    echo '<label class="w3-text-teal">Date (début):</label>
          <input class="w3-input w3-border w3-pale-blue" type="date" name="date" required />

          <label class="w3-text-teal">Date (fin):</label>
          <input class="w3-input w3-border w3-pale-blue" type="date" name="date1" value="' . date("Y-m-d") . '" required />

          <button class="w3-btn w3-blue" name="envoyer">Chercher</button>
          <button class="w3-button w3-teal w3-large" onclick="history.go(-1)">← Retour</button>';

    // Handle form submission
    if (isset($_POST['envoyer'])) {
        $date = $_POST['date'];
        $date1 = $_POST['date1'];
        $ctrl1 = $_POST['ctr'];
        list($ctrlID, $controle1) = explode(";", $ctrl1);

        // Check if absenceclasse already exists for this class + semester
        $sql1 = 'SELECT * FROM absenceclasse WHERE classID = "' . $classeid . '" AND semesterID = "' . $ctrlID . '"';
        $req1 = mysqli_query($link, $sql1);
        if (!$req1) {
            echo "ERROR: Could not execute $sql1. " . mysqli_error($link);
        }

        $alreadyExists = mysqli_num_rows($req1) > 0;

        if ($alreadyExists) {
            echo '<div class="w3-panel w3-leftbar w3-sand w3-xxlarge w3-serif">
                    <p align="center"><i>"Absence pour ce contrôle est faite!"</i></p>
                  </div>';
        } else {
            // Collect absences between the selected dates
            $sql = 'SELECT * FROM absences 
                    WHERE classID = "' . $classeid . '" 
                    AND date BETWEEN "' . $date . '" AND "' . $date1 . '" 
                    ORDER BY studentID';

            $req = mysqli_query($link, $sql);
            if (!$req) {
                echo "ERROR: Could not execute $sql. " . mysqli_error($link);
            }

            $absenceCounts = [];
            $absenceMessages = [];

            while ($data = mysqli_fetch_array($req)) {
                $sid = $data['studentID'];
                $absenceCounts[$sid] = ($absenceCounts[$sid] ?? 0) + 1;
                $absenceMessages[$sid] = $data['message'];
            }

            echo '<table class="w3-table w3-striped w3-bordered">';
            foreach ($absenceCounts as $sid => $count) {
                $msg = htmlspecialchars($absenceMessages[$sid]);
                echo "<tr>
                        <td width='40%'><strong>{$msg}</strong></td>
                        <td width='60%'><strong>Nbre Des Jours: {$count}</strong></td>
                      </tr>";

                $sqlInsert = "INSERT INTO absenceclasse 
                              VALUES (DEFAULT, '$sid', '$classeid', '$date1', '$count', '$ctrlID')";
                if (!mysqli_query($link, $sqlInsert)) {
                    echo "ERROR inserting: " . mysqli_error($link);
                }
            }
            echo '</table>';

            echo '<div class="w3-panel w3-leftbar w3-sand w3-xxlarge w3-serif">
                    <p align="center"><i>"Absence par mois écrite!"</i></p>
                  </div>';
        }
    }
    ?>
</form>

</body>
</html>