<!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 — Classement Final</title>
<style type="text/css">
@media print{.noprint{display:none}.page-break{display:block;page-break-after:always}@page{size:210mm 297mm;margin:10mm 8mm}}
*,*::before,*::after{box-sizing:border-box}
body{margin:0;background:#f0ede8;font-family:'Source Sans 3',sans-serif;color:#2c2c2c}
.page-header{background:#1a2942;color:#fff;padding:18px 32px 14px;display:flex;align-items:center;justify-content:space-between;border-bottom:4px solid #c9a84c}
.print-btn{background:transparent;border:1.5px solid rgba(255,255,255,.45);color:#fff;padding:7px 16px;border-radius:4px;cursor:pointer;font-size:.82rem;display:flex;align-items:center;gap:6px;transition:background .2s}
.print-btn:hover{background:rgba(255,255,255,.1);border-color:#c9a84c}
.filter-wrap{max-width:960px;margin:28px auto 0;padding:0 20px}
.filter-card{background:#fff;border-radius:8px;box-shadow:0 2px 12px rgba(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}
.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:.75rem;font-weight:600;color:#1a2942;text-transform:uppercase;letter-spacing:.06em}
.filter-group select{border:1.5px solid #d0cfc9;border-radius:5px;padding:9px 12px;font-family:'Source Sans 3',sans-serif;font-size:.92rem;background:#fafaf8;outline:none;transition:border-color .2s}
.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:.92rem;font-weight:600;cursor:pointer;letter-spacing:.04em;transition:background .2s}
.btn-submit:hover{background:#243a5e}
.sem-group{display:flex;flex-direction:column;gap:6px;flex:2;min-width:260px}
.sem-group>.sem-label-row{display:flex;align-items:center;gap:10px}
.sem-label-row span{font-size:.75rem;font-weight:600;color:#1a2942;text-transform:uppercase;letter-spacing:.06em}
.sem-toggle-all{font-size:.72rem;color:#1a2942;background:none;border:1px solid #d0cfc9;border-radius:3px;cursor:pointer;padding:2px 8px;opacity:.75}
.sem-toggle-all:hover{opacity:1;border-color:#1a2942}
.sem-checks{display:flex;flex-wrap:wrap;gap:7px}
.sem-pill{display:inline-flex;align-items:center;gap:5px;border:1.5px solid #d0cfc9;border-radius:20px;padding:4px 12px;cursor:pointer;font-size:.82rem;color:#555;background:#fafaf8;transition:all .15s;user-select:none}
.sem-pill:hover{border-color:#1a2942;color:#1a2942}
.sem-pill input[type=checkbox]{display:none}
.sem-pill.on{background:#1a2942;color:#fff;border-color:#1a2942}
.result-wrap{max-width:1300px;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}
.class-badge{background:#1a2942;color:#fff;font-family:'Playfair Display',serif;font-size:1.05rem;padding:6px 18px;border-radius:4px}
.date-info{font-size:.82rem;color:#666}
.table-wrap{background:#fff;border-radius:8px;box-shadow:0 2px 14px rgba(0,0,0,.07);overflow:hidden;overflow-x:auto}
.stat-table{width:100%;border-collapse:collapse;font-size:.88rem}
.stat-table thead tr{background:#1a2942;color:#fff}
.stat-table thead th{padding:11px 10px;text-align:center;font-size:.78rem;font-weight:600;letter-spacing:.04em;text-transform:uppercase;border-right:1px solid rgba(255,255,255,.12);white-space:nowrap}
.stat-table thead th:first-child{text-align:center;padding-left:10px;width:44px}
.stat-table thead th:nth-child(2){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.name-cell{text-align:left;padding-left:16px;font-weight:600;color:#1a2942;white-space:nowrap}
.g-high{color:#1a7a4a;font-weight:700}
.g-mid {color:#c07a00;font-weight:600}
.g-low {color:#b83232;font-weight:600}
.avg-cell{font-weight:700;color:#1a2942}
.medal{display:inline-flex;align-items:center;justify-content:center;width:22px;height:22px;border-radius:50%;font-size:.72rem;font-weight:700}
.medal-1{background:#c9a84c;color:#fff}
.medal-2{background:#b0b0b0;color:#fff}
.medal-3{background:#a05c2c;color:#fff}
.chart-panel{background:#fff;border-radius:8px;box-shadow:0 2px 14px rgba(0,0,0,.07);margin-top:24px;padding:20px;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:.8rem}
.chart-panel .close-btn:hover{background:#c9a84c;color:#1a2942}
.chart-panel h3{font-family:'Playfair Display',serif;font-size:.95rem;color:#1a2942;margin:0 0 6px}
.chart-panel p{font-size:.8rem;color:#888;margin:0 0 14px}
</style>
</head>
<body>

<div class="page-header noprint">
  <div>
    <div style="font-family:'Playfair Display',serif;font-size:1.35rem;font-weight:700;color:#fff">Classement Final par Moyenne</div>
    <div style="font-size:.78rem;opacity:.65;margin-top:2px">Tous contrôles confondus — trié par moyenne décroissante</div>
  </div>
  <button class="print-btn" onclick="window.print()">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><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
include 'header.php';
$cycle = $_GET['cycle'] ?? '';
include '_serveur.php';

if(isset($_GET['ajax']) && $_GET['ajax']==='sems'){
    $cid=(int)($_GET['classID']??0);
    $out=[];
    if($cid){
        $r=mysqli_query($link,'SELECT DISTINCT s.id, s.name FROM semesters s
            JOIN classesSemesters cs ON s.id=cs.semesterID
            WHERE cs.classID='.$cid.' ORDER BY s.id ASC');
        while($row=mysqli_fetch_assoc($r)) $out[]=['id'=>(int)$row['id'],'name'=>$row['name']];
    }
    header('Content-Type: application/json');
    echo json_encode($out);
    exit;
}
?>

<div class="filter-wrap noprint">
  <div class="filter-card">
    <h2>Sélection de la classe et des contrôles</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">
        <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);
          $selCla=$_POST['cla']??'';
          $allClasses=[];
          while($d=mysqli_fetch_array($req)) $allClasses[]=$d;
          echo '<select name="cla" id="claSelect" onchange="reloadSems()">';
          foreach($allClasses as $d){
              $val=$d['id'].';'.strtoupper($d['name']);
              $sel=($selCla===$val)?' selected':'';
              echo '<option value="'.htmlspecialchars($val).'"'.$sel.'>'.htmlspecialchars(strtoupper($d['name'])).'</option>';
          }
          echo '</select>';
          $activeClaVal=$selCla?:($allClasses[0]['id'].';'.strtoupper($allClasses[0]['name']??''));
          $activeClaID=(int)explode(';',$activeClaVal)[0];
          ?>
        </div>
        <div class="sem-group">
          <div class="sem-label-row">
            <span>Contrôles</span>
            <button type="button" class="sem-toggle-all" id="toggleBtn" onclick="toggleAll()">Tout désélectionner</button>
          </div>
          <div class="sem-checks" id="semChecks">
            <?php
            $selSems=isset($_POST['sems'])?(array)$_POST['sems']:null;
            if($activeClaID){
                $rs=mysqli_query($link,'SELECT DISTINCT s.id, s.name FROM semesters s
                    JOIN classesSemesters cs ON s.id=cs.semesterID
                    WHERE cs.classID='.$activeClaID.' ORDER BY s.id ASC');
                while($row=mysqli_fetch_assoc($rs)){
                    $sid=(int)$row['id'];
                    $on=($selSems===null||in_array($sid,$selSems));
                    echo '<label class="sem-pill'.($on?' on':'').'" onclick="togglePill(this)">';
                    echo '<input type="checkbox" name="sems[]" value="'.$sid.'"'.($on?' checked':'').'>';
                    echo htmlspecialchars($row['name']).'</label>';
                }
            }
            ?>
          </div>
        </div>
        <button type="submit" name="chercher" class="btn-submit">Afficher</button>
      </div>
    </form>
  </div>
</div>

<script>
function togglePill(lbl){var cb=lbl.querySelector('input');cb.checked=!cb.checked;lbl.classList.toggle('on',cb.checked);syncToggleBtn();}
function syncToggleBtn(){var all=document.querySelectorAll('#semChecks .sem-pill');var allOn=Array.from(all).every(l=>l.querySelector('input').checked);document.getElementById('toggleBtn').textContent=allOn?'Tout désélectionner':'Tout sélectionner';}
function toggleAll(){var pills=document.querySelectorAll('#semChecks .sem-pill');var allOn=Array.from(pills).every(l=>l.querySelector('input').checked);pills.forEach(function(l){var cb=l.querySelector('input');cb.checked=!allOn;l.classList.toggle('on',!allOn);});document.getElementById('toggleBtn').textContent=allOn?'Tout sélectionner':'Tout désélectionner';}
function reloadSems(){var val=document.getElementById('claSelect').value;var id=parseInt(val.split(';')[0]);if(!id)return;fetch(location.pathname+'?ajax=sems&classID='+id+'&cycle=<?php echo urlencode($cycle);?>').then(r=>r.json()).then(function(data){var box=document.getElementById('semChecks');box.innerHTML='';data.forEach(function(s){var lbl=document.createElement('label');lbl.className='sem-pill on';lbl.onclick=function(){togglePill(this);};var cb=document.createElement('input');cb.type='checkbox';cb.name='sems[]';cb.value=s.id;cb.checked=true;lbl.appendChild(cb);lbl.appendChild(document.createTextNode(s.name));box.appendChild(lbl);});document.getElementById('toggleBtn').textContent='Tout désélectionner';});}
</script>

<?php
function gc6($v){if($v>=14)return 'g-high';if($v>=10)return 'g-mid';return 'g-low';}

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

    $reqA=mysqli_query($link,'SELECT DISTINCT s.id, s.name FROM semesters s
          JOIN classesSemesters cs ON s.id=cs.semesterID
          WHERE cs.classID='.$classeID.' ORDER BY s.id ASC');
    $allSemIDs=[];$semNames=[];
    while($row=mysqli_fetch_assoc($reqA)){$allSemIDs[]=(int)$row['id'];$semNames[(int)$row['id']]=$row['name'];}

    $selSems=isset($_POST['sems'])?(array)$_POST['sems']:null;
    if($selSems!==null) $selSems=array_map('intval',$selSems);
    $semIDs=($selSems===null||count($selSems)===0)
        ? $allSemIDs
        : array_values(array_filter($allSemIDs,fn($id)=>in_array($id,$selSems)));
    $nbSem=count($semIDs);

    if($nbSem===0){
        echo '<div class="result-wrap"><p style="color:#b83232;padding:20px;font-weight:600">⚠ Veuillez sélectionner au moins un contrôle.</p></div>';
    } else {

    $semIN=implode(',',$semIDs);
    $req=mysqli_query($link,'SELECT g.studentID, g.semesterID, g.grade, gs.coeficient AS coef,
             st.firstName, st.lastName
          FROM grades g
          JOIN students st ON st.id=g.studentID
          JOIN gradesSubjects gs ON gs.subSubjectID=g.subSubjectID AND gs.classID=g.classID
          WHERE g.classID='.$classeID.'
            AND g.semesterID IN ('.$semIN.')
            AND g.grade != -1
          ORDER BY g.studentID, g.semesterID');

    $raw=[];$names=[];
    while($row=mysqli_fetch_assoc($req)){
        $sid=(int)$row['studentID'];$cid=(int)$row['semesterID'];
        $g=(float)$row['grade'];$c=(float)$row['coef'];
        if(!isset($raw[$sid])){ $raw[$sid]=[]; $names[$sid]=strtoupper($row['firstName'].' '.$row['lastName']); }
        if(!isset($raw[$sid][$cid])) $raw[$sid][$cid]=['sumGC'=>0,'sumC'=>0];
        $raw[$sid][$cid]['sumGC']+=$g;$raw[$sid][$cid]['sumC']+=$c;
    }

    $students=[];
    foreach($raw as $sid=>$semData){
        $moys=[];$totalSum=0;$totalCnt=0;
        foreach($semIDs as $cid){
            if(isset($semData[$cid])&&$semData[$cid]['sumC']>0){
                $avg=round($semData[$cid]['sumGC']*20/$semData[$cid]['sumC'],2);
                $moys[$cid]=$avg;$totalSum+=$avg;$totalCnt++;
            } else { $moys[$cid]=null; }
        }
        $overall=$totalCnt>0?round($totalSum/$totalCnt,2):0;
        $students[]=['name'=>$names[$sid],'moys'=>$moys,'overall'=>$overall];
    }

    usort($students,fn($a,$b)=>$b['overall']<=>$a['overall']);

    echo '<div class="result-wrap">';
    echo '<div class="result-meta"><span class="class-badge">'.strtoupper($classe).'</span>';
    if(count($semIDs)<count($allSemIDs)){
        $lbl=implode(', ',array_map(fn($id)=>htmlspecialchars($semNames[$id]),$semIDs));
        echo '<span style="font-size:.8rem;color:#666;background:#fff;padding:4px 12px;border-radius:4px;box-shadow:0 1px 4px rgba(0,0,0,.08);">Contrôles : '.$lbl.'</span>';
    }
    echo '<span class="date-info">'.date('d/m/Y').'</span></div>';
    echo '<div class="table-wrap"><table class="stat-table"><thead><tr><th>#</th><th>Élève</th>';
    foreach($semIDs as $cid) echo '<th>'.htmlspecialchars($semNames[$cid]).'</th>';
    echo '<th class="col-avg">Moyenne</th></tr></thead><tbody>';

    foreach($students as $rank0=>$stu){
        $rank=$rank0+1;
        if($rank===1) $med='<span class="medal medal-1">1</span>';
        elseif($rank===2) $med='<span class="medal medal-2">2</span>';
        elseif($rank===3) $med='<span class="medal medal-3">3</span>';
        else $med='<span style="color:#aaa;font-size:.82rem">'.$rank.'</span>';
        echo '<tr><td style="text-align:center">'.$med.'</td>';
        echo '<td class="name-cell">'.htmlspecialchars($stu['name']).'</td>';
        foreach($semIDs as $cid){
            $v=$stu['moys'][$cid];
            if($v===null) echo '<td style="color:#bbb;">—</td>';
            else{ $gc=gc6($v); echo '<td class="'.$gc.'">'.$v.'</td>'; }
        }
        $gc=gc6($stu['overall']);
        echo '<td class="avg-cell '.$gc.'">'.$stu['overall'].'</td></tr>';
    }
    echo '</tbody></table></div>';

    $num1=count($students);
    $moyencl=$num1>0?round(array_sum(array_column($students,'overall'))/$num1,2):0;
    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">'.$num1.'</div>';
    echo '</div>';
    echo '</div>';

    // Chart
    $colors=['#c9a84c','#2e7d5e','#e67e22','#2980b9','#8e44ad','#e74c3c'];
    $markers=['square','cross','circle','triangle','square','circle'];
    $dataPoints=[];
    foreach($semIDs as $s=>$cid){
        $pts=[];
        foreach($students as $stu) $pts[]=['y'=>$stu['moys'][$cid]??0,'label'=>$stu['name']];
        $dataPoints[$s]=$pts;
    }
    ?>
    <div class="chart-panel noprint">
      <button class="close-btn" onclick="this.parentElement.style.display='none'">✕ Fermer</button>
      <h3>Classement des moyennes — <?php echo strtoupper($classe); ?></h3>
      <p>Cliquez sur une légende pour masquer/afficher un contrôle.</p>
      <div id="chartContainer" style="height:580px;width:98%;"></div>
    </div>
    <script src="https://cdn.canvasjs.com/canvasjs.min.js"></script>
    <script>
    window.onload=function(){
      var chart=new CanvasJS.Chart("chartContainer",{
        backgroundColor:"#fff",
        legend:{cursor:"pointer",itemclick:function(e){e.dataSeries.visible=(typeof e.dataSeries.visible==="undefined"||e.dataSeries.visible)?false:true;chart.render();}},
        axisX:{labelAngle:90,labelFontSize:12,interval:1},
        axisY:{title:"Moyenne /20",maximum:20,minimum:0},
        data:[
          <?php
          foreach($semIDs as $s=>$cid){
              $comma=($s<$nbSem-1)?',':'';
              echo '{type:"line",markerType:"'.($markers[$s]??'circle').'",markerSize:10,';
              echo 'markerColor:"'.($colors[$s]??'#999').'",color:"'.($colors[$s]??'#999').'",';
              echo 'name:'.json_encode($semNames[$cid]).',showInLegend:true,';
              echo 'dataPoints:'.json_encode($dataPoints[$s],JSON_NUMERIC_CHECK).'}' .$comma;
          }
          ?>
        ]
      });
      chart.render();
    };
    </script>
    <?php
    echo '</div>';
    } // end nbSem > 0
}
?>
</body>
</html>
