<?php
/**
 * Génération des bulletins scolaires
 * Affiche la liste des élèves d'une classe avec lien vers chaque bulletin
 */
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']);

$schoolFilter  = currentSchoolId();
if (isSuperAdmin() && !empty($_GET['school_id'])) {
    $schoolFilter = (int)$_GET['school_id'];
}
$class_id       = (int)($_GET['class_id']       ?? 0);
$trimestre      = (int)($_GET['trimestre']      ?? getActivePeriod());
$academic_year  = trim($_GET['academic_year']   ?? getDefaultAcademicYear($pdo, currentSchoolId()));
$student_id     = (int)($_GET['student_id']     ?? 0);
$production_date = trim($_GET['production_date'] ?? '');

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

$classes = $pdo->query("SELECT c.id,c.name,c.academic_year FROM classes c ORDER BY " . getClassSortSQL('c'))->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)]));

// ── Fonctions de calcul ─────────────────────────────────────────────────────
function getMention(float $moy): string {
    return autoAppreciation($moy);
}
function ordinalFr(int $n): string {
    return $n . ($n === 1 ? 'er' : 'ème');
}
// Si on demande un bulletin précis → afficher le bulletin HTML
if ($class_id && $student_id) {
    // ── Charger toutes les données du bulletin ──────────────────────────────

    // Vérifier que l'enseignant est bien affecté à cette classe (si rôle teacher)
    if (hasRole('teacher')) {
        $assigned = $pdo->prepare("SELECT ta.id FROM teacher_assignments ta JOIN teachers t ON ta.teacher_id=t.id JOIN users u ON u.email=t.email WHERE u.id=? AND ta.class_id=? LIMIT 1");
        $assigned->execute([$_SESSION['user_id'], $class_id]);
        if (!$assigned->fetch()) {
            flashMessage('error','Vous n\'êtes pas autorisé à consulter cette classe.');
            header('Location: bulletin.php'); exit;
        }
    }

    // Infos élève + vérifier qu'il appartient bien à la classe
    $studentInfo = $pdo->prepare("SELECT * FROM students WHERE id=? AND class_id=?");
    $studentInfo->execute([$student_id, $class_id]); $studentInfo = $studentInfo->fetch();
    if (!$studentInfo) { flashMessage('error','Élève introuvable dans cette classe.'); header('Location: bulletin.php'); exit; }

    // Infos classe
    $classInfo = $pdo->prepare("SELECT c.* FROM classes c WHERE c.id=?");
    $classInfo->execute([$class_id]); $classInfo = $classInfo->fetch();
    if (!$classInfo) { flashMessage('error','Classe introuvable.'); header('Location: bulletin.php'); exit; }

    $schoolId = (int)$studentInfo['school_id'];

    // Infos école pour le template bulletin_view
    $scStmt = $pdo->prepare("SELECT name AS school_name, address, logo FROM schools WHERE id=?");
    $scStmt->execute([$schoolId]);
    $schoolInfo = $scStmt->fetch() ?: [];
    foreach ($schoolInfo as $k => $v) $classInfo[$k] = $v;

    // Titulaire de la classe
    $titulaire = '';
    $ttStmt = $pdo->prepare("SELECT t.first_name, t.last_name FROM classes c
        JOIN teachers t ON c.titulaire_id = t.id
        WHERE c.id = ?");
    $ttStmt->execute([$class_id]);
    if ($ttRow = $ttStmt->fetch()) {
        $titulaire = 'M. ' . strtoupper($ttRow['last_name']) . ' ' . $ttRow['first_name'];
    }

    // Directeur de l'école
    $directeur = '';
    $dirStmt = $pdo->prepare("SELECT name FROM users WHERE school_id = ? AND role = 'school_admin' LIMIT 1");
    $dirStmt->execute([$schoolId]);
    if ($dirRow = $dirStmt->fetch()) {
        $directeur = $dirRow['name'];
    }

    // Effectif de la classe
    $effStmt = $pdo->prepare("SELECT COUNT(*) FROM students WHERE class_id=?");
    $effStmt->execute([$class_id]);
    $effectif = (int)$effStmt->fetchColumn();

    // Matières avec groupes et coefficients — filtre par école
    $subjStmt = $pdo->prepare("
        SELECT s.id, s.name, s.code,
               COALESCE(sg.name,'Autres') AS group_name,
               COALESCE(sg.sort_order,99) AS group_order,
               COALESCE(cs.coefficient,1) AS coefficient
        FROM class_subjects cs
        JOIN subjects s       ON cs.subject_id = s.id
        LEFT JOIN subject_groups sg ON s.group_id = sg.id
        WHERE cs.class_id = ? AND cs.school_id = ?
        ORDER BY COALESCE(sg.sort_order,99), cs.sort_order, s.name");
    $subjStmt->execute([$class_id, $schoolId]);
    $allSubjects = $subjStmt->fetchAll();

    // Notes de l'élève
    $grStmt = $pdo->prepare("SELECT * FROM grades WHERE student_id=? AND class_id=? AND trimestre=? AND academic_year=?");
    $grStmt->execute([$student_id,$class_id,$trimestre,$academic_year]);
    $gradesBySubject = [];
    foreach ($grStmt->fetchAll() as $r) $gradesBySubject[$r['subject_id']] = $r;

    // Assiduité de l'élève
    $attStmt = $pdo->prepare("SELECT * FROM attendance WHERE student_id=? AND class_id=? AND trimestre=? AND academic_year=?");
    $attStmt->execute([$student_id,$class_id,$trimestre,$academic_year]);
    $att = $attStmt->fetch() ?: [];

    // ── Calculs des moyennes ────────────────────────────────────────────────

    // Calculer moyennes par matière et par groupe
    $groupedSubjects = [];
    $totalPoints = 0; $totalCoef = 0;

    foreach ($allSubjects as $subj) {
        $g = $gradesBySubject[$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);
        $moyCoef = $moy !== null ? $moy * $coef : null;

        // Rang dans la classe pour cette matière
        $rangStmt = $pdo->prepare("
            SELECT COUNT(*) + 1 AS rang FROM grades g2
            WHERE g2.class_id=? AND g2.trimestre=? AND g2.academic_year=?
              AND g2.subject_id=?
              AND (
                CASE
                  WHEN g2.note_interro IS NOT NULL AND g2.note_devoir IS NOT NULL AND g2.note_compo IS NOT NULL
                    THEN (g2.note_interro*1+g2.note_devoir*2+g2.note_compo*3)/6
                  WHEN g2.note_interro IS NOT NULL AND g2.note_devoir IS NOT NULL
                    THEN (g2.note_interro*1+g2.note_devoir*2)/3
                  WHEN g2.note_interro IS NOT NULL AND g2.note_compo IS NOT NULL
                    THEN (g2.note_interro*1+g2.note_compo*3)/4
                  WHEN g2.note_devoir IS NOT NULL AND g2.note_compo IS NOT NULL
                    THEN (g2.note_devoir*2+g2.note_compo*3)/5
                  WHEN g2.note_interro IS NOT NULL THEN g2.note_interro
                  WHEN g2.note_devoir IS NOT NULL THEN g2.note_devoir
                  WHEN g2.note_compo IS NOT NULL THEN g2.note_compo
                  ELSE NULL
                END
              ) > ?");
        $rangStmt->execute([$class_id,$trimestre,$academic_year,$subj['id'],$moy ?? -1]);
        $rang = $moy !== null ? (int)$rangStmt->fetchColumn() : null;

        $grpName = $subj['group_name'] ?? 'Autres';
        if (!isset($groupedSubjects[$grpName])) {
            $groupedSubjects[$grpName] = ['subjects'=>[],'totalPts'=>0,'totalCoef'=>0,'moy'=>null];
        }
        $groupedSubjects[$grpName]['subjects'][] = [
            'id'=>$subj['id'],'name'=>$subj['name'],'code'=>$subj['code'],
            'coef'=>$coef,'ni'=>$ni,'nd'=>$nd,'nc'=>$nc,'moy'=>$moy,
            'moyCoef'=>$moyCoef,'rang'=>$rang,
            'moy_classe'=>$g['moy_classe'] ?? null,
            'appreciation'=>$g['appreciation'] ?? '',
        ];
        if ($moy !== null) {
            $groupedSubjects[$grpName]['totalPts']  += $moyCoef;
            $groupedSubjects[$grpName]['totalCoef'] += $coef;
            $totalPoints += $moyCoef;
            $totalCoef   += $coef;
        }
    }

    // Moy par groupe
    foreach ($groupedSubjects as &$grp) {
        $grp['moy'] = $grp['totalCoef'] > 0 ? $grp['totalPts']/$grp['totalCoef'] : null;
    }
    unset($grp);

    // Moyenne générale
    $moyGeneral = $totalCoef > 0 ? round($totalPoints/$totalCoef,2) : null;

    // Rang général — sous-requête nommée correctement pour MySQL 5.7+
    $rangGeneralStmt = $pdo->prepare("
        SELECT COUNT(*) + 1 FROM (
            SELECT g.student_id,
                SUM(CASE
                    WHEN g.note_interro IS NOT NULL AND g.note_devoir IS NOT NULL AND g.note_compo IS NOT NULL
                        THEN (g.note_interro*1+g.note_devoir*2+g.note_compo*3)/6 * COALESCE(cs.coefficient,1)
                    WHEN g.note_interro IS NOT NULL AND g.note_devoir IS NOT NULL
                        THEN (g.note_interro*1+g.note_devoir*2)/3 * COALESCE(cs.coefficient,1)
                    WHEN g.note_interro IS NOT NULL AND g.note_compo IS NOT NULL
                        THEN (g.note_interro*1+g.note_compo*3)/4 * COALESCE(cs.coefficient,1)
                    WHEN g.note_devoir IS NOT NULL AND g.note_compo IS NOT NULL
                        THEN (g.note_devoir*2+g.note_compo*3)/5 * COALESCE(cs.coefficient,1)
                    WHEN g.note_interro IS NOT NULL
                        THEN g.note_interro * COALESCE(cs.coefficient,1)
                    WHEN g.note_devoir IS NOT NULL
                        THEN g.note_devoir * COALESCE(cs.coefficient,1)
                    WHEN g.note_compo IS NOT NULL
                        THEN g.note_compo * COALESCE(cs.coefficient,1)
                    ELSE 0 END) /
                NULLIF(SUM(COALESCE(cs.coefficient,1)),0) AS moy_gen
            FROM grades g
            LEFT JOIN class_subjects cs ON cs.subject_id=g.subject_id AND cs.class_id=g.class_id
            WHERE g.class_id=? AND g.trimestre=? AND g.academic_year=?
            GROUP BY g.student_id
        ) AS rang_sub WHERE rang_sub.moy_gen > ?");
    $rangGeneralStmt->execute([$class_id,$trimestre,$academic_year,$moyGeneral ?? -1]);
    $rangGeneral = $moyGeneral !== null ? (int)$rangGeneralStmt->fetchColumn() : null;

    // Moyennes extrêmes — sous-requête nommée correctement
    $extremesStmt = $pdo->prepare("
        SELECT MAX(moy_gen) AS max_moy, MIN(moy_gen) AS min_moy, AVG(moy_gen) AS avg_moy FROM (
            SELECT g.student_id,
                SUM(CASE
                    WHEN g.note_interro IS NOT NULL AND g.note_devoir IS NOT NULL AND g.note_compo IS NOT NULL
                        THEN (g.note_interro*1+g.note_devoir*2+g.note_compo*3)/6 * COALESCE(cs.coefficient,1)
                    WHEN g.note_interro IS NOT NULL AND g.note_devoir IS NOT NULL
                        THEN (g.note_interro*1+g.note_devoir*2)/3 * COALESCE(cs.coefficient,1)
                    WHEN g.note_interro IS NOT NULL AND g.note_compo IS NOT NULL
                        THEN (g.note_interro*1+g.note_compo*3)/4 * COALESCE(cs.coefficient,1)
                    WHEN g.note_devoir IS NOT NULL AND g.note_compo IS NOT NULL
                        THEN (g.note_devoir*2+g.note_compo*3)/5 * COALESCE(cs.coefficient,1)
                    WHEN g.note_interro IS NOT NULL THEN g.note_interro * COALESCE(cs.coefficient,1)
                    WHEN g.note_devoir IS NOT NULL THEN g.note_devoir * COALESCE(cs.coefficient,1)
                    WHEN g.note_compo IS NOT NULL THEN g.note_compo * COALESCE(cs.coefficient,1)
                    ELSE 0 END) /
                NULLIF(SUM(COALESCE(cs.coefficient,1)),0) AS moy_gen
            FROM grades g
            LEFT JOIN class_subjects cs ON cs.subject_id=g.subject_id AND cs.class_id=g.class_id
            WHERE g.class_id=? AND g.trimestre=? AND g.academic_year=?
            GROUP BY g.student_id
        ) AS extremes_sub");
    $extremesStmt->execute([$class_id,$trimestre,$academic_year]);
    $extremes = $extremesStmt->fetch();

    // Mention travail générale
    $mentionTravail = $moyGeneral !== null ? getMention($moyGeneral) : '';

    // Template de bulletin (récupérer le défaut ou le premier de l'école)
    $tplStmt = $pdo->prepare("SELECT * FROM report_templates WHERE school_id=? ORDER BY is_default DESC LIMIT 1");
    $tplStmt->execute([$schoolId]);
    $tpl = $tplStmt->fetch() ?: [];

    // Vérifier si un template PDF est assigné pour cette classe/école
    require_once '../includes/bulletin_pdf.php';
    $bulletinTemplatePath = getBulletinTemplatePath($pdo, $schoolId, $class_id, $academic_year);

    // Mode impression ?
    $print = isset($_GET['print']);

    // Mode téléchargement PDF
    if (isset($_GET['download_pdf'])) {
        ob_start();
        include '../includes/bulletin_view.php';
        $html = ob_get_clean();
        $filename = 'bulletin_' . $studentInfo['last_name'] . '_' . $studentInfo['first_name'] . '_T' . $trimestre . '.pdf';
        if ($bulletinTemplatePath) {
            generateBulletinPDFWithTemplate($html, $filename, $bulletinTemplatePath);
        } else {
            generateBulletinPDF($html, $filename);
        }
        exit;
    }

    include '../includes/bulletin_view.php';
    exit;
}

// Fonction pour ajouter production_date à une URL
function addProdDate($url) {
    global $production_date;
    if ($production_date) $url .= '&production_date=' . urlencode($production_date);
    return $url;
}

// ══ FONCTION CALCUL BULLETIN (pour réutilisation dans print_all) ══
function computeBulletin($pdo, $student_id, $class_id, $trimestre, $academic_year, $allSubjects, $classInfo = [], $schoolId = 0) {
    $stInfo = $pdo->prepare("SELECT * FROM students WHERE id=?");
    $stInfo->execute([$student_id]); $studentInfo = $stInfo->fetch();
    if ($schoolId === 0) $schoolId = (int)($studentInfo['school_id'] ?? 0);

    $grStmt = $pdo->prepare("SELECT * FROM grades WHERE student_id=? AND class_id=? AND trimestre=? AND academic_year=?");
    $grStmt->execute([$student_id,$class_id,$trimestre,$academic_year]);
    $gradesBySubject = []; foreach ($grStmt->fetchAll() as $r) $gradesBySubject[$r['subject_id']] = $r;

    $attStmt = $pdo->prepare("SELECT * FROM attendance WHERE student_id=? AND class_id=? AND trimestre=? AND academic_year=?");
    $attStmt->execute([$student_id,$class_id,$trimestre,$academic_year]); $att = $attStmt->fetch() ?: [];

    $groupedSubjects = []; $totalPoints = 0; $totalCoef = 0;
    foreach ($allSubjects as $subj) {
        $g = $gradesBySubject[$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);
        $moyCoef = $moy !== null ? $moy * $coef : null;
        $rangStmt = $pdo->prepare("SELECT COUNT(*)+1 FROM grades g2 WHERE g2.class_id=? AND g2.trimestre=? AND g2.academic_year=? AND g2.subject_id=? AND (CASE WHEN g2.note_interro IS NOT NULL AND g2.note_devoir IS NOT NULL AND g2.note_compo IS NOT NULL THEN (g2.note_interro*1+g2.note_devoir*2+g2.note_compo*3)/6 WHEN g2.note_interro IS NOT NULL AND g2.note_devoir IS NOT NULL THEN (g2.note_interro*1+g2.note_devoir*2)/3 WHEN g2.note_interro IS NOT NULL AND g2.note_compo IS NOT NULL THEN (g2.note_interro*1+g2.note_compo*3)/4 WHEN g2.note_devoir IS NOT NULL AND g2.note_compo IS NOT NULL THEN (g2.note_devoir*2+g2.note_compo*3)/5 WHEN g2.note_interro IS NOT NULL THEN g2.note_interro WHEN g2.note_devoir IS NOT NULL THEN g2.note_devoir WHEN g2.note_compo IS NOT NULL THEN g2.note_compo ELSE NULL END) > ?");
        $rangStmt->execute([$class_id,$trimestre,$academic_year,$subj['id'],$moy ?? -1]);
        $rang = $moy !== null ? (int)$rangStmt->fetchColumn() : null;
        $grpName = $subj['group_name'] ?? 'Autres';
        if (!isset($groupedSubjects[$grpName])) $groupedSubjects[$grpName] = ['subjects'=>[],'totalPts'=>0,'totalCoef'=>0,'moy'=>null];
        $groupedSubjects[$grpName]['subjects'][] = [
            'id'=>$subj['id'],'name'=>$subj['name'],'code'=>$subj['code'],
            'coef'=>$coef,'ni'=>$ni,'nd'=>$nd,'nc'=>$nc,'moy'=>$moy,
            'moyCoef'=>$moyCoef,'rang'=>$rang,
            'moy_classe'=>$g['moy_classe'] ?? null,'appreciation'=>$g['appreciation'] ?? '',
        ];
        if ($moy !== null) { $groupedSubjects[$grpName]['totalPts'] += $moyCoef; $groupedSubjects[$grpName]['totalCoef'] += $coef; $totalPoints += $moyCoef; $totalCoef += $coef; }
    }
    foreach ($groupedSubjects as &$grp) { $grp['moy'] = $grp['totalCoef'] > 0 ? $grp['totalPts']/$grp['totalCoef'] : null; } unset($grp);
    $moyGeneral = $totalCoef > 0 ? round($totalPoints/$totalCoef,2) : null;
    $rangGeneralStmt = $pdo->prepare("SELECT COUNT(*)+1 FROM (SELECT g.student_id, SUM(CASE WHEN g.note_interro IS NOT NULL AND g.note_devoir IS NOT NULL AND g.note_compo IS NOT NULL THEN (g.note_interro*1+g.note_devoir*2+g.note_compo*3)/6*COALESCE(cs.coefficient,1) WHEN g.note_interro IS NOT NULL AND g.note_devoir IS NOT NULL THEN (g.note_interro*1+g.note_devoir*2)/3*COALESCE(cs.coefficient,1) WHEN g.note_interro IS NOT NULL AND g.note_compo IS NOT NULL THEN (g.note_interro*1+g.note_compo*3)/4*COALESCE(cs.coefficient,1) WHEN g.note_devoir IS NOT NULL AND g.note_compo IS NOT NULL THEN (g.note_devoir*2+g.note_compo*3)/5*COALESCE(cs.coefficient,1) WHEN g.note_interro IS NOT NULL THEN g.note_interro*COALESCE(cs.coefficient,1) WHEN g.note_devoir IS NOT NULL THEN g.note_devoir*COALESCE(cs.coefficient,1) WHEN g.note_compo IS NOT NULL THEN g.note_compo*COALESCE(cs.coefficient,1) ELSE 0 END)/NULLIF(SUM(COALESCE(cs.coefficient,1)),0) AS moy_gen FROM grades g LEFT JOIN class_subjects cs ON cs.subject_id=g.subject_id AND cs.class_id=g.class_id WHERE g.class_id=? AND g.trimestre=? AND g.academic_year=? GROUP BY g.student_id) AS rang_sub WHERE rang_sub.moy_gen > ?");
    $rangGeneralStmt->execute([$class_id,$trimestre,$academic_year,$moyGeneral ?? -1]);
    $rangGeneral = $moyGeneral !== null ? (int)$rangGeneralStmt->fetchColumn() : null;
    $extremesStmt = $pdo->prepare("SELECT MAX(moy_gen) AS max_moy, MIN(moy_gen) AS min_moy, AVG(moy_gen) AS avg_moy FROM (SELECT g.student_id, SUM(CASE WHEN g.note_interro IS NOT NULL AND g.note_devoir IS NOT NULL AND g.note_compo IS NOT NULL THEN (g.note_interro*1+g.note_devoir*2+g.note_compo*3)/6*COALESCE(cs.coefficient,1) WHEN g.note_interro IS NOT NULL AND g.note_devoir IS NOT NULL THEN (g.note_interro*1+g.note_devoir*2)/3*COALESCE(cs.coefficient,1) WHEN g.note_interro IS NOT NULL AND g.note_compo IS NOT NULL THEN (g.note_interro*1+g.note_compo*3)/4*COALESCE(cs.coefficient,1) WHEN g.note_devoir IS NOT NULL AND g.note_compo IS NOT NULL THEN (g.note_devoir*2+g.note_compo*3)/5*COALESCE(cs.coefficient,1) WHEN g.note_interro IS NOT NULL THEN g.note_interro*COALESCE(cs.coefficient,1) WHEN g.note_devoir IS NOT NULL THEN g.note_devoir*COALESCE(cs.coefficient,1) WHEN g.note_compo IS NOT NULL THEN g.note_compo*COALESCE(cs.coefficient,1) ELSE 0 END)/NULLIF(SUM(COALESCE(cs.coefficient,1)),0) AS moy_gen FROM grades g LEFT JOIN class_subjects cs ON cs.subject_id=g.subject_id AND cs.class_id=g.class_id WHERE g.class_id=? AND g.trimestre=? AND g.academic_year=? GROUP BY g.student_id) AS extremes_sub");
    $extremesStmt->execute([$class_id,$trimestre,$academic_year]);
    $extremes = $extremesStmt->fetch();
    $mentionTravail = $moyGeneral !== null ? getMention($moyGeneral) : '';

    // Titulaire
    $titulaire = '';
    $ttStmt = $pdo->prepare("SELECT t.first_name, t.last_name FROM classes c
        JOIN teachers t ON c.titulaire_id = t.id
        WHERE c.id = ?");
    $ttStmt->execute([$class_id]);
    if ($ttRow = $ttStmt->fetch()) {
        $titulaire = 'M. ' . strtoupper($ttRow['last_name']) . ' ' . $ttRow['first_name'];
    }

    // Directeur
    $directeur = '';
    $dirStmt = $pdo->prepare("SELECT name FROM users WHERE school_id = ? AND role = 'school_admin' LIMIT 1");
    $dirStmt->execute([$schoolId]);
    if ($dirRow = $dirStmt->fetch()) {
        $directeur = $dirRow['name'];
    }

    return compact('studentInfo','groupedSubjects','totalPoints','totalCoef','moyGeneral','rangGeneral','extremes','mentionTravail','att','titulaire','directeur');
}

// ══ MODE TOUT IMPRIMER (tous les élèves sur une page) ══
if (isset($_GET['print_all']) && $class_id && !$student_id) {
    $stAll = $pdo->prepare("SELECT id,first_name,last_name FROM students WHERE class_id=? ORDER BY last_name, first_name");
    $stAll->execute([$class_id]); $studentsAll = $stAll->fetchAll();
    if (empty($studentsAll)) { flashMessage('error','Aucun élève.'); header('Location: bulletin.php'); exit; }

    $classInfo = $pdo->prepare("SELECT c.* FROM classes c WHERE c.id=?");
    $classInfo->execute([$class_id]); $classInfo = $classInfo->fetch();
    if (!$classInfo) { flashMessage('error','Classe introuvable.'); header('Location: bulletin.php'); exit; }

    $effStmt = $pdo->prepare("SELECT COUNT(*) FROM students WHERE class_id=?");
    $effStmt->execute([$class_id]); $effectif = (int)$effStmt->fetchColumn();

    $schoolId = $schoolFilter;
    if (!$schoolId) {
        $st = $pdo->prepare("SELECT school_id FROM students WHERE class_id=? LIMIT 1");
        $st->execute([$class_id]);
        $schoolId = (int)$st->fetchColumn();
    }

    // Infos école pour le template bulletin_view
    $scStmt = $pdo->prepare("SELECT name AS school_name, address, logo FROM schools WHERE id=?");
    $scStmt->execute([$schoolId]);
    $schoolInfo = $scStmt->fetch() ?: [];
    foreach ($schoolInfo as $k => $v) $classInfo[$k] = $v;

    $cycleIds = getCycleClassIds($pdo, $class_id);
    $classPl = implode(',', array_fill(0, count($cycleIds), '?'));
    $subjStmt = $pdo->prepare("SELECT DISTINCT s.id,s.name,s.code,COALESCE(sg.name,'Autres') AS group_name,COALESCE(sg.sort_order,99) AS group_order,COALESCE(cs.coefficient,1) AS coefficient FROM class_subjects cs JOIN subjects s ON cs.subject_id=s.id LEFT JOIN subject_groups sg ON s.group_id=sg.id WHERE cs.class_id IN ($classPl) AND cs.school_id=? ORDER BY COALESCE(sg.sort_order,99),cs.sort_order,s.name");
    $subjStmt->execute(array_merge($cycleIds, [$schoolId])); $allSubjects = $subjStmt->fetchAll();

    $tplStmt = $pdo->prepare("SELECT * FROM report_templates WHERE school_id=? ORDER BY is_default DESC LIMIT 1");
    $tplStmt->execute([$schoolId]); $tpl = $tplStmt->fetch() ?: [];

    require_once '../includes/bulletin_pdf.php';
    $bulletinTemplatePath = getBulletinTemplatePath($pdo, $schoolId, $class_id, $academic_year);

    // Pré-calculer tous les bulletins une seule fois
    $bulletinsData = [];
    foreach ($studentsAll as $st) {
        $cacheKey = 'bulletin_' . $st['id'] . '_' . $class_id . '_T' . $trimestre . '_' . $academic_year;
        $_vars = cacheGet($cacheKey, 60) ?: computeBulletin($pdo, $st['id'], $class_id, $trimestre, $academic_year, $allSubjects, $classInfo, $schoolId);
        cacheSet($cacheKey, $_vars, 60);
        $bulletinsData[$st['id']] = $_vars;
    }

    if (isset($_GET['download_pdf'])) {
        ob_start();
        $print = true;
        $i = 0;
        foreach ($studentsAll as $st) {
            $_vars = $bulletinsData[$st['id']];
            extract($_vars);
            include '../includes/bulletin_view.php';
            if ($i++ < count($studentsAll) - 1) echo '<div style="page-break-after:always;"></div>';
        }
        $html = ob_get_clean();
        $filename = 'bulletins_' . $classInfo['name'] . '_T' . $trimestre . '.pdf';
        if ($bulletinTemplatePath) {
            generateBulletinPDFWithTemplate($html, $filename, $bulletinTemplatePath);
        } else {
            generateBulletinPDF($html, $filename);
        }
        exit;
    }

    ?><!DOCTYPE html><html lang="fr"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Bulletins — <?=e($classInfo['name'])?></title>
    <link rel="stylesheet" href="<?=BASE_URL?>assets/css/style.css"><link rel="stylesheet" href="<?=BASE_URL?>assets/css/bulletin.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"></head>
    <body class="bulletin-page print-mode"><?php
    $print = true;
    $i = 0;
    foreach ($studentsAll as $st) {
        $_vars = $bulletinsData[$st['id']];
        extract($_vars);
        include '../includes/bulletin_view.php';
        if ($i++ < count($studentsAll) - 1) echo '<div style="page-break-after:always;"></div>';
    }
    ?></body></html><?php
    exit;
}

// ── LISTE des élèves de la classe ───────────────────────────────────────────
$students = [];
$importedBulletins = [];
if ($class_id) {
    $stStmt = $pdo->prepare("SELECT id,first_name,last_name,gender FROM students WHERE class_id=? ORDER BY last_name, first_name");
    $stStmt->execute([$class_id]); $students = $stStmt->fetchAll();
    // Charger les bulletins importés pour cette classe/trimestre/année
    $ibStmt = $pdo->prepare("SELECT id, student_id, filename, original_name, status FROM imported_bulletins WHERE class_id=? AND trimestre=? AND academic_year=? AND student_id IS NOT NULL");
    $ibStmt->execute([$class_id, $trimestre, $academic_year]);
    foreach ($ibStmt->fetchAll() as $ib) {
        $importedBulletins[$ib['student_id']] = $ib;
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bulletins - 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);}
.date-input{padding:12px 16px;border:1px solid #D1D5DB;border-radius:8px;font-size:.95rem;background:white;}
.date-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;}
.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;}
.student-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:15px;}
.student-card{background:white;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,0.06);padding:18px 20px;display:flex;flex-direction:column;align-items:center;gap:10px;text-align:center;transition:all .2s;}
.student-card:hover{box-shadow:0 4px 20px rgba(0,0,0,0.1);transform:translateY(-2px);}
.student-avatar{width:48px;height:48px;border-radius:50%;background:var(--light);color:var(--primary);display:flex;align-items:center;justify-content:center;font-weight:700;font-size:1.1rem;}
.student-name{font-weight:600;font-size:.9rem;color:var(--text);}
.student-gender{font-size:.75rem;color:#9CA3AF;}
.student-actions{display:flex;gap:8px;margin-top:4px;}
.student-actions a{padding:6px 12px;border-radius:6px;font-size:.78rem;font-weight:600;text-decoration:none;display:inline-flex;align-items:center;gap:5px;transition:all .15s;}
.action-view{background:var(--light);color:var(--primary);}
.action-view:hover{background:#C5D9EC;}
.action-pdf{background:#FEE2E2;color:#DC2626;}
.action-pdf:hover{background:#FECACA;}
.action-imported{background:#D1FAE5;color:#065F46;}
.action-imported:hover{background:#A7F3D0;}
.card-header-bar{display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:15px;padding:18px 30px;background:var(--light);}
.card-title-bar{font-family:Georgia,serif;color:var(--primary);font-size:1.15rem;display:flex;align-items:center;gap:12px;}
@media(max-width:768px){
.selection-row{flex-direction:column;align-items:stretch;}
.select-group{min-width:100%;}
.content{padding:16px;}
.student-grid{grid-template-columns:repeat(auto-fill,minmax(160px,1fr));}
}
</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-file-alt"></i> Bulletins de notes'; 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 bulletins</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
                        $schoolsList = $pdo->query("SELECT id,name FROM schools ORDER BY name")->fetchAll();
                        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" onchange="this.form.submit()">
                        <?php foreach($years as $y): ?>
                        <option value="<?= e($y) ?>" <?= $y===$academic_year?'selected':'' ?>><?= e($y) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php if($class_id): ?>
                <div class="select-group" style="flex:0 0 180px;">
                    <label class="select-label">Date du bulletin <small style="font-weight:400;">(optionnelle)</small></label>
                    <input type="date" name="production_date" value="<?= e($production_date) ?>" class="date-input" onchange="this.form.submit()">
                </div>
                <a href="grades.php?class_id=<?= $class_id ?>&trimestre=<?= $trimestre ?>&academic_year=<?= urlencode($academic_year) ?>" class="btn btn-primary" style="padding:.55rem 1.1rem;"><i class="fas fa-pen-alt"></i> Saisir les notes</a>
                <?php endif; ?>
            </form>
        </div>

        <?php if (!$class_id): ?>
        <div class="selection-card">
            <div class="empty-state">
                <i class="fas fa-file-alt" style="font-size:2.5rem;display:block;margin-bottom:.75rem;color:#CBD5E1;"></i>
                <p style="font-size:1.05rem;">Sélectionnez une classe pour générer les bulletins.</p>
            </div>
        </div>
        <?php elseif(empty($students)): ?>
        <div class="selection-card">
            <div class="empty-state">
                <i class="fas fa-user-graduate" style="font-size:2.5rem;display:block;margin-bottom:.75rem;color:#CBD5E1;"></i>
                <p style="font-size:1.05rem;">Aucun élève dans cette classe.</p>
            </div>
        </div>
        <?php else: ?>
        <div class="selection-card" style="padding:0;overflow:hidden;">
            <div class="card-header-bar">
                <div class="card-title-bar">
                    <i class="fas fa-file-alt"></i>
                    <?= e($classes[array_search($class_id,array_column($classes,'id'))]['name'] ?? '') ?>
                    — <?= $effectif ?? count($students) ?> élèves — Trimestre <?= $trimestre ?>
                </div>
                <div style="display:flex;gap:8px;flex-wrap:wrap;">
                    <a href="<?= addProdDate("?class_id=$class_id&trimestre=$trimestre&academic_year=".urlencode($academic_year)."&print_all=1") ?>" class="btn btn-light" style="padding:.45rem .9rem;font-size:.82rem;" target="_blank"><i class="fas fa-print"></i> Imprimer tout</a>
                    <a href="<?= addProdDate("?class_id=$class_id&trimestre=$trimestre&academic_year=".urlencode($academic_year)."&print_all=1&download_pdf=1") ?>" class="btn btn-primary" style="padding:.45rem .9rem;font-size:.82rem;" target="_blank"><i class="fas fa-file-pdf"></i> PDF tout</a>
                </div>
            </div>
            <div style="padding:24px 30px;">
            <div class="student-grid">
                <?php foreach($students as $st): ?>
                <div class="student-card">
                    <div class="student-avatar"><?= strtoupper(mb_substr($st['first_name'],0,1).mb_substr($st['last_name'],0,1)) ?></div>
                    <div class="student-name"><?= e($st['last_name'].' '.$st['first_name']) ?></div>
                    <div class="student-gender"><?= $st['gender'] === 'M' ? 'Masculin' : ($st['gender'] === 'F' ? 'Féminin' : '') ?></div>
                    <div class="student-actions">
                        <a href="<?= addProdDate("?class_id=$class_id&student_id={$st['id']}&trimestre=$trimestre&academic_year=".urlencode($academic_year)) ?>" class="action-view" title="Voir le bulletin"><i class="fas fa-eye"></i></a>
                        <a href="<?= addProdDate("?class_id=$class_id&student_id={$st['id']}&trimestre=$trimestre&academic_year=".urlencode($academic_year)."&print=1") ?>" class="action-pdf" title="Télécharger le PDF" target="_blank"><i class="fas fa-file-pdf"></i></a>
                        <?php if (isset($importedBulletins[$st['id']])): $ib = $importedBulletins[$st['id']]; ?>
                        <a href="import_bulletins.php?action=view&id=<?= $ib['id'] ?>" class="action-imported" title="Bulletin importé : <?= e($ib['original_name']) ?>" target="_blank"><i class="fas fa-file-import"></i></a>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </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>
