<?php
/**
 * Gestion des classes — liste globale (Super Admin)
 */
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']);
$action = $_GET['action'] ?? 'list';
$id     = isset($_GET['id']) ? (int)$_GET['id'] : null;
$error  = '';

// ── Suppression ───────────────────────────────────────────────────────────────
if ($action === 'delete' && $id) {
    verifyCsrf();
    checkDeleteAllowed();
    $cnt = $pdo->prepare("SELECT COUNT(*) FROM students WHERE class_id=?");
    $cnt->execute([$id]);
    if ($cnt->fetchColumn() > 0) {
        flashMessage('error','Impossible de supprimer : des élèves sont rattachés à cette classe.');
        header('Location: classes.php'); exit;
    }
    $pdo->prepare("DELETE FROM classes WHERE id=?")->execute([$id]);
    flashMessage('success','Classe supprimée.');
    header('Location: classes.php'); exit;
}

// ── Suppression multiple ──────────────────────────────────────────────────────
if (isset($_POST['bulk_delete'])) {
    verifyCsrf();
    checkDeleteAllowed();
    $ids = isset($_POST['class_ids']) ? array_map('intval', (array)$_POST['class_ids']) : [];
    $deleted = 0; $skipped = 0;
    foreach ($ids as $cid) {
        $cnt = $pdo->prepare("SELECT COUNT(*) FROM students WHERE class_id=?");
        $cnt->execute([$cid]);
        if ($cnt->fetchColumn() > 0) { $skipped++; continue; }
        $pdo->prepare("DELETE FROM classes WHERE id=?")->execute([$cid]);
        $deleted++;
    }
    flashMessage('success', "$deleted classe(s) supprimée(s)." . ($skipped ? " $skipped ignorée(s) (élèves présents)." : ''));
    header('Location: classes.php'); exit;
}

// ── Ajout / Modification ──────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && in_array($action, ['add','edit','save'])) {
    verifyCsrf();
    $name          = trim($_POST['name'] ?? '');
    $level         = trim($_POST['level'] ?? '');
    $academic_year = trim($_POST['academic_year'] ?? '');

    if (empty($name)) $error = 'Le nom de la classe est requis.';

    if (empty($error)) {
        // Vérifier unicité du nom
        $dup = $pdo->prepare("SELECT id FROM classes WHERE name=? AND id!=COALESCE(?,0)");
        $dup->execute([$name, $id ?? 0]);
        if ($dup->fetch()) {
            $error = 'Une classe avec ce nom existe déjà.';
        } elseif ($id) {
            $pdo->prepare("UPDATE classes SET name=?,level=?,academic_year=? WHERE id=?")
                ->execute([$name, $level, $academic_year, $id]);
            flashMessage('success','Classe mise à jour.');
            header('Location: classes.php'); exit;
        } else {
            $pdo->prepare("INSERT INTO classes (name,level,academic_year) VALUES (?,?,?)")
                ->execute([$name, $level, $academic_year]);
            flashMessage('success','Classe ajoutée.');
            header('Location: classes.php'); exit;
        }
    }
}

// ── Import CSV ────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['import_csv'])) {
    verifyCsrf();
    if (empty($_FILES['csv_file']['tmp_name'])) {
        flashMessage('error', 'Veuillez sélectionner un fichier CSV.');
    } else {
        $handle = fopen($_FILES['csv_file']['tmp_name'], 'r');
        $header = fgetcsv($handle, 0, ';');
        if (!$header || count($header) < 1) {
            flashMessage('error', 'Format CSV invalide. Utilisez le séparateur ";"');
        } else {
            $imported = 0; $errors = []; $line = 1;
            while (($row = fgetcsv($handle, 0, ';')) !== false) {
                $line++;
                $name  = trim($row[0] ?? '');
                $level = trim($row[1] ?? '');
                $year  = trim($row[2] ?? '');
                if (empty($name)) { $errors[] = "Ligne $line : nom manquant."; continue; }
                $dup = $pdo->prepare("SELECT id FROM classes WHERE name=?");
                $dup->execute([$name]);
                if ($dup->fetch()) { $errors[] = "Ligne $line : '$name' existe déjà."; continue; }
                $pdo->prepare("INSERT INTO classes (name,level,academic_year) VALUES (?,?,?)")
                    ->execute([$name, $level ?: null, $year ?: null]);
                $imported++;
            }
            fclose($handle);
            $msg = "$imported classe(s) importée(s).";
            if (!empty($errors)) $msg .= ' ' . implode(' | ', array_slice($errors, 0, 5));
            flashMessage($imported > 0 ? 'success' : 'error', $msg);
        }
    }
    header('Location: classes.php'); exit;
}

// ── Données ───────────────────────────────────────────────────────────────────
$sort = resolveSort(['name','level','academic_year','student_count','subject_count'], 'name', 'asc');
$sortMap = [
    'name'           => getClassSortSQL('c'),
    'level'          => 'c.level',
    'academic_year'  => 'c.academic_year',
    'student_count'  => 'student_count',
    'subject_count'  => 'subject_count',
];
$orderExpr = ($sortMap[$sort['col']] ?? getClassSortSQL('c')) . ' ' . $sort['dir'];

$classRows = $pdo->query("
    SELECT c.*,
           (SELECT COUNT(*) FROM students st WHERE st.class_id = c.id) AS student_count,
           (SELECT COUNT(*) FROM class_subjects cs WHERE cs.class_id = c.id) AS subject_count
    FROM classes c
    ORDER BY $orderExpr
")->fetchAll();

// ── Export CSV ────────────────────────────────────────────────────────────────
if (isset($_GET['export'])) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=classes_' . date('Ymd') . '.csv');
    echo "\xEF\xBB\xBF";
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Nom', 'Niveau', 'Année scolaire'], ';');
    foreach ($classRows as $cl) {
        fputcsv($out, [$cl['name'], $cl['level'], $cl['academic_year']], ';');
    }
    fclose($out);
    exit;
}

// Classe en édition
$editClass = null;
if ($action === 'edit' && $id) {
    $s = $pdo->prepare("SELECT * FROM classes WHERE id=?");
    $s->execute([$id]); $editClass = $s->fetch();
    if (!$editClass) { flashMessage('error','Classe introuvable.'); header('Location: classes.php'); exit; }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Classes - 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;}
.btn{display:inline-flex;align-items:center;gap:6px;padding:.55rem 1.25rem;border:none;border-radius:6px;font-size:.82rem;font-weight:600;cursor:pointer;transition:all .2s;text-decoration:none;}
.btn-primary{background:var(--primary);color:white;}.btn-primary:hover{background:#163a5c;}
.btn-light{background:#E5E7EB;color:#374151;}.btn-light:hover{background:#D1D5DB;}
.btn-danger{background:#DC2626;color:white;}.btn-danger:hover{background:#B91C1C;}
.btn-sm{padding:.35rem .75rem;font-size:.75rem;}
.card{background:white;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,0.06);overflow:hidden;margin-bottom:1.25rem;}
.card-body{padding:1.25rem 1.5rem;}
.prog-table{width:100%;border-collapse:collapse;}
.prog-table thead{background:var(--primary);color:white;}
.prog-table th{padding:.7rem 1rem;text-align:left;font-weight:600;font-size:.78rem;text-transform:uppercase;letter-spacing:.4px;}
.prog-table td{padding:.7rem 1rem;border-bottom:1px solid #E5E7EB;font-size:.85rem;vertical-align:middle;}
.prog-table tbody tr:hover{background:#F9FAFB;}
.toast-container{position:fixed;bottom:30px;right:30px;z-index:2000;display:flex;flex-direction:column;gap:10px;}
.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;}.toast-error{border-left-color:#EF4444;}
@keyframes slideIn{from{transform:translateX(100%);opacity:0;}to{transform:translateX(0);opacity:1;}}
.modal-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.4);z-index:1500;align-items:center;justify-content:center;}
.modal-overlay.open{display:flex;}
.modal-box{background:white;border-radius:12px;padding:2rem;width:90%;max-width:500px;box-shadow:0 10px 40px rgba(0,0,0,0.2);}
.modal-box h2{font-family:Georgia, serif;color:var(--primary);font-size:1.2rem;margin-bottom:1.25rem;display:flex;align-items:center;gap:.5rem;}
.modal-box .form-group{margin-bottom:1rem;}
.modal-box .form-group label{display:block;font-weight:600;color:var(--primary);font-size:.82rem;margin-bottom:4px;}
.modal-box .form-group input{width:100%;padding:.6rem .75rem;border:1px solid #D1D5DB;border-radius:6px;font-size:.85rem;}
.modal-box .form-group input:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 3px rgba(46,117,182,0.15);}
.modal-box .modal-actions{display:flex;gap:.75rem;margin-top:1.25rem;justify-content:flex-end;}
.empty-state{text-align:center;padding:3rem 1rem;color:#9CA3AF;}
@media(max-width:768px){.prog-table th,.prog-table td{padding:.5rem .6rem;font-size:.78rem;}}
</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-users"></i> Gestion des classes'; include '../includes/topbar.php'; ?>

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

        <div class="prog-header">
            <div>
                <h1><i class="fas fa-users" style="color:var(--primary);"></i> Classes (globales)</h1>
                <p>Gérez les classes communes à toutes les écoles</p>
            </div>
            <div style="display:flex;gap:.5rem;flex-wrap:wrap;">
                <button class="btn btn-primary" onclick="openAddModal()"><i class="fas fa-plus"></i> Ajouter</button>
                <a href="?export=1" class="btn btn-light"><i class="fas fa-download"></i> Export CSV</a>
                <button class="btn btn-light" onclick="document.getElementById('importModal').classList.add('open')"><i class="fas fa-upload"></i> Import CSV</button>
            </div>
        </div>

        <div class="card">
            <div class="card-body" style="overflow-x:auto;">
            <?php if (empty($classRows)): ?>
            <div class="empty-state">
                <i class="fas fa-users" style="font-size:2.5rem;margin-bottom:.5rem;display:block;color:#CBD5E1;"></i>
                <p>Aucune classe. Créez la première.</p>
            </div>
            <?php else: ?>
            <form method="POST" id="bulkForm">
                <?= csrfField() ?>
                <input type="hidden" name="bulk_delete" value="1">
                <table class="prog-table">
                    <thead>
                        <tr>
                            <th style="width:36px;"><input type="checkbox" onchange="document.querySelectorAll('.cb').forEach(c=>c.checked=this.checked)"></th>
                            <th><?= sortTh('name', 'Classe', $sort) ?></th>
                            <th><?= sortTh('level', 'Niveau', $sort) ?></th>
                            <th><?= sortTh('academic_year', 'Année', $sort) ?></th>
                            <th><?= sortTh('student_count', 'Élèves', $sort) ?></th>
                            <th><?= sortTh('subject_count', 'Matières', $sort) ?></th>
                            <th style="width:100px;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($classRows as $cl): ?>
                        <tr>
                            <td><input type="checkbox" name="class_ids[]" value="<?= $cl['id'] ?>" class="cb"></td>
                            <td><strong><?= e($cl['name']) ?></strong></td>
                            <td><?= e($cl['level'] ?? '-') ?></td>
                            <td><?= e($cl['academic_year'] ?? '-') ?></td>
                            <td><?= (int)$cl['student_count'] ?></td>
                            <td><?= (int)$cl['subject_count'] ?></td>
                            <td style="white-space:nowrap;">
                                <button class="btn btn-sm btn-light" onclick="openEditModal(<?= htmlspecialchars(json_encode($cl), ENT_QUOTES) ?>)" title="Modifier"><i class="fas fa-edit"></i></button>
                                <form method="POST" action="?action=delete&id=<?= $cl['id'] ?>" style="display:inline" onsubmit="return confirm('Supprimer la classe <?= e($cl['name']) ?> ?')">
                                    <?= csrfField() ?>
                                    <button type="submit" class="btn btn-sm btn-danger" title="Supprimer"><i class="fas fa-trash"></i></button>
                                </form>
                                <a href="subjects.php?action=class_subjects&filter_class=<?= $cl['id'] ?>" class="btn btn-sm btn-light" title="Matières"><i class="fas fa-book"></i></a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php if (count($classRows) > 0): ?>
                <div style="padding:.75rem 1.5rem;border-top:1px solid #E5E7EB;">
                    <button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-trash-alt"></i> Supprimer la sélection</button>
                </div>
                <?php endif; ?>
            </form>
            <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Modal Import CSV -->
<div class="modal-overlay" id="importModal">
    <div class="modal-box">
        <h2><i class="fas fa-upload"></i> Importer des classes</h2>
        <p style="color:#718096;font-size:.9rem;margin-bottom:1rem;">Format CSV (séparateur <code>;</code>)<br>Colonnes : <code>Nom;Niveau;Année scolaire</code></p>
        <form method="POST" enctype="multipart/form-data">
            <?= csrfField() ?>
            <div class="form-group"><input type="file" name="csv_file" accept=".csv,.txt" required></div>
            <div class="modal-actions">
                <button type="button" class="btn btn-light" onclick="document.getElementById('importModal').classList.remove('open')">Annuler</button>
                <button type="submit" name="import_csv" class="btn btn-primary"><i class="fas fa-upload"></i> Importer</button>
            </div>
        </form>
    </div>
</div>

<!-- Modal Ajout / Modification -->
<div class="modal-overlay" id="classModal">
    <div class="modal-box">
        <h2 id="modalTitle"><i class="fas fa-plus-circle"></i> Ajouter une classe</h2>
        <form method="POST" id="classForm">
            <?= csrfField() ?>
            <div class="form-group">
                <label>Nom de la classe <span style="color:red">*</span></label>
                <input type="text" name="name" id="modalName" required placeholder="ex: CM1 A, 6ème B">
            </div>
            <div class="form-group">
                <label>Niveau</label>
                <input type="text" name="level" id="modalLevel" placeholder="ex: CM1, 6ème">
            </div>
            <div class="form-group">
                <label>Année scolaire</label>
                <input type="text" name="academic_year" id="modalYear" placeholder="ex: 2025-2026">
            </div>
            <div class="modal-actions">
                <button type="button" class="btn btn-light" onclick="closeModal()">Annuler</button>
                <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Enregistrer</button>
            </div>
        </form>
    </div>
</div>

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

<script>
function showToast(message, type) {
    const c = document.getElementById('toastContainer'), t = document.createElement('div');
    t.className = 'toast toast-' + type;
    const icons = { success: '&#10004;&#65039;', warning: '&#9888;&#65039;', error: '&#10060;' };
    t.innerHTML = '<span>' + (icons[type] || '&#8505;&#65039;') + '</span><span>' + message + '</span>';
    c.appendChild(t); setTimeout(() => t.remove(), 4000);
}
function openAddModal() {
    document.getElementById('modalTitle').innerHTML = '<i class="fas fa-plus-circle"></i> Ajouter une classe';
    document.getElementById('classForm').action = '?action=add';
    document.getElementById('modalName').value = ''; document.getElementById('modalLevel').value = ''; document.getElementById('modalYear').value = '';
    const hid = document.getElementById('hiddenClassId'); if (hid) hid.remove();
    document.getElementById('classModal').classList.add('open');
}
function openEditModal(cl) {
    document.getElementById('modalTitle').innerHTML = '<i class="fas fa-edit"></i> Modifier la classe';
    document.getElementById('classForm').action = '?action=edit&id=' + cl.id;
    document.getElementById('modalName').value = cl.name; document.getElementById('modalLevel').value = cl.level || '';
    document.getElementById('modalYear').value = cl.academic_year || '';
    document.getElementById('classModal').classList.add('open');
}
function closeModal() { document.getElementById('classModal').classList.remove('open'); }
document.getElementById('classModal').addEventListener('click', function(e) { if (e.target === this) closeModal(); });
document.getElementById('importModal').addEventListener('click', function(e) { if (e.target === this) this.classList.remove('open'); });
<?php if ($editClass): ?>
document.addEventListener('DOMContentLoaded', function() { openEditModal(<?= json_encode($editClass) ?>); });
<?php endif; ?>
<?php if ($__flash): ?>
document.addEventListener('DOMContentLoaded', function() { showToast(<?= json_encode($__flash['message']) ?>, <?= json_encode($__flash['type'] === 'success' ? 'success' : 'error') ?>); });
<?php endif; ?>
</script>
</body>
</html>
