<?php
require_once '../config/database.php';
require_once '../includes/auth_check.php';
require_once '../includes/functions.php';

header('Content-Type: text/html; charset=utf-8');

checkRole(['super_admin','school_admin','teacher']);
requirePermission('grades', 'view');

$schoolFilter = currentSchoolId();
$class_id     = (int)($_GET['class_id']     ?? 0);
$trimestre    = (int)($_GET['trimestre']    ?? getActivePeriod());
$academic_year = trim($_GET['academic_year'] ?? getDefaultAcademicYear($pdo, $schoolFilter));

if (!in_array($trimestre,[1,2,3])) $trimestre = 1;

// ── Classes ──
if ($schoolFilter) {
    $classes = $pdo->query("SELECT c.id,c.name FROM classes c ORDER BY " . getClassSortSQL('c'))->fetchAll();
} else {
    $selSchool = (int)($_GET['school_id'] ?? 0);
    if ($selSchool) {
        $classes = $pdo->query("SELECT c.id,c.name FROM classes c ORDER BY " . getClassSortSQL('c'))->fetchAll();
    } else {
        $classes = $pdo->query("SELECT c.id,c.name FROM classes c ORDER BY " . getClassSortSQL('c'))->fetchAll();
    }
}

$schoolsList = $pdo->query("SELECT id,name FROM schools ORDER BY name")->fetchAll();
$years = $pdo->query("SELECT DISTINCT year FROM academic_years WHERE school_id=" . (int)($schoolFilter ?: 0))->fetchAll(PDO::FETCH_COLUMN);
if (empty($years)) {
    $years = $pdo->query("SELECT DISTINCT year FROM academic_years ORDER BY year DESC")->fetchAll(PDO::FETCH_COLUMN);
}
if (empty($years)) { $years = []; }
$years = array_unique(array_merge($years, [date('Y') . '-' . (date('Y')+1)]));

// ── Calculs ──
$students = []; $distrib = ['0-8'=>0,'8-10'=>0,'10-12'=>0,'12-16'=>0,'16-20'=>0];
$classInfo = null;

if ($class_id) {
    $cl = $pdo->prepare("SELECT c.* FROM classes c WHERE c.id=?");
    $cl->execute([$class_id]); $classInfo = $cl->fetch();

    // Tous les élèves
    $stAll = $pdo->prepare("SELECT id,first_name,last_name,gender FROM students WHERE class_id=? ORDER BY last_name, first_name");
    $stAll->execute([$class_id]); $stAll = $stAll->fetchAll();

    // Matières
    $subjStmt = $pdo->prepare("SELECT DISTINCT s.id,s.name,s.code,COALESCE(cs.coefficient,1) AS coefficient FROM class_subjects cs JOIN subjects s ON cs.subject_id=s.id WHERE cs.class_id=? ORDER BY cs.sort_order,s.name");
    $subjStmt->execute([$class_id]); $allSubjects = $subjStmt->fetchAll();

    // Toutes les notes de la classe
    $grStmt = $pdo->prepare("SELECT * FROM grades WHERE class_id=? AND trimestre=? AND academic_year=?");
    $grStmt->execute([$class_id,$trimestre,$academic_year]);
    $allGrades = [];
    foreach ($grStmt->fetchAll() as $r) $allGrades[$r['student_id']][$r['subject_id']] = $r;

    // Calcul moyenne générale par matière pour chaque élève
    foreach ($stAll as $st) {
        $totalPts = 0; $totalCoef = 0; $subjMoys = [];
        $grades = $allGrades[$st['id']] ?? [];
        foreach ($allSubjects as $subj) {
            $g = $grades[$subj['id']] ?? [];
            $ni = isset($g['note_interro']) && $g['note_interro'] !== null ? (float)$g['note_interro'] : null;
            $nd = isset($g['note_devoir'])  && $g['note_devoir']  !== null ? (float)$g['note_devoir']  : null;
            $nc = isset($g['note_compo'])   && $g['note_compo']   !== null ? (float)$g['note_compo']   : null;
            $moy = calcMoyMatiere($ni, $nd, $nc);
            $coef = (float)($subj['coefficient'] ?? 1);
            $subjMoys[$subj['id']] = $moy;
            if ($moy !== null) { $totalPts += $moy * $coef; $totalCoef += $coef; }
        }
        $moyGen = $totalCoef > 0 ? round($totalPts/$totalCoef,2) : null;
        $students[] = ['id'=>$st['id'],'first_name'=>$st['first_name'],'last_name'=>$st['last_name'],'gender'=>$st['gender'],'moy'=>$moyGen,'subjs'=>$subjMoys];
    }

    // Classement par moyenne décroissante
    usort($students, fn($a,$b) => ($b['moy']??-1) <=> ($a['moy']??-1));

    // Assigner les rangs (gestion des ex-aequo)
    $rank = 1; $prevMoy = null; $skip = 0;
    foreach ($students as $i => &$st) {
        if ($st['moy'] === null) { $st['rank'] = null; continue; }
        if ($prevMoy !== null && $st['moy'] < $prevMoy) { $rank += $skip; $skip = 0; }
        elseif ($prevMoy !== null && $st['moy'] == $prevMoy) { $skip++; }
        else { $skip = 0; }
        $st['rank'] = $rank;
        $prevMoy = $st['moy'];
        $skip++;

        // Distribution
        if ($st['moy'] !== null) {
            if ($st['moy'] < 8) $distrib['0-8']++;
            elseif ($st['moy'] < 10) $distrib['8-10']++;
            elseif ($st['moy'] < 12) $distrib['10-12']++;
            elseif ($st['moy'] < 16) $distrib['12-16']++;
            else $distrib['16-20']++;
        }
    }
    unset($st);
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Statistiques de classe — Nukunu Mofiala</title>
<link rel="stylesheet" href="../assets/css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
:root{--primary:#1F4E79;--accent:#2E75B6;--light:#D6E4F0;--success:#10B981;--warning:#F59E0B;--error:#EF4444;--bg:#F1F5F9;--text:#1E293B;}
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;background:var(--bg);color:var(--text);line-height:1.6;}
.main-content{padding-top:0;}
.content{padding:30px;max-width:1400px;}
.selection-card{background:white;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,0.06);padding:24px 30px;margin-bottom:25px;}
.selection-title{font-family:Georgia,serif;color:var(--primary);font-size:1.2rem;margin-bottom:20px;padding-bottom:10px;border-bottom:2px solid var(--light);}
.selection-row{display:flex;gap:25px;align-items:flex-end;flex-wrap:wrap;}
.select-group{display:flex;flex-direction:column;gap:8px;flex:1;min-width:200px;}
.select-label{font-weight:600;color:var(--primary);font-size:.85rem;}
.select-input{padding:12px 16px;border:1px solid #D1D5DB;border-radius:8px;font-size:.95rem;background:white;cursor:pointer;transition:all .2s;appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23666' d='M6 9L1 4h10z'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 14px center;padding-right:36px;}
.select-input:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 3px rgba(46,117,182,0.15);}
.btn{padding:10px 20px;border:none;border-radius:8px;font-size:.9rem;font-weight:600;cursor:pointer;transition:all .2s;display:inline-flex;align-items:center;gap:8px;text-decoration:none;}
.btn-primary{background:var(--primary);color:white;}
.btn-primary:hover{background:#163a5c;}
.btn-success{background:var(--success);color:white;}
.btn-light{background:#E5E7EB;color:#374151;}
.btn-light:hover{background:#D1D5DB;}
.stats-row{display:flex;gap:20px;margin-bottom:25px;flex-wrap:wrap;}
.stat-card{background:white;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,0.06);padding:20px 24px;flex:1;min-width:170px;display:flex;align-items:center;gap:16px;}
.stat-icon{width:48px;height:48px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:1.5rem;flex-shrink:0;}
.stat-icon.blue{background:#DBEAFE;}.stat-icon.green{background:#D1FAE5;}.stat-icon.orange{background:#FEF3C7;}.stat-icon.purple{background:#E9E5FF;}
.stat-value{font-size:1.6rem;font-weight:700;color:var(--primary);}
.stat-label{font-size:.85rem;color:#6B7280;}
.stats-card{background:white;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,0.06);margin-bottom:25px;overflow:hidden;}
.stats-card-header{padding:18px 30px;background:var(--light);display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;}
.stats-card-title{font-family:Georgia,serif;color:var(--primary);font-size:1.15rem;display:flex;align-items:center;gap:12px;}
.saisie-table{width:100%;border-collapse:collapse;}
.saisie-table thead{background:var(--primary);color:white;}
.saisie-table th{padding:12px 14px;text-align:center;font-weight:600;font-size:.78rem;text-transform:uppercase;letter-spacing:.5px;white-space:nowrap;}
.saisie-table th:first-child,.saisie-table th:nth-child(2){text-align:left;}
.saisie-table td{padding:8px 14px;border-bottom:1px solid #E5E7EB;text-align:center;font-size:.82rem;}
.saisie-table tbody tr:hover{background:#F9FAFB;}
.saisie-table tbody tr:nth-child(even){background:#F9FAFB;}
.table-moy-high{color:#059669;font-weight:700;}
.table-moy-mid{color:#D97706;font-weight:600;}
.table-moy-low{color:#DC2626;font-weight:600;}
.distrib-container{display:flex;align-items:center;gap:1.5rem;flex-wrap:wrap;justify-content:center;}
.distrib-card{text-align:center;padding:.75rem 1.25rem;border-radius:8px;min-width:110px;flex-shrink:0;}
.distrib-card.echec{background:#FEF2F2;border:1px solid #FECACA;}
.distrib-card.reussite{background:#F0FFF4;border:1px solid #BBF7D0;}
.distrib-card .label{font-size:.7rem;text-transform:uppercase;font-weight:600;}
.distrib-card .count{font-size:1.2rem;font-weight:800;}
.distrib-card .pct{font-size:.8rem;}
.distrib-table{width:100%;max-width:520px;margin:0 auto;border-collapse:collapse;font-size:.85rem;}
.distrib-table th{background:var(--primary);color:white;padding:.45rem .5rem;text-align:center;font-size:.8rem;text-transform:uppercase;letter-spacing:.03em;}
.distrib-table td{padding:.35rem .5rem;border-bottom:1px solid #E5E7EB;text-align:center;font-size:.85rem;}
.distrib-table td:first-child{text-align:left;font-weight:500;}
.distrib-table td:nth-child(2){font-weight:700;font-size:.95rem;}
.distrib-table tfoot td{font-size:.85rem;font-weight:700;background:#F1F5F9;}
.stats-bar{height:18px;border-radius:4px;background:#E5E7EB;overflow:hidden;min-width:40px;}
.stats-bar-fill{height:100%;border-radius:4px;transition:width .4s;}
.bar-0-8 .stats-bar-fill{background:#DC2626;}
.bar-8-10 .stats-bar-fill{background:#F59E0B;}
.bar-10-12 .stats-bar-fill{background:#D97706;}
.bar-12-16 .stats-bar-fill{background:#10B981;}
.bar-16-20 .stats-bar-fill{background:#2563EB;}
.toast-container{position:fixed;bottom:30px;right:30px;z-index:2000;display:flex;flex-direction:column;gap:10px;}
.toast{background:white;padding:14px 20px;border-radius:8px;box-shadow:0 4px 20px rgba(0,0,0,0.15);display:flex;align-items:center;gap:12px;animation:slideIn .3s ease;border-left:4px solid var(--primary);}
.toast-success{border-left-color:#10B981;}
.toast-error{border-left-color:#EF4444;}
@keyframes slideIn{from{transform:translateX(100%);opacity:0;} to{transform:translateX(0);opacity:1;}}
.empty-state{text-align:center;padding:3rem 1rem;color:#9CA3AF;}
.stats-actions{display:flex;gap:.75rem;flex-wrap:wrap;align-items:center;padding:.75rem 0;}
@media(max-width:768px){
.selection-row{flex-direction:column;align-items:stretch;}
.select-group{min-width:100%;}
.content{padding:16px;}
.saisie-table{font-size:.75rem;}
}
@media print{
.selection-card,.stats-actions{display:none!important;}
.content{padding:0;max-width:100%;}
.stats-card{box-shadow:none;border:1px solid #ddd;break-inside:avoid;}
.saisie-table{font-size:.72rem;}
.stats-card-header{padding:12px 16px;}
}
</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-chart-bar"></i> Statistiques de classe'; include '../includes/topbar.php'; ?>
        <?php $__flash = $_SESSION['flash_toast'] ?? null; unset($_SESSION['flash_toast']); ?>
        <?php if ($__flash): ?>
        <script>document.addEventListener('DOMContentLoaded',function(){showToast(<?= json_encode($__flash['message']) ?>,<?= json_encode($__flash['type']) ?>);});</script>
        <?php endif; ?>

        <div class="content">

        <!-- ═══ FILTRES ═══ -->
        <div class="selection-card">
            <div class="selection-title"><i class="fas fa-filter"></i> Filtres statistiques</div>
            <form method="GET" class="selection-row">
                <?php if (!$schoolFilter): ?>
                <div class="select-group">
                    <label class="select-label">École</label>
                    <select name="school_id" class="select-input" onchange="this.form.submit()">
                        <option value="">— Toutes —</option>
                        <?php foreach($schoolsList as $sc): ?>
                        <option value="<?=$sc['id']?>" <?=($_GET['school_id']??'')==$sc['id']?'selected':''?>><?=e($sc['name'])?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <div class="select-group">
                    <label class="select-label">Classe</label>
                    <select name="class_id" class="select-input" onchange="this.form.submit()">
                        <option value="">— Choisir —</option>
                        <?php foreach($classes as $cl): ?>
                        <option value="<?=$cl['id']?>" <?=$cl['id']==$class_id?'selected':''?>>
                            <?=e($cl['name'])?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="select-group">
                    <label class="select-label">Trimestre</label>
                    <select name="trimestre" class="select-input" onchange="this.form.submit()">
                        <option value="1" <?=$trimestre==1?'selected':''?>>1er Trimestre</option>
                        <option value="2" <?=$trimestre==2?'selected':''?>>2ème Trimestre</option>
                        <option value="3" <?=$trimestre==3?'selected':''?>>3ème Trimestre</option>
                    </select>
                </div>
                <div class="select-group">
                    <label class="select-label">Année scolaire</label>
                    <select name="academic_year" class="select-input">
                        <?php foreach($years as $y): ?>
                        <option value="<?=e($y)?>" <?=$y===$academic_year?'selected':''?>><?=e($y)?></option>
                        <?php endforeach; ?>
                    </select>
                    <noscript><button type="submit" class="btn btn-primary" style="margin-top:8px;">Valider</button></noscript>
                </div>
            </form>
        </div>

        <?php if ($class_id): ?>
        <div class="stats-actions">
            <span style="font-weight:600;font-size:.85rem;color:var(--primary);"><i class="fas fa-exchange-alt"></i> Import / Export</span>
            <a href="grades.php?class_id=<?= $class_id ?>&trimestre=<?= $trimestre ?>&academic_year=<?= urlencode($academic_year) ?>&export=1&csrf_token=<?= csrfToken() ?>" class="btn btn-success" style="padding:.5rem 1rem;font-size:.82rem;"><i class="fas fa-download"></i> Export classe</a>
            <a href="grades.php?class_id=<?= $class_id ?>&trimestre=<?= $trimestre ?>&academic_year=<?= urlencode($academic_year) ?>" class="btn btn-light" style="padding:.5rem 1rem;font-size:.82rem;"><i class="fas fa-upload"></i> Import classe</a>
        </div>
        <?php endif; ?>

        <?php if (!$class_id): ?>
        <div class="selection-card">
            <div class="empty-state">
                <i class="fas fa-chart-bar" style="font-size:2.5rem;display:block;margin-bottom:.75rem;color:#CBD5E1;"></i>
                <p style="font-size:1.05rem;">Sélectionnez une classe pour voir les statistiques.</p>
            </div>
        </div>
        <?php else: ?>

        <!-- ══ CLASSEMENT ══ -->
        <div class="stats-card">
            <div class="stats-card-header">
                <div class="stats-card-title">
                    <i class="fas fa-trophy"></i> Classement — <?=e($classInfo['name']??'')?> — Trimestre <?=$trimestre?> — <?=e($academic_year)?>
                    <span style="font-weight:400;font-size:.82rem;color:#6B7280;margin-left:.5rem;">(<?=count($students)?> élève<?=count($students)>1?'s':''?>)</span>
                </div>
                <button onclick="window.print()" class="btn btn-light" style="padding:.4rem .9rem;font-size:.82rem;"><i class="fas fa-print"></i> Imprimer</button>
            </div>
            <div style="overflow-x:auto;padding:0;">
            <table class="saisie-table">
                <thead>
                    <tr>
                        <th style="width:50px;">Rang</th>
                        <th>Élève</th>
                        <th style="width:40px;">Sexe</th>
                        <?php foreach($allSubjects as $subj): ?>
                        <th style="font-size:.7rem;min-width:46px;white-space:nowrap;">
                            <?=e($subj['code'] ?: $subj['name'])?>
                            <small style="display:block;font-size:.65rem;color:rgba(255,255,255,0.8);font-weight:400;">&times;<?=number_format($subj['coefficient']??1,1)?></small>
                        </th>
                        <?php endforeach; ?>
                        <th style="width:80px;">Moy. Gén</th>
                        <th>Appréciation</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($students as $st):
                        $cls = '';
                        if ($st['moy'] !== null) {
                            if ($st['moy'] >= 16) $cls = 'table-moy-high';
                            elseif ($st['moy'] >= 12) $cls = 'table-moy-mid';
                            elseif ($st['moy'] < 10) $cls = 'table-moy-low';
                        }
                        $mention = $st['moy'] !== null
                            ? ($st['moy']>=16?'Très Bien':($st['moy']>=14?'Bien':($st['moy']>=12?'Assez Bien':($st['moy']>=10?'Passable':($st['moy']>=8?'Insuffisant':'Très Insuffisant')))))
                            : '—';
                        $icon = $st['gender'] === 'M' ? 'fa-male' : ($st['gender'] === 'F' ? 'fa-female' : 'fa-venus-mars');
                    ?>
                    <tr>
                        <td style="font-weight:700;text-align:center;"><?=$st['rank']!==null?$st['rank'].($st['rank']===1?'<sup>er</sup>':'<sup>ème</sup>'):'—'?></td>
                        <td style="text-align:left;"><?=e($st['last_name'].' '.$st['first_name'])?></td>
                        <td style="text-align:center;color:#9CA3AF;"><i class="fas <?=$icon?>"></i></td>
                        <?php foreach($allSubjects as $subj):
                            $sm = $st['subjs'][$subj['id']] ?? null;
                            $sc = $sm !== null ? ($sm>=12?'table-moy-high':($sm>=10?'table-moy-mid':'table-moy-low')) : '';
                        ?>
                        <td class="<?=$sc?>" style="text-align:center;font-size:.75rem;"><?=$sm!==null?number_format($sm,2):'—'?></td>
                        <?php endforeach; ?>
                        <td class="<?=$cls?>" style="text-align:center;"><?=$st['moy']!==null?number_format($st['moy'],2):'—'?></td>
                        <td style="font-size:.78rem;color:#6B7280;"><?=$mention?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            </div>
        </div>

        <!-- ══ RÉPARTITION ══ -->
        <div class="stats-card">
            <div class="stats-card-header">
                <div class="stats-card-title"><i class="fas fa-chart-pie"></i> Répartition des moyennes</div>
            </div>
            <div style="padding:1.5rem;">
            <?php $total = array_sum($distrib); $max = max($distrib) ?: 1;
                  $reussite = ($distrib['10-12']??0) + ($distrib['12-16']??0) + ($distrib['16-20']??0);
                  $echec    = ($distrib['0-8']??0) + ($distrib['8-10']??0);
                  $tauxR    = $total > 0 ? round($reussite/$total*100,1) : 0;
                  $tauxE    = $total > 0 ? round($echec/$total*100,1) : 0;
            ?>
            <div class="distrib-container">
                <div class="distrib-card echec">
                    <div class="label" style="color:#991B1B;">Échec</div>
                    <div class="count" style="color:#7F1D1D;"><?=$echec?></div>
                    <div class="pct" style="color:#DC2626;"><?=$tauxE?>%</div>
                </div>
                <div style="flex:1;min-width:300px;">
                <table class="distrib-table">
                    <thead>
                        <tr>
                            <th>Tranche</th>
                            <th>Effectif</th>
                            <th>%</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($distrib as $key => $count): ?>
                        <?php $pct = $total > 0 ? round($count/$total*100,1) : 0; ?>
                        <tr class="bar-<?=$key?>">
                            <td style="text-align:left;padding-left:1rem;"><?=str_replace('-',' à ',$key)?></td>
                            <td><?=$count?></td>
                            <td><?=$pct?>%</td>
                            <td>
                                <div class="stats-bar">
                                    <div class="stats-bar-fill" style="width:<?=max(5,$count/$max*100)?>%;"></div>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td style="text-align:left;padding-left:1rem;">Total</td>
                            <td><?=$total?></td>
                            <td>100%</td>
                            <td></td>
                        </tr>
                    </tfoot>
                </table>
                </div>
                <div class="distrib-card reussite">
                    <div class="label" style="color:#166534;">Réussite</div>
                    <div class="count" style="color:#14532D;"><?=$reussite?></div>
                    <div class="pct" style="color:#10B981;"><?=$tauxR?>%</div>
                </div>
            </div>
            </div>
        </div>

        <?php endif; ?>
        </div>
    </div>
</div>

<div class="toast-container" id="toastContainer"></div>

<script>
function showToast(message,type){var c=document.getElementById('toastContainer');var t=document.createElement('div');t.className='toast toast-'+(type||'success');var icons={success:'&#x2705;',error:'&#x274C;'};t.innerHTML='<span>'+(icons[type]||'&#x2139;&#xFE0F;')+'</span><span>'+message+'</span>';c.appendChild(t);setTimeout(function(){t.remove();},4000);}
</script>
</body>
</html>
