<?php
/**
 * Matières globales, coefficients par école et affectations
 */
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('subjects', 'view');

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

// ── CRUD matières (Super Admin uniquement) ─────────────────────────────────
if ($action === 'delete_subject' && $id) {
    verifyCsrf(); if (!isSuperAdmin()) { flashMessage('error','Action réservée au super administrateur.'); header('Location: subjects.php'); exit; }
    checkDeleteAllowed(); requirePermission('subjects','delete');
    $pdo->prepare("DELETE FROM subjects WHERE id=?")->execute([$id]);
    flashMessage('success','Matière supprimée.'); header('Location: subjects.php'); exit;
}
if ($action === 'save_subject' && $_SERVER['REQUEST_METHOD']==='POST') {
    verifyCsrf(); requirePermission('subjects',$id?'edit':'create');
    $name=trim($_POST['name']??''); $code=trim($_POST['code']??''); $desc=trim($_POST['description']??'');
    $sort_subj=(int)($_POST['sort_order']??0);
    $group_id = !empty($_POST['group_id']) ? (int)$_POST['group_id'] : null;
    if(empty($name)) $error='Le nom est requis.';
    if(empty($error)){
        // Vérifier l'unicité du nom
        $dup = $pdo->prepare("SELECT id FROM subjects WHERE name=? AND id!=COALESCE(?,0)");
        $dup->execute([$name, $id ?? 0]);
        if ($dup->fetch()) {
            $error = 'Une matière avec ce nom existe déjà.';
        } elseif($id){
            $pdo->prepare("UPDATE subjects SET name=?,code=?,description=?,sort_order=?,group_id=? WHERE id=?")->execute([$name,$code,$desc,$sort_subj,$group_id,$id]);
            flashMessage('success','Matière mise à jour.');
            header('Location: subjects.php'); exit;
        } else {
            $pdo->prepare("INSERT INTO subjects (name,code,description,sort_order,group_id) VALUES(?,?,?,?,?)")->execute([$name,$code,$desc,$sort_subj,$group_id]);
            flashMessage('success','Matière ajoutée.');
            header('Location: subjects.php'); exit;
        }
    }
}

// ── CRUD class_subjects (avec school_id pour coefficients différents par école) ──
if ($action === 'delete_cs' && $id) {
    verifyCsrf(); if (!isSuperAdmin()) { flashMessage('error','Action réservée au super administrateur.'); header('Location: subjects.php?action=class_subjects'); exit; }
    checkDeleteAllowed(); requirePermission('subjects','delete');
    $pdo->prepare("DELETE FROM class_subjects WHERE id=?")->execute([$id]);
    flashMessage('success','Matière retirée de la classe.'); header('Location: subjects.php?action=class_subjects'); exit;
}
if ($action === 'save_cs' && $_SERVER['REQUEST_METHOD']==='POST') {
    verifyCsrf(); requirePermission('subjects','edit');
    $class_id=(int)($_POST['class_id']??0); $subject_id=(int)($_POST['subject_id']??0);
    $coef=filter_var($_POST['coefficient']??1,FILTER_VALIDATE_FLOAT);
    $hrs=!empty($_POST['hours_per_week'])?(float)$_POST['hours_per_week']:null;
    $cs_sort=(int)($_POST['cs_sort_order']??0);
    $cs_id=!empty($_POST['cs_id'])?(int)$_POST['cs_id']:null;
    $cs_school = (int)($_POST['cs_school_id'] ?? ($schoolFilter ?? 0));
    if($class_id<=0||$subject_id<=0) $error='Classe et matière requises.';
    elseif($coef===false||$coef<=0) $error='Coefficient invalide.';
    if(empty($error)){
        if($cs_id){
            $pdo->prepare("UPDATE class_subjects SET coefficient=?,hours_per_week=?,sort_order=? WHERE id=?")->execute([$coef,$hrs,$cs_sort,$cs_id]);
            flashMessage('success','Coefficient mis à jour.');
        } else {
            if ($cs_school <= 0) { $error = 'École requise pour le coefficient.'; }
            else {
                $pdo->prepare("INSERT INTO class_subjects (school_id,class_id,subject_id,coefficient,hours_per_week,sort_order) VALUES(?,?,?,?,?,?) ON DUPLICATE KEY UPDATE coefficient=VALUES(coefficient),hours_per_week=VALUES(hours_per_week),sort_order=VALUES(sort_order)")
                    ->execute([$cs_school, $class_id, $subject_id, $coef, $hrs, $cs_sort]);
                flashMessage('success','Matière ajoutée à la classe.');
            }
        }
        if (empty($error)) { header('Location: subjects.php?action=class_subjects'); exit; }
    }
}

// ── CRUD teacher_assignments ─────────────────────────────────────────────────
if ($action === 'delete_ta' && $id) {
    verifyCsrf(); if (!isSuperAdmin()) { flashMessage('error','Action réservée au super administrateur.'); header('Location: subjects.php?action=assignments'); exit; }
    checkDeleteAllowed(); requirePermission('subjects','delete');
    $pdo->prepare("DELETE FROM teacher_assignments WHERE id=?")->execute([$id]);
    flashMessage('success','Affectation supprimée.'); header('Location: subjects.php?action=assignments'); exit;
}
if ($action === 'save_ta' && $_SERVER['REQUEST_METHOD']==='POST') {
    verifyCsrf(); requirePermission('subjects','edit');
    $tid=(int)($_POST['teacher_id']??0); $sid2=(int)($_POST['subject_id']??0); $cid=(int)($_POST['class_id']??0); $ay=trim($_POST['academic_year']??'');
    if($tid<=0||$sid2<=0||$cid<=0) $error='Professeur, matière et classe requis.';
    if(empty($error)){
        $pdo->prepare("INSERT INTO teacher_assignments (teacher_id,subject_id,class_id,academic_year) VALUES(?,?,?,?) ON DUPLICATE KEY UPDATE academic_year=VALUES(academic_year)")->execute([$tid,$sid2,$cid,$ay]);
        flashMessage('success','Affectation enregistrée.'); header('Location: subjects.php?action=assignments'); exit;
    }
}

// Colonnes imported_at
try { $pdo->exec("ALTER TABLE subjects ADD COLUMN imported_at DATETIME DEFAULT NULL"); } catch (PDOException $e) {}
try { $pdo->exec("ALTER TABLE class_subjects ADD COLUMN imported_at DATETIME DEFAULT NULL"); } catch (PDOException $e) {}

// ── Export / Import ────────────────────────────────────────────────────────────
if (isset($_GET['export'])) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=matieres.csv');
    $out = fopen('php://output', 'w'); fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
    fputcsv($out, ['Nom', 'Code', 'Description'], ';');
    foreach ($pdo->query("SELECT * FROM subjects ORDER BY name") as $s) {
        fputcsv($out, [$s['name'], $s['code'] ?? '', $s['description'] ?? ''], ';');
    }
    fclose($out); exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
    verifyCsrf();
    if ($_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) { flashMessage('error', 'Erreur fichier.'); header('Location: subjects.php'); exit; }
    $handle = fopen($_FILES['csv_file']['tmp_name'], 'r');
    $header = fgetcsv($handle, 0, ';');
    if (!$header || count($header) < 1) { flashMessage('error', 'CSV invalide.'); header('Location: subjects.php'); exit; }
    $imported = 0; $errors = []; $rowNum = 0;
    while (($row = fgetcsv($handle, 0, ';')) !== false) {
        $rowNum++; $name = trim($row[0] ?? ''); if (empty($name)) continue;
        $code = trim($row[1] ?? ''); $desc = trim($row[2] ?? '');
        $dup = $pdo->prepare("SELECT id FROM subjects WHERE name=?");
        $dup->execute([$name]);
        if ($dup->fetch()) { $errors[] = "Ligne $rowNum : '$name' existe déjà"; continue; }
        $pdo->prepare("INSERT INTO subjects (name, code, description, imported_at) VALUES (?,?,?,NOW())")->execute([$name, $code, $desc]);
        $imported++;
    }
    fclose($handle);
    $msg = "$imported matière(s) importée(s).";
    if (!empty($errors)) $msg .= ' ' . implode('. ', array_slice($errors, 0, 10));
    flashMessage('success', $msg); header('Location: subjects.php'); exit;
}

// Export / Import matières par classe
if (isset($_GET['export_cs'])) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=matieres_par_classe.csv');
    $out = fopen('php://output', 'w'); fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
    fputcsv($out, ['Classe', 'Matière', 'Code', 'Coefficient', 'H/semaine', 'École'], ';');
    $csData = $pdo->query("SELECT c.name AS class_name,subj.name AS subject_name,subj.code,cs.coefficient,cs.hours_per_week,sc.name AS school_name FROM class_subjects cs JOIN classes c ON cs.class_id=c.id JOIN subjects subj ON cs.subject_id=subj.id LEFT JOIN schools sc ON cs.school_id=sc.id ORDER BY c.name, subj.name")->fetchAll();
    foreach ($csData as $cs) fputcsv($out, [$cs['class_name'], $cs['subject_name'], $cs['code'] ?? '', $cs['coefficient'], $cs['hours_per_week'] ?? '', $cs['school_name'] ?? ''], ';');
    fclose($out); exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['cs_csv'])) {
    verifyCsrf();
    if ($_FILES['cs_csv']['error'] !== UPLOAD_ERR_OK) { flashMessage('error', 'Erreur fichier.'); header('Location: subjects.php?action=class_subjects'); exit; }
    $handle = fopen($_FILES['cs_csv']['tmp_name'], 'r');
    $header = fgetcsv($handle, 0, ';');
    if (!$header || count($header) < 2) { flashMessage('error', 'CSV invalide.'); header('Location: subjects.php?action=class_subjects'); exit; }
    $classMap = []; foreach ($pdo->query("SELECT id, name FROM classes c ORDER BY " . getClassSortSQL('c')) as $c) { $classMap[strtolower(trim($c['name']))] = $c['id']; }
    $subjectMap = []; foreach ($pdo->query("SELECT id, name, code FROM subjects ORDER BY name") as $s) { $subjectMap[strtolower(trim($s['name']))] = $s['id']; $subjectMap[strtolower(trim($s['code']))] = $s['id']; }
    $schoolMap = []; foreach ($pdo->query("SELECT id, name FROM schools") as $sc) { $schoolMap[strtolower(trim($sc['name']))] = $sc['id']; }
    $imported = 0; $errors = []; $rowNum = 0;
    while (($row = fgetcsv($handle, 0, ';')) !== false) {
        $rowNum++; $className = trim($row[0] ?? ''); $subjectName = trim($row[1] ?? '');
        $coef = (float)str_replace(',', '.', trim($row[3] ?? '1'));
        $hrs = !empty($row[4]) ? (float)str_replace(',', '.', trim($row[4])) : null;
        $schoolName = trim($row[5] ?? '');
        if (empty($className) || empty($subjectName)) continue;
        $classId = $classMap[strtolower($className)] ?? 0;
        $subjectId = $subjectMap[strtolower($subjectName)] ?? 0;
        $schoolId = $schoolName ? ($schoolMap[strtolower($schoolName)] ?? 0) : ($schoolFilter ?? 0);
        if (!$classId) { $errors[] = "Ligne $rowNum : classe '$className' introuvable"; continue; }
        if (!$subjectId) { $errors[] = "Ligne $rowNum : matière '$subjectName' introuvable"; continue; }
        if ($coef <= 0) { $errors[] = "Ligne $rowNum : coefficient invalide"; continue; }
        if (!$schoolId) { $errors[] = "Ligne $rowNum : école '$schoolName' introuvable"; continue; }
        $pdo->prepare("INSERT INTO class_subjects (school_id, class_id, subject_id, coefficient, hours_per_week, imported_at) VALUES (?,?,?,?,?,NOW()) ON DUPLICATE KEY UPDATE coefficient=VALUES(coefficient), hours_per_week=VALUES(hours_per_week), imported_at=NOW()")
            ->execute([$schoolId, $classId, $subjectId, $coef, $hrs]);
        $imported++;
    }
    fclose($handle);
    $msg = "$imported affectation(s) importée(s).";
    if (!empty($errors)) $msg .= ' ' . implode('. ', array_slice($errors, 0, 10));
    flashMessage('success', $msg); header('Location: subjects.php?action=class_subjects'); exit;
}

if ($action === 'clear_imports') {
    verifyCsrf(); checkDeleteAllowed();
    if (!isSuperAdmin()) { flashMessage('error','Action réservée au super administrateur.'); header('Location: subjects.php'); exit; }
    $pdo->exec("DELETE FROM subjects WHERE imported_at IS NOT NULL");
    $pdo->exec("DELETE FROM class_subjects WHERE imported_at IS NOT NULL");
    flashMessage('success','Importations supprimées.'); header('Location: subjects.php'); exit;
}

// ── Données ─────────────────────────────────────────────────────────────────
$filterClass = isset($_GET['filter_class']) ? (int)$_GET['filter_class'] : 0;

// Toutes les classes (globales)
$allClasses = $pdo->query("SELECT id,name,level,academic_year FROM classes c ORDER BY " . getClassSortSQL('c'))->fetchAll();
// Tous les professeurs (filtrés par école si school_admin)
if ($schoolFilter) {
    $allTeachers = $pdo->prepare("SELECT id,CONCAT(last_name,' ',first_name) AS full_name FROM teachers WHERE school_id=? ORDER BY last_name, first_name");
    $allTeachers->execute([$schoolFilter]); $allTeachers=$allTeachers->fetchAll();
} else {
    $allTeachers = $pdo->query("SELECT t.id,CONCAT(t.last_name,' ',t.first_name) AS full_name,s.name AS school_name FROM teachers t LEFT JOIN schools s ON t.school_id=s.id ORDER BY s.name,t.last_name")->fetchAll();
}
// Toutes les matières (globales)
$allSubjects = $pdo->query("SELECT id,name,code FROM subjects ORDER BY name")->fetchAll();
// Toutes les écoles
$schools = $pdo->query("SELECT id,name FROM schools ORDER BY name")->fetchAll();

// Liste matières
$sort = resolveSort(['name','code','sort_order','created_at','group_name'],'sort_order','asc');
$sortMap=['name'=>'s.name','code'=>'s.code','sort_order'=>'s.sort_order','created_at'=>'s.created_at','group_name'=>'sg.name'];
$orderExpr=($sortMap[$sort['col']]??'s.sort_order').' '.$sort['dir'];
$subjects = $pdo->query("SELECT s.*,sg.name AS group_name FROM subjects s LEFT JOIN subject_groups sg ON s.group_id=sg.id ORDER BY $orderExpr")->fetchAll();

// Matières par classe (avec school_id)
$csWhere = "";
$csConditions = [];
if ($filterClass) $csConditions[] = "cs.class_id=$filterClass";
if ($schoolFilter) $csConditions[] = "cs.school_id=$schoolFilter";
if ($csConditions) $csWhere = "WHERE " . implode(" AND ", $csConditions);
$classSubjects = $pdo->query("SELECT cs.*,c.name AS class_name,c.academic_year,subj.name AS subject_name,subj.code,sc.name AS school_name FROM class_subjects cs JOIN classes c ON cs.class_id=c.id JOIN subjects subj ON cs.subject_id=subj.id LEFT JOIN schools sc ON cs.school_id=sc.id $csWhere ORDER BY c.name,cs.sort_order,subj.name")->fetchAll();
$csByClass = [];
foreach($classSubjects as $cs){ $csByClass[$cs['class_id']]=($csByClass[$cs['class_id']]??['name'=>$cs['class_name'],'year'=>$cs['academic_year'],'items'=>[]]); $csByClass[$cs['class_id']]['items'][]=$cs; }

// Affectations
$taWhere = $schoolFilter ? "WHERE t.school_id=$schoolFilter" : "";
$assignments = $pdo->query("SELECT ta.*,CONCAT(t.last_name,' ',t.first_name) AS teacher_name,subj.name AS subject_name,c.name AS class_name,s.name AS school_name FROM teacher_assignments ta JOIN teachers t ON ta.teacher_id=t.id JOIN subjects subj ON ta.subject_id=subj.id JOIN classes c ON ta.class_id=c.id LEFT JOIN schools s ON t.school_id=s.id $taWhere ORDER BY c.name,subj.name,t.last_name")->fetchAll();

// Groupes de matières (globaux)
$subjectGroups = $pdo->query("SELECT id, name FROM subject_groups WHERE school_id=0 OR school_id IS NULL ORDER BY sort_order")->fetchAll();
if (empty($subjectGroups)) $subjectGroups = $pdo->query("SELECT id, name FROM subject_groups ORDER BY sort_order")->fetchAll();

$editSubject=null;
if($action==='edit_subject'&&$id){ $s=$pdo->prepare("SELECT * FROM subjects WHERE id=?"); $s->execute([$id]); $editSubject=$s->fetch(); }
$editCs=null;
if($action==='edit_cs'&&$id){ $s=$pdo->prepare("SELECT * FROM class_subjects WHERE id=?"); $s->execute([$id]); $editCs=$s->fetch(); }
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Matières - 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;}
.card{background:white;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,0.06);padding:1.5rem;margin-bottom:1.5rem;}
.card-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem;}
.card-title{font-size:1.1rem;font-weight:600;color:#2d3748;}
.form-group{margin-bottom:1rem;}
.form-group label{display:block;margin-bottom:.4rem;font-weight:600;color:var(--primary);font-size:.82rem;}
.form-group input,.form-group select,.form-group textarea{width:100%;padding:.6rem .75rem;border:1px solid #D1D5DB;border-radius:6px;font-size:.85rem;}
.form-group input:focus,.form-group select:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 3px rgba(46,117,182,0.15);}
.form-grid-2{display:grid;grid-template-columns:1fr 1fr;gap:1rem;}
.btn{display:inline-flex;align-items:center;gap:6px;padding:.5rem 1rem;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-action{display:inline-block;padding:.45rem .9rem;border-radius:5px;text-decoration:none;font-size:.82rem;font-weight:500;transition:opacity .3s;}
.btn-edit{background:#bee3f8;color:#2b6cb0;}.btn-delete{background:#fed7d7;color:#c53030;}.btn-view{background:#e2e8f0;color:#4a5568;}
.btn-submit{width:100%;padding:.65rem;background:linear-gradient(135deg,#667eea,#764ba2);color:white;border:none;border-radius:8px;font-size:.95rem;font-weight:600;cursor:pointer;}
.btn-sm{padding:.3rem .6rem;font-size:.78rem;}
.error-msg{background:#FEE2E2;color:#991B1B;border:1px solid #FECACA;border-radius:8px;padding:.75rem 1rem;margin-bottom:1rem;font-size:.88rem;}
.tab-nav{display:flex;gap:0;margin-bottom:1.5rem;background:white;border-radius:10px;overflow:hidden;box-shadow:0 2px 12px rgba(0,0,0,0.06);}
.tab-btn{padding:.8rem 1.5rem;text-decoration:none;color:#6B7280;font-weight:600;font-size:.88rem;transition:all .2s;border-bottom:3px solid transparent;}
.tab-btn:hover{background:#F9FAFB;color:var(--primary);}
.tab-btn.active{color:var(--primary);border-bottom-color:var(--primary);background:#F0F7FF;}
.data-table{width:100%;border-collapse:collapse;}
.data-table th,.data-table td{padding:.65rem .75rem;text-align:left;border-bottom:1px solid #e2e8f0;font-size:.85rem;}
.data-table th{background:#f7fafc;font-weight:600;color:#4a5568;}
.data-table tr:hover{background:#f7fafc;}
.data-table-wrapper{overflow-x:auto;}
.subjects-chips{display:flex;flex-wrap:wrap;gap:.5rem;}
.subject-chip{display:flex;align-items:center;gap:.4rem;padding:.4rem .8rem;background:#F9FAFB;border:1px solid #E5E7EB;border-radius:8px;font-size:.85rem;transition:all .2s;}
.subject-chip:hover{border-color:var(--accent);background:#F0F7FF;}
.subject-chip-code{color:var(--accent);font-weight:700;font-size:.75rem;}
.subject-chip-name{font-weight:600;color:var(--text);}
.subject-chip-actions{display:flex;gap:4px;margin-left:.3rem;}
.subject-chip-actions a,.subject-chip-actions button{color:#9CA3AF;background:none;border:none;cursor:pointer;padding:2px 4px;font-size:.78rem;transition:color .2s;text-decoration:none;}
.subject-chip-actions a:hover,.subject-chip-actions button:hover{color:var(--danger);}
.coef-badge{display:inline-block;padding:2px 8px;background:#E8F5E9;color:var(--success);border-radius:6px;font-weight:700;font-size:.82rem;}
.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;}}
@media(max-width:768px){.tab-btn{padding:.6rem 1rem;font-size:.8rem;}.form-grid-2{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-book"></i> Matières &amp; Coefficients'; include '../includes/topbar.php'; ?>
        <?= showFlash() ?>
        <?php if ($error): ?><div class="error-msg"><?= e($error) ?></div><?php endif; ?>

        <div class="tab-nav">
            <a href="subjects.php" class="tab-btn <?= !in_array($action,['class_subjects','assignments','edit_cs','edit_subject']) ? 'active' : '' ?>"><i class="fas fa-book"></i> Matières</a>
            <a href="subjects.php?action=class_subjects" class="tab-btn <?= in_array($action,['class_subjects','edit_cs']) ? 'active' : '' ?>"><i class="fas fa-layer-group"></i> Matières par classe</a>
            <a href="subjects.php?action=assignments" class="tab-btn <?= $action==='assignments' ? 'active' : '' ?>"><i class="fas fa-chalkboard-teacher"></i> Affectations</a>
        </div>

        <?php if (!in_array($action,['class_subjects','assignments','edit_cs'])): ?>
        <!-- ═══ ONGLET MATIÈRES ═══ -->
        <?php if (isSuperAdmin() && (hasPermission('subjects','create')||hasPermission('subjects','edit'))): ?>
        <div class="card" style="max-width:640px;">
            <div class="card-header">
                <span class="card-title"><?= $editSubject?'Modifier':'Ajouter' ?> une matière</span>
                <?php if($editSubject):?><a href="subjects.php" class="btn-action btn-view">Annuler</a><?php endif;?>
            </div>
            <form method="POST" action="?action=save_subject<?= $editSubject?'&id='.$editSubject['id']:'' ?>">
                <?= csrfField() ?>
                <div class="form-grid-2">
                    <div class="form-group">
                        <label>Nom <span style="color:red">*</span></label>
                        <input type="text" name="name" required value="<?= e($editSubject['name']??'') ?>" placeholder="ex: Mathématiques">
                    </div>
                    <div class="form-group">
                        <label>Code</label>
                        <input type="text" name="code" value="<?= e($editSubject['code']??'') ?>" placeholder="MATH">
                    </div>
                </div>
                <div class="form-grid-2">
                    <div class="form-group">
                        <label>Ordre</label>
                        <input type="number" name="sort_order" min="0" value="<?=e($editSubject['sort_order']??'0')?>" style="width:80px;">
                    </div>
                    <div class="form-group">
                        <label>Type</label>
                        <select name="group_id">
                            <option value="">— Aucun —</option>
                            <?php foreach($subjectGroups as $g):?>
                            <option value="<?=$g['id']?>" <?=($editSubject['group_id']??'')==$g['id']?'selected':''?>><?=e($g['name'])?></option>
                            <?php endforeach;?>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <input type="text" name="description" value="<?=e($editSubject['description']??'')?>" placeholder="Description courte...">
                </div>
                <button type="submit" class="btn-submit"><i class="fas fa-save"></i> Enregistrer</button>
            </form>
        </div>
        <?php endif; ?>

        <div style="display:flex;gap:.5rem;margin-bottom:1rem;flex-wrap:wrap;">
            <?php if (hasRole(['super_admin','school_admin'])): ?>
            <a href="?export=1" class="btn-action btn-view"><i class="fas fa-download"></i> Export CSV</a>
            <button type="button" class="btn-action btn-edit" onclick="document.getElementById('importModal').style.display='flex'"><i class="fas fa-upload"></i> Import CSV</button>
            <?php endif; ?>
            <?php if (isSuperAdmin()): ?>
            <form method="POST" action="?action=clear_imports" style="display:inline" onsubmit="return confirm('Supprimer toutes les matières importées ?')">
                <?= csrfField() ?>
                <button type="submit" class="btn-action btn-delete"><i class="fas fa-trash"></i> Suppr. importations</button>
            </form>
            <?php endif; ?>
        </div>

        <div id="importModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:999;align-items:center;justify-content:center;" onclick="if(event.target===this)this.style.display='none'">
            <div style="background:#fff;border-radius:12px;padding:2rem;max-width:540px;width:90%;box-shadow:0 20px 60px rgba(0,0,0,.3);">
                <h3 style="margin:0 0 1rem;"><i class="fas fa-upload"></i> Importer des matières</h3>
                <p style="color:#718096;font-size:.9rem;margin-bottom:1.5rem;">
                    <strong>Format CSV</strong> (séparateur <code>;</code>)<br>
                    Colonnes : <code>Nom;Code;Description</code>
                </p>
                <form method="POST" enctype="multipart/form-data">
                    <?= csrfField() ?>
                    <input type="file" name="csv_file" accept=".csv,.txt" required style="width:100%;padding:.5rem;border:1px solid #e2e8f0;border-radius:6px;margin-bottom:1rem;">
                    <div style="display:flex;gap:.5rem;">
                        <button type="submit" class="btn-submit"><i class="fas fa-upload"></i> Importer</button>
                        <button type="button" class="btn-action" onclick="document.getElementById('importModal').style.display='none'" style="background:#e2e8f0;">Annuler</button>
                    </div>
                </form>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <span class="card-title"><i class="fas fa-book" style="color:var(--primary);"></i> Liste globale des matières</span>
                <span style="color:#718096;font-size:.85rem;"><?=count($subjects)?> matière<?=count($subjects)>1?'s':''?></span>
            </div>
            <div class="subjects-chips">
                <?php foreach($subjects as $subj):?>
                <div class="subject-chip">
                    <span class="subject-chip-code"><?=e($subj['code']??'—')?></span>
                    <span class="subject-chip-name"><?=e($subj['name'])?></span>
                    <span style="color:#a0aec0;font-size:.75rem;">#<?=e($subj['sort_order']??'0')?></span>
                    <?php if(!empty($subj['group_name'])):?>
                    <span class="badge" style="background:#edf2f7;color:#4a5568;font-size:.65rem;padding:.1rem .4rem;"><?=e($subj['group_name'])?></span>
                    <?php endif;?>
                    <div class="subject-chip-actions">
                        <?php if(isSuperAdmin() && hasPermission('subjects','edit')):?>
                        <a href="?action=edit_subject&id=<?=$subj['id']?>" title="Modifier"><i class="fas fa-edit"></i></a>
                        <?php endif;?>
                        <?php if(isSuperAdmin() && hasPermission('subjects','delete')):?>
                        <form method="POST" action="?action=delete_subject&id=<?=$subj['id']?>" style="display:inline" onsubmit="return confirm('Supprimer cette matière ?')">
                            <?=csrfField()?><button type="submit" title="Supprimer"><i class="fas fa-trash"></i></button>
                        </form>
                        <?php endif;?>
                    </div>
                </div>
                <?php endforeach;?>
            </div>
            <?php if(empty($subjects)):?>
            <div style="text-align:center;color:#999;padding:2rem;"><i class="fas fa-book" style="font-size:2rem;margin-bottom:.5rem;display:block;"></i>Aucune matière.</div>
            <?php endif;?>
        </div>

        <?php elseif(in_array($action,['class_subjects','edit_cs'])): ?>
        <!-- ═══ ONGLET MATIÈRES PAR CLASSE ═══ -->

        <div style="margin-bottom:1rem;display:flex;align-items:center;gap:.5rem;flex-wrap:wrap;">
            <span style="font-weight:600;color:#4a5568;">Filtrer :</span>
            <a href="subjects.php?action=class_subjects" class="btn-action <?=!$filterClass?'btn-view':''?>" style="<?=!$filterClass?'background:#667eea;color:white;':''?>">Toutes</a>
            <?php foreach($allClasses as $cl):?>
            <a href="?action=class_subjects&filter_class=<?=$cl['id']?>" class="btn-action <?=$filterClass==$cl['id']?'btn-view':''?>" style="<?=$filterClass==$cl['id']?'background:#667eea;color:white;':''?> font-size:.8rem;"><?=e($cl['name'])?></a>
            <?php endforeach;?>
        </div>

        <div style="display:flex;gap:.5rem;margin-bottom:1rem;flex-wrap:wrap;">
            <a href="?export_cs=1" class="btn-action btn-view"><i class="fas fa-download"></i> Export CSV</a>
            <button type="button" class="btn-action btn-edit" onclick="document.getElementById('importCsModal').style.display='flex'"><i class="fas fa-upload"></i> Import CSV</button>
        </div>

        <div id="importCsModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:999;align-items:center;justify-content:center;" onclick="if(event.target===this)this.style.display='none'">
            <div style="background:#fff;border-radius:12px;padding:2rem;max-width:540px;width:90%;box-shadow:0 20px 60px rgba(0,0,0,.3);">
                <h3 style="margin:0 0 1rem;"><i class="fas fa-upload"></i> Importer des affectations</h3>
                <p style="color:#718096;font-size:.9rem;margin-bottom:1.5rem;">
                    Colonnes : <code>Classe;Matière;Code;Coefficient;H/semaine;École</code><br>
                    Les colonnes Classe, Matière et École sont obligatoires.
                </p>
                <form method="POST" enctype="multipart/form-data">
                    <?= csrfField() ?>
                    <input type="file" name="cs_csv" accept=".csv,.txt" required style="width:100%;padding:.5rem;border:1px solid #e2e8f0;border-radius:6px;margin-bottom:1rem;">
                    <div style="display:flex;gap:.5rem;">
                        <button type="submit" class="btn-submit"><i class="fas fa-upload"></i> Importer</button>
                        <button type="button" class="btn-action" onclick="document.getElementById('importCsModal').style.display='none'" style="background:#e2e8f0;">Annuler</button>
                    </div>
                </form>
            </div>
        </div>

        <?php if(hasPermission('subjects','edit')):?>
        <div class="card" style="max-width:640px;">
            <div class="card-header">
                <span class="card-title"><?=$editCs?'Modifier coefficient':'Affecter une matière à une classe'?></span>
                <?php if($editCs):?><a href="subjects.php?action=class_subjects" class="btn-action btn-view">Annuler</a><?php endif;?>
            </div>
            <form method="POST" action="?action=save_cs">
                <?=csrfField()?>
                <?php if($editCs):?><input type="hidden" name="cs_id" value="<?=$editCs['id']?>"><?php endif;?>
                <div class="form-grid-2">
                    <div class="form-group">
                        <label>Classe <span style="color:red">*</span></label>
                        <select name="class_id" required <?=$editCs?'disabled':''?>>
                            <option value="">Choisir...</option>
                            <?php foreach($allClasses as $cl):?>
                            <option value="<?=$cl['id']?>" <?=($editCs['class_id']??$filterClass)==$cl['id']?'selected':''?>><?=e($cl['name'])?></option>
                            <?php endforeach;?>
                        </select>
                        <?php if($editCs):?><input type="hidden" name="class_id" value="<?=$editCs['class_id']?>"><?php endif;?>
                    </div>
                    <div class="form-group">
                        <label>Matière <span style="color:red">*</span></label>
                        <select name="subject_id" required <?=$editCs?'disabled':''?>>
                            <option value="">Choisir...</option>
                            <?php foreach($allSubjects as $subj):?>
                            <option value="<?=$subj['id']?>" <?=($editCs['subject_id']??'')==$subj['id']?'selected':''?>><?=e(($subj['code']?'['.$subj['code'].'] ':'').$subj['name'])?></option>
                            <?php endforeach;?>
                        </select>
                        <?php if($editCs):?><input type="hidden" name="subject_id" value="<?=$editCs['subject_id']?>"><?php endif;?>
                    </div>
                </div>
                <?php if(!$editCs):?>
                <div class="form-group">
                    <label>École <span style="color:red">*</span></label>
                    <select name="cs_school_id" required <?=$schoolFilter?'disabled':''?>>
                        <option value="">Choisir...</option>
                        <?php foreach($schools as $sc):?>
                        <option value="<?=$sc['id']?>" <?=$schoolFilter==$sc['id']?'selected':''?>><?=e($sc['name'])?></option>
                        <?php endforeach;?>
                    </select>
                    <?php if($schoolFilter):?><input type="hidden" name="cs_school_id" value="<?=$schoolFilter?>"><?php endif;?>
                </div>
                <?php endif;?>
                <div style="display:grid;grid-template-columns:1fr 1fr 80px;gap:1rem;">
                    <div class="form-group">
                        <label>Coefficient <span style="color:red">*</span></label>
                        <input type="number" name="coefficient" required min="0.5" max="20" step="0.5" value="<?=e($editCs['coefficient']??'1')?>">
                    </div>
                    <div class="form-group">
                        <label>H/semaine</label>
                        <input type="number" name="hours_per_week" min="0.5" max="40" step="0.5" value="<?=e($editCs['hours_per_week']??'')?>">
                    </div>
                    <div class="form-group">
                        <label>Ordre</label>
                        <input type="number" name="cs_sort_order" min="0" value="<?=e($editCs['sort_order']??'0')?>">
                    </div>
                </div>
                <button type="submit" class="btn-submit"><i class="fas fa-save"></i> Enregistrer</button>
            </form>
        </div>
        <?php endif;?>

        <?php if(empty($csByClass)):?>
        <div class="card" style="text-align:center;color:#999;padding:2rem;">Aucune matière assignée à une classe.</div>
        <?php else:?>
        <?php foreach($csByClass as $cid=>$classGroup): ?>
        <div class="card" style="overflow:hidden;">
            <div style="display:flex;align-items:center;gap:.5rem;padding:.5rem .75rem;background:#f7fafc;border-radius:8px;border:1px solid #e2e8f0;">
                <i class="fas fa-users" style="color:#667eea;"></i>
                <strong><?=e($classGroup['name'])?></strong>
                <?php if($classGroup['year']):?><small style="color:#718096;">— <?=e($classGroup['year'])?></small><?php endif;?>
                <span style="color:#718096;font-size:.8rem;margin-left:auto;"><?=count($classGroup['items'])?> matière<?=count($classGroup['items'])>1?'s':''?></span>
            </div>
            <div class="data-table-wrapper">
            <table class="data-table">
                <thead><tr><th>Ordre</th><th>Matière</th><th>Code</th><th>Coefficient</th><th>H/sem</th><th>École</th><th>Actions</th></tr></thead>
                <tbody>
                <?php foreach($classGroup['items'] as $cs):?>
                <tr>
                    <td><span style="color:#718096;"><?=e($cs['sort_order']??'0')?></span></td>
                    <td><strong><?=e($cs['subject_name'])?></strong></td>
                    <td><code><?=e($cs['code']??'—')?></code></td>
                    <td><span class="coef-badge">&times;<?=e($cs['coefficient'])?></span></td>
                    <td><?=e($cs['hours_per_week']??'—')?></td>
                    <td><?=e($cs['school_name'] ?? 'Globale')?></td>
                    <td>
                        <?php if(hasPermission('subjects','edit')):?>
                        <a href="?action=edit_cs&id=<?=$cs['id']?>" class="btn-action btn-edit" style="font-size:.8rem;padding:.3rem .6rem;"><i class="fas fa-edit"></i></a>
                        <?php endif;?>
                        <?php if(isSuperAdmin() && hasPermission('subjects','delete')):?>
                        <form method="POST" action="?action=delete_cs&id=<?=$cs['id']?>" style="display:inline" onsubmit="return confirm('Retirer cette matière de la classe ?')">
                            <?=csrfField()?><button type="submit" class="btn-action btn-delete" style="font-size:.8rem;padding:.3rem .6rem;"><i class="fas fa-trash"></i></button>
                        </form>
                        <?php endif;?>
                    </td>
                </tr>
                <?php endforeach;?>
                </tbody>
            </table>
            </div>
        </div>
        <?php endforeach; ?>
        <?php endif;?>

        <?php else: ?>
        <!-- ═══ ONGLET AFFECTATIONS ═══ -->
        <?php if(hasPermission('subjects','edit')):?>
        <div class="card" style="max-width:640px;">
            <div class="card-header"><span class="card-title">Affecter un professeur à une matière</span></div>
            <form method="POST" action="?action=save_ta">
                <?=csrfField()?>
                <div class="form-grid-2">
                    <div class="form-group">
                        <label>Professeur <span style="color:red">*</span></label>
                        <select name="teacher_id" required>
                            <option value="">Choisir...</option>
                            <?php foreach($allTeachers as $t):?>
                            <option value="<?=$t['id']?>"><?=e($t['full_name'].(isset($t['school_name'])?' ('.$t['school_name'].')':''))?></option>
                            <?php endforeach;?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Matière <span style="color:red">*</span></label>
                        <select name="subject_id" required>
                            <option value="">Choisir...</option>
                            <?php foreach($allSubjects as $subj):?>
                            <option value="<?=$subj['id']?>"><?=e(($subj['code']?'['.$subj['code'].'] ':'').$subj['name'])?></option>
                            <?php endforeach;?>
                        </select>
                    </div>
                </div>
                <div class="form-grid-2">
                    <div class="form-group">
                        <label>Classe <span style="color:red">*</span></label>
                        <select name="class_id" required>
                            <option value="">Choisir...</option>
                            <?php foreach($allClasses as $cl):?>
                            <option value="<?=$cl['id']?>"><?=e($cl['name'])?></option>
                            <?php endforeach;?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Année scolaire</label>
                        <input type="text" name="academic_year" placeholder="2025-2026">
                    </div>
                </div>
                <button type="submit" class="btn-submit"><i class="fas fa-save"></i> Affecter</button>
            </form>
        </div>
        <?php endif;?>
        <div class="card">
            <div class="data-table-wrapper">
            <table class="data-table">
                <thead><tr><th>Professeur</th><th>Matière</th><th>Classe</th><th>Année</th><?php if(!$schoolFilter):?><th>École</th><?php endif;?><th>Actions</th></tr></thead>
                <tbody>
                <?php foreach($assignments as $a):?>
                <tr>
                    <td><?=e($a['teacher_name'])?></td>
                    <td><?=e($a['subject_name'])?></td>
                    <td><?=e($a['class_name'])?></td>
                    <td><?=e($a['academic_year']??'—')?></td>
                    <?php if(!$schoolFilter):?><td><?=e($a['school_name'])?></td><?php endif;?>
                    <td>
                        <?php if(isSuperAdmin() && hasPermission('subjects','delete')):?>
                        <form method="POST" action="?action=delete_ta&id=<?=$a['id']?>" style="display:inline" onsubmit="return confirm('Supprimer cette affectation ?')">
                            <?=csrfField()?><button type="submit" class="btn-action btn-delete" style="font-size:.8rem;padding:.3rem .6rem;"><i class="fas fa-trash"></i></button>
                        </form>
                        <?php endif;?>
                    </td>
                </tr>
                <?php endforeach;?>
                <?php if(empty($assignments)):?><tr><td colspan="6" style="text-align:center;color:#999;">Aucune affectation.</td></tr><?php endif;?>
                </tbody>
            </table>
            </div>
        </div>
        <?php endif; ?>
    </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);
}
</script>
</body>
</html>
