<?php
/**
 * Duplicata de bulletins — impression avec mention "DUPLICATA"
 */
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('students', 'view');

$schoolFilter = currentSchoolId();
if (isSuperAdmin() && !empty($_GET['school_id'])) {
    $schoolFilter = (int)$_GET['school_id'];
}
$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)]));

$class_id       = (int)($_GET['class_id']   ?? 0);
$student_id     = (int)($_GET['student_id']  ?? 0);
$trimestre      = (int)($_GET['trimestre']   ?? getActivePeriod());
$academic_year  = trim($_GET['academic_year'] ?? getDefaultAcademicYear($pdo, currentSchoolId()));
$print          = isset($_GET['print']);
sessionClose();
$production_date = trim($_GET['production_date'] ?? '');

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

// ── Fonctions de calcul ─────────────────────────────────────────────────────
function getMention(float $moy): string {
    return autoAppreciation($moy);
}
function ordinalFr(int $n): string {
    return $n . ($n === 1 ? 'er' : 'ème');
}

function computeDuplicataBulletin($pdo, $student_id, $class_id, $trimestre, $academic_year, $allSubjects) {
    $stInfo = $pdo->prepare("SELECT * FROM students WHERE id=?");
    $stInfo->execute([$student_id]); $studentInfo = $stInfo->fetch();
    $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) : '';
    return compact('studentInfo','groupedSubjects','totalPoints','totalCoef','moyGeneral','rangGeneral','extremes','mentionTravail','att');
}

// ── Si bulletin demandé → afficher ────────────────────────────────────────────
if ($class_id && $student_id) {
    // Vérification enseignant
    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: duplicata.php'); exit;
        }
    }

    // Infos classe + école
    $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: duplicata.php'); exit; }

    // Infos élève
    $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: duplicata.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;

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

    // Matières
    $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
    $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é
    $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 ────────────────────────────────────────────────────────────
    $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 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_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 AND g2.note_devoir IS NOT NULL THEN (g2.note_interro*1+g2.note_devoir*2)/3
                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_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 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 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_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 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 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) : '';

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

    $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 = '';
    $dirStmt = $pdo->prepare("SELECT CONCAT(first_name, ' ', last_name) AS name FROM directors WHERE school_id=? LIMIT 1");
    $dirStmt->execute([$schoolId]);
    if ($dirRow = $dirStmt->fetch()) {
        $directeur = $dirRow['name'];
    }

    // ══ INCLURE LE BULLETIN AVEC DUPLICATA ══
    ?>
    <!DOCTYPE html>
    <html lang="fr">
    <head>
        <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Duplicata — <?= e($studentInfo['last_name'].' '.$studentInfo['first_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">
        <style>
            .bl-col-appr {
                position: relative;
            }
            .bl-col-appr::after {
                content: "DUPLICATA";
                position: absolute;
                right: 1px;
                top: 1px;
                bottom: 1px;
                writing-mode: vertical-lr;
                text-orientation: upright;
                font-size: 50px;
                font-weight: 900;
                color: #dc2626;
                opacity: .5;
                letter-spacing: 5;
                pointer-events: none;
                display: flex;
                align-items: center;
                justify-content: center;
                text-transform: uppercase;
            }
            .bulletin-thead .bl-col-appr::after {
                content: none;
            }
            @media print {
                .bl-col-appr::after {
                    color: #dc2626 !important;
                    opacity: .7 !important;
                    -webkit-print-color-adjust: exact;
                    print-color-adjust: exact;
                }
            }
        </style>
    </head>
    <body class="bulletin-page<?= $print ? ' print-mode' : '' ?>">


        <?php
        if (isset($_GET['download_pdf'])) {
            ob_start();
            include '../includes/bulletin_view.php';
            $html = ob_get_clean();
            require_once '../includes/bulletin_pdf.php';
            $bulletinTemplatePath = getBulletinTemplatePath($pdo, $schoolId, $class_id, $academic_year);
            $filename = 'duplicata_' . $studentInfo['last_name'] . '_' . $studentInfo['first_name'] . '_T' . $trimestre . '.pdf';
            if ($bulletinTemplatePath) {
                generateBulletinPDFWithTemplate($html, $filename, $bulletinTemplatePath);
            } else {
                generateBulletinPDF($html, $filename);
            }
            exit;
        }
        ?>
        <?php include '../includes/bulletin_view.php'; ?>
    </body>
    </html>
    <?php
    exit;
}

// ══ 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 dans cette classe.'); header('Location: duplicata.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: duplicata.php'); exit; }

    $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() ?: [];

    $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 = '';
    $dirStmt = $pdo->prepare("SELECT CONCAT(first_name, ' ', last_name) AS name FROM directors WHERE school_id=? LIMIT 1");
    $dirStmt->execute([$schoolId]);
    if ($dirRow = $dirStmt->fetch()) {
        $directeur = $dirRow['name'];
    }

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

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

    if (isset($_GET['download_pdf'])) {
        require_once '../includes/bulletin_pdf.php';
        $bulletinTemplatePath = getBulletinTemplatePath($pdo, $schoolId, $class_id, $academic_year);
        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 = 'duplicatas_' . $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>Duplicatas — <?=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">
    <style>.bl-col-appr{position:relative}.bl-col-appr::after{content:"DUPLICATA";position:absolute;right:1px;top:1px;bottom:1px;writing-mode:vertical-lr;text-orientation:upright;font-size:50px;font-weight:900;color:#dc2626;opacity:.5;letter-spacing:5;pointer-events:none;display:flex;align-items:center;justify-content:center;text-transform:uppercase}.bulletin-thead .bl-col-appr::after{content:none}@media print{.bl-col-appr::after{color:#dc2626!important;opacity:.7!important;-webkit-print-color-adjust:exact;print-color-adjust:exact}}</style></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;
}

// ── Formulaire de sélection ──────────────────────────────────────────────────

// Écoles
$schoolsList = $pdo->query("SELECT id,name FROM schools ORDER BY name")->fetchAll();

$classes = $pdo->query("SELECT c.id, c.name FROM classes c ORDER BY " . getClassSortSQL('c'))->fetchAll();

// Élèves (si classe sélectionnée)
$students = [];
if ($class_id) {
    $st = $pdo->prepare("SELECT id, first_name, last_name FROM students WHERE class_id=? ORDER BY last_name, first_name");
    $st->execute([$class_id]);
    $students = $st->fetchAll();
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Duplicata de 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-danger{background:#DC2626;color:white;}
.btn-danger:hover{background:#B91C1C;}
.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;}
.actions-row{display:flex;gap:10px;flex-wrap:wrap;align-items:center;}
@media(max-width:768px){
.selection-row{flex-direction:column;align-items:stretch;}
.select-group{min-width:100%;}
.content{padding:16px;}
}
</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-copy" style="color:#DC2626;"></i> Duplicata de bulletins'; 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">

        <div class="selection-card">
            <div class="selection-title"><i class="fas fa-search"></i> Sélectionner un bulletin</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" style="flex:0 0 220px;">
                    <label class="select-label">Classe <span style="color:red;">*</span></label>
                    <select name="class_id" class="select-input" onchange="this.form.submit()" required>
                        <option value="">— Choisir —</option>
                        <?php foreach ($classes as $cl): ?>
                        <option value="<?= $cl['id'] ?>" <?= $class_id===$cl['id']?'selected':'' ?>>
                            <?= e($cl['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="select-group" style="flex:0 0 150px;">
                    <label class="select-label">Trimestre</label>
                    <select name="trimestre" class="select-input">
                        <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" style="flex:0 0 170px;">
                    <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>
                </div>
                <?php if (!empty($students)): ?>
                <div class="select-group" style="flex:0 0 220px;">
                    <label class="select-label">Élève <span style="color:red;">*</span></label>
                    <select name="student_id" class="select-input" required>
                        <option value="">— Choisir —</option>
                        <?php foreach ($students as $st): ?>
                        <option value="<?= $st['id'] ?>" <?= $student_id===$st['id']?'selected':'' ?>><?= e($st['last_name'].' '.$st['first_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <?php if (!empty($students) && $class_id): ?>
                <div class="select-group" style="flex:0 0 180px;">
                    <label class="select-label">Date du duplicata <small style="font-weight:400;">(opt.)</small></label>
                    <input type="date" name="production_date" value="<?= e($production_date) ?>" class="date-input">
                </div>
                <?php endif; ?>
                <button type="submit" class="btn btn-danger" style="padding:.75rem 1.5rem;"><i class="fas fa-copy"></i> Générer le duplicata</button>
            </form>
            <?php if (!empty($students)): ?>
            <div class="actions-row" style="margin-top:20px;padding-top:15px;border-top:1px solid #E5E7EB;">
                <span style="font-weight:600;font-size:.85rem;color:var(--primary);">Actions groupées :</span>
                <a href="<?= "?class_id=$class_id&trimestre=$trimestre&academic_year=".urlencode($academic_year) . ($production_date ? "&production_date=".urlencode($production_date) : "") ?>&print_all=1" class="btn btn-light" style="padding:.5rem 1rem;font-size:.82rem;" target="_blank"><i class="fas fa-print"></i> Imprimer tout</a>
                <a href="<?= "?class_id=$class_id&trimestre=$trimestre&academic_year=".urlencode($academic_year) . ($production_date ? "&production_date=".urlencode($production_date) : "") ?>&print_all=1&download_pdf=1" class="btn btn-primary" style="padding:.5rem 1rem;font-size:.82rem;" target="_blank"><i class="fas fa-file-pdf"></i> PDF tout</a>
            </div>
            <?php endif; ?>
        </div>

        <?php if ($class_id && 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 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>
