<?php
/**
 * Templates de bulletins scolaires
 */
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']);

$action = $_GET['action'] ?? 'list';
$id     = isset($_GET['id']) ? (int)$_GET['id'] : null;
$error  = '';
$schoolFilter = currentSchoolId();

// ── Suppression ───────────────────────────────────────────────────────────────
if ($action === 'delete' && $id) {
    verifyCsrf();
    if (!isSuperAdmin()) { flashMessage('error','Action réservée au super administrateur.'); header('Location: report_templates.php'); exit; }
    checkDeleteAllowed();
    if ($schoolFilter) {
        $chk = $pdo->prepare("SELECT id FROM report_templates WHERE id=? AND school_id=?");
        $chk->execute([$id,$schoolFilter]);
        if (!$chk->fetch()) { flashMessage('error','Action non autorisée.'); header('Location: report_templates.php'); exit; }
    }
    $pdo->prepare("DELETE FROM report_templates WHERE id=?")->execute([$id]);
    flashMessage('success','Template supprimé.'); header('Location: report_templates.php'); exit;
}

// ── Duplication ───────────────────────────────────────────────────────────────
if ($action === 'duplicate' && $id) {
    verifyCsrf();
    $src = $pdo->prepare("SELECT * FROM report_templates WHERE id=?");
    $src->execute([$id]); $src = $src->fetch();
    if ($src) {
        $pdo->prepare("INSERT INTO report_templates (school_id,name,header_title,header_subtitle,header_text,show_logo,show_rank,show_appreciation,show_signature,show_absences,grade_min,grade_max,passing_grade,mention_labels,footer_text,is_default,layout_style,primary_color,accent_color,font_family,show_border,show_watermark,header_bg_color,header_text_color,table_header_bg,table_header_text,show_coefficients,show_teacher_appreciation) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,?,?,?,?,?,?,?,?,?,?,?,?)")
            ->execute([$src['school_id'],'Copie de '.$src['name'],$src['header_title'],$src['header_subtitle'],$src['header_text'],$src['show_logo'],$src['show_rank'],$src['show_appreciation'],$src['show_signature'],$src['show_absences'],$src['grade_min'],$src['grade_max'],$src['passing_grade'],$src['mention_labels'],$src['footer_text'],$src['layout_style'],$src['primary_color'],$src['accent_color'],$src['font_family'],$src['show_border'],$src['show_watermark'],$src['header_bg_color'],$src['header_text_color'],$src['table_header_bg'],$src['table_header_text'],$src['show_coefficients'],$src['show_teacher_appreciation']]);
        flashMessage('success','Template dupliqué.'); header('Location: report_templates.php'); exit;
    }
}

// ── Définir comme défaut ──────────────────────────────────────────────────────
if ($action === 'set_default' && $id) {
    verifyCsrf();
    $pdo->prepare("UPDATE report_templates SET is_default=0 WHERE school_id=?")->execute([$schoolFilter??0]);
    $pdo->prepare("UPDATE report_templates SET is_default=1 WHERE id=?")->execute([$id]);
    flashMessage('success','Template défini par défaut.'); header('Location: report_templates.php'); exit;
}

    // ── Sauvegarde ────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && in_array($action,['add','edit','save'])) {
    verifyCsrf();
    $school_id        = $schoolFilter ?? (int)($_POST['school_id']??0);
    $name             = trim($_POST['name']??'');
    $header_title     = trim($_POST['header_title']??'');
    $header_subtitle  = trim($_POST['header_subtitle']??'');
    $header_text      = trim($_POST['header_text']??'');
    $show_logo        = isset($_POST['show_logo']) ? 1 : 0;
    $show_rank        = isset($_POST['show_rank']) ? 1 : 0;
    $show_appreciation= isset($_POST['show_appreciation']) ? 1 : 0;
    $show_signature   = isset($_POST['show_signature']) ? 1 : 0;
    $show_absences    = isset($_POST['show_absences']) ? 1 : 0;
    $grade_min        = (float)($_POST['grade_min']??0);
    $grade_max        = (float)($_POST['grade_max']??20);
    $passing_grade    = (float)($_POST['passing_grade']??10);
    $footer_text      = trim($_POST['footer_text']??'');
    $is_default       = isset($_POST['is_default']) ? 1 : 0;
    // Nouveaux champs design
    $layout_style         = $_POST['layout_style'] ?? 'classic';
    $primary_color        = $_POST['primary_color'] ?? '#1a56db';
    $accent_color         = $_POST['accent_color'] ?? '#1e40af';
    $font_family          = $_POST['font_family'] ?? 'DejaVu Sans';
    $show_border          = isset($_POST['show_border']) ? 1 : 0;
    $show_watermark       = isset($_POST['show_watermark']) ? 1 : 0;
    $header_bg_color      = $_POST['header_bg_color'] ?? '#1a56db';
    $header_text_color    = $_POST['header_text_color'] ?? '#ffffff';
    $table_header_bg      = $_POST['table_header_bg'] ?? '#eef1f5';
    $table_header_text    = $_POST['table_header_text'] ?? '#000000';
    $show_coefficients    = isset($_POST['show_coefficients']) ? 1 : 0;
    $show_teacher_appreciation = isset($_POST['show_teacher_appreciation']) ? 1 : 0;
    // Mentions : tableau clé=seuil, valeur=libellé
    $mentions = [];
    $mSeuilsRaw  = $_POST['mention_seuils']  ?? [];
    $mLabelsRaw  = $_POST['mention_labels_arr'] ?? [];
    $mColors     = $_POST['mention_colors']  ?? [];
    foreach ($mSeuilsRaw as $i => $seuil) {
        if (trim($seuil)==='' || trim($mLabelsRaw[$i]??'')==='' ) continue;
        $mentions[] = ['seuil'=>(float)$seuil,'label'=>trim($mLabelsRaw[$i]),'color'=>$mColors[$i]??'#22543d'];
    }
    usort($mentions, fn($a,$b)=>$b['seuil']<=>$a['seuil']);
    $mention_json = json_encode($mentions, JSON_UNESCAPED_UNICODE);

    if (empty($name)) $error = 'Le nom du template est requis.';
    elseif ($school_id<=0 && !hasRole('super_admin')) $error = 'École requise.';
    elseif ($grade_max<=$grade_min) $error = 'La note max doit être supérieure à la note min.';
    elseif ($passing_grade>$grade_max) $error = 'La note de passage ne peut dépasser la note max.';

    if (empty($error)) {
        $data = [$school_id,$name,$header_title,$header_subtitle,$header_text,$show_logo,$show_rank,$show_appreciation,$show_signature,$show_absences,$grade_min,$grade_max,$passing_grade,$mention_json,$footer_text,$is_default,
                 $layout_style,$primary_color,$accent_color,$font_family,$show_border,$show_watermark,$header_bg_color,$header_text_color,$table_header_bg,$table_header_text,$show_coefficients,$show_teacher_appreciation];
        if ($id) {
            $pdo->prepare("UPDATE report_templates SET school_id=?,name=?,header_title=?,header_subtitle=?,header_text=?,show_logo=?,show_rank=?,show_appreciation=?,show_signature=?,show_absences=?,grade_min=?,grade_max=?,passing_grade=?,mention_labels=?,footer_text=?,is_default=?,layout_style=?,primary_color=?,accent_color=?,font_family=?,show_border=?,show_watermark=?,header_bg_color=?,header_text_color=?,table_header_bg=?,table_header_text=?,show_coefficients=?,show_teacher_appreciation=? WHERE id=?")
                ->execute([...$data, $id]);
            flashMessage('success','Template mis à jour.');
        } else {
            $pdo->prepare("INSERT INTO report_templates (school_id,name,header_title,header_subtitle,header_text,show_logo,show_rank,show_appreciation,show_signature,show_absences,grade_min,grade_max,passing_grade,mention_labels,footer_text,is_default,layout_style,primary_color,accent_color,font_family,show_border,show_watermark,header_bg_color,header_text_color,table_header_bg,table_header_text,show_coefficients,show_teacher_appreciation) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
                ->execute($data);
            flashMessage('success','Template créé.');
        }
        if ($is_default) {
            $newId = $id ?? (int)$pdo->lastInsertId();
            $pdo->prepare("UPDATE report_templates SET is_default=0 WHERE school_id=? AND id!=?")->execute([$school_id,$newId]);
        }
        header('Location: report_templates.php'); exit;
    }
}

// ── Chargement pour édition ───────────────────────────────────────────────────
$tpl = null;
$mentionsDecoded = [];
if (in_array($action,['edit']) && $id) {
    $s = $pdo->prepare("SELECT * FROM report_templates WHERE id=?");
    $s->execute([$id]); $tpl = $s->fetch();
    if (!$tpl) { flashMessage('error','Template introuvable.'); header('Location: report_templates.php'); exit; }
    $mentionsDecoded = json_decode($tpl['mention_labels']??'[]', true) ?? [];
}

// Par défaut : mentions standard si nouveau template
if (empty($mentionsDecoded)) {
    $mentionsDecoded = [
        ['seuil'=>16,'label'=>'Très Bien','color'=>'#22543d'],
        ['seuil'=>14,'label'=>'Bien','color'=>'#276749'],
        ['seuil'=>12,'label'=>'Assez Bien','color'=>'#2b6cb0'],
        ['seuil'=>10,'label'=>'Passable','color'=>'#744210'],
        ['seuil'=>0, 'label'=>'Insuffisant','color'=>'#c53030'],
    ];
}

if ($schoolFilter) {
    $schools = $pdo->prepare("SELECT id,name FROM schools WHERE id=?");
    $schools->execute([$schoolFilter]); $schools=$schools->fetchAll();
} else {
    $schools = $pdo->query("SELECT id,name FROM schools ORDER BY name")->fetchAll();
}

$sort = resolveSort(['name','school_name','grade_max','is_default','created_at'],'name','asc');
$sortMap=['name'=>'rt.name','school_name'=>'s.name','grade_max'=>'rt.grade_max','is_default'=>'rt.is_default','created_at'=>'rt.created_at'];
$orderExpr=($sortMap[$sort['col']]??'rt.name').' '.$sort['dir'];
$tmplSql="SELECT rt.*,s.name AS school_name FROM report_templates rt LEFT JOIN schools s ON rt.school_id=s.id";
$tmplStmt=$schoolFilter?$pdo->prepare($tmplSql." WHERE rt.school_id=? ORDER BY $orderExpr"):$pdo->query($tmplSql." ORDER BY $orderExpr");
if($schoolFilter) $tmplStmt->execute([$schoolFilter]);
$templates=$tmplStmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Templates 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);}
.form-card{background:white;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,0.06);padding:24px 30px;margin-bottom:20px;}
.form-card-title{font-family:Georgia,serif;color:var(--primary);font-size:1rem;margin-bottom:16px;padding-bottom:8px;border-bottom:2px solid var(--light);display:flex;align-items:center;gap:10px;}
.form-group{display:flex;flex-direction:column;gap:6px;margin-bottom:14px;}
.form-group label{font-weight:600;color:var(--primary);font-size:.82rem;}
.form-group input,.form-group select,.form-group textarea{padding:10px 14px;border:1px solid #D1D5DB;border-radius:6px;font-size:.9rem;background:white;transition:all .2s;}
.form-group input:focus,.form-group select:focus,.form-group textarea:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 3px rgba(46,117,182,0.15);}
.form-group textarea{resize:vertical;font-family:inherit;}
.toggle-label{display:flex;align-items:center;gap:10px;cursor:pointer;padding:6px 0;font-size:.88rem;}
.toggle-label input[type=checkbox]{width:18px;height:18px;accent-color:var(--primary);cursor:pointer;}
.options-grid{display:grid;grid-template-columns:1fr 1fr;gap:4px;}
.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;}
.btn-danger{background:#DC2626;color:white;}
.form-grid-2{display:grid;grid-template-columns:1fr 1fr;gap:20px;}
.mention-row{display:flex;align-items:center;gap:8px;padding:8px 0;border-bottom:1px solid #E5E7EB;}
.mention-row input[type=number]{width:70px;padding:8px 10px;border:1px solid #D1D5DB;border-radius:6px;}
.mention-row input[type=text]{flex:1;padding:8px 10px;border:1px solid #D1D5DB;border-radius:6px;}
.mention-row input[type=color]{width:40px;height:34px;padding:2px;border:1px solid #D1D5DB;border-radius:6px;cursor:pointer;}
.btn-icon{width:34px;height:34px;border:none;border-radius:6px;cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:.85rem;transition:all .15s;}
.btn-icon-delete{background:#FEE2E2;color:#DC2626;}
.btn-icon-delete:hover{background:#FECACA;}
.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;}
.templates-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(320px,1fr));gap:20px;}
.template-card{background:white;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,0.06);overflow:hidden;transition:all .2s;position:relative;border:2px solid transparent;}
.template-card:hover{box-shadow:0 4px 20px rgba(0,0,0,0.1);}
.template-card-default{border-color:var(--warning);}
.template-default-badge{background:var(--warning);color:white;text-align:center;padding:4px 8px;font-size:.75rem;font-weight:700;text-transform:uppercase;letter-spacing:1px;}
.template-card-header{display:flex;align-items:center;gap:12px;padding:18px 20px;background:var(--light);}
.template-card-header i{font-size:1.8rem;color:var(--primary);}
.template-name{font-weight:700;font-size:.95rem;color:var(--primary);}
.template-school{font-size:.78rem;color:#6B7280;}
.template-card-body{padding:16px 20px;}
.template-info-row{font-size:.82rem;color:#4B5563;padding:4px 0;display:flex;align-items:center;gap:8px;flex-wrap:wrap;}
.mention-chips{display:flex;flex-wrap:wrap;gap:4px;margin-top:8px;}
.mention-chip{font-size:.7rem;padding:2px 6px;border-radius:4px;border:1px solid;font-weight:600;}
.template-card-footer{display:flex;gap:6px;padding:12px 20px;border-top:1px solid #E5E7EB;flex-wrap:wrap;}
.template-card-footer form{display:inline;}
.error-msg{background:#FEE2E2;color:#991B1B;border:1px solid #FECACA;border-radius:8px;padding:12px 18px;margin-bottom:16px;font-size:.9rem;}
@media(max-width:768px){
.form-grid-2{grid-template-columns:1fr;}
.options-grid{grid-template-columns:1fr;}
.content{padding:16px;}
.templates-grid{grid-template-columns: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> Templates 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">

        <?php if ($error): ?><div class="error-msg"><?= e($error) ?></div><?php endif; ?>

        <?php if(in_array($action,['add','edit'])): ?>
        <!-- ═══ FORMULAIRE TEMPLATE ═══ -->
        <form method="POST" action="?action=<?=$id?'edit&id='.$id:'add'?>" id="tplForm">
            <?=csrfField()?>
            <div class="form-grid-2">

                <!-- Colonne gauche -->
                <div>
                    <div class="form-card">
                        <div class="form-card-title"><i class="fas fa-info-circle"></i> Informations générales</div>
                        <div class="form-group">
                            <label>Nom du template <span style="color:red">*</span></label>
                            <input type="text" name="name" required value="<?=e($tpl['name']??'')?>" placeholder="ex: Bulletin Trimestriel CM">
                        </div>
                        <div class="form-group">
                            <label>École</label>
                            <select name="school_id" <?=$schoolFilter?'disabled':''?>>
                                <option value="">Toutes les écoles</option>
                                <?php foreach($schools as $sc):?>
                                <option value="<?=$sc['id']?>" <?=($tpl['school_id']??$schoolFilter)==$sc['id']?'selected':''?>><?=e($sc['name'])?></option>
                                <?php endforeach;?>
                            </select>
                            <?php if($schoolFilter):?><input type="hidden" name="school_id" value="<?=$schoolFilter?>"><?php endif;?>
                        </div>
                        <div class="form-group">
                            <label class="toggle-label">
                                <input type="checkbox" name="is_default" value="1" <?=($tpl['is_default']??0)?'checked':''?>>
                                <span>Template par défaut pour cette école</span>
                            </label>
                        </div>
                    </div>

                    <div class="form-card">
                        <div class="form-card-title"><i class="fas fa-heading"></i> En-tête du bulletin</div>
                        <div class="form-group">
                            <label>Titre principal</label>
                            <input type="text" name="header_title" value="<?=e($tpl['header_title']??'BULLETIN DE NOTES')?>" placeholder="BULLETIN DE NOTES">
                        </div>
                        <div class="form-group">
                            <label>Sous-titre</label>
                            <input type="text" name="header_subtitle" value="<?=e($tpl['header_subtitle']??'')?>" placeholder="ex: 1er Trimestre — Année 2025-2026">
                        </div>
                        <div class="form-group">
                            <label>Texte d'introduction</label>
                            <textarea name="header_text" rows="2" placeholder="Texte libre affiché sous l'en-tête..."><?=e($tpl['header_text']??'')?></textarea>
                        </div>
                    </div>

                    <div class="form-card">
                        <div class="form-card-title"><i class="fas fa-star"></i> Notes &amp; Barème</div>
                        <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:1rem;">
                            <div class="form-group">
                                <label>Note min</label>
                                <input type="number" name="grade_min" value="<?=e($tpl['grade_min']??0)?>" min="0" max="100" step="0.5">
                            </div>
                            <div class="form-group">
                                <label>Note max</label>
                                <input type="number" name="grade_max" value="<?=e($tpl['grade_max']??20)?>" min="1" max="100" step="0.5">
                            </div>
                            <div class="form-group">
                                <label>Passage</label>
                                <input type="number" name="passing_grade" value="<?=e($tpl['passing_grade']??10)?>" min="0" max="100" step="0.5">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Colonne droite -->
                <div>
                    <div class="form-card">
                        <div class="form-card-title"><i class="fas fa-toggle-on"></i> Éléments affichés</div>
                        <div class="options-grid">
                            <label class="toggle-label"><input type="checkbox" name="show_logo" value="1" <?=($tpl['show_logo']??1)?'checked':''?>><span><i class="fas fa-image"></i> Logo de l'école</span></label>
                            <label class="toggle-label"><input type="checkbox" name="show_rank" value="1" <?=($tpl['show_rank']??1)?'checked':''?>><span><i class="fas fa-trophy"></i> Classement</span></label>
                            <label class="toggle-label"><input type="checkbox" name="show_appreciation" value="1" <?=($tpl['show_appreciation']??1)?'checked':''?>><span><i class="fas fa-comment"></i> Appréciation</span></label>
                            <label class="toggle-label"><input type="checkbox" name="show_signature" value="1" <?=($tpl['show_signature']??1)?'checked':''?>><span><i class="fas fa-pen-nib"></i> Zone signature</span></label>
                            <label class="toggle-label"><input type="checkbox" name="show_absences" value="1" <?=($tpl['show_absences']??1)?'checked':''?>><span><i class="fas fa-calendar-times"></i> Absences</span></label>
                        </div>
                    </div>

                    <div class="form-card">
                        <div class="form-card-title"><i class="fas fa-palette"></i> Design &amp; Apparence</div>
                        <div class="form-group">
                            <label>Style de mise en page</label>
                            <select name="layout_style">
                                <option value="classic" <?=($tpl['layout_style']??'classic')=='classic'?'selected':''?>>Classique</option>
                                <option value="modern" <?=($tpl['layout_style']??'')=='modern'?'selected':''?>>Moderne</option>
                                <option value="compact" <?=($tpl['layout_style']??'')=='compact'?'selected':''?>>Compact</option>
                            </select>
                        </div>
                        <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
                            <div class="form-group">
                                <label>Couleur primaire</label>
                                <input type="color" name="primary_color" value="<?=e($tpl['primary_color']??'#1a56db')?>" style="width:100%;height:38px;padding:3px;border:1px solid #D1D5DB;border-radius:6px;cursor:pointer;">
                            </div>
                            <div class="form-group">
                                <label>Couleur accent</label>
                                <input type="color" name="accent_color" value="<?=e($tpl['accent_color']??'#1e40af')?>" style="width:100%;height:38px;padding:3px;border:1px solid #D1D5DB;border-radius:6px;cursor:pointer;">
                            </div>
                        </div>
                        <div class="form-group">
                            <label>Police d'écriture</label>
                            <select name="font_family">
                                <option value="DejaVu Sans" <?=($tpl['font_family']??'DejaVu Sans')=='DejaVu Sans'?'selected':''?>>DejaVu Sans</option>
                                <option value="DejaVu Serif" <?=($tpl['font_family']??'')=='DejaVu Serif'?'selected':''?>>DejaVu Serif</option>
                                <option value="Times New Roman" <?=($tpl['font_family']??'')=='Times New Roman'?'selected':''?>>Times New Roman</option>
                                <option value="Arial" <?=($tpl['font_family']??'')=='Arial'?'selected':''?>>Arial</option>
                                <option value="Courier New" <?=($tpl['font_family']??'')=='Courier New'?'selected':''?>>Courier New</option>
                                <option value="Georgia" <?=($tpl['font_family']??'')=='Georgia'?'selected':''?>>Georgia</option>
                            </select>
                        </div>
                        <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
                            <div class="form-group">
                                <label>Fond en-tête</label>
                                <input type="color" name="header_bg_color" value="<?=e($tpl['header_bg_color']??'#1a56db')?>" style="width:100%;height:38px;padding:3px;border:1px solid #D1D5DB;border-radius:6px;cursor:pointer;">
                            </div>
                            <div class="form-group">
                                <label>Texte en-tête</label>
                                <input type="color" name="header_text_color" value="<?=e($tpl['header_text_color']??'#ffffff')?>" style="width:100%;height:38px;padding:3px;border:1px solid #D1D5DB;border-radius:6px;cursor:pointer;">
                            </div>
                            <div class="form-group">
                                <label>Fond tableau en-tête</label>
                                <input type="color" name="table_header_bg" value="<?=e($tpl['table_header_bg']??'#eef1f5')?>" style="width:100%;height:38px;padding:3px;border:1px solid #D1D5DB;border-radius:6px;cursor:pointer;">
                            </div>
                            <div class="form-group">
                                <label>Texte tableau en-tête</label>
                                <input type="color" name="table_header_text" value="<?=e($tpl['table_header_text']??'#000000')?>" style="width:100%;height:38px;padding:3px;border:1px solid #D1D5DB;border-radius:6px;cursor:pointer;">
                            </div>
                        </div>
                        <div class="options-grid" style="margin-top:8px;">
                            <label class="toggle-label"><input type="checkbox" name="show_border" value="1" <?=($tpl['show_border']??1)?'checked':''?>><span><i class="fas fa-border-all"></i> Afficher bordures</span></label>
                            <label class="toggle-label"><input type="checkbox" name="show_watermark" value="1" <?=($tpl['show_watermark']??1)?'checked':''?>><span><i class="fas fa-tint"></i> Filigrane logo</span></label>
                            <label class="toggle-label"><input type="checkbox" name="show_coefficients" value="1" <?=($tpl['show_coefficients']??1)?'checked':''?>><span><i class="fas fa-percentage"></i> Afficher coefficients</span></label>
                            <label class="toggle-label"><input type="checkbox" name="show_teacher_appreciation" value="1" <?=($tpl['show_teacher_appreciation']??1)?'checked':''?>><span><i class="fas fa-chalkboard-teacher"></i> Appréciations prof.</span></label>
                        </div>
                    </div>

                    <div class="form-card">
                        <div class="form-card-title" style="justify-content:space-between;">
                            <span><i class="fas fa-award"></i> Mentions &amp; Appréciations</span>
                            <button type="button" onclick="addMention()" class="btn btn-light" style="padding:5px 12px;font-size:.8rem;"><i class="fas fa-plus"></i> Ajouter</button>
                        </div>
                        <div id="mentionsList">
                            <?php foreach($mentionsDecoded as $i=>$m):?>
                            <div class="mention-row" id="mention-<?=$i?>">
                                <input type="number" name="mention_seuils[]" value="<?=e($m['seuil'])?>" min="0" max="100" step="0.5" placeholder="Seuil">
                                <span style="color:#6B7280;font-size:.82rem;">&le; moy. &lt;</span>
                                <input type="text" name="mention_labels_arr[]" value="<?=e($m['label'])?>" placeholder="Libellé">
                                <input type="color" name="mention_colors[]" value="<?=e($m['color']??'#333333')?>">
                                <button type="button" onclick="this.closest('.mention-row').remove()" class="btn-icon btn-icon-delete"><i class="fas fa-times"></i></button>
                            </div>
                            <?php endforeach;?>
                        </div>
                        <small style="color:#6B7280;display:block;margin-top:8px;">Les mentions s'affichent selon la moyenne de l'élève par rapport au seuil (de haut en bas).</small>
                    </div>

                    <div class="form-card">
                        <div class="form-card-title"><i class="fas fa-align-center"></i> Pied de page</div>
                        <div class="form-group">
                            <label>Texte de pied de page</label>
                            <textarea name="footer_text" rows="2" placeholder="ex: Ce bulletin est confidentiel. Signature du directeur..."><?=e($tpl['footer_text']??'')?></textarea>
                        </div>
                    </div>
                </div>
            </div>

            <div style="display:flex;gap:1rem;margin-top:10px;">
                <button type="submit" class="btn btn-primary" style="padding:.75rem 2.5rem;font-size:1rem;"><i class="fas fa-save"></i> Enregistrer le template</button>
                <a href="report_templates.php" class="btn btn-light" style="padding:.75rem 1.5rem;">Annuler</a>
            </div>
        </form>

        <?php else: ?>
        <!-- ═══ LISTE DES TEMPLATES ═══ -->
        <div style="margin-bottom:20px;">
            <a href="?action=add" class="btn btn-primary"><i class="fas fa-plus"></i> Nouveau template</a>
        </div>

        <?php if(empty($templates)):?>
        <div class="selection-card">
            <div class="empty-state">
                <i class="fas fa-file-alt" style="font-size:2.5rem;margin-bottom:1rem;display:block;color:#CBD5E1;"></i>
                <p style="font-size:1.05rem;">Aucun template. Créez votre premier modèle de bulletin.</p>
                <a href="?action=add" class="btn btn-primary" style="margin-top:1rem;display:inline-flex;">Créer un template</a>
            </div>
        </div>
        <?php else:?>
        <div class="templates-grid">
            <?php foreach($templates as $t):
                $mentions=json_decode($t['mention_labels']??'[]',true)??[];
            ?>
            <div class="template-card <?=$t['is_default']?'template-card-default':''?>">
                <?php if($t['is_default']):?>
                <div class="template-default-badge"><i class="fas fa-star"></i> Par défaut</div>
                <?php endif;?>
                <div class="template-card-header">
                    <i class="fas fa-file-alt"></i>
                    <div>
                        <div class="template-name"><?=e($t['name'])?></div>
                        <div class="template-school"><?=e($t['school_name']??'Toutes les écoles')?></div>
                    </div>
                </div>
                <div class="template-card-body">
                    <div class="template-info-row">
                        <span><i class="fas fa-ruler"></i> Barème : <?=e($t['grade_min'])?>–<?=e($t['grade_max'])?> (passage : <?=e($t['passing_grade'])?>)</span>
                    </div>
                    <div class="template-info-row">
                        <span>
                            <?=$t['show_logo']?'<i class="fas fa-image" title="Logo"></i>':''?>
                            <?=$t['show_rank']?'<i class="fas fa-trophy" title="Classement"></i>':''?>
                            <?=$t['show_appreciation']?'<i class="fas fa-comment" title="Appréciation"></i>':''?>
                            <?=$t['show_signature']?'<i class="fas fa-pen-nib" title="Signature"></i>':''?>
                            <?=$t['show_absences']?'<i class="fas fa-calendar-times" title="Absences"></i>':''?>
                        </span>
                    </div>
                    <?php if(!empty($mentions)):?>
                    <div class="mention-chips">
                        <?php foreach($mentions as $m):?>
                        <span class="mention-chip" style="color:<?=e($m['color']??'#333')?>;border-color:<?=e($m['color']??'#D1D5DB')?>;">
                            &ge;<?=$m['seuil']?> <?=e($m['label'])?>
                        </span>
                        <?php endforeach;?>
                    </div>
                    <?php endif;?>
                </div>
                <div class="template-card-footer">
                    <a href="?action=edit&id=<?=$t['id']?>" class="btn btn-primary" style="font-size:.82rem;padding:.35rem .7rem;"><i class="fas fa-edit"></i> Modifier</a>
                    <?php if(!$t['is_default']):?>
                    <form method="POST" action="?action=set_default&id=<?=$t['id']?>" style="display:inline" title="Définir par défaut">
                        <?=csrfField()?>
                        <button type="submit" class="btn btn-light" style="font-size:.82rem;padding:.35rem .7rem;"><i class="fas fa-star"></i> Défaut</button>
                    </form>
                    <?php endif;?>
                    <form method="POST" action="?action=duplicate&id=<?=$t['id']?>" style="display:inline" title="Dupliquer">
                        <?=csrfField()?>
                        <button type="submit" class="btn btn-light" style="font-size:.82rem;padding:.35rem .7rem;"><i class="fas fa-copy"></i></button>
                    </form>
                    <?php if (isSuperAdmin()): ?>
                    <form method="POST" action="?action=delete&id=<?=$t['id']?>" style="display:inline" onsubmit="return confirm('Supprimer ce template ?')">
                        <?=csrfField()?>
                        <button type="submit" class="btn btn-danger" style="font-size:.82rem;padding:.35rem .7rem;"><i class="fas fa-trash"></i></button>
                    </form>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach;?>
        </div>
        <?php endif;?>
        <?php endif;?>

        </div>
    </div>
</div>

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

<script>
let mentionCount = <?=count($mentionsDecoded)?>;
function addMention(){const list=document.getElementById('mentionsList');const div=document.createElement('div');div.className='mention-row';div.id='mention-'+(mentionCount++);div.innerHTML='<input type="number" name="mention_seuils[]" value="" min="0" max="100" step="0.5" placeholder="Seuil"><span style="color:#6B7280;font-size:.82rem;">&le; moy. &lt;</span><input type="text" name="mention_labels_arr[]" value="" placeholder="Libellé"><input type="color" name="mention_colors[]" value="#333333"><button type="button" onclick="this.closest(\'.mention-row\').remove()" class="btn-icon btn-icon-delete"><i class="fas fa-times"></i></button>';list.appendChild(div);}
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>
