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

header('Content-Type: text/html; charset=utf-8');
checkRole(['super_admin', 'school_admin']);

$schoolFilter = currentSchoolId();

// ── Sauvegarde ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_types'])) {
    verifyCsrf();
    $updType  = $pdo->prepare("UPDATE classes SET type=? WHERE id=?");
    $updGroupe = $pdo->prepare("UPDATE classes SET groupe=? WHERE id=?");
    foreach ($_POST['class_type'] ?? [] as $id => $type) {
        $id = (int)$id;
        if (!in_array($type, ['CEG', 'Lycee'], true)) continue;
        $updType->execute([$type, $id]);
    }
    foreach ($_POST['class_groupe'] ?? [] as $id => $groupe) {
        $id = (int)$id;
        if (!in_array($groupe, ['General', 'Technique'], true)) continue;
        $updGroupe->execute([$groupe, $id]);
    }
    flashMessage('success', 'Types et groupes mis à jour.');
    header('Location: class_types.php');
    exit;
}

// ── Données ──
$order = getClassSortSQL('c');

if ($schoolFilter) {
    $classes = $pdo->prepare("
        SELECT c.*,
          COALESCE(c.type,
            CASE WHEN c.level REGEXP '^(6|5|4|3)' THEN 'CEG'
                 WHEN c.level REGEXP '^(2nde|1.ère|Tle|Premiere|Terminale)' THEN 'Lycee'
                 ELSE NULL END
          ) AS inferred_type,
          COALESCE(c.groupe,
            CASE WHEN c.level REGEXP '^(6|5|4|3)' THEN 'General'
                 WHEN c.level REGEXP '(A4|C4|D|CD|S|L)' THEN 'General'
                 WHEN c.level REGEXP '(G|E|F|T1|T2|TI|ET)' THEN 'Technique'
                 ELSE NULL END
          ) AS inferred_groupe
        FROM classes c
        WHERE c.id IN (SELECT DISTINCT cs.class_id FROM class_subjects cs WHERE cs.school_id=?)
        ORDER BY $order");
    $classes->execute([$schoolFilter]);
    $classes = $classes->fetchAll();
} else {
    $classes = $pdo->query("
        SELECT c.*,
          COALESCE(c.type,
            CASE WHEN c.level REGEXP '^(6|5|4|3)' THEN 'CEG'
                 WHEN c.level REGEXP '^(2nde|1.ère|Tle|Premiere|Terminale)' THEN 'Lycee'
                 ELSE NULL END
          ) AS inferred_type,
          COALESCE(c.groupe,
            CASE WHEN c.level REGEXP '^(6|5|4|3)' THEN 'General'
                 WHEN c.level REGEXP '(A4|C4|D|CD|S|L)' THEN 'General'
                 WHEN c.level REGEXP '(G|E|F|T1|T2|TI|ET)' THEN 'Technique'
                 ELSE NULL END
          ) AS inferred_groupe
        FROM classes c ORDER BY $order")->fetchAll();
}

// Regrouper par (type, groupe)
$sections = [];
$sectionMeta = [
    'CEG_General'   => ['label' => 'CEG — Groupe Général',             'icon' => 'school',          'color' => '#3B82F6'],
    'Lycee_General'   => ['label' => 'Lycée — Groupe Général',           'icon' => 'university',       'color' => '#F59E0B'],
    'Lycee_Technique' => ['label' => 'Lycée — Groupe Technique',         'icon' => 'microchip',        'color' => '#10B981'],
    'other'         => ['label' => 'Autres / Non défini',              'icon' => 'question-circle',  'color' => '#9CA3AF'],
];

foreach ($classes as $cl) {
    $t = $cl['type'] ?? ($cl['inferred_type'] ?? null);
    $g = $cl['groupe'] ?? ($cl['inferred_groupe'] ?? null);
    $key = ($t && $g) ? "{$t}_{$g}" : 'other';
    if (!isset($sections[$key])) $sections[$key] = [];
    $sections[$key][] = $cl;
}

$summary = [];
foreach ($sections as $key => $list) {
    $meta = $sectionMeta[$key] ?? $sectionMeta['other'];
    $summary[] = ['key' => $key, 'count' => count($list), 'label' => $meta['label'], 'icon' => $meta['icon'], 'color' => $meta['color']];
}
usort($summary, fn($a, $b) => array_search($a['key'], array_keys($sectionMeta)) - array_search($b['key'], array_keys($sectionMeta)));

$__flash = $_SESSION['flash_toast'] ?? null;
unset($_SESSION['flash_toast']);
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Niveaux de classe - Nukunu Mofiala</title>
<link rel="stylesheet" href="../assets/css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
:root { --primary: #1F4E79; --accent: #2E75B6; --light: #D6E4F0; }
.prog-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:1.5rem; flex-wrap:wrap; gap:1rem; }
.prog-header h1 { font-family:Georgia,serif; color:var(--primary); font-size:1.6rem; }
.prog-header p { color:#666; font-size:.9rem; }
.card-summary { display:flex; gap:1.25rem; margin-bottom:1.5rem; flex-wrap:wrap; }
.summary-item { background:white; border-radius:10px; box-shadow:0 2px 12px rgba(0,0,0,0.06); padding:1.25rem 1.5rem; flex:1; min-width:180px; text-align:center; }
.summary-item .nb { font-size:2rem; font-weight:700; }
.summary-item .lb { font-size:.85rem; color:#6B7280; margin-top:.25rem; }
.types-card { background:white; border-radius:10px; box-shadow:0 2px 12px rgba(0,0,0,0.06); margin-bottom:1.5rem; overflow:hidden; }
.types-card .tc-header { padding:1rem 1.5rem; border-bottom:2px solid; display:flex; align-items:center; gap:.75rem; font-family:Georgia,serif; font-size:1.1rem; color:var(--primary); }
.types-card .tc-body { padding:1rem 1.5rem; overflow-x:auto; }
.types-table { width:100%; border-collapse:collapse; min-width:600px; }
.types-table th { text-align:left; padding:.6rem .8rem; font-size:.76rem; text-transform:uppercase; letter-spacing:.4px; color:#6B7280; border-bottom:1px solid #E5E7EB; white-space:nowrap; }
.types-table td { padding:.5rem .8rem; border-bottom:1px solid #E5E7EB; font-size:.84rem; vertical-align:middle; }
.types-table tbody tr:hover { background:#F9FAFB; }
.badge { display:inline-block; padding:.15rem .55rem; border-radius:20px; font-size:.72rem; font-weight:600; }
.badge-ceg { background:#DBEAFE; color:#1E40AF; }
.badge-lycee { background:#FEF3C7; color:#92400E; }
.badge-general { background:#E0E7FF; color:#3730A3; }
.badge-technique { background:#D1FAE5; color:#065F46; }
.badge-none { background:#E5E7EB; color:#6B7280; }
.radio-group { display:flex; gap:.5rem; align-items:center; flex-wrap:wrap; }
.radio-group label { display:flex; align-items:center; gap:.25rem; font-size:.82rem; cursor:pointer; white-space:nowrap; }
.btn-save { background:var(--primary); color:white; border:none; padding:.6rem 2rem; border-radius:8px; font-size:.9rem; font-weight:600; cursor:pointer; }
.btn-save:hover { background:#163a5c; }
@media (max-width:768px) { .card-summary { flex-direction:column; } .types-table { font-size:.8rem; } }
.toast-container { position:fixed; bottom:30px; right:30px; z-index:2000; }
.toast { background:white; padding:12px 18px; border-radius:8px; box-shadow:0 4px 20px rgba(0,0,0,0.15); display:flex; align-items:center; gap:10px; animation:slideIn .3s ease; border-left:4px solid var(--primary); font-size:.9rem; }
.toast-success { border-left-color:#10B981; }
@keyframes slideIn { from{transform:translateX(100%);opacity:0;} to{transform:translateX(0);opacity:1;} }
</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-layer-group"></i> Niveaux de classe'; include '../includes/topbar.php'; ?>

        <?php if ($__flash): ?>
        <script>document.addEventListener('DOMContentLoaded',function(){showToast(<?= json_encode($__flash['message']) ?>,<?= json_encode($__flash['type']) ?>);});</script>
        <?php endif; ?>

        <div class="prog-header">
            <div>
                <h1><i class="fas fa-sitemap"></i> Niveaux & Groupes de classe</h1>
                <p>Définir le type (<strong>CEG</strong> / <strong>Lycée</strong>) et le groupe (<strong>Général</strong> / <strong>Technique</strong>) de chaque classe</p>
            </div>
        </div>

        <!-- Cartes résumé -->
        <div class="card-summary">
            <?php foreach ($summary as $s): ?>
            <div class="summary-item" style="border-top:4px solid <?= $s['color'] ?>;">
                <div class="nb" style="color:<?= $s['color'] ?>;"><?= $s['count'] ?></div>
                <div class="lb"><?= e($s['label']) ?></div>
            </div>
            <?php endforeach; ?>
        </div>

        <form method="POST">
            <?= csrfField() ?>
            <input type="hidden" name="save_types" value="1">

            <?php foreach ($sections as $secKey => $secClasses):
                $meta = $sectionMeta[$secKey] ?? $sectionMeta['other'];
            ?>
            <?php if (empty($secClasses)) continue; ?>
            <div class="types-card">
                <div class="tc-header" style="border-bottom-color: <?= $meta['color'] ?>;">
                    <i class="fas fa-<?= $meta['icon'] ?>"></i>
                    <?= e($meta['label']) ?>
                    <span style="font-size:.8rem;color:#6B7280;font-weight:400;margin-left:auto;"><?= count($secClasses) ?> classe(s)</span>
                </div>
                <div class="tc-body">
                    <table class="types-table">
                        <thead>
                            <tr>
                                <th>Classe</th>
                                <th>Niveau</th>
                                <th>Type</th>
                                <th>Groupe</th>
                                <th>Nouveau type</th>
                                <th>Nouveau groupe</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($secClasses as $cl):
                                $curType  = $cl['type'] ?? ($cl['inferred_type'] ?? '');
                                $curGroupe = $cl['groupe'] ?? ($cl['inferred_groupe'] ?? '');
                            ?>
                            <tr>
                                <td><strong><?= e($cl['name']) ?></strong></td>
                                <td><?= e($cl['level'] ?? '—') ?></td>
                                <td>
                                    <?php if ($curType === 'CEG'): ?><span class="badge badge-ceg">CEG</span>
                                    <?php elseif ($curType === 'Lycee'): ?><span class="badge badge-lycee">Lycée</span>
                                    <?php else: ?><span class="badge badge-none">—</span><?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($curGroupe === 'General'): ?><span class="badge badge-general">Général</span>
                                    <?php elseif ($curGroupe === 'Technique'): ?><span class="badge badge-technique">Technique</span>
                                    <?php else: ?><span class="badge badge-none">—</span><?php endif; ?>
                                </td>
                                <td>
                                    <div class="radio-group">
                                        <label><input type="radio" name="class_type[<?= $cl['id'] ?>]" value="CEG" <?= $curType==='CEG'?'checked':'' ?>> CEG</label>
                                        <label><input type="radio" name="class_type[<?= $cl['id'] ?>]" value="Lycee" <?= $curType==='Lycee'?'checked':'' ?>> Lycée</label>
                                    </div>
                                </td>
                                <td>
                                    <div class="radio-group">
                                        <label><input type="radio" name="class_groupe[<?= $cl['id'] ?>]" value="General" <?= $curGroupe==='General'?'checked':'' ?>> Général</label>
                                        <label><input type="radio" name="class_groupe[<?= $cl['id'] ?>]" value="Technique" <?= $curGroupe==='Technique'?'checked':'' ?>> Technique</label>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php endforeach; ?>

            <div style="text-align:right;margin-top:1.5rem;">
                <button type="submit" class="btn-save"><i class="fas fa-save"></i> Enregistrer les modifications</button>
            </div>
        </form>

        <div style="margin-top:2rem;padding:1rem;background:#F9FAFB;border-radius:8px;font-size:.85rem;color:#6B7280;">
            <strong>Rappel :</strong><br>
            <strong>CEG</strong> = 6<sup>ème</sup>, 5<sup>ème</sup>, 4<sup>ème</sup>, 3<sup>ème</sup> (Groupe Général uniquement)<br>
            <strong>Lycée Général</strong> = 2<sup>nde</sup>, 1<sup>ère</sup>, T<sup>le</sup> (séries A4, C4, D, CD, …)<br>
            <strong>Lycée Technique</strong> = classes techniques (G1, G2, G3, E, F, T1, T2, …)
        </div>
    </div>
</div>

<div class="toast-container" id="toastContainer"></div>
<script>
function showToast(msg,type){var c=document.getElementById('toastContainer');var t=document.createElement('div');t.className='toast toast-'+(type==='success'?'success':'error');t.innerHTML='<span>'+(type==='success'?'&#x2705;':'&#x274C;')+'</span><span>'+msg+'</span>';c.appendChild(t);setTimeout(function(){t.remove()},4000);}
</script>
</body>
</html>
