<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8">
<title>Saisie des Observations</title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style>
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: #f0f2f5;
    color: #1a1a2e;
    min-height: 100vh;
  }

  .page-wrapper {
    max-width: 1100px;
    margin: 0 auto;
    padding: 2rem 1.5rem 4rem;
  }

  /* ── Page header ── */
  .page-header {
    background: linear-gradient(135deg, #1a1a2e 0%, #16213e 60%, #0f3460 100%);
    border-radius: 16px;
    padding: 2rem 2.5rem;
    margin-bottom: 2rem;
    display: flex;
    align-items: center;
    gap: 1.5rem;
    box-shadow: 0 8px 32px rgba(15,52,96,0.25);
    flex-wrap: wrap;
  }
  .page-header-icon {
    width: 56px; height: 56px;
    background: rgba(255,255,255,0.12);
    border-radius: 14px;
    display: flex; align-items: center; justify-content: center;
    font-size: 26px; flex-shrink: 0;
  }
  .page-header h1  { color: #fff; font-size: 1.5rem; font-weight: 700; }
  .page-header p   { color: rgba(255,255,255,0.6); font-size: 0.88rem; margin-top: 4px; }
  .class-badge {
    margin-left: auto;
    background: rgba(255,255,255,0.15);
    color: #fff;
    border: 1px solid rgba(255,255,255,0.3);
    border-radius: 50px;
    padding: 6px 20px;
    font-size: 0.9rem; font-weight: 600;
    white-space: nowrap;
  }

  /* ── Banners ── */
  .banner {
    display: flex; align-items: center; gap: 1rem;
    border-radius: 12px; padding: 1.2rem 1.8rem;
    font-size: 0.97rem; font-weight: 500;
    margin-bottom: 1.2rem;
  }
  .banner-warning { background:#fff8e1; border:1.5px solid #ffd54f; color:#5d4037; }
  .banner-success { background:#e8f5e9; border:1.5px solid #a5d6a7; color:#2e7d32; font-weight:600; }
  .banner-info    { background:#e3f2fd; border:1.5px solid #90caf9; color:#0d47a1; }
  .banner-error   { background:#fdecea; border:1.5px solid #f5c6cb; color:#721c24; font-size:0.88rem; }

  /* ── Main card ── */
  .main-card {
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 2px 16px rgba(0,0,0,0.07);
    overflow: hidden;
  }

  /* ── Table ── */
  .obs-table { width: 100%; border-collapse: collapse; }
  .obs-table thead tr { background: #f8f9fb; border-bottom: 2px solid #e8ecf0; }
  .obs-table thead th {
    padding: 0.85rem 1.2rem; text-align: left;
    font-size: 0.74rem; font-weight: 700;
    text-transform: uppercase; letter-spacing: 0.6px; color: #6b7280;
  }
  .obs-table thead th.col-num  { width: 55px; }
  .obs-table thead th.col-name { width: 28%; }

  .obs-table tbody tr { border-bottom: 1px solid #f1f3f6; transition: background 0.12s; }
  .obs-table tbody tr:last-child { border-bottom: none; }
  .obs-table tbody tr:hover { background: #fafbfc; }
  .obs-table td { padding: 0.8rem 1.2rem; vertical-align: middle; }

  .row-num {
    width: 30px; height: 30px; border-radius: 50%;
    background: #e8ecf7; color: #3d52a0;
    font-size: 0.78rem; font-weight: 700;
    display: inline-flex; align-items: center; justify-content: center;
  }
  .student-name { font-weight: 600; font-size: 0.93rem; color: #1a1a2e; line-height: 1.3; }
  .student-info { font-size: 0.8rem; color: #9ca3af; margin-top: 2px; }

  /* ── Observation select ── */
  .obs-select-wrapper { position: relative; }
  .obs-select-wrapper::after {
    content: '▾'; position: absolute; right: 11px; top: 50%;
    transform: translateY(-50%); color: #6b7280;
    pointer-events: none; font-size: 0.82rem;
  }
  select.obs-select {
    width: 100%;
    padding: 0.52rem 2rem 0.52rem 0.85rem;
    border: 1.5px solid #e2e8f0; border-radius: 8px;
    background: #fafbfc; font-size: 0.86rem; color: #374151;
    appearance: none; -webkit-appearance: none; outline: none;
    transition: border-color 0.18s, box-shadow 0.18s; cursor: pointer;
  }
  select.obs-select:focus {
    border-color: #3d52a0;
    box-shadow: 0 0 0 3px rgba(61,82,160,0.12);
    background: #fff;
  }

  /* ── Admis sub-panel ── */
  .admis-panel {
    display: none; margin-top: 8px;
    background: #f0f4ff; border: 1.5px solid #c7d3f5;
    border-radius: 8px; padding: 10px 12px;
    flex-direction: column; gap: 8px;
  }
  .admis-panel.visible { display: flex; }
  .admis-panel-label {
    font-size: 0.74rem; font-weight: 700; color: #3d52a0;
    text-transform: uppercase; letter-spacing: 0.5px;
  }
  .admis-row { display: flex; gap: 8px; flex-wrap: wrap; }

  select.admis-gender, select.admis-dest {
    flex: 1; min-width: 130px;
    padding: 0.42rem 0.75rem;
    border: 1.5px solid #c7d3f5; border-radius: 6px;
    background: #fff; font-size: 0.84rem; color: #374151;
    appearance: none; -webkit-appearance: none;
    outline: none; cursor: pointer;
    transition: border-color 0.18s;
  }
  select.admis-gender:focus, select.admis-dest:focus { border-color: #3d52a0; }

  /* ── Submit bar ── */
  .submit-bar {
    display: flex; align-items: center; justify-content: space-between;
    padding: 1.1rem 1.5rem;
    background: #f8f9fb; border-top: 1px solid #e8ecf0;
    flex-wrap: wrap; gap: 0.75rem;
  }
  .submit-count { font-size: 0.85rem; color: #6b7280; }
  .btn-publish {
    background: linear-gradient(135deg, #3d52a0 0%, #1a1a2e 100%);
    color: #fff; border: none; border-radius: 10px;
    padding: 0.68rem 2rem; font-size: 0.95rem; font-weight: 700;
    cursor: pointer; letter-spacing: 0.3px;
    box-shadow: 0 4px 14px rgba(61,82,160,0.3);
    transition: transform 0.12s, box-shadow 0.12s;
  }
  .btn-publish:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(61,82,160,0.4); }
  .btn-publish:active { transform: translateY(0); }

  /* ── Action buttons (Modifier / Effacer) ── */
  .btn-modifier {
    display: inline-flex; align-items: center; gap: 7px;
    background: linear-gradient(135deg, #3d52a0 0%, #1a1a2e 100%);
    color: #fff; border: none; border-radius: 9px;
    padding: 0.6rem 1.4rem; font-size: 0.9rem; font-weight: 700;
    cursor: pointer; text-decoration: none;
    box-shadow: 0 3px 12px rgba(61,82,160,0.3);
    transition: transform 0.12s, box-shadow 0.12s;
  }
  .btn-modifier:hover { transform: translateY(-2px); box-shadow: 0 5px 18px rgba(61,82,160,0.4); }

  .btn-effacer {
    display: inline-flex; align-items: center; gap: 7px;
    background: #fff; color: #c0392b;
    border: 2px solid #e74c3c; border-radius: 9px;
    padding: 0.58rem 1.4rem; font-size: 0.9rem; font-weight: 700;
    cursor: pointer; transition: background 0.14s, color 0.14s;
  }
  .btn-effacer:hover { background: #fdecea; }

  .btn-save-modifier {
    background: linear-gradient(135deg, #27ae60 0%, #1a6e3c 100%);
    color: #fff; border: none; border-radius: 10px;
    padding: 0.68rem 2rem; font-size: 0.95rem; font-weight: 700;
    cursor: pointer; letter-spacing: 0.3px;
    box-shadow: 0 4px 14px rgba(39,174,96,0.3);
    transition: transform 0.12s, box-shadow 0.12s;
  }
  .btn-save-modifier:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(39,174,96,0.4); }

  .banner-actions { display: flex; gap: 0.75rem; flex-wrap: wrap; margin-top: 0.9rem; }

  /* Confirm overlay */
  #confirmOverlay {
    display: none; position: fixed; inset: 0;
    background: rgba(0,0,0,0.45); z-index: 9999;
    align-items: center; justify-content: center;
  }
  #confirmOverlay.active { display: flex; }
  .confirm-box {
    background: #fff; border-radius: 16px; padding: 2rem 2.5rem;
    max-width: 420px; width: 90%; text-align: center;
    box-shadow: 0 20px 60px rgba(0,0,0,0.2);
  }
  .confirm-box h3 { font-size: 1.15rem; color: #1a1a2e; margin-bottom: 0.5rem; }
  .confirm-box p  { font-size: 0.9rem; color: #6b7280; margin-bottom: 1.4rem; }
  .confirm-actions { display: flex; gap: 0.75rem; justify-content: center; }

  @media (max-width: 620px) {
    .page-header { padding: 1.2rem; }
    .class-badge { margin-left: 0; }
    .obs-table thead th.col-name,
    .obs-table td:nth-child(2) { display: none; }
    .admis-row { flex-direction: column; }
  }
</style>
</head>
<body>

<?php
/* ════════════════════════════════════════════════
   BOOTSTRAP
   ════════════════════════════════════════════════ */
include("_serveur.php");
include 'header.php';

/* ── Resolve classID from GET or POST ── */
if (!empty($_GET['classeid'])) {
    $classeID = intval($_GET['classeid']);
} elseif (!empty($_POST['classe'])) {
    $classeID = intval($_POST['classe']);
} else {
    $classeID = 0;
}

/* ════════════════════════════════════════════════
   LOAD ALL CLASSES FROM DB  (no more hardcoded map)
   ════════════════════════════════════════════════ */
$allClassesDB = [];   // id => ['name'=>..., 'cycleID'=>...]
$res = mysqli_query($link, 'SELECT id, name, cycleID FROM classes ORDER BY id');
if ($res) {
    while ($r = mysqli_fetch_assoc($res)) {
        $allClassesDB[(int)$r['id']] = ['name' => $r['name'], 'cycleID' => (int)$r['cycleID']];
    }
}

/* Current class name */
$currentClass = isset($allClassesDB[$classeID]) ? $allClassesDB[$classeID]['name'] : '';
$currentCycle = isset($allClassesDB[$classeID]) ? $allClassesDB[$classeID]['cycleID'] : 0;

/* ── Build "Admis en …" destination list:
       all classes EXCEPT Primaire (cycle 5) and the current one,
       ordered naturally by id  ── */
$admisDestClasses = [];
foreach ($allClassesDB as $cid => $cdata) {
    if ($cdata['cycleID'] == 5) continue;   // skip Primaire
    if ($cid === $classeID)     continue;   // skip current
    $admisDestClasses[$cid] = $cdata['name'];
}

/* Logical next class = next id in the same or adjacent cycle */
$nextClassName = '';
$ids = array_keys($allClassesDB);
$pos = array_search($classeID, $ids);
if ($pos !== false && isset($ids[$pos + 1])) {
    $nextId = $ids[$pos + 1];
    if ($allClassesDB[$nextId]['cycleID'] != 5) {
        $nextClassName = $allClassesDB[$nextId]['name'];
    }
}

/* ── Detect real column name in `observations` ── */
$obsColumn = '';
$colRes = mysqli_query($link, 'SHOW COLUMNS FROM observations');
if ($colRes) {
    while ($c = mysqli_fetch_assoc($colRes)) {
        $f = strtolower($c['Field']);
        if ($f === 'id' || $f === 'observationid') continue;
        $obsColumn = $c['Field'];
        break;
    }
}
if ($obsColumn === '') $obsColumn = 'observation'; // ultimate fallback

/* ── Fetch observations list ── */
$observationsList = [];
$reqO = mysqli_query($link, 'SELECT `'.$obsColumn.'` FROM observations ORDER BY `'.$obsColumn.'`');
if ($reqO) {
    while ($row = mysqli_fetch_row($reqO)) {
        if (trim($row[0]) !== '') $observationsList[] = $row[0];
    }
}

/* ── Detect observation column in observationsele ── */
$obsEleColumn = 'observation';
$colRes2 = mysqli_query($link, 'SHOW COLUMNS FROM observationsele');
if ($colRes2) {
    while ($c2 = mysqli_fetch_assoc($colRes2)) {
        $f2 = strtolower($c2['Field']);
        if (!in_array($f2, ['id', 'studentid', 'classid'])) {
            $obsEleColumn = $c2['Field'];
            break;
        }
    }
}

/* ── Check if already recorded ── */
$alreadyDone = false;
if ($classeID > 0) {
    $chk = mysqli_query($link, 'SELECT 1 FROM observationsele WHERE classID='.intval($classeID).' LIMIT 1');
    $alreadyDone = ($chk && mysqli_num_rows($chk) > 0);
}

/* ── Modifier mode (GET ?modifier=1) ── */
$modifierMode = (!empty($_GET['modifier']) && $_GET['modifier'] == '1');

/* ════════════════════════════════════════════════
   HANDLE POST
   ════════════════════════════════════════════════ */
$postSuccess    = false;
$modifierSuccess = false;
$effacerSuccess = false;
$postErrors     = [];

/* ── Handle EFFACER (delete all observations for class) ── */
if (isset($_POST['effacer']) && $classeID > 0) {
    mysqli_query($link, 'DELETE FROM observationsele WHERE classID='.intval($classeID));
    $alreadyDone    = false;
    $effacerSuccess = true;
    $modifierMode   = false;
}

/* ── Helper: insert observations rows ── */
function insertObservations($link, $obs1, $stud1, $classeID, $currentClass, &$postErrors) {
    $m = count($stud1);
    for ($j = 0; $j < $m; $j++) {
        $obsVal = trim($obs1[$j] ?? '');
        /* Safety: if observation contains "admis en" or "admise en" but ends there (no class yet),
           append current class as fallback */
        $lobs = strtolower($obsVal);
        $hasAdmisEn = (strpos($lobs, 'admis en') !== false || strpos($lobs, 'admise en') !== false);
        if ($hasAdmisEn && preg_match('/admis[e]?\s+en\s*$/i', $obsVal)) {
            $obsVal = rtrim($obsVal) . ' ' . $currentClass;
        }
        $safeObs = mysqli_real_escape_string($link, $obsVal);
        $safeSid = intval($stud1[$j]);
        $ins = 'INSERT INTO observationsele VALUES(DEFAULT,"'.$safeSid.'","'.$classeID.'","'.$safeObs.'")';
        if (!mysqli_query($link, $ins)) {
            $postErrors[] = 'Élève #'.($j+1).' : '.mysqli_error($link);
        }
    }
}

/* ── Handle PUBLISH (first time) ── */
if (isset($_POST['publish']) && $classeID > 0 && !$alreadyDone) {
    $obs1  = isset($_POST['ob'])        ? (array)$_POST['ob']        : [];
    $stud1 = isset($_POST['studentID']) ? (array)$_POST['studentID'] : [];
    insertObservations($link, $obs1, $stud1, $classeID, $currentClass, $postErrors);
    if (empty($postErrors)) {
        $postSuccess = true;
        $alreadyDone = true;
        $modifierMode = false;
    }
}

/* ── Handle MODIFIER SAVE (update = delete + reinsert) ── */
if (isset($_POST['modifier_save']) && $classeID > 0) {
    $obs1  = isset($_POST['ob'])        ? (array)$_POST['ob']        : [];
    $stud1 = isset($_POST['studentID']) ? (array)$_POST['studentID'] : [];
    mysqli_query($link, 'DELETE FROM observationsele WHERE classID='.intval($classeID));
    insertObservations($link, $obs1, $stud1, $classeID, $currentClass, $postErrors);
    if (empty($postErrors)) {
        $modifierSuccess = true;
        $alreadyDone  = true;
        $modifierMode = false;
    }
}

/* ── Fetch existing observations per student (for modifier mode) ── */
$existingObs = [];
if ($alreadyDone && $modifierMode) {
    $resObs = mysqli_query($link,
        'SELECT studentID, `'.$obsEleColumn.'` FROM observationsele WHERE classID='.intval($classeID));
    if ($resObs) {
        while ($ro = mysqli_fetch_assoc($resObs)) {
            $existingObs[(int)$ro['studentID']] = $ro[$obsEleColumn];
        }
    }
}

/* ── Fetch students ── */
$students = [];
if ($classeID > 0 && (!$alreadyDone || $modifierMode)) {
    $sqlS = 'SELECT id, firstName, lastName, photo
             FROM students
             WHERE classID='.intval($classeID).'
             ORDER BY firstName, lastName';
    $reqS = mysqli_query($link, $sqlS);
    if ($reqS) {
        while ($d = mysqli_fetch_assoc($reqS)) { $students[] = $d; }
    }
}
?>

<div class="page-wrapper">

  <!-- ── Page header ── -->
  <div class="page-header">
    <div class="page-header-icon">📋</div>
    <div>
      <h1>Saisie des Observations</h1>
      <p>Attribuer une observation à chaque élève de la classe</p>
    </div>
    <?php if ($currentClass): ?>
      <span class="class-badge">Classe&nbsp;: <?php echo htmlspecialchars($currentClass); ?></span>
    <?php endif; ?>
  </div>

  <?php if ($classeID === 0 || $currentClass === ''): ?>
    <div class="banner banner-error">
      ⚠️&nbsp; Classe introuvable. Veuillez revenir au menu et sélectionner une classe valide.
    </div>

  <?php elseif ($postSuccess): ?>
    <div class="banner banner-success">
      ✅&nbsp; Observations enregistrées avec succès pour la classe
      <strong><?php echo htmlspecialchars($currentClass); ?></strong>.
    </div>

  <?php elseif ($modifierSuccess): ?>
    <div class="banner banner-success">
      ✏️&nbsp; Observations <strong>modifiées</strong> avec succès pour la classe
      <strong><?php echo htmlspecialchars($currentClass); ?></strong>.
    </div>

  <?php elseif ($effacerSuccess): ?>
    <div class="banner banner-info">
      🗑️&nbsp; Toutes les observations de la classe
      <strong><?php echo htmlspecialchars($currentClass); ?></strong> ont été effacées.
    </div>

  <?php elseif ($alreadyDone && !$modifierMode): ?>
    <div class="banner banner-warning">
      <div style="flex:1">
        ⚠️&nbsp; Les observations de la classe
        <strong><?php echo htmlspecialchars($currentClass); ?></strong>
        ont déjà été saisies.
        <div class="banner-actions">
          <!-- Modifier → reload in modifier mode -->
          <a href="?classeid=<?php echo $classeID; ?>&modifier=1"
             class="btn-modifier">✏️ Modifier les observations</a>

          <!-- Effacer → POST with confirmation -->
          <button type="button" class="btn-effacer"
                  onclick="document.getElementById('confirmOverlay').classList.add('active')">
            🗑️ Effacer toute la classe
          </button>
        </div>
      </div>
    </div>

    <!-- Confirm dialog -->
    <div id="confirmOverlay">
      <div class="confirm-box">
        <h3>Confirmer la suppression</h3>
        <p>Effacer <strong>toutes les observations</strong> de la classe
           <strong><?php echo htmlspecialchars($currentClass); ?></strong>&nbsp;?<br>
           Cette action est irréversible.</p>
        <div class="confirm-actions">
          <button type="button" class="btn-modifier"
                  onclick="document.getElementById('confirmOverlay').classList.remove('active')">
            Annuler
          </button>
          <form method="post"
                action="<?php echo htmlspecialchars(strtok($_SERVER['REQUEST_URI'],'?')); ?>?classeid=<?php echo $classeID; ?>"
                style="display:inline">
            <input type="hidden" name="classe" value="<?php echo $classeID; ?>">
            <button type="submit" name="effacer" class="btn-effacer">
              🗑️ Oui, effacer
            </button>
          </form>
        </div>
      </div>
    </div>

  <?php else: /* either not done, or modifier mode */ ?>

    <?php if (!empty($postErrors)): ?>
      <div class="banner banner-error">
        <?php echo implode('<br>', array_map('htmlspecialchars', $postErrors)); ?>
      </div>
    <?php endif; ?>

    <?php if (empty($observationsList)): ?>
      <div class="banner banner-error">
        ⚠️&nbsp; Aucune observation trouvée dans la table <code>observations</code>.
      </div>
    <?php elseif (empty($students)): ?>
      <div class="banner banner-info">
        ℹ️&nbsp; Aucun élève inscrit dans cette classe.
      </div>
    <?php else: ?>

    <?php if ($modifierMode): ?>
      <div class="banner banner-info">
        ✏️&nbsp; Mode <strong>Modification</strong> — Modifiez les observations puis cliquez sur
        <em>Enregistrer les modifications</em>.
        &nbsp;<a href="?classeid=<?php echo $classeID; ?>"
                 style="font-size:0.85rem;color:#0d47a1;">← Annuler</a>
      </div>
    <?php endif; ?>

    <!-- classeid kept in action URL so it survives POST redirect -->
    <form method="post"
          action="<?php echo htmlspecialchars(strtok($_SERVER['REQUEST_URI'],'?')); ?>?classeid=<?php echo $classeID; ?>"
          id="obsForm">

      <input type="hidden" name="classe" value="<?php echo $classeID; ?>">
      <?php if ($modifierMode): ?>
        <input type="hidden" name="modifier_mode" value="1">
      <?php endif; ?>

      <div class="main-card">
        <table class="obs-table" id="obsTable">
          <thead>
            <tr>
              <th class="col-num">#</th>
              <th class="col-name">Élève</th>
              <th>Observation</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($students as $i => $stu):
            $sid      = intval($stu['id']);
            $prenom   = htmlspecialchars($stu['firstName'] ?? '');
            $nom      = htmlspecialchars($stu['lastName']  ?? '');
            $photo    = trim($stu['photo'] ?? '');
            $initials = strtoupper(mb_substr($stu['firstName'] ?? '?', 0, 1) .
                                   mb_substr($stu['lastName']  ?? '',  0, 1));
            /* Pre-select existing value in modifier mode, else first observation */
            $currentObsVal = $modifierMode && isset($existingObs[$sid])
                             ? $existingObs[$sid]
                             : ($observationsList[0] ?? '');
            $firstObs = htmlspecialchars($currentObsVal);
          ?>
            <tr>
              <td><span class="row-num"><?php echo $i + 1; ?></span></td>

              <td>
                <div style="display:flex;align-items:center;gap:10px;">
                  <?php if ($photo): ?>
                    <img src="<?php echo htmlspecialchars($photo); ?>"
                         alt=""
                         style="width:34px;height:34px;border-radius:50%;object-fit:cover;
                                flex-shrink:0;border:1.5px solid #e2e8f0;">
                  <?php else: ?>
                    <span style="width:34px;height:34px;border-radius:50%;background:#e8ecf7;
                                 color:#3d52a0;font-size:0.75rem;font-weight:700;
                                 display:inline-flex;align-items:center;
                                 justify-content:center;flex-shrink:0;">
                      <?php echo $initials; ?>
                    </span>
                  <?php endif; ?>
                  <div class="student-name"><?php echo $prenom . ' ' . $nom; ?></div>
                </div>
              </td>

              <td>
                <!-- This hidden field is what actually gets submitted -->
                <input type="hidden"
                       name="ob[]"
                       id="ob_final_<?php echo $i; ?>"
                       value="<?php echo $firstObs; ?>">
                <input type="hidden"
                       name="studentID[]"
                       value="<?php echo $sid; ?>">

                <!-- Main observation dropdown -->
                <div class="obs-select-wrapper">
                  <select class="obs-select"
                          id="ob_main_<?php echo $i; ?>"
                          data-idx="<?php echo $i; ?>"
                          data-existing="<?php echo $firstObs; ?>">
                    <?php foreach ($observationsList as $obs): ?>
                      <option value="<?php echo htmlspecialchars($obs); ?>">
                        <?php echo htmlspecialchars($obs); ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                </div>

                <!-- Admis/Admise sub-panel -->
                <div class="admis-panel" id="admis_panel_<?php echo $i; ?>">
                  <div class="admis-panel-label">🏫 Choisir la classe d'admission</div>
                  <div class="admis-row">

                    <!-- Destination class (from DB, skip Primaire) -->
                    <select class="admis-dest"
                            id="admis_dest_<?php echo $i; ?>"
                            data-idx="<?php echo $i; ?>">
                      <?php foreach ($admisDestClasses as $cid => $cname): ?>
                        <option value="<?php echo htmlspecialchars($cname); ?>"
                          <?php echo ($cname === $nextClassName) ? 'selected' : ''; ?>>
                          <?php echo htmlspecialchars($cname); ?>
                        </option>
                      <?php endforeach; ?>
                    </select>

                  </div>
                </div><!-- /.admis-panel -->
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>

        <div class="submit-bar">
          <span class="submit-count">
            <?php echo count($students); ?> élève(s) —
            <?php echo htmlspecialchars($currentClass); ?>
          </span>
          <div style="display:flex;gap:0.6rem;flex-wrap:wrap;align-items:center;">
            <?php if ($modifierMode): ?>
              <!-- Effacer button inside form (modifier mode) -->
              <button type="button" class="btn-effacer"
                      onclick="document.getElementById('confirmOverlay').classList.add('active')">
                🗑️ Effacer toute la classe
              </button>
              <button type="submit" name="modifier_save" class="btn-save-modifier">
                ✔&nbsp; Enregistrer les modifications
              </button>
            <?php else: ?>
              <button type="submit" name="publish" class="btn-publish">
                ✔&nbsp; Publier les observations
              </button>
            <?php endif; ?>
          </div>
        </div>
      </div><!-- /.main-card -->

    </form>

    <!-- Confirm dialog (inside modifier mode form too) -->
    <div id="confirmOverlay">
      <div class="confirm-box">
        <h3>Confirmer la suppression</h3>
        <p>Effacer <strong>toutes les observations</strong> de la classe
           <strong><?php echo htmlspecialchars($currentClass); ?></strong>&nbsp;?<br>
           Cette action est irréversible.</p>
        <div class="confirm-actions">
          <button type="button" class="btn-modifier"
                  onclick="document.getElementById('confirmOverlay').classList.remove('active')">
            Annuler
          </button>
          <form method="post"
                action="<?php echo htmlspecialchars(strtok($_SERVER['REQUEST_URI'],'?')); ?>?classeid=<?php echo $classeID; ?>"
                style="display:inline">
            <input type="hidden" name="classe" value="<?php echo $classeID; ?>">
            <button type="submit" name="effacer" class="btn-effacer">
              🗑️ Oui, effacer
            </button>
          </form>
        </div>
      </div>
    </div>

    <?php endif; /* students / observations empty */ ?>
  <?php endif; /* alreadyDone / classeID */ ?>

</div><!-- /.page-wrapper -->

<script>
(function () {

  function buildAdmisValue(idx) {
    var sel  = document.getElementById('ob_main_' + idx);
    var dSel = document.getElementById('admis_dest_' + idx);
    /* Observation text already contains "admis en" or "admise en" — just append the class */
    var obsText = sel  ? sel.value.replace(/\s+$/, '')  : '';
    var dest    = dSel ? dSel.value : '';
    document.getElementById('ob_final_' + idx).value = obsText + ' ' + dest;
  }

  function handleMainChange(sel) {
    var idx   = parseInt(sel.getAttribute('data-idx'), 10);
    var val   = sel.value;
    var lv    = val.toLowerCase();
    var panel = document.getElementById('admis_panel_' + idx);
    /* Show panel whenever the observation contains "admis en" or "admise en" anywhere */
    var isAdmis = (lv.indexOf('admis en') !== -1 || lv.indexOf('admise en') !== -1);
    if (isAdmis) {
      panel.classList.add('visible');
      buildAdmisValue(idx);
    } else {
      panel.classList.remove('visible');
      document.getElementById('ob_final_' + idx).value = val;
    }
  }

  /* Single delegated listener for all selects */
  document.addEventListener('change', function (e) {
    var el = e.target;
    if (el.classList.contains('obs-select'))  { handleMainChange(el); return; }
    if (el.classList.contains('admis-gender') ||
        el.classList.contains('admis-dest'))  {
      buildAdmisValue(parseInt(el.getAttribute('data-idx'), 10));
    }
  });

  /* Sync all rows before submit */
  var form = document.getElementById('obsForm');
  if (form) {
    form.addEventListener('submit', function () {
      document.querySelectorAll('select.obs-select').forEach(function (sel) {
        handleMainChange(sel);
      });
    });
  }

  /* Init on page load — pre-select existing value if in modifier mode */
  document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('select.obs-select').forEach(function (sel) {
      var existing = sel.getAttribute('data-existing');
      if (existing) {
        var idx = parseInt(sel.getAttribute('data-idx'), 10);
        var lv  = existing.toLowerCase();
        /* Check if stored value contains "admis en" or "admise en" */
        var isAdmis = (lv.indexOf('admis en') !== -1 || lv.indexOf('admise en') !== -1);
        if (isAdmis) {
          /* Find which dropdown option is a prefix of the stored value
             e.g. stored = "Promu et admis en 6ème A"
                  option  = "Promu et admis en"  → match! class = "6ème A" */
          var classPart = '';
          for (var o = 0; o < sel.options.length; o++) {
            var optVal = sel.options[o].value;
            var optLv  = optVal.toLowerCase();
            if ((optLv.indexOf('admis en') !== -1 || optLv.indexOf('admise en') !== -1) &&
                lv.indexOf(optLv) === 0) {
              sel.selectedIndex = o;
              /* class = everything after the option text (trimmed) */
              classPart = existing.substring(optVal.length).trim();
              break;
            }
          }
          /* Set destination dropdown */
          if (classPart) {
            var dSel = document.getElementById('admis_dest_' + idx);
            if (dSel) {
              for (var d = 0; d < dSel.options.length; d++) {
                if (dSel.options[d].value === classPart) { dSel.selectedIndex = d; break; }
              }
            }
          }
        } else {
          /* Plain observation — find exact match */
          for (var o2 = 0; o2 < sel.options.length; o2++) {
            if (sel.options[o2].value === existing) { sel.selectedIndex = o2; break; }
          }
        }
      }
      handleMainChange(sel);
    });
  });

})();
</script>

</body>
</html>
