<!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">
<link rel="stylesheet" href="w3.css">
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@600;700&family=Source+Sans+3:wght@300;400;600&display=swap" rel="stylesheet">
<title>Statistiques — Moyennes par Contrôle</title>
<style type="text/css">
/* ============ PRINT ============ */
@media print {
  .noprint { display: none; }
  .page-break { display:block; page-break-after:always; }
  @page { size: 210mm 297mm; margin: 10mm 8mm 10mm 8mm; }
  body { background: #fff !important; }
  .stat-table td, .stat-table th { font-size: 10px !important; }
}

/* ============ RESET & BASE ============ */
*, *::before, *::after { box-sizing: border-box; }
body {
  margin: 0;
  background: #f0ede8;
  font-family: 'Source Sans 3', sans-serif;
  font-weight: 400;
  color: #2c2c2c;
  min-height: 100vh;
}

/* ============ HEADER BAND ============ */
.page-header {
  background: #1a2942;
  color: #fff;
  padding: 18px 32px 14px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 4px solid #c9a84c;
}
.page-header h1 {
  font-family: 'Playfair Display', serif;
  font-size: 1.35rem;
  font-weight: 700;
  margin: 0;
  letter-spacing: 0.02em;
}
.page-header .subtitle {
  font-size: 0.78rem;
  opacity: 0.65;
  margin-top: 2px;
  font-weight: 300;
}
.print-btn {
  background: transparent;
  border: 1.5px solid rgba(255,255,255,0.45);
  color: #fff;
  padding: 7px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.82rem;
  letter-spacing: 0.04em;
  transition: background 0.2s, border-color 0.2s;
  display: flex;
  align-items: center;
  gap: 6px;
}
.print-btn:hover { background: rgba(255,255,255,0.1); border-color: #c9a84c; }
.print-btn svg { width:16px; height:16px; }

/* ============ FILTER CARD ============ */
.filter-wrap {
  max-width: 900px;
  margin: 28px auto 0;
  padding: 0 20px;
}
.filter-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  padding: 22px 28px;
  border-top: 3px solid #c9a84c;
}
.filter-card h2 {
  font-family: 'Playfair Display', serif;
  font-size: 1rem;
  color: #1a2942;
  margin: 0 0 18px;
  font-weight: 600;
}
.filter-row {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
  align-items: flex-end;
}
.filter-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
  flex: 1;
  min-width: 180px;
}
.filter-group label {
  font-size: 0.75rem;
  font-weight: 600;
  color: #1a2942;
  text-transform: uppercase;
  letter-spacing: 0.06em;
}
.filter-group select {
  border: 1.5px solid #d0cfc9;
  border-radius: 5px;
  padding: 9px 12px;
  font-family: 'Source Sans 3', sans-serif;
  font-size: 0.92rem;
  color: #2c2c2c;
  background: #fafaf8;
  outline: none;
  transition: border-color 0.2s;
  cursor: pointer;
}
.filter-group select:focus { border-color: #1a2942; }
.btn-submit {
  background: #1a2942;
  color: #fff;
  border: none;
  padding: 10px 26px;
  border-radius: 5px;
  font-family: 'Source Sans 3', sans-serif;
  font-size: 0.92rem;
  font-weight: 600;
  cursor: pointer;
  letter-spacing: 0.04em;
  transition: background 0.2s;
  white-space: nowrap;
}
.btn-submit:hover { background: #243a5e; }

/* ============ RESULT SECTION ============ */
.result-wrap {
  max-width: 1200px;
  margin: 28px auto 40px;
  padding: 0 20px;
}
.result-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 14px;
  flex-wrap: wrap;
  gap: 8px;
}
.result-meta .class-badge {
  background: #1a2942;
  color: #fff;
  font-family: 'Playfair Display', serif;
  font-size: 1.05rem;
  padding: 6px 18px;
  border-radius: 4px;
  letter-spacing: 0.04em;
}
.result-meta .date-info {
  font-size: 0.82rem;
  color: #666;
}

/* ============ TABLE ============ */
.table-wrap {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 14px rgba(0,0,0,0.07);
  overflow: hidden;
  overflow-x: auto;
}
.stat-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 0.88rem;
}
.stat-table thead tr {
  background: #1a2942;
  color: #fff;
}
.stat-table thead th {
  padding: 11px 10px;
  text-align: center;
  font-weight: 600;
  font-size: 0.80rem;
  letter-spacing: 0.04em;
  text-transform: uppercase;
  border-right: 1px solid rgba(255,255,255,0.12);
  white-space: nowrap;
}
.stat-table thead th:first-child { text-align: left; padding-left: 16px; }
.stat-table thead th.col-avg {
  background: #c9a84c;
  color: #1a2942;
}
.stat-table tbody tr { border-bottom: 1px solid #ece9e2; }
.stat-table tbody tr:nth-child(even) { background: #f9f7f4; }
.stat-table tbody tr:hover { background: #f0ede6; }
.stat-table tbody td {
  padding: 9px 10px;
  text-align: center;
  vertical-align: middle;
}
.stat-table tbody td:first-child {
  text-align: left;
  padding-left: 16px;
  font-weight: 600;
  color: #1a2942;
  white-space: nowrap;
}
.stat-table tbody td.num-rank {
  color: #888;
  font-size: 0.78rem;
  font-weight: 400;
  padding-right: 4px;
}
.stat-table .avg-cell {
  font-weight: 700;
  color: #1a2942;
}
.stat-table .coef-cell { color: #777; font-size: 0.82rem; }

/* Grade colour bands */
.g-high  { color: #1a7a4a; font-weight: 700; }
.g-mid   { color: #c07a00; font-weight: 600; }
.g-low   { color: #b83232; font-weight: 600; }

/* ============ CHART PANEL ============ */
.chart-panel {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 14px rgba(0,0,0,0.07);
  margin-top: 24px;
  padding: 20px 20px 16px;
  position: relative;
}
.chart-panel .close-btn {
  position: absolute;
  top: 12px; right: 14px;
  background: #1a2942;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 4px 10px;
  cursor: pointer;
  font-size: 0.8rem;
}
.chart-panel .close-btn:hover { background: #c9a84c; color: #1a2942; }
.chart-panel h3 {
  font-family: 'Playfair Display', serif;
  font-size: 0.95rem;
  color: #1a2942;
  margin: 0 0 14px;
}
</style>
</head>
<body>

<!-- ========== PAGE HEADER ========== -->
<div class="page-header noprint">
  <div>
    <div class="page-header h1" style="font-family:'Playfair Display',serif;font-size:1.35rem;font-weight:700;margin:0;">Statistiques — Moyennes par Contrôle</div>
    <div class="subtitle">Tableau de bord académique</div>
  </div>
  <button class="print-btn" onclick="window.print()">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9V2h12v7"/><rect x="6" y="17" width="12" height="5"/><path d="M6 13H4a2 2 0 0 0-2 2v4h4"/><path d="M18 13h2a2 2 0 0 1 2 2v4h-4"/></svg>
    Imprimer
  </button>
</div>

<?php
// ── server / header includes ──────────────────────────────────────────────────
$cycle = $_GET['cycle'] ?? '';
include '_serveur.php';
?>

<!-- ========== FILTER CARD ========== -->
<div class="filter-wrap noprint">
  <div class="filter-card">
    <h2>Sélection de la classe et du contrôle</h2>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']); ?>">
      <input name="cycle" type="hidden" value="<?php echo htmlspecialchars($cycle); ?>">
      <div class="filter-row">

        <!-- Classe dropdown -->
        <div class="filter-group">
          <label>Classe</label>
          <?php
          $sql = 'SELECT * FROM classes WHERE cycleID="'.mysqli_real_escape_string($link,$cycle).'" ORDER BY id DESC';
          $req = mysqli_query($link, $sql);
          $selectedClass = $_POST['cla'] ?? '';
          echo '<select name="cla" id="sel_cla" onchange="updateSemesters()">';
          $classOptions = [];
          while ($data = mysqli_fetch_array($req)) {
              $cid   = $data['id'];
              $cname = strtoupper($data['name']);
              $val   = $cid.';'.$cname;
              $sel   = ($selectedClass === $val) ? ' selected' : '';
              echo '<option value="'.htmlspecialchars($val).'"'.$sel.'>'.htmlspecialchars($cname).'</option>';
              $classOptions[] = ['id'=>$cid,'name'=>$cname];
          }
          echo '</select>';
          ?>
        </div>

        <!-- Semester dropdown — populated via JS (AJAX) -->
        <div class="filter-group">
          <label>Contrôle</label>
          <select name="ctr" id="sel_ctr">
            <?php
            // Pre-populate on POST (so selection survives submit)
            if (isset($_POST['chercher'])) {
                $selCla   = $_POST['cla'];
                $claParts = explode(';', $selCla);
                $classIDf = (int)$claParts[0];
                $sql2 = 'SELECT DISTINCT s.id, s.name
                         FROM semesters s
                         JOIN classesSemesters cs ON s.id = cs.semesterID
                         JOIN grades g ON g.semesterID = s.id AND g.classID = cs.classID
                         WHERE cs.classID = '.$classIDf.'
                         ORDER BY s.id ASC';
                $req2 = mysqli_query($link, $sql2);
                $selCtr = $_POST['ctr'];
                while ($d = mysqli_fetch_array($req2)) {
                    $v   = $d[0].';'.$d[1];
                    $sel = ($selCtr === $v) ? ' selected' : '';
                    echo '<option value="'.htmlspecialchars($v).'"'.$sel.'>'.htmlspecialchars($d[1]).'</option>';
                }
            } else {
                // Initial load: populate from first class
                if (!empty($classOptions)) {
                    $firstCID = $classOptions[0]['id'];
                    $sql2 = 'SELECT DISTINCT s.id, s.name
                             FROM semesters s
                             JOIN classesSemesters cs ON s.id = cs.semesterID
                             JOIN grades g ON g.semesterID = s.id AND g.classID = cs.classID
                             WHERE cs.classID = '.(int)$firstCID.'
                             ORDER BY s.id ASC';
                    $req2 = mysqli_query($link, $sql2);
                    while ($d = mysqli_fetch_array($req2)) {
                        echo '<option value="'.htmlspecialchars($d[0].';'.$d[1]).'">'.htmlspecialchars($d[1]).'</option>';
                    }
                }
            }
            ?>
          </select>
        </div>

        <button type="submit" name="chercher" class="btn-submit">Afficher</button>
      </div>
    </form>
  </div>
</div>

<!-- AJAX: update semesters when class changes -->
<script>
function updateSemesters() {
  var claVal = document.getElementById('sel_cla').value;
  var classID = claVal.split(';')[0];
  var ctrSel  = document.getElementById('sel_ctr');
  ctrSel.innerHTML = '<option>Chargement…</option>';
  fetch('ajax_semesters.php?classID=' + encodeURIComponent(classID))
    .then(function(r){ return r.json(); })
    .then(function(data){
      ctrSel.innerHTML = '';
      data.forEach(function(s){
        var opt = document.createElement('option');
        opt.value = s.id + ';' + s.name;
        opt.textContent = s.name;
        ctrSel.appendChild(opt);
      });
    })
    .catch(function(){ ctrSel.innerHTML = '<option>Erreur</option>'; });
}
</script>

<?php
// ────────────────────────────────────────────────────────────────────────────
// RESULTS
// ────────────────────────────────────────────────────────────────────────────
if (isset($_POST['chercher'])) {
    $cla1     = $_POST['cla'];
    $cellcla  = explode(';', $cla1);
    $classeID = (int)$cellcla[0];
    $classe   = htmlspecialchars($cellcla[1]);

    $ctrole1  = $_POST['ctr'];
    $cellctr  = explode(';', $ctrole1);
    $ctrlID   = (int)$cellctr[0];
    $controle1= htmlspecialchars($cellctr[1]);

    // Delete old averages
    $sql1 = 'DELETE FROM moyens WHERE classID='.$classeID.' AND semesterID='.$ctrlID;
    mysqli_query($link, $sql1);

    // ── Subject columns ──────────────────────────────────────────────────────
    $req = mysqli_query($link, 'SELECT * FROM subjects WHERE id<=10');
    $subjectList = [];
    while ($d = mysqli_fetch_array($req)) {
        $subjectList[] = ['id'=>$d['id'], 'name'=>$d['name']];
    }
    $cel = 1;
    $cellule = [];
    foreach ($subjectList as $s) { $cellule[$s['name']] = $cel++; }

    // ── Grades fetch ─────────────────────────────────────────────────────────
    $sql = 'SELECT * FROM classes
            LEFT JOIN students     ON students.classID = classes.id
            LEFT JOIN grades       ON students.id = grades.studentID AND students.classID = grades.classID
            LEFT JOIN gradesSubjects ON grades.subSubjectID = gradesSubjects.subSubjectID AND grades.classID = gradesSubjects.classID
            LEFT JOIN subSubjects  ON grades.subSubjectID = subSubjects.id
            LEFT JOIN subjects     ON subSubjects.subjectID = subjects.id
            LEFT JOIN classesSemesters ON classesSemesters.classId = classes.id AND grades.semesterID = classesSemesters.semesterID
            LEFT JOIN semesters    ON semesters.id = classesSemesters.semesterID
            LEFT JOIN users        ON users.id = students.userID
            WHERE classes.id='.$classeID.' AND semesters.id='.$ctrlID.'
            ORDER BY students.firstName, students.lastName, students.id, subjects.id, subSubjects.id, semesters.id, subjects.ordering';
    $req = mysqli_query($link, $sql);

    $studentid=[];$prenom=[];$famille=[];$pere=[];$grade=[];
    $discipcoef=[];$discipid=[];$discip=[];$matid=[];$mat=[];
    $orderm=[];$ctrlid=[];$ctrl=[];$cl=[];$clid=[];
    $i=0;
    while ($data = mysqli_fetch_array($req)) {
        $studentid[$i]=$data[3]; $prenom[$i]=$data[5]; $famille[$i]=$data[6]; $pere[$i]=$data[33];
        $grade[$i]=$data[14]; $discipcoef[$i]=$data[17]; $discipid[$i]=$data[19]; $discip[$i]=$data[21];
        $matid[$i]=$data[22]; $mat[$i]=$data[23]; $orderm[$i]=$data[24];
        $ctrlid[$i]=$data[29]; $ctrl[$i]=$data[30]; $cl[$i]=$data[1]; $clid[$i]=$data[0];
        $i++;
    }

    // ── Helper: grade colour ─────────────────────────────────────────────────
    function gradeClass($v) {
        if ($v === '' || $v === null) return '';
        if ($v >= 14) return 'g-high';
        if ($v >= 10) return 'g-mid';
        return 'g-low';
    }

    // ── Build result header ──────────────────────────────────────────────────
    echo '<div class="result-wrap">';
    echo '<div class="result-meta">';
    echo '<span class="class-badge">'.strtoupper($classe).' &mdash; '.$controle1.'</span>';
    echo '<span class="date-info">'.date('d/m/Y').'</span>';
    echo '</div>';
    echo '<div class="table-wrap"><table class="stat-table">';
    echo '<thead><tr><th>Élève</th>';
    foreach ($subjectList as $s) {
        echo '<th>'.htmlspecialchars($s['name']).'</th>';
    }
    echo '<th>Total</th><th>Coef.</th><th class="col-avg">Moyenne /20</th></tr></thead>';
    echo '<tbody>';

    $i=0; $j=1;
    $nb=0; $summat=0; $coefmat=0; $sumcla=0; $coeft=0;
    $trig=0; $num=1; $cel1=0;
    $summat1=0;
    $texte=[]; $donn=[];

    while ($i < count($studentid)) {
        if ($studentid[$i] == $studentid[$j]) {
            if ($trig == 0) {
                $name = htmlspecialchars($prenom[$i].' '.$pere[$i].' '.$famille[$i]);
                echo '<tr><td><span style="color:#aaa;font-size:.78rem;margin-right:6px">'.$num.'.</span>'.$name.'</td>';
                $trig=1; $num++; $cel1++;
            }
            if ($mat[$i] == $mat[$j]) {
                if ($grade[$i] != -1) {
                    $summat+=$grade[$i]; $coefmat+=$discipcoef[$i];
                    $summat1+=$grade[$i]; $coeft+=$discipcoef[$i];
                }
            } else {
                if ($grade[$i] != -1) {
                    $summat+=$grade[$i]; $coefmat+=$discipcoef[$i];
                    $summat1+=$grade[$i]; $coeft+=$discipcoef[$i];
                }
                while ($cellule[$mat[$i]] != $cel1) { echo '<td>—</td>'; $cel1++; }
                $subAvg = $coefmat > 0 ? round($summat*20/$coefmat, 2) : 0;
                $gc = gradeClass($subAvg);
                echo '<td class="'.$gc.'">'.($subAvg > 0 ? $subAvg : '—').'</td>';
                $summat=0; $coefmat=0; $cel1++;
            }
        } else {
            if ($grade[$i] != -1) {
                $summat+=$grade[$i]; $coefmat+=$discipcoef[$i];
                $summat1+=$grade[$i]; $coeft+=$discipcoef[$i];
            }
            while ($cellule[$mat[$i]] != $cel1) { echo '<td>—</td>'; $cel1++; }
            $subAvg = $coefmat > 0 ? round($summat*20/$coefmat, 2) : 0;
            $gc = gradeClass($subAvg);
            echo '<td class="'.$gc.'">'.($subAvg > 0 ? $subAvg : '—').'</td>';
            $cel1++;
            $trig=0; $summat=0; $coefmat=0;
            if ($coeft == 0) $coeft = 1;
            $moyenf = round($summat1*20/$coeft, 2);
            while ($cel1 < $cel) { echo '<td>—</td>'; $cel1++; }
            $mgc = gradeClass($moyenf);
            echo '<td class="avg-cell">'.$summat1.'</td>';
            echo '<td class="coef-cell">'.$coeft.'</td>';
            echo '<td class="avg-cell '.$mgc.'">'.$moyenf.'</td></tr>';
            $texte[$nb] = $prenom[$i].' '.$famille[$i];
            $donn[$nb]  = $moyenf;
            $sumcla    += $moyenf;
            $nb++; $cel1=0; $summat1=0; $coeft=0;
        }
        $i++; $j++;
    }
    echo '</tbody></table></div>';

    $num--; 
    $moyencl = $num > 0 ? round($sumcla/$num, 2) : 0;

    // ── Class average summary bar ────────────────────────────────────────────
    echo '<div style="margin-top:14px;display:flex;gap:20px;flex-wrap:wrap;">';
    echo '<div style="background:#1a2942;color:#fff;border-radius:6px;padding:12px 22px;font-family:\'Playfair Display\',serif;">';
    echo '<div style="font-size:.75rem;opacity:.65;text-transform:uppercase;letter-spacing:.06em">Moyenne de classe</div>';
    echo '<div style="font-size:1.6rem;font-weight:700;color:#c9a84c">'.$moyencl.' <span style="font-size:.9rem;font-weight:400;opacity:.7">/ 20</span></div>';
    echo '</div>';
    echo '<div style="background:#fff;border-radius:6px;padding:12px 22px;box-shadow:0 2px 10px rgba(0,0,0,.07);">';
    echo '<div style="font-size:.75rem;color:#888;text-transform:uppercase;letter-spacing:.06em">Effectif</div>';
    echo '<div style="font-size:1.6rem;font-weight:700;color:#1a2942">'.$num.'</div>';
    echo '</div>';
    echo '</div>';

    // ── Chart ────────────────────────────────────────────────────────────────
    echo '<div class="chart-panel noprint">';
    echo '<button class="close-btn" onclick="this.parentElement.style.display=\'none\'">✕ Fermer</button>';
    echo '<h3>Distribution des moyennes &mdash; '.htmlspecialchars($controle1).'</h3>';
    include 'histogrammenotes.php';
    histo(1000, 420, $donn, $texte, 'Moyennes — '.$controle1, $moyencl);
    echo '</div></div>';
}
?>

</body>
</html>
