<!DOCTYPE html>
<html lang="fr">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ecrire Ctrl</title>
<link rel="stylesheet" href="w3.css">
<style>
body {width:90%; margin:auto;}
.w3-check {margin-right:6px;}
</style>
<script>
function toggleAll(source, groupName) {
    const checkboxes = document.querySelectorAll(`input[name="${groupName}[]"]`);
    checkboxes.forEach(cb => cb.checked = source.checked);
}
</script>
</head>
<body>

<div class="w3-card-4 w3-padding">
<form method="post" action="">
<?php
include 'header.php';
include '_serveur.php';

$cycle = isset($_REQUEST['cycle']) ? intval($_REQUEST['cycle']) : 0;
echo '<input type="hidden" name="cycle" value="'.$cycle.'">';

// Fetch classes
$sql = "SELECT id, name FROM classes WHERE cycleID = '$cycle' ORDER BY id ASC";
$result = mysqli_query($link, $sql) or die("Erreur SQL: " . mysqli_error($link));

echo '<p><label class="w3-text-teal"><b>Classes :</b></label><br>';
echo '<input type="checkbox" onclick="toggleAll(this, \'cla\')" class="w3-check">
      <label><b>Sélectionner tout</b></label><br>';
while ($row = mysqli_fetch_assoc($result)) {
    echo '<input class="w3-check" type="checkbox" name="cla[]" value="'.$row['id'].'">
          <label>'.strtoupper($row['name']).'</label><br>';
}
echo '</p>';

// Fetch semesters
$sql = "SELECT id, name FROM semesters ORDER BY id ASC";
$result = mysqli_query($link, $sql) or die("Erreur SQL: " . mysqli_error($link));

echo '<p><label class="w3-text-teal"><b>Semestres :</b></label><br>';
echo '<input type="checkbox" onclick="toggleAll(this, \'sem\')" class="w3-check">
      <label><b>Sélectionner tout</b></label><br>';
while ($row = mysqli_fetch_assoc($result)) {
    echo '<input class="w3-check" type="checkbox" name="sem[]" value="'.$row['id'].'">
          <label>'.$row['name'].'</label><br>';
}
echo '</p>';

echo '<p><input name="envoyer" type="submit" class="w3-button w3-teal" value="Envoyer" /></p>';
?>
</form>
</div>

<?php
if (isset($_POST['envoyer'])) {
    $cla1 = $_POST['cla'] ?? [];
    $sem1 = $_POST['sem'] ?? [];
    $countInserted = 0;
    $countExists = 0;

    foreach ($cla1 as $classId) {
        foreach ($sem1 as $semesterId) {
            $classIdInt = intval($classId);
            $semesterIdInt = intval($semesterId);

            // Check if this class-semester pair already exists
            $checkSql = "SELECT 1 FROM classesSemesters 
                         WHERE classID = '$classIdInt' AND semesterID = '$semesterIdInt' LIMIT 1";
            $checkResult = mysqli_query($link, $checkSql) or die("Erreur: " . mysqli_error($link));

            if (mysqli_num_rows($checkResult) == 0) {
                // Not exists yet, insert new record
                $sqlInsert = "INSERT INTO classesSemesters 
                              (classID, semesterID, teachersActive, parentsActive)
                              VALUES ('$classIdInt', '$semesterIdInt', 0, 0)";
                mysqli_query($link, $sqlInsert) or die("Erreur: " . mysqli_error($link));
                $countInserted++;
            } else {
                $countExists++;
            }
        }
    }

    echo '<div class="w3-panel w3-leftbar w3-sand w3-xlarge w3-serif">';
    if ($countInserted > 0) {
        echo '<p><i>'.$countInserted.' nouveaux contrôles ajoutés (activés pour les notes)</i></p>';
    }
    if ($countExists > 0) {
        echo '<p><i>'.$countExists.' contrôle(s) existent déjà et n\'ont pas été ajoutés.</i></p>';
    }
    echo '</div>';
}

/* ══════════════════════════════════════════════════════════════════
   HANDLE DELETE
   ══════════════════════════════════════════════════════════════════ */
if (isset($_POST['supprimer']) && !empty($_POST['del_pairs'])) {
    $pairs   = $_POST['del_pairs'];
    $deleted = 0;
    $notFound = 0;

    foreach ($pairs as $pair) {
        [$cId, $sId] = array_map('intval', explode('_', $pair));
        if ($cId > 0 && $sId > 0) {
            $del = mysqli_query($link,
                "DELETE FROM classesSemesters WHERE classID=$cId AND semesterID=$sId"
            ) or die("Erreur: " . mysqli_error($link));
            if (mysqli_affected_rows($link) > 0) $deleted++;
            else $notFound++;
        }
    }

    echo '<div class="w3-panel w3-leftbar w3-pale-red w3-xlarge w3-serif">';
    if ($deleted  > 0) echo '<p><i>'.$deleted.' contrôle(s) supprimé(s) avec succès.</i></p>';
    if ($notFound > 0) echo '<p><i>'.$notFound.' combinaison(s) introuvable(s).</i></p>';
    echo '</div>';
}

/* ══════════════════════════════════════════════════════════════════
   DELETE FORM — show existing links for this cycle's classes
   ══════════════════════════════════════════════════════════════════ */
?>
<hr class="w3-margin-top">
<div class="w3-card-4 w3-padding w3-margin-top" style="border-left:4px solid #f44336;">
  <h4 class="w3-text-red">🗑 Supprimer un contrôle / examen d'une classe</h4>

  <?php
  /* Build a table showing what currently exists in classesSemesters for this cycle */
  $sql_existing = "SELECT cs.classID, c.name AS class_name, cs.semesterID, s.name AS sem_name
                   FROM classesSemesters cs
                   JOIN classes c ON c.id = cs.classID
                   JOIN semesters s ON s.id = cs.semesterID
                   WHERE c.cycleID = '$cycle'
                   ORDER BY c.name ASC, s.id ASC";
  $res_existing = mysqli_query($link, $sql_existing) or die("Erreur: " . mysqli_error($link));
  $rows = [];
  while ($r = mysqli_fetch_assoc($res_existing)) $rows[] = $r;

  if (empty($rows)) {
      echo '<p class="w3-text-grey"><i>Aucun contrôle enregistré pour ce cycle.</i></p>';
  } else {
  ?>
  <form method="post" action=""
        onsubmit="return confirm('Confirmer la suppression des contrôles sélectionnés ?');">
    <input type="hidden" name="cycle" value="<?php echo $cycle; ?>">

    <table class="w3-table w3-bordered w3-striped w3-small" style="max-width:700px;">
      <thead class="w3-red">
        <tr>
          <th style="width:40px;">
            <input type="checkbox" class="w3-check"
                   onclick="toggleAllDel(this)" title="Tout sélectionner">
          </th>
          <th>Classe</th>
          <th>Contrôle / Semestre</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach ($rows as $row): ?>
        <tr>
          <td>
            <input type="checkbox" class="w3-check del-cb"
                   name="del_pairs[]"
                   value="<?php echo intval($row['classID']).'_'.intval($row['semesterID']); ?>">
          </td>
          <td><?php echo strtoupper(htmlspecialchars($row['class_name'])); ?></td>
          <td><?php echo htmlspecialchars($row['sem_name']); ?></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>

    <p>
      <input name="supprimer" type="submit"
             class="w3-button w3-red w3-margin-top"
             value="Supprimer la sélection" />
    </p>
  </form>

  <script>
  function toggleAllDel(source) {
      document.querySelectorAll('.del-cb').forEach(cb => cb.checked = source.checked);
  }
  </script>
  <?php } ?>
</div>
