<?php
/**
 * Gestion des enseignants
 */
require_once '../config/database.php';
require_once '../includes/auth_check.php';
require_once '../includes/functions.php';
header('Content-Type: text/html; charset=utf-8');

try { $pdo->exec("ALTER TABLE teachers ADD COLUMN user_id INT DEFAULT NULL AFTER school_id"); } catch (PDOException $e) {}
try { $pdo->exec("ALTER TABLE teachers ADD INDEX user_id (user_id)"); } catch (PDOException $e) {}

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

$schoolFilter = currentSchoolId();
requirePermission('teachers', 'view');

// ── Session : définir année/période/école active ──
if ($action === 'set_session_filters') {
    if (isset($_POST['annee_active'])) {
        $val = trim($_POST['annee_active']);
        $_SESSION['active_academic_year'] = $val ?: null;
    }
    if (isset($_POST['periode_active'])) {
        $val = (int)$_POST['periode_active'];
        setActivePeriod($val);
    }
    if (isset($_POST['ecole_active'])) {
        $val = (int)$_POST['ecole_active'];
        $_SESSION['active_school_filter'] = $val ?: null;
    }
    flashMessage('success', 'Filtres mis à jour.');
    header('Location: teachers.php'); exit;
}

if ($action === 'clear_session') {
    verifyCsrf();
    unset($_SESSION['active_academic_year']);
    unset($_SESSION['active_period']);
    unset($_SESSION['active_school_filter']);
    flashMessage('success', 'Filtres réinitialisés.');
    header('Location: teachers.php'); exit;
}

// Colonne imported_at pour le suivi des importations
try { $pdo->exec("ALTER TABLE teachers ADD COLUMN imported_at DATETIME DEFAULT NULL"); } catch (PDOException $e) {}
// Table teacher_subjects pour plusieurs matières par enseignant
try { $pdo->exec("CREATE TABLE IF NOT EXISTS teacher_subjects (teacher_id INT NOT NULL, subject_id INT NOT NULL, PRIMARY KEY (teacher_id, subject_id))"); } catch (PDOException $e) {}
// Colonne gender
try { $pdo->exec("ALTER TABLE teachers ADD COLUMN gender ENUM('M','F','Autre') DEFAULT 'M' AFTER last_name"); } catch (PDOException $e) {}

// ── Export ─────────────────────────────────────────────────────────────────────
if (isset($_GET['export'])) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=enseignants.csv');
    $out = fopen('php://output', 'w');
    fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF)); // BOM UTF-8
    fputcsv($out, ['Prénom', 'Nom', 'Téléphone', 'Email', 'Matière', 'DateNaissance', 'Diplôme', 'École'], ';');
    $expStmt = $pdo->query("SELECT t.*, s.name AS school_name FROM teachers t LEFT JOIN schools s ON t.school_id=s.id ORDER BY t.last_name, t.first_name");
    foreach ($expStmt as $t) {
        fputcsv($out, [$t['first_name'], $t['last_name'], $t['phone'] ?? '', $t['email'] ?? '', $t['subject'] ?? '', $t['birth_date'] ?? '', $t['diploma'] ?? '', $t['school_name'] ?? ''], ';');
    }
    fclose($out);
    exit;
}

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

// ── Import CSV ─────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
    verifyCsrf();
    if ($_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
        flashMessage('error', 'Erreur lors du téléchargement du fichier.');
        header('Location: teachers.php'); exit;
    }
    $handle = fopen($_FILES['csv_file']['tmp_name'], 'r');
    $header = fgetcsv($handle, 0, ';');
    if (!$header || count($header) < 2) {
        fclose($handle);
        flashMessage('error', 'Format CSV invalide. Vérifiez le séparateur (;) et le nombre de colonnes.');
        header('Location: teachers.php'); exit;
    }
    $schoolMap = [];
    foreach ($pdo->query("SELECT id, name FROM schools ORDER BY name") as $sc) {
        $schoolMap[strtolower(trim($sc['name']))] = $sc['id'];
    }
    $imported = 0; $errors = []; $rowNum = 0;
    while (($row = fgetcsv($handle, 0, ';')) !== false) {
        $rowNum++;
        $first_name = trim($row[0] ?? '');
        $last_name  = trim($row[1] ?? '');
        $phone      = trim($row[2] ?? '');
        $email      = trim($row[3] ?? '');
        $subject    = trim($row[4] ?? '');
        $birth_date = trim($row[5] ?? '');
        $diploma    = trim($row[6] ?? '');
        $schoolName = trim($row[7] ?? '');
        if (empty($first_name) || empty($last_name)) continue;
        $schoolId = $schoolName ? ($schoolMap[strtolower($schoolName)] ?? 0) : ($schoolFilter ?? 0);
        if (!$schoolId && $schoolName) {
            $errors[] = "Ligne $rowNum : école '$schoolName' introuvable"; continue;
        }
        $bd = $birth_date ?: null;
        $pdo->prepare("INSERT INTO teachers (school_id, first_name, last_name, phone, email, subject, birth_date, diploma, imported_at) VALUES (?,?,?,?,?,?,?,?,NOW())")
            ->execute([$schoolId ?: 0, $first_name, $last_name, $phone, $email, $subject, $bd, $diploma]);
        $imported++;
    }
    fclose($handle);
    $msg = "$imported enseignant(s) importé(s).";
    if (!empty($errors)) $msg .= ' ' . implode('. ', array_slice($errors, 0, 10));
    flashMessage('success', $msg);
    header('Location: teachers.php'); exit;
}

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

// ── Suppression multiple ──
if (isset($_POST['bulk_delete'])) {
    verifyCsrf();
    if (!isSuperAdmin()) { flashMessage('error','Action réservée au super administrateur.'); header('Location: teachers.php'); exit; }
    checkDeleteAllowed();
    $ids = isset($_POST['teacher_ids']) ? array_map('intval', (array)$_POST['teacher_ids']) : [];
    $deleted = 0;
    foreach ($ids as $tid) {
        if ($schoolFilter) {
            $chk = $pdo->prepare("SELECT id FROM teachers WHERE id=? AND school_id=?");
            $chk->execute([$tid, $schoolFilter]);
            if (!$chk->fetch()) continue;
        }
        $pdo->prepare("DELETE FROM teachers WHERE id=?")->execute([$tid]);
        $deleted++;
    }
    flashMessage('success', "$deleted enseignant(s) supprimé(s).");
    header('Location: teachers.php'); exit;
}

// ── Sync vers Utilisateurs ──────────────────────────────────────────────────────
if (isset($_GET['sync_users'])) {
    verifyCsrf();
    requirePermission('users', 'edit');
    $query = "SELECT t.*, s.name AS school_name FROM teachers t LEFT JOIN schools s ON t.school_id=s.id";
    if ($schoolFilter) $query .= " WHERE t.school_id=" . (int)$schoolFilter;
    $query .= " ORDER BY t.last_name, t.first_name";
    $teachers = $pdo->query($query)->fetchAll();
    $created = 0; $updated = 0; $skipped = 0; $errors = [];
    foreach ($teachers as $t) {
        $fullName = trim($t['last_name'] . ' ' . $t['first_name']);
        $email = trim($t['email'] ?? '');
        if (empty($email)) { $skipped++; continue; }
        if ($t['user_id']) {
            // Mettre à jour l'utilisateur existant
            try {
                $pdo->prepare("UPDATE users SET name=?, email=?, gender=?, birth_date=?, school_id=? WHERE id=?")
                    ->execute([$fullName, $email, $t['gender'], $t['birth_date'] ?: null, $t['school_id'], $t['user_id']]);
                $updated++;
            } catch (PDOException $e) {
                $errors[] = $fullName . ' (UPDATE): ' . $e->getMessage();
            }
        } else {
            // Créer un nouvel utilisateur
            try {
                $password = bin2hex(random_bytes(4));
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $pdo->prepare("INSERT INTO users (school_id, name, email, password, plain_password, role, gender, birth_date, active) VALUES (?,?,?,?,?,'teacher',?,?,1)")
                    ->execute([$t['school_id'], $fullName, $email, $hash, $password, $t['gender'], $t['birth_date'] ?: null]);
                $newUid = $pdo->lastInsertId();
                $pdo->prepare("UPDATE teachers SET user_id=? WHERE id=?")->execute([$newUid, $t['id']]);
                $created++;
            } catch (PDOException $e) {
                if ($e->errorInfo[1] == 1062) {
                    // Email en double — essayer de lier à l'utilisateur existant
                    $existing = $pdo->prepare("SELECT id FROM users WHERE email=? AND role='teacher' LIMIT 1");
                    $existing->execute([$email]);
                    if ($exUser = $existing->fetch()) {
                        $pdo->prepare("UPDATE teachers SET user_id=? WHERE id=?")->execute([$exUser['id'], $t['id']]);
                        $pdo->prepare("UPDATE users SET name=?, gender=?, birth_date=?, school_id=? WHERE id=?")
                            ->execute([$fullName, $t['gender'], $t['birth_date'] ?: null, $t['school_id'], $exUser['id']]);
                        $updated++;
                    } else {
                        $errors[] = $fullName . ' : email déjà utilisé (' . $email . ')';
                    }
                } else {
                    $errors[] = $fullName . ' : ' . $e->getMessage();
                }
            }
        }
    }
    $msg = "Synchronisation terminée : $created créé(s), $updated mis à jour, $skipped ignoré(s) (sans email).";
    if (!empty($errors)) $msg .= ' Erreurs : ' . implode(' | ', array_slice($errors, 0, 10));
    flashMessage('success', $msg);
    header('Location: teachers.php'); exit;
}

// ── Ajout / Modification ──────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_FILES['csv_file'])) {
    verifyCsrf();
    $school_id  = $schoolFilter ?? (int)($_POST['school_id'] ?? 0);
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name  = trim($_POST['last_name']  ?? '');
    $gender     = ($_POST['gender'] ?? 'M') === 'F' ? 'F' : (($_POST['gender'] ?? 'M') === 'Autre' ? 'Autre' : 'M');
    $phone      = trim($_POST['phone']   ?? '');
    $email      = trim($_POST['email']   ?? '');
    $birth_date = $_POST['birth_date']   ?? '';
    $diploma    = trim($_POST['diploma']  ?? '');

    if (empty($first_name) || empty($last_name)) $error = 'Le prénom et le nom sont requis.';
    elseif ($school_id <= 0) $error = 'Veuillez sélectionner une école.';
    elseif (!empty($email) && !validateEmail($email)) $error = 'Adresse email invalide.';
    else {
        $sc = $pdo->prepare("SELECT id FROM schools WHERE id = ?");
        $sc->execute([$school_id]);
        if (!$sc->fetch()) $error = 'École invalide.';
    }

    if (empty($error)) {
        $subject_ids = array_map('intval', $_POST['subject_ids'] ?? []);
        $birth_date = $birth_date ?: null;
        $data = [$school_id, $first_name, $last_name, $gender, $phone, $email, $birth_date, $diploma];
        $redirect_sid = $school_id;
        if ($id) {
            if ($schoolFilter) {
                $check = $pdo->prepare("SELECT id FROM teachers WHERE id = ? AND school_id = ?");
                $check->execute([$id, $schoolFilter]);
                if (!$check->fetch()) { flashMessage('error', 'Action non autorisée.'); header('Location: teachers.php'); exit; }
            }
            $data[] = $id;
            $pdo->prepare("UPDATE teachers SET school_id=?, first_name=?, last_name=?, gender=?, phone=?, email=?, birth_date=?, diploma=? WHERE id=?")->execute($data);
            // Sync user account if linked
            $fullName = trim("$last_name $first_name");
            $st = $pdo->prepare("SELECT user_id FROM teachers WHERE id=?");
            $st->execute([$id]);
            $uid = $st->fetchColumn();
            if ($uid) {
                $pdo->prepare("UPDATE users SET name=?, email=?, gender=?, birth_date=? WHERE id=?")
                    ->execute([$fullName, $email, $gender, $birth_date, $uid]);
            } elseif (!empty($email)) {
                $password = bin2hex(random_bytes(4));
                $hash = password_hash($password, PASSWORD_DEFAULT);
                try {
                    $pdo->prepare("INSERT INTO users (school_id, name, email, password, plain_password, role, gender, birth_date, active) VALUES (?,?,?,?,?,'teacher',?,?,1)")
                        ->execute([$school_id, $fullName, $email, $hash, $password, $gender, $birth_date]);
                    $newUid = $pdo->lastInsertId();
                    $pdo->prepare("UPDATE teachers SET user_id=? WHERE id=?")->execute([$newUid, $id]);
                } catch (PDOException $e) {}
            }
            // Syncer teacher_subjects
            $pdo->prepare("DELETE FROM teacher_subjects WHERE teacher_id=?")->execute([$id]);
            $ins = $pdo->prepare("INSERT INTO teacher_subjects (teacher_id,subject_id) VALUES (?,?)");
            foreach ($subject_ids as $subjId) $ins->execute([$id, $subjId]);
            flashMessage('success', 'Enseignant mis à jour.');
        } else {
            $pdo->prepare("INSERT INTO teachers (school_id, first_name, last_name, gender, phone, email, birth_date, diploma) VALUES (?,?,?,?,?,?,?,?)")->execute($data);
            $newId = $pdo->lastInsertId();
            $fullName = trim("$last_name $first_name");
            if (!empty($email)) {
                $password = bin2hex(random_bytes(4));
                $hash = password_hash($password, PASSWORD_DEFAULT);
                try {
                    $pdo->prepare("INSERT INTO users (school_id, name, email, password, plain_password, role, gender, birth_date, active) VALUES (?,?,?,?,?,'teacher',?,?,1)")
                        ->execute([$school_id, $fullName, $email, $hash, $password, $gender, $birth_date]);
                    $newUid = $pdo->lastInsertId();
                    $pdo->prepare("UPDATE teachers SET user_id=? WHERE id=?")->execute([$newUid, $newId]);
                } catch (PDOException $e) {}
            }
            $ins = $pdo->prepare("INSERT INTO teacher_subjects (teacher_id,subject_id) VALUES (?,?)");
            foreach ($subject_ids as $subjId) $ins->execute([$newId, $subjId]);
            $redirect_sid = $school_id ?: ($schoolFilter ?: 0);
            flashMessage('success', 'Enseignant ajouté.');
        }
        header('Location: teachers.php' . ($redirect_sid ? '?open=' . $redirect_sid : '')); exit;
    }
}

// ── Chargement pour édition ───────────────────────────────────────────────────
$teacher = null;
if ($action === 'edit' && $id) {
    $stmt = $pdo->prepare("SELECT * FROM teachers WHERE id = ?" . ($schoolFilter ? " AND school_id = ?" : ""));
    $stmt->execute($schoolFilter ? [$id, $schoolFilter] : [$id]);
    $teacher = $stmt->fetch();
    if (!$teacher) { flashMessage('error', 'Enseignant introuvable.'); header('Location: teachers.php'); exit; }
}

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

// ── Tri ───────────────────────────────────────────────────────────────────────
$sortAllowed = ['first_name', 'last_name', 'school_name', 'phone', 'email', 'birth_date', 'diploma', 'created_at'];
$sort = resolveSort($sortAllowed, 'last_name', 'asc');
$sortMap = [
    'first_name'  => 't.first_name',
    'last_name'   => 't.last_name',
    'school_name' => 's.name',
    'phone'       => 't.phone',
    'email'       => 't.email',
    'birth_date'  => 't.birth_date',
    'diploma'     => 't.diploma',
    'created_at'  => 't.created_at',
];
$orderExpr = ($sortMap[$sort['col']] ?? 't.last_name') . ' ' . $sort['dir'];

$listSql = "SELECT t.*, s.name AS school_name FROM teachers t LEFT JOIN schools s ON t.school_id = s.id";
if ($schoolFilter) {
    $listStmt = $pdo->prepare($listSql . " WHERE t.school_id = ? ORDER BY $orderExpr");
    $listStmt->execute([$schoolFilter]);
} else {
    $listStmt = $pdo->query($listSql . " ORDER BY $orderExpr");
}
$teachers = $listStmt->fetchAll();

// Récupérer les affectations enseignant → classes
$taList = $pdo->query("
    SELECT ta.teacher_id, c.name AS class_name, c.academic_year
    FROM teacher_assignments ta
    JOIN classes c ON ta.class_id = c.id
    ORDER BY " . getClassSortSQL('c') . "
")->fetchAll();

$teacherClasses = [];
foreach ($taList as $ta) {
    $tid = $ta['teacher_id'];
    if (!isset($teacherClasses[$tid])) $teacherClasses[$tid] = [];
    $teacherClasses[$tid][] = $ta['class_name'] . ($ta['academic_year'] ? ' (' . $ta['academic_year'] . ')' : '');
}

// Récupérer les matières liées via teacher_subjects
$tsList = $pdo->query("
    SELECT ts.teacher_id, s.name AS subject_name, s.code
    FROM teacher_subjects ts
    JOIN subjects s ON ts.subject_id = s.id
    ORDER BY s.name
")->fetchAll();
$teacherSubjects = [];
foreach ($tsList as $ts) {
    $tid = $ts['teacher_id'];
    if (!isset($teacherSubjects[$tid])) $teacherSubjects[$tid] = [];
    $teacherSubjects[$tid][] = $ts;
}

// Grouper les enseignants par école
$teachersBySchool = [];
foreach ($teachers as $t) {
    $sid = $t['school_id'];
    if (!isset($teachersBySchool[$sid])) $teachersBySchool[$sid] = ['name' => $t['school_name'] ?? 'Sans école', 'teachers' => []];
    $t['class_list'] = $teacherClasses[$t['id']] ?? [];
    $t['subject_list'] = $teacherSubjects[$t['id']] ?? [];
    $teachersBySchool[$sid]['teachers'][] = $t;
}
// Trier les écoles par nom
ksort($teachersBySchool);

$sessionYear   = $_SESSION['active_academic_year'] ?? '';
$sessionPeriod = getActivePeriod();
$sessionSchool = $_SESSION['active_school_filter'] ?? $schoolFilter;
$yearsList = $pdo->query("SELECT DISTINCT year FROM academic_years ORDER BY year DESC")->fetchAll(PDO::FETCH_COLUMN);
$ecoles = $pdo->query("SELECT id, name FROM schools ORDER BY name")->fetchAll();

// Capture flash for JS toast
$__flash = $_SESSION['flash'] ?? null;
unset($_SESSION['flash']);
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Enseignants - 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;
  }

  .filters-card {
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.06);
    padding: 1.25rem 1.5rem;
    margin-bottom: 1.5rem;
  }
  .filters-row {
    display: flex;
    gap: 1.25rem;
    align-items: flex-end;
    flex-wrap: wrap;
  }
  .filter-group {
    display: flex;
    flex-direction: column;
    gap: 6px;
    flex: 1;
    min-width: 180px;
  }
  .filter-group label {
    font-weight: 600;
    color: var(--primary);
    font-size: .8rem;
  }
  .filter-group select {
    padding: .55rem .75rem;
    border: 1px solid #D1D5DB;
    border-radius: 6px;
    font-size: .85rem;
    background: white;
    cursor: pointer;
  }
  .filter-group select:focus {
    outline: none;
    border-color: var(--accent);
    box-shadow: 0 0 0 3px rgba(46,117,182,0.15);
  }

  .teacher-card {
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.06);
    margin-bottom: 1.5rem;
    overflow: hidden;
  }
  .teacher-card .tc-header {
    padding: 1rem 1.5rem;
    border-bottom: 1px solid #E5E7EB;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;
    user-select: none;
  }
  .teacher-card .tc-title {
    display: flex;
    align-items: center;
    gap: .75rem;
    font-family: Georgia, serif;
    color: var(--primary);
    font-size: 1.05rem;
  }
  .teacher-card .tc-count {
    background: var(--light);
    color: var(--primary);
    padding: 3px 10px;
    border-radius: 20px;
    font-size: .75rem;
    font-weight: 600;
  }

  .teacher-list {
    padding: 0;
  }
  .teacher-item {
    display: flex;
    align-items: flex-start;
    gap: 1rem;
    padding: 1rem 1.5rem;
    border-bottom: 1px solid #F3F4F6;
    transition: background .15s;
  }
  .teacher-item:last-child {
    border-bottom: none;
  }
  .teacher-item:hover {
    background: #F9FAFB;
  }

  .teacher-avatar {
    width: 44px;
    height: 44px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.15rem;
    flex-shrink: 0;
  }
  .avatar-m { background: #DBEAFE; color: #1E40AF; }
  .avatar-f { background: #FCE7F3; color: #BE185D; }
  .avatar-o { background: #E5E7EB; color: #4B5563; }

  .teacher-body { flex: 1; min-width: 0; }
  .teacher-name {
    display: flex;
    align-items: center;
    gap: .5rem;
    flex-wrap: wrap;
    font-weight: 600;
    color: #1F2937;
    font-size: .95rem;
  }
  .subject-badge {
    display: inline-block;
    padding: 2px 10px;
    border-radius: 20px;
    font-size: .7rem;
    font-weight: 600;
    background: var(--light);
    color: var(--primary);
  }
  .diploma-tag {
    color: #6B7280;
    font-size: .78rem;
    padding: 2px 8px;
    background: #F3F4F6;
    border-radius: 4px;
  }
  .teacher-meta {
    margin-top: .3rem;
    display: flex;
    gap: .75rem;
    flex-wrap: wrap;
    font-size: .8rem;
    color: #6B7280;
  }
  .teacher-meta span {
    display: inline-flex;
    align-items: center;
    gap: 4px;
  }
  .class-badges {
    margin-top: .5rem;
    display: flex;
    flex-wrap: wrap;
    gap: .35rem;
  }
  .class-badge {
    background: #F0FFF4;
    color: #276749;
    font-size: .72rem;
    padding: 2px 10px;
    border-radius: 4px;
    border: 1px solid #C6F6D5;
    display: inline-flex;
    align-items: center;
    gap: 4px;
  }

  .teacher-actions {
    flex-shrink: 0;
    display: flex;
    gap: .35rem;
    align-items: center;
  }
  .teacher-actions .btn {
    padding: .35rem .6rem;
    font-size: .75rem;
  }

  .empty-state {
    text-align: center;
    padding: 3rem 1.5rem;
    color: #9CA3AF;
  }
  .empty-state i {
    font-size: 2.5rem;
    margin-bottom: .5rem;
    display: block;
  }

  .modal-overlay {
    display: none;
    position: fixed;
    top: 0; left: 0; right: 0; bottom: 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: 540px;
    max-height: 90vh;
    overflow-y: auto;
    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 { font-size: .8rem; font-weight: 600; color: var(--primary); display: block; margin-bottom: 4px; }
  .modal-box .form-group input,
  .modal-box .form-group select {
    width: 100%;
    padding: .55rem .75rem;
    border: 1px solid #D1D5DB;
    border-radius: 6px;
    font-size: .85rem;
  }
  .modal-box .modal-actions {
    display: flex;
    gap: .75rem;
    margin-top: 1.25rem;
    justify-content: flex-end;
  }

  .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; }
  }

  .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-danger { background: #DC2626; color: white; }
  .btn-danger:hover { background: #B91C1C; }
  .btn-light { background: #E5E7EB; color: #374151; }
  .btn-light:hover { background: #D1D5DB; }
  .btn-outline { background: white; border: 1px solid #D1D5DB; color: var(--primary); }
  .btn-outline:hover { background: var(--light); }
  .btn-success { background: #059669; color: white; }
  .btn-success:hover { background: #047857; }

  .form-card {
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.06);
    padding: 1.5rem 2rem;
    max-width: 680px;
  }
  .form-card h2 {
    font-family: Georgia, serif;
    color: var(--primary);
    font-size: 1.2rem;
    margin-bottom: 1.25rem;
    display: flex;
    align-items: center;
    gap: .5rem;
  }
  .form-card .form-group { margin-bottom: 1rem; }
  .form-card .form-group label { font-weight: 600; color: var(--primary); font-size: .8rem; display: block; margin-bottom: 4px; }
  .form-card .form-group input,
  .form-card .form-group select,
  .form-card .form-group textarea {
    width: 100%;
    padding: .55rem .75rem;
    border: 1px solid #D1D5DB;
    border-radius: 6px;
    font-size: .85rem;
  }
  .form-card .form-group input:focus,
  .form-card .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: .75rem;
  }
  .form-card .form-actions {
    display: flex;
    gap: .75rem;
    margin-top: 1.25rem;
    align-items: center;
  }
  .radio-group {
    display: flex;
    gap: 1.5rem;
    margin-top: .3rem;
    flex-wrap: wrap;
  }
  .radio-group label {
    display: inline-flex;
    align-items: center;
    gap: .4rem;
    cursor: pointer;
    font-weight: 400 !important;
    font-size: .85rem !important;
  }

  @media (max-width: 768px) {
    .filters-row { flex-direction: column; }
    .filter-group { min-width: 100%; }
    .form-grid-2 { grid-template-columns: 1fr; }
    .prog-header { flex-direction: column; align-items: flex-start; }
  }
</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-chalkboard-teacher"></i> Enseignants'; include '../includes/topbar.php'; ?>

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

        <!-- ═══ Header ═══ -->
        <div class="prog-header">
            <div>
                <h1><i class="fas fa-chalkboard-teacher"></i> Enseignants</h1>
                <p>Gérez les enseignants et leurs affectations</p>
            </div>
            <div style="display:flex;gap:.5rem;flex-wrap:wrap;">
                <a href="?action=add" class="btn btn-primary"><i class="fas fa-plus"></i> Ajouter</a>
                <a href="?export=1" class="btn btn-outline"><i class="fas fa-download"></i> Exporter CSV</a>
                <a href="#" onclick="document.getElementById('importModal').classList.add('open');return false;" class="btn btn-outline"><i class="fas fa-upload"></i> Importer CSV</a>
                <a href="#" onclick="return downloadTemplate()" class="btn btn-light"><i class="fas fa-file-export"></i> Modèle</a>
                <?php if (isSuperAdmin()): ?>
                <form method="POST" action="?action=clear_imports" style="display:inline" onsubmit="return confirm('Supprimer tous les enseignants importés ? Cette action est irréversible.')">
                    <?= csrfField() ?>
                    <button type="submit" class="btn btn-danger"><i class="fas fa-trash"></i> Suppr. importations</button>
                </form>
                <?php endif; ?>
                <a href="?sync_users=1&csrf_token=<?= csrfToken() ?>" class="btn btn-outline" style="border-color:var(--accent);color:var(--accent);" onclick="return confirm('Synchroniser tous les enseignants vers les utilisateurs ? Cela créera ou mettra à jour les comptes utilisateurs.')"><i class="fas fa-sync-alt"></i> Sync utilisateurs</a>
                <a href="id_cards.php?type=teachers&school_id=<?= $schoolFilter ?? '' ?>" class="btn btn-outline" style="border-color:var(--accent);color:var(--accent);"><i class="fas fa-id-card"></i> Cartes identité</a>
            </div>
        </div>

        <!-- ═══ Filtres ═══ -->
        <form method="post" action="?action=set_session_filters" class="filters-card">
            <div class="filters-row">
                <div class="filter-group">
                    <label><i class="fas fa-calendar"></i> Année activée</label>
                    <select name="annee_active" onchange="this.form.submit()">
                        <option value="">-- Par défaut (BDD) --</option>
                        <?php foreach ($yearsList as $y): ?>
                        <option value="<?= e($y) ?>" <?= $y === $sessionYear ? 'selected' : '' ?>><?= e($y) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label><i class="fas fa-layer-group"></i> Période activée</label>
                    <select name="periode_active" onchange="this.form.submit()">
                        <option value="">-- Par défaut --</option>
                        <?php for ($p = 1; $p <= 3; $p++): ?>
                        <option value="<?= $p ?>" <?= $p === $sessionPeriod ? 'selected' : '' ?>><?= $p ?><?= $p === 1 ? 'er' : 'ème' ?> Trimestre</option>
                        <?php endfor; ?>
                    </select>
                </div>
                <?php if (isSuperAdmin()): ?>
                <div class="filter-group">
                    <label><i class="fas fa-school"></i> École concernée</label>
                    <select name="ecole_active" onchange="this.form.submit()">
                        <option value="">-- Toutes les écoles --</option>
                        <?php foreach ($ecoles as $ec): ?>
                        <option value="<?= $ec['id'] ?>" <?= ($sessionSchool && $sessionSchool == $ec['id']) ? 'selected' : '' ?>><?= e($ec['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <div style="align-self:flex-end;">
                    <a href="?action=clear_session&csrf_token=<?= csrfToken() ?>" class="btn btn-light" onclick="return confirm('Réinitialiser les filtres ?')">
                        <i class="fas fa-undo-alt"></i>
                    </a>
                </div>
            </div>
        </form>

        <!-- ═══ Import Modal ═══ -->
        <div class="modal-overlay" id="importModal">
            <div class="modal-box">
                <h2><i class="fas fa-upload"></i> Importer des enseignants</h2>
                <p style="color:#6B7280;font-size:.85rem;margin-bottom:1.25rem;">
                    <strong>Format CSV</strong> (séparateur <code>;</code>)<br>
                    Colonnes : <code>Prénom;Nom;Téléphone;Email;Matière;DateNaissance;Diplôme;École</code><br>
                    <a href="#" onclick="return downloadTemplate()" style="color:var(--accent);">Télécharger un modèle</a>
                </p>
                <form method="POST" enctype="multipart/form-data">
                    <?= csrfField() ?>
                    <div class="form-group">
                        <label>Fichier CSV</label>
                        <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" class="btn btn-primary"><i class="fas fa-upload"></i> Importer</button>
                    </div>
                </form>
            </div>
        </div>

        <?php if ($action === 'add' || $action === 'edit'): ?>
        <!-- ═══ Formulaire ajout/modification ═══ -->
        <div class="form-card">
            <h2><i class="fas fa-<?= $teacher ? 'edit' : 'plus-circle' ?>"></i> <?= $teacher ? 'Modifier' : 'Ajouter' ?> un enseignant</h2>
            <form method="POST">
                <?= csrfField() ?>
                <div class="form-group">
                    <label>École <span style="color:#DC2626;">*</span></label>
                    <select name="school_id" required <?= $schoolFilter ? 'disabled' : '' ?>>
                        <option value="">Choisir...</option>
                        <?php foreach ($schools as $sc): ?>
                        <option value="<?= $sc['id'] ?>" <?= ($teacher['school_id'] ?? '') == $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-grid-2">
                    <div class="form-group"><label>Prénom <span style="color:#DC2626;">*</span></label><input type="text" name="first_name" required value="<?= e($teacher['first_name'] ?? '') ?>"></div>
                    <div class="form-group"><label>Nom <span style="color:#DC2626;">*</span></label><input type="text" name="last_name" required value="<?= e($teacher['last_name'] ?? '') ?>"></div>
                </div>
                <div class="form-group">
                    <label>Genre</label>
                    <div class="radio-group">
                        <label>
                            <input type="radio" name="gender" value="M" <?=($teacher['gender']??'M')==='M'?'checked':''?>>
                            <i class="fas fa-male" style="color:#3182ce;"></i> Masculin
                        </label>
                        <label>
                            <input type="radio" name="gender" value="F" <?=($teacher['gender']??'')==='F'?'checked':''?>>
                            <i class="fas fa-female" style="color:#d53f8c;"></i> Féminin
                        </label>
                        <label>
                            <input type="radio" name="gender" value="Autre" <?=($teacher['gender']??'')==='Autre'?'checked':''?>>
                            <i class="fas fa-venus-mars" style="color:#718096;"></i> Autre
                        </label>
                    </div>
                </div>
                <div class="form-grid-2">
                    <div class="form-group"><label>Date de naissance</label><input type="date" name="birth_date" value="<?= e($teacher['birth_date'] ?? '') ?>"></div>
                    <div class="form-group"><label>Diplôme / Niveau</label><input type="text" name="diploma" value="<?= e($teacher['diploma'] ?? '') ?>" placeholder="Ex: Licence, Master, CAP..."></div>
                </div>
                <div class="form-group">
                    <label>Matière(s) enseignée(s)</label>
                    <select name="subject_ids[]" multiple style="width:100%;min-height:100px;padding:.5rem;border:1px solid #D1D5DB;border-radius:6px;font-size:.85rem;">
                        <?php
                        $allSubjs = $pdo->query("SELECT id,name,code FROM subjects ORDER BY name")->fetchAll();
                        $teacherSubjIds = [];
                        if ($teacher) {
                            $ts = $pdo->prepare("SELECT subject_id FROM teacher_subjects WHERE teacher_id=?");
                            $ts->execute([$teacher['id']]);
                            $teacherSubjIds = $ts->fetchAll(PDO::FETCH_COLUMN);
                        }
                        foreach ($allSubjs as $sb):
                        ?>
                        <option value="<?=$sb['id']?>" <?=in_array($sb['id'], $teacherSubjIds) ? 'selected' : ''?>>
                            <?=e(($sb['code']?'['.$sb['code'].'] ':'') . $sb['name'])?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <small style="color:#6B7280;font-size:.75rem;">Maintenez Ctrl (Windows) / Cmd (Mac) pour sélectionner plusieurs matières</small>
                </div>
                <div class="form-grid-2">
                    <div class="form-group"><label>Téléphone</label><input type="text" name="phone" value="<?= e($teacher['phone'] ?? '') ?>"></div>
                    <div class="form-group"><label>Email</label><input type="email" name="email" value="<?= e($teacher['email'] ?? '') ?>"></div>
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Enregistrer</button>
                    <a href="teachers.php" class="btn btn-light">Annuler</a>
                </div>
            </form>
        </div>

        <?php elseif (empty($teachersBySchool)): ?>
        <!-- ═══ Aucun enseignant ═══ -->
        <div class="teacher-card">
            <div class="empty-state">
                <i class="fas fa-chalkboard-teacher"></i>
                <p>Aucun enseignant enregistré.</p>
                <a href="?action=add" class="btn btn-primary" style="margin-top:1rem;display:inline-flex;"><i class="fas fa-plus"></i> Ajouter un enseignant</a>
            </div>
        </div>

        <?php else: $openSchool = isset($_GET['open']) ? (int)$_GET['open'] : 0; ?>
        <!-- ═══ Liste des enseignants par école ═══ -->
        <?php foreach ($teachersBySchool as $sid => $schoolGroup): ?>
        <div class="teacher-card">
            <div class="tc-header" onclick="toggleSchool('ts_<?=$sid?>')">
                <div class="tc-title">
                    <i class="fas fa-chevron-right" id="icon_ts_<?=$sid?>" style="transition:transform .2s;<?=$openSchool===$sid?'transform:rotate(90deg);':''?>"></i>
                    <i class="fas fa-school" style="color:var(--primary);"></i>
                    <span><?=e($schoolGroup['name'])?></span>
                </div>
                <span class="tc-count"><?=count($schoolGroup['teachers'])?> enseignant<?=count($schoolGroup['teachers'])>1?'s':''?></span>
            </div>
            <div id="ts_<?=$sid?>" style="<?=$openSchool===$sid?'':'display:none;'?>">
                <?php foreach ($schoolGroup['teachers'] as $t):
                    $gender = $t['gender'] ?? 'M';
                    $avatarClass = $gender === 'F' ? 'avatar-f' : ($gender === 'M' ? 'avatar-m' : 'avatar-o');
                    $genderIcon = $gender === 'F' ? 'fa-female' : ($gender === 'M' ? 'fa-male' : 'fa-venus-mars');
                    $genderColor = $gender === 'F' ? '#d53f8c' : ($gender === 'M' ? '#3182ce' : '#718096');
                ?>
                <div class="teacher-item">
                    <div class="teacher-avatar <?= $avatarClass ?>">
                        <i class="fas <?= $genderIcon ?>"></i>
                    </div>
                    <div class="teacher-body">
                        <div class="teacher-name">
                            <span><?=e($t['last_name'] . ' ' . $t['first_name'])?></span>
                            <?php foreach ($t['subject_list'] as $sb): ?>
                            <span class="subject-badge"><?=e($sb['code'] ? '['.$sb['code'].'] ' : '') . e($sb['subject_name'])?></span>
                            <?php endforeach; ?>
                            <?php if ($t['diploma']): ?>
                            <span class="diploma-tag"><?=e($t['diploma'])?></span>
                            <?php endif; ?>
                        </div>
                        <div class="teacher-meta">
                            <?php if ($t['phone']): ?><span><i class="fas fa-phone" style="color:var(--accent);"></i> <?=e($t['phone'])?></span><?php endif; ?>
                            <?php if ($t['email']): ?><span><i class="fas fa-envelope" style="color:var(--accent);"></i> <?=e($t['email'])?></span><?php endif; ?>
                            <?php if ($t['birth_date']): ?><span><i class="fas fa-calendar" style="color:var(--accent);"></i> <?=e(formatDate($t['birth_date']))?></span><?php endif; ?>
                            <span><i class="fas fa-clock" style="color:var(--accent);"></i> <?=formatDate($t['created_at'])?></span>
                        </div>
                        <?php if (!empty($t['class_list'])): ?>
                        <div class="class-badges">
                            <?php foreach ($t['class_list'] as $cls): ?>
                            <span class="class-badge"><i class="fas fa-users" style="font-size:.65rem;"></i> <?=e($cls)?></span>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                    <div class="teacher-actions">
                        <a href="?action=edit&id=<?=$t['id']?>" class="btn btn-light" title="Modifier"><i class="fas fa-edit"></i></a>
                        <?php if (isSuperAdmin()): ?>
                        <form method="POST" action="?action=delete&id=<?=$t['id']?>" style="display:inline" onsubmit="return confirm('Supprimer <?=e($t['last_name'].' '.$t['first_name'])?> ?')">
                            <?=csrfField()?>
                            <button type="submit" class="btn btn-danger" title="Supprimer"><i class="fas fa-trash"></i></button>
                        </form>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

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

<script>
function toggleSchool(id) {
    const div = document.getElementById(id);
    const icon = document.getElementById('icon_' + id);
    if (div) {
        div.style.display = div.style.display === 'none' ? '' : 'none';
        if (icon) icon.style.transform = div.style.display === 'none' ? '' : 'rotate(90deg)';
    }
}

function downloadTemplate() {
    const w = window.open('', '_blank');
    w.document.write('<html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><style>td,th{border:1px solid #ccc;padding:4px 8px;font:11px Calibri,sans-serif}th{background:#4472c4;color:#fff;font-weight:700}</style></head><body><table>');
    w.document.write('<tr><th>Prénom</th><th>Nom</th><th>Téléphone</th><th>Email</th><th>Matière</th><th>DateNaissance</th><th>Diplôme</th><th>École</th></tr>');
    w.document.write('<tr><td>Jean</td><td>Dupont</td><td>0123456789</td><td>jean@exemple.fr</td><td>Mathématiques</td><td>15/03/1985</td><td>Master</td><td>École 1</td></tr>');
    w.document.write('<tr><td>Marie</td><td>Martin</td><td>0987654321</td><td>marie@exemple.fr</td><td>Français</td><td>22/07/1990</td><td>Licence</td><td>École 1</td></tr>');
    w.document.write('</table></body></html>');
    w.document.close();
    w.focus();
    w.print();
    return false;
}

function showToast(message, type) {
    const container = document.getElementById('toastContainer');
    const toast = document.createElement('div');
    toast.className = 'toast toast-' + type;
    const icons = { success: '&#10004;&#65039;', warning: '&#9888;&#65039;', error: '&#10060;' };
    toast.innerHTML = '<span>' + (icons[type] || '&#8505;&#65039;') + '</span><span>' + message + '</span>';
    container.appendChild(toast);
    setTimeout(function() { toast.remove(); }, 4000);
}

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