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

checkRole(['super_admin','school_admin']);

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

$schoolFilter = currentSchoolId();

// ── Session filters ──
if ($action === 'set_session_filters' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['annee_active'])) { $_SESSION['active_academic_year'] = trim($_POST['annee_active']) ?: null; }
    if (isset($_POST['periode_active'])) { setActivePeriod((int)$_POST['periode_active']); }
    if (isset($_POST['ecole_active'])) { $_SESSION['active_school_filter'] = (int)$_POST['ecole_active'] ?: null; }
    flashMessage('success', 'Filtres mis à jour.');
    header('Location: directors.php'); exit;
}
if ($action === 'clear_session') {
    verifyCsrf();
    unset($_SESSION['active_academic_year'], $_SESSION['active_period'], $_SESSION['active_school_filter']);
    flashMessage('success', 'Filtres réinitialisés.');
    header('Location: directors.php'); exit;
}

// Création auto de la table
try { $pdo->exec("CREATE TABLE IF NOT EXISTS directors (
    id INT AUTO_INCREMENT PRIMARY KEY,
    school_id INT NOT NULL,
    first_name VARCHAR(100) NOT NULL,
    last_name  VARCHAR(100) NOT NULL,
    phone      VARCHAR(30) DEFAULT NULL,
    email      VARCHAR(255) DEFAULT NULL,
    diploma    VARCHAR(255) DEFAULT NULL,
    start_date DATE DEFAULT NULL,
    is_active  TINYINT(1) DEFAULT 1,
    gender     ENUM('M','F') DEFAULT 'M',
    user_id    INT DEFAULT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    KEY school_id (school_id),
    KEY user_id (user_id)
)"); } catch (PDOException $e) {}
// Ajout colonne gender si elle n'existe pas
try { $pdo->exec("ALTER TABLE directors ADD COLUMN gender ENUM('M','F') DEFAULT 'M' AFTER is_active"); } catch (PDOException $e) {}

// ── Export CSV ─────────────────────────────────────────────────────────────────
if (isset($_GET['export'])) {
    verifyCsrf();
    $exWhere = ''; $exParams = [];
    if ($schoolFilter) {
        $exWhere = 'WHERE d.school_id = ?';
        $exParams[] = $schoolFilter;
    }
    $exDirs = $pdo->prepare("SELECT d.*, s.name AS school_name FROM directors d LEFT JOIN schools s ON d.school_id=s.id $exWhere ORDER BY d.last_name, d.first_name");
    $exDirs->execute($exParams);
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=directeurs_' . date('Y-m-d') . '.csv');
    header('Content-Encoding: UTF-8');
    echo "\xEF\xBB\xBF";
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Prénom','Nom','Genre','Email','Téléphone','Diplôme','Prise de fonction','Actif','École'], ';');
    foreach ($exDirs as $d) {
        fputcsv($out, [
            $d['first_name'], $d['last_name'],
            $d['gender'] === 'F' ? 'F' : 'M',
            $d['email'] ?? '', $d['phone'] ?? '',
            $d['diploma'] ?? '', $d['start_date'] ?? '',
            $d['is_active'] ? 'Oui' : 'Non',
            $d['school_name'] ?? '',
        ], ';');
    }
    fclose($out);
    exit;
}

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

// ── Import CSV ─────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['import_csv'])) {
    verifyCsrf();
    $imported = 0; $errors = [];
    if (empty($_FILES['csv_file']['tmp_name'])) {
        flashMessage('error', 'Veuillez sélectionner un fichier CSV.');
        header('Location: directors.php'); exit;
    } else {
        $handle = fopen($_FILES['csv_file']['tmp_name'], 'r');
        $header = fgetcsv($handle, 0, ';');
        if (!$header || count($header) < 3) {
            fclose($handle);
            flashMessage('error', 'Format CSV invalide. En-têtes : Prénom;Nom;Genre;Email;Téléphone;Diplôme;Prise de fonction;Actif;École');
            header('Location: directors.php'); exit;
        } else {
            $rowNum = 1;
            while (($row = fgetcsv($handle, 0, ';')) !== false) {
                $rowNum++;
                list($fname, $lname, $gender, $email, $phone, $diploma, $startDate, $active, $schoolName) = array_pad($row, 9, '');
                $fname = trim($fname); $lname = trim($lname); $gender = trim($gender);
                $email = trim($email); $phone = trim($phone); $diploma = trim($diploma);
                $startDate = trim($startDate); $active = trim($active); $schoolName = trim($schoolName);
                if (empty($fname) && empty($lname)) continue;
                if (empty($fname) || empty($lname)) { $errors[] = "Ligne $rowNum : Prénom et nom requis."; continue; }
                $genderVal = in_array($gender, ['M','F'], true) ? $gender : 'M';
                $isActiveVal = in_array(strtolower($active), ['oui','1','true','yes'], true) ? 1 : 0;
                $schoolId = $schoolFilter;
                if (!$schoolId && !empty($schoolName)) {
                    $st = $pdo->prepare("SELECT id FROM schools WHERE name=?");
                    $st->execute([$schoolName]);
                    $schoolId = $st->fetchColumn();
                    if (!$schoolId) { $errors[] = "Ligne $rowNum : École introuvable ($schoolName)."; continue; }
                } elseif (!$schoolId) {
                    $schoolId = null;
                }
                $pdo->prepare("INSERT INTO directors (school_id, first_name, last_name, gender, email, phone, diploma, start_date, is_active) VALUES (?,?,?,?,?,?,?,?,?)")
                    ->execute([$schoolId, $fname, $lname, $genderVal, $email ?: null, $phone ?: null, $diploma ?: null, $startDate ?: null, $isActiveVal]);
                $imported++;
            }
        }
        fclose($handle);
    }
    if ($imported > 0) {
        flashMessage('success', "$imported directeur(s) importé(s) avec succès.");
    }
    if (!empty($errors)) {
        flashMessage('error', 'Erreurs : ' . implode('. ', array_slice($errors, 0, 20)));
    }
    header('Location: directors.php'); exit;
}

// ── Ajout / Modification ──
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $school_id  = $schoolFilter ?? (int)($_POST['school_id'] ?? 0);
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name  = trim($_POST['last_name']  ?? '');
    $phone      = trim($_POST['phone']      ?? '');
    $email      = trim($_POST['email']      ?? '');
    $diploma    = trim($_POST['diploma']    ?? '');
    $start_date = $_POST['start_date']      ?? '';
    $is_active  = isset($_POST['is_active']) ? 1 : 0;
    $gender     = ($_POST['gender'] ?? 'M') === 'F' ? 'F' : 'M';

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

    if (empty($error)) {
        $start_date = $start_date ?: null;
        if ($id) {
            if ($schoolFilter) {
                $chk = $pdo->prepare("SELECT id FROM directors WHERE id=? AND school_id=?");
                $chk->execute([$id, $schoolFilter]);
                if (!$chk->fetch()) { flashMessage('error','Action non autorisée.'); header('Location: directors.php'); exit; }
            }
            $pdo->prepare("UPDATE directors SET school_id=?,first_name=?,last_name=?,phone=?,email=?,diploma=?,start_date=?,is_active=?,gender=? WHERE id=?")
                ->execute([$school_id,$first_name,$last_name,$phone,$email,$diploma,$start_date,$is_active,$gender,$id]);
            // Synchroniser le compte utilisateur lié
            $st = $pdo->prepare("SELECT user_id FROM directors WHERE id=?");
            $st->execute([$id]);
            $linkedUserId = $st->fetchColumn();
            $fullName = trim("$last_name $first_name");
            if ($linkedUserId) {
                $pdo->prepare("UPDATE users SET name=?, email=?, gender=?, active=? WHERE id=?")
                    ->execute([$fullName, $email, $gender, $is_active, $linkedUserId]);
            } elseif (!empty($email)) {
                // Créer le compte manquant
                $password = bin2hex(random_bytes(4));
                $hashed = password_hash($password, PASSWORD_DEFAULT);
                try {
                    $pdo->prepare("INSERT INTO users (school_id, email, password, plain_password, role, name, gender, active) VALUES (?,?,?,?,'school_admin',?,?,?)")
                        ->execute([$school_id, $email, $hashed, $password, $fullName, $gender, $is_active]);
                    $uid = $pdo->lastInsertId();
                    $pdo->prepare("UPDATE directors SET user_id=? WHERE id=?")->execute([$uid, $id]);
                } catch (PDOException $e) {}
            }
            $usersLink = ' <a href="users.php?filter_role=school_admin" style="color:#667eea;text-decoration:underline;">Voir dans les utilisateurs</a>';
            flashMessage('success', ($gender === 'F' ? 'Directrice mise à jour.' : 'Directeur mis à jour.') . $usersLink);
        } else {
            $pdo->prepare("INSERT INTO directors (school_id,first_name,last_name,phone,email,diploma,start_date,is_active,gender) VALUES (?,?,?,?,?,?,?,?,?)")
                ->execute([$school_id,$first_name,$last_name,$phone,$email,$diploma,$start_date,$is_active,$gender]);
            $newId = $pdo->lastInsertId();

            // Créer un compte utilisateur automatiquement
            if (!empty($email)) {
                $password = bin2hex(random_bytes(4)); // 8 caractères
                $hashed   = password_hash($password, PASSWORD_DEFAULT);
                try {
                    $fullName = trim("$last_name $first_name");
                    $pdo->prepare("INSERT INTO users (school_id, email, password, plain_password, role, name, gender, active) VALUES (?,?,?,?,'school_admin',?,?,1)")
                        ->execute([$school_id, $email, $hashed, $password, $fullName, $gender]);
                    $uid = $pdo->lastInsertId();
                    $pdo->prepare("UPDATE directors SET user_id=? WHERE id=?")->execute([$uid, $newId]);
                    $label = $gender === 'F' ? 'Directrice' : 'Directeur';
                    $usersLink = ' <a href="users.php?filter_role=school_admin" style="color:#667eea;text-decoration:underline;">Voir dans les utilisateurs</a>';
                    flashMessage('success', "$label ajouté(e). Compte créé : <strong>$email</strong> / mot de passe : <strong>$password</strong>$usersLink");
                } catch (PDOException $e) {
                    flashMessage('warning', "Directeur(trice) ajouté(e) mais échec création compte (email peut-être déjà utilisé).");
                }
            } else {
                $usersLink = ' <a href="users.php?filter_role=school_admin" style="color:#667eea;text-decoration:underline;">Voir dans les utilisateurs</a>';
                flashMessage('success', ($gender === 'F' ? 'Directrice' : 'Directeur') . ' ajouté(e).' . $usersLink);
            }
        }
        header('Location: directors.php'); exit;
    }
}

// ── Chargement édition ──
$editDir = null;
if ($action === 'edit' && $id) {
    $s = $pdo->prepare("SELECT d.*, u.email AS user_email FROM directors d LEFT JOIN users u ON d.user_id=u.id WHERE d.id=?" . ($schoolFilter ? " AND d.school_id=?" : ""));
    $s->execute($schoolFilter ? [$id, $schoolFilter] : [$id]);
    $editDir = $s->fetch();
    if (!$editDir) { flashMessage('error','Directeur introuvable.'); header('Location: directors.php'); exit; }
}

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

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

// Grouper par école
$dirBySchool = [];
foreach ($directors as $d) {
    $sid = $d['school_id'];
    if (!isset($dirBySchool[$sid])) $dirBySchool[$sid] = ['name' => $d['school_name'] ?? 'Sans école', 'directors' => []];
    $dirBySchool[$sid]['directors'][] = $d;
}
$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();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Directeurs - 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, .filter-group input { padding:.55rem .75rem; border:1px solid #D1D5DB; border-radius:6px; font-size:.85rem; background:white; cursor:pointer; }
  .filter-group select:focus, .filter-group input:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 3px rgba(46,117,182,0.15); }
  .table-card { background:white; border-radius:10px; box-shadow:0 2px 12px rgba(0,0,0,0.06); overflow:hidden; margin-bottom:1rem; }
  .table-card .tc-header { padding:1rem 1.5rem; border-bottom:1px solid #E5E7EB; display:flex; justify-content:space-between; align-items:center; }
  .table-card .tc-title { font-family:Georgia,serif; color:var(--primary); font-size:1.05rem; }
  .table-card .tc-count { background:var(--light); color:var(--primary); padding:3px 10px; border-radius:20px; font-size:.75rem; font-weight:600; }
  .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; }
  .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; }
  .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; 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; box-sizing:border-box; }
  .modal-box .form-group input:focus, .modal-box .form-group select: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; }
  .form-card { background:white; border-radius:10px; box-shadow:0 2px 12px rgba(0,0,0,0.06); padding:1.5rem; max-width:640px; }
  .form-card h2 { font-family:Georgia,serif; color:var(--primary); font-size:1.2rem; margin-bottom:1.25rem; }
  .form-card .form-group { margin-bottom:1rem; }
  .form-card .form-group label { display:block; font-weight:600; color:var(--primary); font-size:.82rem; margin-bottom:4px; }
  .form-card .form-group input, .form-card .form-group select { width:100%; padding:.55rem .75rem; border:1px solid #D1D5DB; border-radius:6px; font-size:.85rem; box-sizing:border-box; }
  .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; }
  .school-header { cursor:pointer; display:flex; align-items:center; gap:.75rem; user-select:none; padding:.75rem 1.25rem; border-bottom:1px solid #E5E7EB; transition:background .15s; }
  .school-header:hover { background:#F9FAFB; }
  .school-header .chevron { transition:transform .2s; color:#9CA3AF; }
  .school-header .chevron.open { transform:rotate(90deg); }
  .empty-state { text-align:center; padding:3rem 1rem; color:#9CA3AF; }
  .empty-state i { font-size:2.5rem; margin-bottom:.5rem; }
  .badge-p { display:inline-block; padding:3px 8px; border-radius:20px; font-size:.7rem; font-weight:600; }
  .badge-green { background:#D1FAE5; color:#065F46; }
  .badge-red { background:#FEE2E2; color:#991B1B; }
  @media (max-width:768px) { .filters-row { flex-direction:column; } .filter-group { min-width:100%; } .prog-table th, .prog-table td { padding:.5rem .6rem; font-size:.78rem; } .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-user-tie"></i> Directeurs'; 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']); ?>

    <?php if ($action === 'add' || $action === 'edit'): ?>

    <!-- ═══ Formulaire ═══ -->
    <div class="form-card">
      <h2><i class="fas fa-<?= $editDir ? 'edit' : 'plus-circle' ?>"></i> <?= $editDir ? 'Modifier' : 'Ajouter' ?> un(e) directeur(trice)</h2>
      <form method="POST">
        <?= csrfField() ?>
        <div class="form-group">
          <label>École <span style="color:red">*</span></label>
          <select name="school_id" required <?= $schoolFilter ? 'disabled' : '' ?>>
            <option value="">Choisir...</option>
            <?php foreach ($schools as $sc): ?>
            <option value="<?=$sc['id']?>" <?=($editDir['school_id']??$schoolFilter)==$sc['id']?'selected':''?>><?=e($sc['name'])?></option>
            <?php endforeach; ?>
          </select>
          <?php if ($schoolFilter): ?><input type="hidden" name="school_id" value="<?=$schoolFilter?>"><?php endif; ?>
        </div>
        <div class="form-grid-2">
          <div class="form-group"><label>Prénom <span style="color:red">*</span></label><input type="text" name="first_name" required value="<?=e($editDir['first_name']??'')?>"></div>
          <div class="form-group"><label>Nom <span style="color:red">*</span></label><input type="text" name="last_name" required value="<?=e($editDir['last_name']??'')?>"></div>
        </div>
        <div class="form-group">
          <label>Genre</label>
          <div style="display:flex;gap:1.5rem;margin-top:.3rem;">
            <label style="display:flex;align-items:center;gap:.4rem;cursor:pointer;">
              <input type="radio" name="gender" value="M" <?=($editDir['gender']??'M')==='M'?'checked':''?>>
              <i class="fas fa-male" style="color:#3182ce;"></i> Masculin
            </label>
            <label style="display:flex;align-items:center;gap:.4rem;cursor:pointer;">
              <input type="radio" name="gender" value="F" <?=($editDir['gender']??'')==='F'?'checked':''?>>
              <i class="fas fa-female" style="color:#d53f8c;"></i> Féminin
            </label>
          </div>
        </div>
        <div class="form-grid-2">
          <div class="form-group"><label>Téléphone</label><input type="text" name="phone" value="<?=e($editDir['phone']??'')?>" placeholder="ex: 01 23 45 67 89"></div>
          <div class="form-group"><label>Email</label><input type="email" name="email" value="<?=e($editDir['email']??'')?>"></div>
        </div>
        <div class="form-grid-2">
          <div class="form-group"><label>Diplôme / Titre</label><input type="text" name="diploma" value="<?=e($editDir['diploma']??'')?>" placeholder="ex: Master en Éducation"></div>
          <div class="form-group"><label>Date de prise de fonction</label><input type="date" name="start_date" value="<?=e($editDir['start_date']??'')?>"></div>
        </div>
        <div class="form-group" style="display:flex;gap:1.5rem;flex-wrap:wrap;">
          <label style="display:flex;align-items:center;gap:.5rem;cursor:pointer;">
            <input type="checkbox" name="is_active" value="1" <?=($editDir['is_active']??1)?'checked':''?>>
            <span>Directeur actif</span>
          </label>
        </div>
        <?php if ($editDir && $editDir['user_id']): ?>
        <p style="color:#718096;font-size:.85rem;margin-bottom:1rem;">
          <i class="fas fa-link"></i> Lié au compte utilisateur #<?=$editDir['user_id']?>
          (<?=e($editDir['user_email']??'')?>)
        </p>
        <?php endif; ?>
        <div style="display:flex;gap:.75rem;">
          <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Enregistrer</button>
          <a href="directors.php" class="btn btn-light">Annuler</a>
        </div>
      </form>
    </div>

    <?php else: ?>

    <!-- ═══ Header ═══ -->
    <div class="prog-header">
      <div>
        <h1><i class="fas fa-user-tie" style="color:var(--primary);"></i> Directeurs</h1>
        <p>Gérez les directeurs d'établissements</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&csrf_token=<?= csrfToken() ?>" class="btn btn-light"><i class="fas fa-download"></i> Exporter</a>
        <button class="btn btn-light" onclick="document.getElementById('importModal').classList.add('open')"><i class="fas fa-upload"></i> Importer</button>
      </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 scolaire</label>
          <select name="annee_active" onchange="this.form.submit()">
            <option value="">-- Par défaut --</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</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>

    <!-- ═══ Liste ═══ -->
    <?php if (empty($dirBySchool)): ?>
    <div class="table-card">
      <div class="empty-state">
        <i class="fas fa-user-tie"></i>
        <p>Aucun directeur(trice) enregistré(e).</p>
        <a href="?action=add" class="btn btn-primary" style="margin-top:1rem;display:inline-flex;"><i class="fas fa-plus"></i> Ajouter</a>
      </div>
    </div>
    <?php else: ?>
    <?php foreach ($dirBySchool as $sid => $group): ?>
    <?php $openId = 'dir_school_' . $sid; ?>
    <div class="table-card">
      <div class="school-header" onclick="toggleSchool('<?=$openId?>')">
        <i class="fas fa-chevron-right chevron" id="icon_<?=$openId?>"></i>
        <span class="tc-title"><i class="fas fa-school" style="color:var(--accent);margin-right:.4rem;"></i><?=e($group['name'])?></span>
        <span class="tc-count"><?=count($group['directors'])?> directeur(s)</span>
      </div>
      <div id="<?=$openId?>" style="display:none;">
        <table class="prog-table">
          <thead>
            <tr>
              <th>Nom complet</th>
              <th>Téléphone</th>
              <th>Email</th>
              <th>Diplôme</th>
              <th>Prise de fonction</th>
              <th>Statut</th>
              <th style="width:80px;">Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($group['directors'] as $d):
              $title = $d['gender'] === 'F' ? 'Directrice' : 'Directeur';
            ?>
            <tr>
              <td>
                <div style="display:flex;align-items:center;gap:.5rem;">
                  <?php if ($d['gender'] === 'F'): ?>
                  <i class="fas fa-female" style="color:#d53f8c;font-size:1.1rem;" title="Féminin"></i>
                  <?php else: ?>
                  <i class="fas fa-male" style="color:#3182ce;font-size:1.1rem;" title="Masculin"></i>
                  <?php endif; ?>
                  <strong><?=$title?> <?=e($d['last_name'].' '.$d['first_name'])?></strong>
                </div>
              </td>
              <td><?=e($d['phone'] ?? '—')?></td>
              <td><?=e($d['email'] ?? '—')?></td>
              <td><?=e($d['diploma'] ?? '—')?></td>
              <td><?=$d['start_date'] ? e(formatDate($d['start_date'])) : '—'?></td>
              <td>
                <?php if ($d['is_active']): ?>
                <span class="badge-p badge-green"><i class="fas fa-check-circle"></i> Actif</span>
                <?php else: ?>
                <span class="badge-p badge-red"><i class="fas fa-times-circle"></i> Inactif</span>
                <?php endif; ?>
              </td>
              <td>
                <div style="display:flex;gap:4px;">
                  <a href="?action=edit&id=<?=$d['id']?>" class="btn btn-light" style="padding:.3rem .6rem;font-size:.75rem;" title="Modifier"><i class="fas fa-edit"></i></a>
                  <form method="POST" action="?action=delete&id=<?=$d['id']?>" style="display:inline" onsubmit="return confirm('Supprimer <?=e($d['last_name'].' '.$d['first_name'])?> ?')">
                    <?=csrfField()?>
                    <button type="submit" class="btn btn-danger" style="padding:.3rem .6rem;font-size:.75rem;" title="Supprimer"><i class="fas fa-trash"></i></button>
                  </form>
                </div>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
    <?php endif; ?>
  </div>
</div>

<!-- ═══ Modal Import CSV ═══ -->
<div class="modal-overlay" id="importModal" onclick="if(event.target===this)this.classList.remove('open')">
  <div class="modal-box">
    <h2><i class="fas fa-upload"></i> Importer des directeurs</h2>
    <form method="POST" enctype="multipart/form-data">
      <?= csrfField() ?>
      <input type="hidden" name="import_csv" value="1">
      <div class="form-group">
        <label>Fichier CSV <span style="color:red">*</span></label>
        <input type="file" name="csv_file" accept=".csv" required>
      </div>
      <div style="font-size:.82rem;color:#555;background:#F9FAFB;padding:.75rem;border-radius:6px;margin-bottom:1rem;">
        <strong>Format attendu :</strong><br>
        <code>Prénom;Nom;Genre;Email;Téléphone;Diplôme;Prise de fonction;Actif;École</code><br><br>
        <strong>Genre :</strong> M ou F<br>
        <strong>Actif :</strong> Oui ou Non<br>
        <strong>École :</strong> Nom exact (ignoré si filtré)
      </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>

<!-- ═══ 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) {
        const isHidden = div.style.display === 'none' || div.style.display === '';
        div.style.display = isHidden ? '' : 'none';
        if (icon) icon.classList.toggle('open', isHidden);
    }
}
function showToast(message, type) {
    const container = document.getElementById('toastContainer');
    if (!container) return;
    const toast = document.createElement('div');
    toast.className = 'toast toast-' + type;
    const icons = { success: '✅', warning: '⚠️', error: '❌' };
    toast.innerHTML = '<span>' + (icons[type] || 'ℹ️') + '</span><span>' + message + '</span>';
    container.appendChild(toast);
    setTimeout(function() { if (toast.parentNode) 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>
