<?php
$groupedSubjects ??= [];
$totalPoints    ??= 0;
$totalCoef      ??= 0;
$moyGeneral     ??= null;
$rangGeneral    ??= null;
$extremes       ??= ['max_moy'=>null,'min_moy'=>null,'avg_moy'=>null];
$mentionTravail ??= '';
$att            ??= ['teacher_appreciation'=>'','council_decision'=>''];
$studentInfo    ??= ['last_name'=>'','first_name'=>'','gender'=>''];
$classInfo      ??= ['name'=>'','school_name'=>'','address'=>'','phone'=>'','email'=>'','logo'=>''];
$effectif       ??= 0;
$academic_year  ??= '';
$trimestre      ??= 1;
$class_id       ??= 0;
$production_date ??= '';
$tpl            ??= [];
$titulaire      ??= '';
$directeur      ??= '';
$print          ??= false;
$student_id     ??= 0;
$observation    ??= $att['council_decision'] ?? '';

// Design vars from template
$layoutStyle  = $tpl['layout_style'] ?? 'classic';
$primaryColor = $tpl['primary_color'] ?? '#1a56db';
$accentColor  = $tpl['accent_color'] ?? '#1e40af';
$fontFamily   = $tpl['font_family'] ?? 'DejaVu Sans';
$showBorder   = $tpl['show_border'] ?? 1;
$showCoeff    = $tpl['show_coefficients'] ?? 1;
$showTchAppr  = $tpl['show_teacher_appreciation'] ?? 1;
$headerBg     = $tpl['header_bg_color'] ?? '#1a56db';
$headerTextCol = $tpl['header_text_color'] ?? '#ffffff';
$tblHeaderBg  = $tpl['table_header_bg'] ?? '#eef1f5';
$tblHeaderTxt = $tpl['table_header_text'] ?? '#000000';
$showLogo     = $tpl['show_logo'] ?? 1;
?><!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Bulletin — <?= 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>
        .bulletin-wrapper { font-family: <?=e($fontFamily)?>, sans-serif; }
        .bulletin-wrapper .entete {
            background: <?=e($headerBg)?>;
            color: <?=e($headerTextCol)?>;
        }
        .bulletin-wrapper .titre-bulletin {
            color: <?=e($primaryColor)?>;
            border-bottom-color: <?=e($primaryColor)?>;
        }
        .bulletin-wrapper .grades thead th {
            background: <?=e($tblHeaderBg)?>;
            color: <?=e($tblHeaderTxt)?>;
        }
        .bulletin-wrapper .sous-total-final td:first-child {
            color: <?=e($primaryColor)?>;
            font-weight: bold;
        }
        <?php if ($layoutStyle === 'compact'): ?>
        .bulletin-wrapper { font-size: 9px; }
        .bulletin-wrapper .entete { padding: 8px; }
        .bulletin-wrapper .grades th,
        .bulletin-wrapper .grades td { padding: 2px 4px; }
        <?php elseif ($layoutStyle === 'modern'): ?>
        .bulletin-wrapper { background: #fafafa; }
        .bulletin-wrapper .grades { border-collapse: collapse; }
        .bulletin-wrapper .grades th,
        .bulletin-wrapper .grades td { border: none; }
        .bulletin-wrapper .grades tbody tr:nth-child(even) { background: #f5f7fa; }
        .bulletin-wrapper .grades th { letter-spacing: 0.5px; font-size: 10px; }
        .bulletin-wrapper .resume { border: none; background: #f5f7fa; border-radius: 8px; }
        .bulletin-wrapper .resume td { padding: 8px 12px; }
        <?php endif; ?>
        .bulletin-wrapper .signatures,
        .bulletin-wrapper .signatures td { border: none; }
        <?php if (!$showBorder): ?>
        .bulletin-wrapper .grades { border: none; }
        .bulletin-wrapper .grades th,
        .bulletin-wrapper .grades td { border: none; }
        <?php endif; ?>
        .bulletin-wrapper .obs-line:before {
            color: <?=e($accentColor)?>;
        }
    </style>
</head>
<body class="bulletin-page<?= $print ? ' print-mode' : '' ?> layout-<?=e($layoutStyle)?>">

<?php if (!$print): ?>
<div class="bulletin-toolbar no-print">
    <a href="bulletin.php?class_id=<?= $class_id ?>&trimestre=<?= $trimestre ?>&academic_year=<?= urlencode($academic_year) ?>"
       class="btn-action btn-view"><i class="fas fa-arrow-left"></i> Retour</a>
    <a href="bulletin.php?class_id=<?= $class_id ?>&student_id=<?= $student_id ?>&trimestre=<?= $trimestre ?>&academic_year=<?= urlencode($academic_year) ?>&download_pdf=1"
       class="btn-action btn-edit" target="_blank"><i class="fas fa-file-pdf"></i> Télécharger PDF</a>
    <a href="?class_id=<?= $class_id ?>&student_id=<?= $student_id ?>&trimestre=<?= $trimestre ?>&academic_year=<?= urlencode($academic_year) ?>&print=1"
       class="btn-action" style="background:#edf2f7;color:#4a5568;" target="_blank"><i class="fas fa-print"></i> Imprimer</a>
    <a href="grade_saisie.php?class_id=<?= $class_id ?>&trimestre=<?= $trimestre ?>&academic_year=<?= urlencode($academic_year) ?>"
       class="btn-action" style="background:#edf2f7;color:#4a5568;"><i class="fas fa-pen-alt"></i> Modifier les notes</a>
</div>
<?php endif; ?>

<?php $logoUrl = !empty($classInfo['logo']) ? logoUrl($classInfo['logo']) : ''; ?>
<?php $watermarkUrl = $logoUrl; ?>
<div class="bulletin-wrapper" style="<?= $watermarkUrl ? '--watermark:url(' . e($watermarkUrl) . ')' : '' ?>">

    <!-- ═══════════════ EN-TÊTE ═══════════════ -->
    <div class="entete">
        <?php if ($showLogo && $logoUrl): ?>
        <div class="entete-logo">
            <img src="<?= e($logoUrl) ?>" alt="Logo" class="school-logo">
        </div>
        <?php endif; ?>
        <div class="etab"><?= e($classInfo['school_name'] ?? '') ?></div>
        <div class="adresse"><?= e($classInfo['address'] ?? '') ?></div>
    </div>

    <div class="titre-bulletin">Bulletin de notes du <?= $trimestre ?><?= $trimestre==1?'<sup>er</sup>':($trimestre==2?'<sup>ème</sup>':'<sup>ème</sup>') ?> trimestre</div>

    <!-- ═══════════════ INFOS ÉLÈVE ═══════════════ -->
    <table class="infos">
        <tr>
            <td colspan="4" style="text-align:center;font-weight:700;font-size:14px;"><?= e(strtoupper($studentInfo['last_name']).' '.$studentInfo['first_name']) ?></td>
        </tr>
        <tr>
            <td><strong>Classe de :</strong> <?= e($classInfo['name'] ?? '') ?></td>
            <td><strong>Effectif :</strong> <?= $effectif ?></td>
            <td><strong>Sexe :</strong> <?= $studentInfo['gender'] === 'M' ? 'M' : 'F' ?></td>
            <td><strong>Année Scolaire :</strong> <?= e($academic_year) ?></td>
        </tr>
    </table>

    <!-- ═══════════════ TABLEAU DES NOTES ═══════════════ -->
    <table class="grades">
        <thead>
            <tr>
                <th>Matières</th><?php if($showCoeff):?><th>Coef</th><?php endif;?><th>Interr</th><th>Dev</th>
                <th>Moy classe</th><th>Comp</th><th>Moy Génér.</th><?php if($showCoeff):?><th>Moy Coef</th><?php endif;?>
                <th>Rang</th><th>Appréciations du professeur</th>
            </tr>
        </thead>
        <tbody>
        <?php
        $groupKeys = array_keys($groupedSubjects);
        $totalCoefAff = 0; $totalPtsAff = 0;
        foreach ($groupedSubjects as $groupName => $grp):
        ?>
            <?php foreach($grp['subjects'] as $s): ?>
            <tr>
                <td class="matiere"><?= e($s['name']) ?></td>
                <?php if($showCoeff):?><td><?= number_format($s['coef'],2) ?></td><?php endif;?>
                <td><?= $s['ni'] !== null ? number_format($s['ni'],2,',','') : '—' ?></td>
                <td><?= $s['nd'] !== null ? number_format($s['nd'],2,',','') : '—' ?></td>
                <td><?= $s['moy_classe'] !== null ? number_format((float)$s['moy_classe'],2,',','') : '—' ?></td>
                <td><?= $s['nc'] !== null ? number_format($s['nc'],2,',','') : '—' ?></td>
                <td class="<?= $s['moy'] !== null && $s['moy'] < 10 ? 'low' : '' ?>"><?= $s['moy'] !== null ? number_format($s['moy'],2,',','') : '—' ?></td>
                <?php if($showCoeff):?><td><?= $s['moyCoef'] !== null ? number_format($s['moyCoef'],2,',','') : '—' ?></td><?php endif;?>
                <td><?= $s['rang'] !== null ? $s['rang'].'<sup>'.($s['rang']===1?'er':'ème').'</sup>' : '—' ?></td>
                <td class="matiere"><?= e($s['appreciation']) ?></td>
            </tr>
            <?php endforeach; ?>

            <!-- Sous-total du groupe -->
            <tr class="sous-total">
                <td class="matiere"><?= e($groupName) ?></td>
                <?php if($showCoeff):?><td><?= number_format($grp['totalCoef'],2) ?></td><?php endif;?>
                <td></td><td></td>
                <td><?= $grp['moy'] !== null ? number_format($grp['moy'],2,',','') : '—' ?></td>
                <td></td>
                <td><?= $grp['moy'] !== null ? number_format($grp['moy'],2,',','') : '—' ?></td>
                <?php if($showCoeff):?><td><?= number_format($grp['totalPts'],2,',','') ?></td><?php endif;?>
                <td></td><td></td>
            </tr>
        <?php endforeach; ?>

        <!-- Matières Fondamentales (premiers groupes) -->
        <?php
        $firstGroups = array_slice($groupedSubjects, 0, min(2, count($groupedSubjects)));
        $fundTotalCoef = 0; $fundTotalPts = 0;
        foreach ($firstGroups as $fg) { $fundTotalCoef += $fg['totalCoef']; $fundTotalPts += $fg['totalPts']; }
        $fundMoy = $fundTotalCoef > 0 ? $fundTotalPts / $fundTotalCoef : null;
        ?>
        <tr class="sous-total">
            <td class="matiere">Matières Fondamentales</td>
            <?php if($showCoeff):?><td><?= number_format($fundTotalCoef,2) ?></td><?php endif;?>
            <td></td><td></td>
            <td><?= $fundMoy !== null ? number_format($fundMoy,2,',','') : '—' ?></td>
            <td></td>
            <td><?= $fundMoy !== null ? number_format($fundMoy,2,',','') : '—' ?></td>
            <?php if($showCoeff):?><td><?= number_format($fundTotalPts,2,',','') ?></td><?php endif;?>
            <td></td><td></td>
        </tr>

        <tr class="sous-total-final">
            <td class="matiere">Résultat de la Composition</td>
            <?php if($showCoeff):?><td><?= number_format($totalCoef,2) ?></td><?php endif;?>
            <td></td><td></td>
            <td><?= $moyGeneral !== null ? number_format($moyGeneral,2,',','') : '—' ?></td>
            <td></td>
            <td><?= $moyGeneral !== null ? number_format($moyGeneral,2,',','') : '—' ?></td>
            <?php if($showCoeff):?><td><?= number_format($totalPoints,2,',','') ?></td><?php endif;?>
            <td></td><td></td>
        </tr>
        <tr class="sous-total" style="font-weight:bold;">
            <td class="matiere" colspan="<?= $showCoeff ? 10 : 8 ?>" style="text-align:center;">
                Total Général — Coefficients : <strong><?= number_format($totalCoef,2) ?></strong> &nbsp;|&nbsp; Total points : <strong><?= number_format($totalPoints,2,',','') ?></strong>
            </td>
        </tr>
        </tbody>
    </table>

    <?php if (!empty($att['council_decision'])): ?>
    <div class="obs-line"><strong>Observation / Avertissement :</strong>
        <?= e($att['council_decision']) ?>
    </div>
    <?php endif; ?>

    <!-- ═══════════════ RÉSUME / MOYENNES ═══════════════ -->
    <table class="resume">
        <tr>
            <td><strong>Moyenne Trimestrielle</strong></td>
            <td><strong>Rang</strong></td>
            <td><strong>Moyennes Extrêmes</strong></td>
            <td><strong>Moyenne de la Classe</strong></td>
        </tr>
        <tr>
            <td><?= $moyGeneral !== null ? number_format($moyGeneral,2,',','').' /20' : '—' ?></td>
            <td><?= $rangGeneral !== null ? $rangGeneral.($rangGeneral===1?'<sup>er</sup>':'<sup>ème</sup>') : '—' ?></td>
            <td>Max <?= $extremes['max_moy'] !== null ? number_format((float)$extremes['max_moy'],2,',','') : '—' ?> et Min <?= $extremes['min_moy'] !== null ? number_format((float)$extremes['min_moy'],2,',','') : '—' ?></td>
            <td><?= $extremes['avg_moy'] !== null ? number_format((float)$extremes['avg_moy'],2,',','') : '—' ?> /20</td>
        </tr>
    </table>

    <!-- ═══════════════ MOYENNE EN TOUTES LETTRES ═══════════════ -->
    <div class="obs-line" style="margin-top:8px;text-align:center;"><strong>La Moyenne Trimestrielle en toutes lettres :</strong>
        <?= $moyGeneral !== null ? e(nombreEnLettres($moyGeneral)) : '________________________' ?>
    </div>

    <!-- ═══════════════ ASSIDUITÉ ═══════════════ -->
    <?php if($tpl['show_absences'] ?? 1): ?>
    <table class="resume" style="margin-top:6px;">
        <tr>
            <td><strong>Retard</strong></td>
            <td><strong>Absence</strong></td>
            <td><strong>Assiduité</strong></td>
            <td><strong>Conduite</strong></td>
            <td><strong>Travail</strong></td>
        </tr>
        <tr>
            <td><?= (int)($att['retards'] ?? 0) ?> Fois</td>
            <td><?= (int)($att['absences'] ?? 0) ?> Heure(s)</td>
            <td><?= e($att['assiduity'] ?? '—') ?></td>
            <td><?= e($att['conduite'] ?? '—') ?></td>
            <td><?= e($mentionTravail) ?></td>
        </tr>
    </table>
    <?php endif; ?>

    <!-- ═══════════════ APPRÉCIATION PROF ═══════════════ -->
    <?php if ($showTchAppr && !empty($att['teacher_appreciation'])): ?>
    <div class="obs-line" style="margin-top:10px;">
        <strong>Appréciation du Professeur :</strong> <?= e($att['teacher_appreciation']) ?>
    </div>
    <?php endif; ?>

    <!-- ═══════════════ SIGNATURES ═══════════════ -->
    <table class="signatures">
        <?php if($tpl['show_signature'] ?? 1): ?>
        <tr>
            <td colspan="2">Fait à <?= e(explode(',', $classInfo['address'] ?? 'Lomé')[0] ?? 'Lomé') ?>, le <?= ($production_date && $dt = \DateTime::createFromFormat('Y-m-d', $production_date)) ? $dt->format('d/m/Y') : date('d/m/Y') ?></td>
        </tr>
        <?php endif; ?>
        <tr>
            <td>
                Titulaire de la <?= e($classInfo['name'] ?? '') ?><br>
                <strong><?= e($titulaire) ?></strong>
            </td>
            <td>
                Le Directeur / La Directrice<br>
                <strong><?= e($directeur) ?></strong>
            </td>
        </tr>
    </table>

    <!-- Pied de page -->
    <?php if(!empty($tpl['footer_text'])): ?>
    <div class="bulletin-footer-text"><?= e($tpl['footer_text']) ?></div>
    <?php endif; ?>
</div>

<?php if($print): ?>
<script>window.onload = function(){ window.print(); }</script>
<?php endif; ?>
</body>
</html>
