<?php
/**
 * Gestion des utilisateurs (tous rôles + activation)
 */
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']);
requirePermission('users', 'view');

$schoolFilter = currentSchoolId();

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

try { $pdo->exec("ALTER TABLE users ADD COLUMN gender ENUM('M','F','Autre') DEFAULT NULL AFTER name"); } catch (PDOException $e) {}
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) {}

// Rôles créables selon l'utilisateur connecté
$creatableRoles = hasRole('super_admin')
    ? ['super_admin','school_admin','teacher','accountant','student','parent']
    : ['teacher','accountant','student','parent'];

// ── Toggle activation ─────────────────────────────────────────────────────────
if ($action === 'toggle_active' && $id) {
    verifyCsrf();
    requirePermission('users','edit');
    if ($id === (int)$_SESSION['user_id']) {
        flashMessage('error','Vous ne pouvez pas désactiver votre propre compte.');
        header('Location: users.php'); exit;
    }
    $pdo->prepare("UPDATE users SET active = NOT active WHERE id=?")->execute([$id]);
    flashMessage('success','Statut du compte mis à jour.');
    header('Location: users.php'); exit;
}

// ── Suppression ───────────────────────────────────────────────────────────────
if ($action === 'delete' && $id) {
    verifyCsrf();
    if (!isSuperAdmin()) { flashMessage('error','Action réservée au super administrateur.'); header('Location: users.php'); exit; }
    checkDeleteAllowed();
    requirePermission('users','delete');
    if ($id === (int)$_SESSION['user_id']) {
        flashMessage('error','Vous ne pouvez pas supprimer votre propre compte.');
        header('Location: users.php'); exit;
    }
    // Vérifier si l'utilisateur est un élève avec bulletin
    $st = $pdo->prepare("SELECT u.role, s.id FROM users u LEFT JOIN students s ON s.user_id=u.id WHERE u.id=?");
    $st->execute([$id]);
    $target = $st->fetch();
    if ($target && $target['role'] === 'student' && $target['id']) {
        $hg = $pdo->prepare("SELECT COUNT(*) FROM grades WHERE student_id=?");
        $hg->execute([$target['id']]);
        if ($hg->fetchColumn() > 0 && !isSuperAdmin()) {
            flashMessage('error','Cet élève a déjà un bulletin. Seul le super administrateur peut supprimer son compte.');
            header('Location: users.php'); exit;
        }
    }
    $pdo->prepare("DELETE FROM users WHERE id=?")->execute([$id]);
    flashMessage('success','Utilisateur supprimé.');
    header('Location: users.php'); exit;
}

// ── Suppression multiple ──
if (isset($_POST['bulk_action']) && $_POST['bulk_action'] === 'delete') {
    verifyCsrf();
    if (!isSuperAdmin()) { flashMessage('error','Action réservée au super administrateur.'); header('Location: users.php'); exit; }
    checkDeleteAllowed();
    requirePermission('users','delete');
    $currentUserId = (int)$_SESSION['user_id'];
    $ids = isset($_POST['user_ids']) ? array_map('intval', (array)$_POST['user_ids']) : [];
    $deleted = 0; $skipped = 0;
    foreach ($ids as $uid) {
        if ($uid === $currentUserId) continue;
        // Vérifier si c'est un élève avec bulletin
        $st = $pdo->prepare("SELECT u.role, s.id FROM users u LEFT JOIN students s ON s.user_id=u.id WHERE u.id=?");
        $st->execute([$uid]);
        $target = $st->fetch();
        if ($target && $target['role'] === 'student' && $target['id']) {
            $hg = $pdo->prepare("SELECT COUNT(*) FROM grades WHERE student_id=?");
            $hg->execute([$target['id']]);
            if ($hg->fetchColumn() > 0 && !isSuperAdmin()) { $skipped++; continue; }
        }
        $pdo->prepare("DELETE FROM users WHERE id=?")->execute([$uid]);
        $deleted++;
    }
    $msg = "$deleted utilisateur(s) supprimé(s).";
    if ($skipped) $msg .= " $skipped élève(s) avec bulletin ignoré(s).";
    flashMessage('success', $msg);
    header('Location: users.php'); exit;
}

// ── Désactivation multiple ──
if (isset($_POST['bulk_action']) && $_POST['bulk_action'] === 'deactivate') {
    verifyCsrf();
    requirePermission('users','edit');
    $currentUserId = (int)$_SESSION['user_id'];
    $ids = isset($_POST['user_ids']) ? array_map('intval', (array)$_POST['user_ids']) : [];
    $deactivated = 0;
    foreach ($ids as $uid) {
        if ($uid === $currentUserId) continue;
        $pdo->prepare("UPDATE users SET active=0 WHERE id=?")->execute([$uid]);
        $deactivated++;
    }
    flashMessage('success', "$deactivated utilisateur(s) désactivé(s).");
    header('Location: users.php'); exit;
}

// ── Export CSV ─────────────────────────────────────────────────────────────────
if (isset($_GET['export'])) {
    verifyCsrf();
    $exWhere = '';
    $exParams = [];
    if ($schoolFilter) {
        $exWhere = 'WHERE u.school_id = ?';
        $exParams[] = $schoolFilter;
    } elseif (!empty($_GET['filter_school'])) {
        $exWhere = 'WHERE u.school_id = ?';
        $exParams[] = (int)$_GET['filter_school'];
    }
    if (!empty($_GET['filter_role']) && in_array($_GET['filter_role'], $creatableRoles, true)) {
        $exWhere .= ($exWhere ? ' AND' : 'WHERE') . ' u.role = ?';
        $exParams[] = $_GET['filter_role'];
    }
    $exUsers = $pdo->prepare("SELECT u.*, s.name AS school_name FROM users u LEFT JOIN schools s ON u.school_id=s.id $exWhere ORDER BY u.name");
    $exUsers->execute($exParams);
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=utilisateurs_' . date('Y-m-d') . '.csv');
    header('Content-Encoding: UTF-8');
    echo "\xEF\xBB\xBF";
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Nom', 'Email', 'Rôle', 'École', 'Genre', 'Date naissance', 'Actif'], ';');
    foreach ($exUsers as $u) {
        fputcsv($out, [
            $u['name'],
            $u['email'],
            $u['role'],
            $u['school_name'] ?? '',
            $u['gender'] ?? '',
            $u['birth_date'] ?? '',
            $u['active'] ? 'Oui' : 'Non',
        ], ';');
    }
    fclose($out);
    exit;
}

// ── Import CSV ─────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['import_csv'])) {
    verifyCsrf();
    requirePermission('users', 'create');
    $imported = 0; $errors = [];
    if (empty($_FILES['csv_file']['tmp_name'])) {
        flashMessage('error', 'Veuillez sélectionner un fichier CSV.');
        header('Location: users.php'); exit;
    } else {
        $schoolMap = [];
        foreach ($pdo->query("SELECT id, name FROM schools ORDER BY name")->fetchAll() as $s) {
            $schoolMap[strtolower(trim($s['name']))] = $s['id'];
        }
        $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 attendus : Nom;Email;Rôle;École;Genre;Date naissance;Actif');
            header('Location: users.php'); exit;
        } else {
            $rowNum = 1;
            while (($row = fgetcsv($handle, 0, ';')) !== false) {
                $rowNum++;
                list($name, $email, $role, $schoolName, $gender, $birthDate, $active) = array_pad($row, 7, '');
                $name = trim($name); $email = trim($email); $role = trim($role);
                $schoolName = trim($schoolName); $gender = trim($gender);
                $birthDate = trim($birthDate); $active = trim($active);
                if (empty($name) && empty($email)) continue;
                if (empty($name)) { $errors[] = "Ligne $rowNum : Nom requis."; continue; }
                if (empty($email) || !validateEmail($email)) { $errors[] = "Ligne $rowNum : Email invalide ($email)."; continue; }
                if (!in_array($role, $creatableRoles, true)) { $errors[] = "Ligne $rowNum : Rôle invalide ($role)."; continue; }
                $schoolId = null;
                if (!empty($schoolName)) {
                    $key = strtolower($schoolName);
                    $schoolId = $schoolMap[$key] ?? null;
                    if (!$schoolId) { $errors[] = "Ligne $rowNum : École introuvable ($schoolName)."; continue; }
                }
                if ($schoolFilter && $schoolId !== $schoolFilter) { $errors[] = "Ligne $rowNum : École non autorisée."; continue; }
                $chk = $pdo->prepare("SELECT id FROM users WHERE email=?");
                $chk->execute([$email]);
                if ($chk->fetch()) { $errors[] = "Ligne $rowNum : Email déjà existant ($email)."; continue; }
                $chk2 = $pdo->prepare("SELECT id FROM users WHERE LOWER(TRIM(name))=LOWER(TRIM(?)) AND role=? AND COALESCE(school_id,0)=COALESCE(?,0)");
                $chk2->execute([$name, $role, $schoolId]);
                if ($chk2->fetch()) { $errors[] = "Ligne $rowNum : Utilisateur déjà existant ($role - $name)."; continue; }
                $genderVal = in_array($gender, ['M','F','Autre'], true) ? $gender : null;
                $birthDateVal = $birthDate ?: null;
                $activeVal = in_array(strtolower($active), ['oui','1','true','yes'], true) ? 1 : 0;
                $password = substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'), 0, 6)
                          . substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZ'), 0, 2)
                          . str_pad(random_int(0, 99), 2, '0', STR_PAD_LEFT)
                          . '@'
                          . substr(str_shuffle('abcdefghjkmnpqrstuvwxyz'), 0, 2);
                $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => BCRYPT_COST]);
                $pdo->prepare("INSERT INTO users (name,email,password,plain_password,role,school_id,active,birth_date,gender) VALUES (?,?,?,?,?,?,?,?,?)")
                    ->execute([$name, $email, $hash, $password, $role, $schoolId, $activeVal, $birthDateVal, $genderVal]);
                $imported++;
                if ($imported <= 5) {
                    $_SESSION['import_passwords'][] = "$email → $password";
                }
            }
            // Nettoyer les mots de passe stockés après affichage
            $pwdMsg = '';
            if (!empty($_SESSION['import_passwords'])) {
                $pwdMsg = ' — Mots de passe : ' . implode(', ', $_SESSION['import_passwords']);
                unset($_SESSION['import_passwords']);
            }
        }
        fclose($handle);
    }
    if ($imported > 0) {
        flashMessage('success', "$imported utilisateur(s) importé(s) avec succès.$pwdMsg");
    }
    if (!empty($errors)) {
        flashMessage('error', 'Erreurs : ' . implode('. ', array_slice($errors, 0, 20)));
    }
    header('Location: users.php'); exit;
}

// ── Sync profiles ──────────────────────────────────────────────────────────────
if (isset($_GET['sync'])) {
    verifyCsrf();
    requirePermission('users', 'edit');
    $synced = 0; $errors = [];

    $where = ''; $params = [];
    if ($schoolFilter) { $where = 'WHERE u.school_id = ?'; $params[] = $schoolFilter; }
    $all = $pdo->prepare("SELECT u.* FROM users u $where ORDER BY u.name");
    $all->execute($params);

    while ($u = $all->fetch(PDO::FETCH_ASSOC)) {
        $uid = (int)$u['id'];
        $parts = explode(' ', $u['name'], 2);
        $fn = $parts[1] ?? ''; $ln = $parts[0];

        try {
            if ($u['role'] === 'school_admin') {
                $st = $pdo->prepare("SELECT id FROM directors WHERE user_id=?");
                $st->execute([$uid]);
                $rid = $st->fetchColumn();
                if ($rid) {
                    $pdo->prepare("UPDATE directors SET first_name=?, last_name=?, email=?, gender=?, is_active=?, school_id=? WHERE id=?")
                        ->execute([$fn, $ln, $u['email'], $u['gender'], $u['active'], $u['school_id'], $rid]);
                } else {
                    $pdo->prepare("INSERT INTO directors (school_id, first_name, last_name, email, gender, is_active, user_id) VALUES (?,?,?,?,?,?,?)")
                        ->execute([$u['school_id'], $fn, $ln, $u['email'], $u['gender'], $u['active'], $uid]);
                }
                $synced++;
            }

            if ($u['role'] === 'teacher') {
                $st = $pdo->prepare("SELECT id FROM teachers WHERE user_id=?");
                $st->execute([$uid]);
                $rid = $st->fetchColumn();
                if ($rid) {
                    $pdo->prepare("UPDATE teachers SET first_name=?, last_name=?, email=?, gender=?, school_id=? WHERE id=?")
                        ->execute([$fn, $ln, $u['email'], $u['gender'], $u['school_id'], $rid]);
                } else {
                    $pdo->prepare("INSERT INTO teachers (school_id, first_name, last_name, gender, email, user_id) VALUES (?,?,?,?,?,?)")
                        ->execute([$u['school_id'], $fn, $ln, $u['gender'], $u['email'], $uid]);
                }
                $synced++;
            }

            if ($u['role'] === 'student') {
                $st = $pdo->prepare("SELECT id FROM students WHERE user_id=?");
                $st->execute([$uid]);
                $rid = $st->fetchColumn();
                if ($rid) {
                    $pdo->prepare("UPDATE students SET first_name=?, last_name=?, gender=?, birth_date=?, school_id=? WHERE user_id=?")
                        ->execute([$fn, $ln, $u['gender'], $u['birth_date'], $u['school_id'], $uid]);
                } else {
                    $pdo->prepare("INSERT INTO students (school_id, first_name, last_name, gender, birth_date, user_id) VALUES (?,?,?,?,?,?)")
                        ->execute([$u['school_id'], $fn, $ln, $u['gender'], $u['birth_date'], $uid]);
                }
                $synced++;
            }
        } catch (PDOException $e) {
            $errors[] = "User #{$uid} ({$u['email']}): " . $e->getMessage();
        }
    }

    if ($synced > 0) {
        flashMessage('success', "$synced profil(s) synchronisé(s) avec succès.");
    }
    if (!empty($errors)) {
        flashMessage('error', 'Erreurs : ' . implode('. ', array_slice($errors, 0, 5)));
    }
    header('Location: users.php'); exit;
}

// ── Ajout / Modification ──────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && in_array($action, ['add','edit','save'])) {
    verifyCsrf();
    requirePermission('users', $id ? 'edit' : 'create');

    $name       = trim($_POST['name']  ?? '');
    $email      = trim($_POST['email'] ?? '');
    $role       = $_POST['role']       ?? '';
    $school_id  = !empty($_POST['school_id']) ? (int)$_POST['school_id'] : null;
    $password   = $_POST['password']   ?? '';
    $active     = isset($_POST['active']) ? 1 : 0;
    $birth_date = $_POST['birth_date'] ?? '';
    $gender     = ($_POST['gender'] ?? '') === 'F' ? 'F' : (($_POST['gender'] ?? '') === 'Autre' ? 'Autre' : null);
    $student_id = !empty($_POST['student_id']) ? (int)$_POST['student_id'] : null;
    $link_student_id = !empty($_POST['link_student_id']) ? (int)$_POST['link_student_id'] : null;
    $autoGen    = isset($_POST['auto_generate']);
    $photo      = null;
    $generatedPassword = '';

    if ($autoGen && !$id) {
        $base = strtolower(trim(preg_replace('/[^a-zA-Z0-9]/', '.', $name), '.'));
        $base = preg_replace('/\.+/', '.', $base);
        $digits = str_pad(random_int(0, 99), 2, '0', STR_PAD_LEFT);
        $email  = $base . $digits . '@nukunu.edu';
        $password = substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'), 0, 6)
                  . substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZ'), 0, 2)
                  . str_pad(random_int(0, 99), 2, '0', STR_PAD_LEFT)
                  . '@'
                  . substr(str_shuffle('abcdefghjkmnpqrstuvwxyz'), 0, 2);
        $generatedPassword = $password;
    }

    // Photo upload
    if (!empty($_FILES['photo']['name'])) {
        $allowedExts = ['jpg','jpeg','png','gif','webp'];
        $ext = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowedExts)) {
            $error = 'Format de photo non autorisé (jpeg, png, gif, webp).';
        } elseif ($_FILES['photo']['size'] > 2 * 1024 * 1024) {
            $error = 'La photo ne doit pas dépasser 2 Mo.';
        } else {
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime = finfo_file($finfo, $_FILES['photo']['tmp_name']);
            finfo_close($finfo);
            if (!in_array($mime, ['image/jpeg','image/png','image/gif','image/webp'])) {
                $error = 'Le fichier n\'est pas une image valide.';
            } else {
                $photo = uniqid('user_') . '.' . $ext;
            }
        }
    }

    if (empty($name))              $error = 'Le nom est requis.';
    elseif (!$autoGen && !validateEmail($email)) $error = 'Adresse email invalide.';
    elseif (!in_array($role, $creatableRoles, true)) $error = 'Rôle invalide.';
    elseif (!$id && empty($password)) $error = 'Le mot de passe est requis.';
    elseif (!empty($password) && strlen($password) < 12) $error = 'Mot de passe : 12 caractères minimum.';
    elseif (!empty($password) && !preg_match('/[A-Z]/', $password)) $error = 'Le mot de passe doit contenir au moins une majuscule.';
    elseif (!empty($password) && !preg_match('/[0-9]/', $password)) $error = 'Le mot de passe doit contenir au moins un chiffre.';
    else {
        $chk = $pdo->prepare("SELECT id FROM users WHERE email=? AND id!=?");
        $chk->execute([$email, $id ?? 0]);
        if ($chk->fetch()) $error = 'Cette adresse email est déjà utilisée.';
        if (!$id) {
            $chk2 = $pdo->prepare("SELECT id FROM users WHERE LOWER(TRIM(name))=LOWER(TRIM(?)) AND role=? AND COALESCE(school_id,0)=COALESCE(?,0)");
            $chk2->execute([$name, $role, $school_id]);
            if ($chk2->fetch()) $error = 'Un utilisateur avec ce nom et ce rôle existe déjà.';
        }
    }

    if (empty($error)) {
        $birth_date = $birth_date ?: null;

        // Gestion photo
        if ($id) {
            $oldPhoto = $pdo->prepare("SELECT photo FROM users WHERE id=?");
            $oldPhoto->execute([$id]); $oldPhotoVal = $oldPhoto->fetchColumn();
            if (!empty($_POST['remove_photo'])) {
                $photo = null;
                if ($oldPhotoVal && file_exists(__DIR__ . '/../uploads/users/' . $oldPhotoVal)) {
                    unlink(__DIR__ . '/../uploads/users/' . $oldPhotoVal);
                }
            } elseif (!empty($_FILES['photo']['name'])) {
                if ($oldPhotoVal && file_exists(__DIR__ . '/../uploads/users/' . $oldPhotoVal)) {
                    unlink(__DIR__ . '/../uploads/users/' . $oldPhotoVal);
                }
                move_uploaded_file($_FILES['photo']['tmp_name'], __DIR__ . '/../uploads/users/' . $photo);
            } else {
                $photo = $oldPhotoVal;
            }
        } elseif (!empty($_FILES['photo']['name'])) {
            move_uploaded_file($_FILES['photo']['tmp_name'], __DIR__ . '/../uploads/users/' . $photo);
        }

        if ($id) {
            if (!empty($password)) {
                $hash = password_hash($password, PASSWORD_BCRYPT, ['cost'=>BCRYPT_COST]);
                $pdo->prepare("UPDATE users SET name=?,email=?,role=?,school_id=?,active=?,birth_date=?,gender=?,photo=?,password=?,plain_password=? WHERE id=?")
                    ->execute([$name,$email,$role,$school_id,$active,$birth_date,$gender,$photo,$hash,$password,$id]);
            } else {
                $pdo->prepare("UPDATE users SET name=?,email=?,role=?,school_id=?,active=?,birth_date=?,gender=?,photo=? WHERE id=?")
                    ->execute([$name,$email,$role,$school_id,$active,$birth_date,$gender,$photo,$id]);
            }
            // ── Synchronisation automatique vers la table métier ──
            $parts = explode(' ', $name, 2);
            $fn = $parts[1] ?? '';
            $ln = $parts[0];

            if ($role === 'school_admin') {
                $st = $pdo->prepare("SELECT id FROM directors WHERE user_id=?");
                $st->execute([$id]);
                $rid = $st->fetchColumn();
                if ($rid) {
                    $pdo->prepare("UPDATE directors SET first_name=?, last_name=?, email=?, gender=?, is_active=?, school_id=? WHERE id=?")
                        ->execute([$fn, $ln, $email, $gender, $active, $school_id, $rid]);
                } else {
                    $pdo->prepare("INSERT INTO directors (school_id, first_name, last_name, email, gender, is_active, user_id) VALUES (?,?,?,?,?,?,?)")
                        ->execute([$school_id, $fn, $ln, $email, $gender, $active, $id]);
                }
            }

            if ($role === 'teacher') {
                $st = $pdo->prepare("SELECT id FROM teachers WHERE user_id=?");
                $st->execute([$id]);
                $rid = $st->fetchColumn();
                if ($rid) {
                    $pdo->prepare("UPDATE teachers SET first_name=?, last_name=?, email=?, gender=?, school_id=? WHERE id=?")
                        ->execute([$fn, $ln, $email, $gender, $school_id, $rid]);
                } else {
                    $pdo->prepare("INSERT INTO teachers (school_id, first_name, last_name, gender, email, user_id) VALUES (?,?,?,?,?,?)")
                        ->execute([$school_id, $fn, $ln, $gender, $email, $id]);
                }
            }

            if ($role === 'student') {
                $st = $pdo->prepare("SELECT id FROM students WHERE user_id=?");
                $st->execute([$id]);
                $rid = $st->fetchColumn();
                if ($link_student_id) {
                    $pdo->prepare("UPDATE students SET user_id=? WHERE id=?")->execute([$id, $link_student_id]);
                } elseif ($rid) {
                    $pdo->prepare("UPDATE students SET first_name=?, last_name=?, gender=?, birth_date=?, school_id=? WHERE user_id=?")
                        ->execute([$fn, $ln, $gender, $birth_date, $school_id, $id]);
                } else {
                    $pdo->prepare("INSERT INTO students (school_id, first_name, last_name, gender, birth_date, user_id) VALUES (?,?,?,?,?,?)")
                        ->execute([$school_id, $fn, $ln, $gender, $birth_date, $id]);
                }
            }

            if ($role === 'parent' && $student_id) {
                $pdo->prepare("INSERT IGNORE INTO parent_students (user_id, student_id) VALUES (?,?)")
                    ->execute([$id, $student_id]);
            }
            flashMessage('success', 'Utilisateur mis à jour.');
            if (!empty($password)) {
                $phone = getUserPhone($pdo, $id, $role);
                if ($phone) {
                    sendWhatsApp($phone, "Bonjour $name, votre nouveau mot de passe Nukunu Mofiala est : $password");
                }
            }
        } else {
            $hash = password_hash($password, PASSWORD_BCRYPT, ['cost'=>BCRYPT_COST]);
            $pdo->prepare("INSERT INTO users (name,email,password,plain_password,role,school_id,active,birth_date,gender,photo) VALUES (?,?,?,?,?,?,?,?,?,?)")
                ->execute([$name,$email,$hash,$password,$role,$school_id,$active,$birth_date,$gender,$photo]);
            $newId = (int)$pdo->lastInsertId();

            // ── Synchronisation automatique vers la table métier ──
            $parts = explode(' ', $name, 2);
            $fn = $parts[1] ?? '';
            $ln = $parts[0];

            if ($role === 'school_admin') {
                $st = $pdo->prepare("SELECT id FROM directors WHERE user_id=?");
                $st->execute([$newId]);
                $rid = $st->fetchColumn();
                if ($rid) {
                    $pdo->prepare("UPDATE directors SET first_name=?, last_name=?, email=?, gender=?, is_active=?, school_id=? WHERE id=?")
                        ->execute([$fn, $ln, $email, $gender, $active, $school_id, $rid]);
                } else {
                    $pdo->prepare("INSERT INTO directors (school_id, first_name, last_name, email, gender, is_active, user_id) VALUES (?,?,?,?,?,?,?)")
                        ->execute([$school_id, $fn, $ln, $email, $gender, $active, $newId]);
                }
            }

            if ($role === 'teacher') {
                $st = $pdo->prepare("SELECT id FROM teachers WHERE user_id=?");
                $st->execute([$newId]);
                $rid = $st->fetchColumn();
                if ($rid) {
                    $pdo->prepare("UPDATE teachers SET first_name=?, last_name=?, email=?, gender=?, school_id=? WHERE id=?")
                        ->execute([$fn, $ln, $email, $gender, $school_id, $rid]);
                } else {
                    $pdo->prepare("INSERT INTO teachers (school_id, first_name, last_name, gender, email, user_id) VALUES (?,?,?,?,?,?)")
                        ->execute([$school_id, $fn, $ln, $gender, $email, $newId]);
                }
            }

            if ($role === 'student') {
                $st = $pdo->prepare("SELECT id FROM students WHERE user_id=?");
                $st->execute([$newId]);
                $rid = $st->fetchColumn();
                if ($link_student_id) {
                    $pdo->prepare("UPDATE students SET user_id=? WHERE id=?")->execute([$newId, $link_student_id]);
                } elseif ($rid) {
                    $pdo->prepare("UPDATE students SET first_name=?, last_name=?, gender=?, birth_date=?, school_id=? WHERE user_id=?")
                        ->execute([$fn, $ln, $gender, $birth_date, $school_id, $newId]);
                } else {
                    $pdo->prepare("INSERT INTO students (school_id, first_name, last_name, gender, birth_date, user_id) VALUES (?,?,?,?,?,?)")
                        ->execute([$school_id, $fn, $ln, $gender, $birth_date, $newId]);
                }
            }

            if ($role === 'parent' && $student_id) {
                $pdo->prepare("INSERT IGNORE INTO parent_students (user_id, student_id) VALUES (?,?)")
                    ->execute([$newId, $student_id]);
            }
            $msg = "Compte créé : <strong>" . e($email) . "</strong>";
            if ($generatedPassword) {
                $msg .= " / Mot de passe : <strong>" . e($generatedPassword) . "</strong>";
            }
            flashMessage('success', $msg);
            $pwdToSend = $generatedPassword ?: $password;
            if ($pwdToSend) {
                $phone = getUserPhone($pdo, $newId, $role);
                if ($phone) {
                    sendWhatsApp($phone, "Bonjour $name, votre compte Nukunu Mofiala a été créé. Email : $email / Mot de passe : $pwdToSend");
                }
            }
        }
        header('Location: users.php'); exit;
    }
}

// ── Gestion enfants d'un parent ───────────────────────────────────────────────
if ($action === 'remove_child' && $id) {
    verifyCsrf();
    $parentId = (int)($_POST['parent_id'] ?? 0);
    if ($schoolFilter) {
        $chk = $pdo->prepare("SELECT id FROM users WHERE id=? AND school_id=?");
        $chk->execute([$parentId, $schoolFilter]);
        if (!$chk->fetch()) { flashMessage('error','Action non autorisée.'); header('Location: users.php'); exit; }
    }
    $pdo->prepare("DELETE FROM parent_students WHERE user_id=? AND student_id=?")->execute([$parentId, $id]);
    flashMessage('success','Enfant retiré.');
    header("Location: users.php?action=edit&id=$parentId"); exit;
}

// ── Chargement édition ────────────────────────────────────────────────────────
$user = null;
$linkedStudents = [];
if ($action === 'edit' && $id) {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id=?");
    $stmt->execute([$id]); $user = $stmt->fetch();
    if (!$user) { flashMessage('error','Utilisateur introuvable.'); header('Location: users.php'); exit; }
    // Enfants liés (si parent)
    if ($user['role'] === 'parent') {
        $ps = $pdo->prepare("SELECT s.id, s.first_name, s.last_name FROM parent_students ps JOIN students s ON ps.student_id=s.id WHERE ps.user_id=? ORDER BY s.last_name, s.first_name");
        $ps->execute([$id]); $linkedStudents = $ps->fetchAll();
    }
}

$schools      = $pdo->query("SELECT id, name FROM schools ORDER BY name")->fetchAll();

// Classes disponibles pour le filtre
$classes = $pdo->query("SELECT id, name FROM classes c ORDER BY " . getClassSortSQL('c'))->fetchAll();

// Charger les élèves disponibles pour les liaisons student/parent
if ($schoolFilter) {
    $sl = $pdo->prepare("SELECT id, first_name, last_name FROM students WHERE school_id=? ORDER BY last_name, first_name");
    $sl->execute([$schoolFilter]);
    $studentsForLink = $sl->fetchAll();
} else {
    $studentsForLink = $pdo->query("SELECT id, first_name, last_name FROM students ORDER BY last_name, first_name")->fetchAll();
}

// Tri et liste
$sort = resolveSort(['name','email','role','school_name','class_name','birth_date','active','created_at'], 'name', 'asc');
$sortMap = ['name'=>'u.name','email'=>'u.email','role'=>'u.role','school_name'=>'s.name','class_name'=>'c.name','birth_date'=>'u.birth_date','active'=>'u.active','created_at'=>'u.created_at'];
$orderExpr = ($sortMap[$sort['col']] ?? 'u.name') . ' ' . $sort['dir'];

// Filtre par rôle via GET
$filterRole = $_GET['filter_role'] ?? '';
$whereRole  = '';
$roleParams = [];
if ($filterRole && in_array($filterRole, ['super_admin','school_admin','teacher','accountant','student','parent'], true)) {
    $whereRole  = 'AND u.role=?';
    $roleParams = [$filterRole];
}
// Filtre par classe via GET
$filterClass = $_GET['filter_class'] ?? '';
$classWhere  = '';
$classParams = [];
if ($filterClass && $filterRole === 'student') {
    $classWhere  = 'AND st.class_id=?';
    $classParams = [(int)$filterClass];
}
// Filtre par statut actif/inactif
$filterActive = $_GET['filter_active'] ?? '';
$activeWhere  = '';
$activeParams = [];
if ($filterActive === 'active') {
    $activeWhere  = 'AND u.active=1';
} elseif ($filterActive === 'inactive') {
    $activeWhere  = 'AND u.active=0';
}
// Filtre par école via GET (pour super_admin)
$filterSchool = $_GET['filter_school'] ?? '';
$schoolParams = [];
if ($schoolFilter) {
    $schoolWhere = "AND u.school_id=" . (int)$schoolFilter;
} elseif ($filterSchool) {
    $schoolWhere  = 'AND u.school_id=?';
    $schoolParams = [(int)$filterSchool];
} else {
    $schoolWhere = '';
}

$users = $pdo->prepare("
    SELECT u.*, s.name AS school_name, s.logo AS school_logo,
           d.id AS director_id,
           d.first_name AS director_first_name,
           d.last_name AS director_last_name,
           d.diploma AS director_diploma,
           d.start_date AS director_start_date,
           d.gender AS director_gender,
           st.id AS student_id_linked,
           st.class_id AS student_class_id,
           st.first_name AS student_first_name,
           st.last_name AS student_last_name,
            st.parent_name AS student_parent_name,
            st.parent_phone AS student_parent_phone,
            c.name AS class_name,
            t.id AS teacher_id_linked,
            t.diploma AS teacher_diploma,
            t.subject AS teacher_subject
    FROM users u LEFT JOIN schools s ON u.school_id=s.id
    LEFT JOIN directors d ON d.user_id = u.id
    LEFT JOIN students st ON st.user_id = u.id
    LEFT JOIN classes c ON st.class_id = c.id
    LEFT JOIN teachers t ON t.user_id = u.id
    WHERE 1=1 $schoolWhere $whereRole $classWhere $activeWhere
    ORDER BY $orderExpr
");
$users->execute(array_merge($schoolParams, $roleParams, $classParams, $activeParams));
$users = $users->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>Utilisateurs - 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);
  }

  .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-table {
    padding: 0;
  }

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

  /* ── Table styling ── */
  .table-wrapper {
    overflow-x: auto;
  }
  .table-wrapper table {
    width: 100%;
    border-collapse: collapse;
    font-size: .85rem;
  }
  .table-wrapper th {
    text-align: left;
    padding: .75rem .75rem;
    font-size: .75rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: .03em;
    color: #6B7280;
    border-bottom: 2px solid #E5E7EB;
    white-space: nowrap;
  }
  .table-wrapper th a {
    color: #6B7280;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 4px;
  }
  .table-wrapper th a:hover {
    color: var(--primary);
  }
  .table-wrapper td {
    padding: .65rem .75rem;
    border-bottom: 1px solid #F3F4F6;
    vertical-align: middle;
  }
  .table-wrapper tr:hover td {
    background: #F9FAFB;
  }
  .table-wrapper tr.user-inactive td {
    opacity: .6;
  }
  .badge {
    display: inline-block;
    padding: 2px 10px;
    border-radius: 20px;
    font-size: .72rem;
    font-weight: 600;
  }
  .badge-super_admin { background: #FEE2E2; color: #991B1B; }
  .badge-school_admin { background: #DBEAFE; color: #1E40AF; }
  .badge-teacher { background: var(--light); color: var(--primary); }
  .badge-accountant { background: #FEF3C7; color: #92400E; }
  .badge-student { background: #D1FAE5; color: #065F46; }
  .badge-parent { background: #E0E7FF; color: #3730A3; }

  .status-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 3px 10px;
    border-radius: 20px;
    font-size: .75rem;
    font-weight: 600;
  }
  .status-active { background: #D1FAE5; color: #065F46; }
  .status-inactive { background: #FEE2E2; color: #991B1B; }

  .user-cell {
    display: flex;
    align-items: center;
    gap: .6rem;
  }
  .user-cell .user-icons {
    display: inline-flex;
    align-items: center;
    gap: 2px;
  }

  .bulk-actions {
    padding: .75rem;
    border-top: 1px solid #E5E7EB;
    text-align: right;
    display: flex;
    gap: .5rem;
    justify-content: flex-end;
  }

  .filter-chips {
    display: flex;
    gap: .5rem;
    flex-wrap: wrap;
    margin-bottom: 1rem;
    align-items: center;
  }
  .filter-chip {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: .4rem .85rem;
    border-radius: 20px;
    font-size: .8rem;
    font-weight: 500;
    text-decoration: none;
    transition: all .15s;
    background: #E5E7EB;
    color: #374151;
    border: 1px solid transparent;
  }
  .filter-chip:hover {
    background: #D1D5DB;
  }
  .filter-chip.active {
    background: var(--primary);
    color: white;
    border-color: var(--primary);
  }
  .filter-chip.active-green {
    background: #059669;
    color: white;
    border-color: #059669;
  }
  .filter-chip.active-red {
    background: #DC2626;
    color: white;
    border-color: #DC2626;
  }
  .filter-sep {
    width: 1px;
    height: 24px;
    background: #D1D5DB;
    margin: 0 .2rem;
  }

  @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-user-shield"></i> Gestion des utilisateurs'; 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-user-shield"></i> Utilisateurs</h1>
                <p>Gérez les comptes utilisateurs et leurs autorisations</p>
            </div>
            <?php if (hasPermission('users','create')): ?>
            <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&filter_role=<?= e($filterRole) ?>&filter_school=<?= e($filterSchool) ?>&csrf_token=<?= csrfToken() ?>" 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="?sync=1&csrf_token=<?= csrfToken() ?>" class="btn btn-outline" style="border-color:var(--accent);color:var(--accent);" onclick="return confirm('Synchroniser tous les profils (directeurs, enseignants, élèves) à partir des utilisateurs ?')"><i class="fas fa-sync-alt"></i> Synchroniser</a>
            </div>
            <?php endif; ?>
        </div>

        <?php if (in_array($action, ['add','edit'])): ?>
        <!-- ═══ Formulaire ajout/modification ═══ -->
        <div class="form-card">
            <h2><i class="fas fa-<?= $user ? 'edit' : 'plus-circle' ?>"></i> <?= $user ? 'Modifier' : 'Ajouter' ?> un utilisateur</h2>
            <form method="POST" action="?action=<?= $id ? 'edit&id='.$id : 'add' ?>" enctype="multipart/form-data">
                <?= csrfField() ?>
                <div class="form-grid-2">
                    <div class="form-group">
                        <label>Nom complet <span style="color:#DC2626;">*</span></label>
                        <input type="text" name="name" required value="<?= e($user['name'] ?? '') ?>">
                    </div>
                    <div class="form-group">
                        <label>Email <span style="color:#DC2626;">*</span></label>
                        <input type="email" name="email" required value="<?= e($user['email'] ?? '') ?>">
                    </div>
                </div>
                <div class="form-grid-2">
                    <div class="form-group">
                        <label>Rôle <span style="color:#DC2626;">*</span></label>
                        <select name="role" required id="roleSelect">
                            <?php foreach ($creatableRoles as $r): ?>
                            <option value="<?= $r ?>" <?= ($user['role'] ?? '') === $r ? 'selected' : '' ?>><?= e(getRoleLabel($r)) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>École</label>
                        <select name="school_id" <?= $schoolFilter ? 'disabled' : '' ?>>
                            <option value="">Toutes</option>
                            <?php foreach ($schools as $sc): ?>
                            <option value="<?= $sc['id'] ?>" <?= ($user['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>
                <div class="form-grid-2">
                    <div class="form-group">
                        <label>Date de naissance</label>
                        <input type="date" name="birth_date" value="<?= e($user['birth_date'] ?? '') ?>">
                    </div>
                    <div class="form-group">
                        <label>Genre</label>
                        <div class="radio-group">
                            <label>
                                <input type="radio" name="gender" value="M" <?=($user['gender']??'')==='M'?'checked':''?>>
                                <i class="fas fa-male" style="color:#3182ce;"></i> M
                            </label>
                            <label>
                                <input type="radio" name="gender" value="F" <?=($user['gender']??'')==='F'?'checked':''?>>
                                <i class="fas fa-female" style="color:#d53f8c;"></i> F
                            </label>
                            <label>
                                <input type="radio" name="gender" value="Autre" <?=($user['gender']??'')==='Autre'?'checked':''?>>
                                <i class="fas fa-venus-mars" style="color:#718096;"></i> Autre
                            </label>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label>Photo passeport</label>
                    <input type="file" name="photo" accept="image/jpeg,image/png,image/gif,image/webp">
                    <small style="color:#718096;font-size:.75rem;">Max 2 Mo — JPEG, PNG, GIF, WebP</small>
                    <?php if (!empty($user['photo'])): ?>
                    <div style="margin-top:.5rem;display:flex;align-items:center;gap:.75rem;">
                        <?= userPhotoImg($user['photo'], $user['name'], 'large') ?>
                        <label style="display:inline-flex;align-items:center;gap:4px;cursor:pointer;margin:0;">
                            <input type="checkbox" name="remove_photo" value="1">
                            <span style="color:#e53e3e;font-size:.85rem;">Supprimer la photo</span>
                        </label>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="form-group" style="position:relative;">
                    <label>Mot de passe <?= $id ? '<small style="color:#6B7280;">(laisser vide pour ne pas changer)</small>' : '<span style="color:#DC2626;">*</span>' ?></label>
                    <div style="display:flex;gap:.5rem;">
                        <input type="password" name="password" id="passwordField" <?= !$id ? 'required' : '' ?> minlength="12" placeholder="Min. 12 caractères" style="flex:1;">
                        <button type="button" class="btn btn-light" onclick="togglePasswordVisibility()" title="Afficher / masquer" style="flex-shrink:0;padding:.4rem .65rem;"><i class="fas fa-eye"></i></button>
                        <?php if (!$id || $user['role'] !== 'super_admin'): ?>
                        <button type="button" class="btn btn-light" onclick="generatePassword()" title="Générer un mot de passe" style="flex-shrink:0;padding:.4rem .65rem;"><i class="fas fa-key"></i></button>
                        <?php endif; ?>
                    </div>
                </div>

                <?php if (!$id): ?>
                <div class="form-group">
                    <label style="display:inline-flex;align-items:center;gap:6px;cursor:pointer;font-weight:400 !important;font-size:.85rem !important;">
                        <input type="checkbox" name="auto_generate" value="1" onchange="toggleAutoGen(this)">
                        <strong>Générer automatiquement</strong>
                    </label>
                    <small style="color:#718096;font-size:.75rem;display:block;">Email = prenom.nomXX@nukunu.edu, mot de passe aléatoire.</small>
                </div>
                <?php endif; ?>

                <!-- Lien élève (pour rôle student) -->
                <div class="form-group" id="studentLinkField" style="<?= ($user['role'] ?? '') !== 'student' ? 'display:none' : '' ?>">
                    <label><i class="fas fa-user-graduate"></i> Lier à un élève</label>
                    <select name="link_student_id">
                        <option value="">— Choisir un élève —</option>
                        <?php foreach ($studentsForLink as $st): ?>
                        <option value="<?= $st['id'] ?>"><?= e($st['last_name'].' '.$st['first_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <small style="color:#6B7280;font-size:.75rem;">Associe ce compte utilisateur à un élève existant.</small>
                </div>

                <!-- Lien enfant (pour rôle parent) -->
                <div class="form-group" id="parentLinkField" style="<?= ($user['role'] ?? '') !== 'parent' ? 'display:none' : '' ?>">
                    <label><i class="fas fa-child"></i> Ajouter un enfant</label>
                    <select name="student_id">
                        <option value="">— Choisir un élève —</option>
                        <?php foreach ($studentsForLink as $st): ?>
                        <option value="<?= $st['id'] ?>"><?= e($st['last_name'].' '.$st['first_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <?php if (!empty($linkedStudents)): ?>
                    <div style="margin-top:.75rem;">
                        <strong style="font-size:.85rem;">Enfants liés :</strong>
                        <?php foreach ($linkedStudents as $ls): ?>
                        <span style="display:inline-flex;align-items:center;gap:.4rem;background:#F3F4F6;color:#374151;padding:.2rem .6rem;border-radius:20px;margin:.2rem;font-size:.82rem;">
                            <?= e($ls['last_name'].' '.$ls['first_name']) ?>
                            <form method="POST" action="?action=remove_child&id=<?= $ls['id'] ?>" style="display:inline" onsubmit="return confirm('Retirer cet enfant ?')">
                                <?= csrfField() ?>
                                <input type="hidden" name="parent_id" value="<?= $id ?>">
                                <button type="submit" style="background:none;border:none;color:#DC2626;cursor:pointer;padding:0;"><i class="fas fa-times"></i></button>
                            </form>
                        </span>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>

                <div class="form-group">
                    <label style="display:inline-flex;align-items:center;gap:6px;cursor:pointer;font-weight:400 !important;font-size:.85rem !important;">
                        <input type="checkbox" name="active" value="1" <?= ($user['active'] ?? 1) ? 'checked' : '' ?>>
                        <span>Compte actif</span>
                    </label>
                    <small style="color:#6B7280;font-size:.75rem;display:block;">Un compte inactif ne peut pas se connecter.</small>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Enregistrer</button>
                    <a href="users.php" class="btn btn-light">Annuler</a>
                </div>
            </form>
        </div>

        <?php else: ?>
        <!-- ═══ Liste des utilisateurs ═══ -->

        <!-- ═══ Import Modal ═══ -->
        <div class="modal-overlay" id="importModal">
            <div class="modal-box">
                <h2><i class="fas fa-upload"></i> Importer des utilisateurs</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:#DC2626;">*</span></label>
                        <input type="file" name="csv_file" accept=".csv" required>
                    </div>
                    <div style="font-size:.82rem;color:#6B7280;background:#F9FAFB;padding:.75rem;border-radius:6px;margin-bottom:1rem;">
                        <strong>Format attendu :</strong><br>
                        <code style="font-size:.78rem;">Nom;Email;Rôle;École;Genre;Date naissance;Actif</code>
                        <br><br>
                        <strong>Rôles acceptés :</strong>
                        <?php foreach ($creatableRoles as $r): ?>
                        <span class="badge badge-<?= $r ?>"><?= e(getRoleLabel($r)) ?></span>
                        <?php endforeach; ?>
                        <br><br>
                        <strong>Genre :</strong> M, F ou Autre<br>
                        <strong>Actif :</strong> Oui ou Non<br>
                        <em style="font-size:.78rem;">Les mots de passe sont générés automatiquement.</em>
                    </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>

        <!-- ═══ Filtres ═══ -->
        <div class="filter-chips">
            <a href="<?= $filterSchool ? "?filter_school=".e($filterSchool) : 'users.php' ?>" class="filter-chip <?= !$filterRole && !$filterSchool && !$filterActive ? 'active' : '' ?>">Tous</a>
            <?php foreach (['super_admin','school_admin','teacher','accountant','student','parent'] as $r):
                if (!isSuperAdmin() && in_array($r, ['super_admin','accountant'], true)) continue; ?>
            <a href="?<?= $filterSchool ? "filter_school=".e($filterSchool)."&" : '' ?>filter_role=<?= $r ?><?= $filterActive ? '&filter_active='.$filterActive : '' ?>" class="filter-chip <?= $filterRole===$r ? 'active' : '' ?>">
                <?= e(getRoleLabel($r)) ?>
            </a>
            <?php endforeach; ?>
            <span class="filter-sep"></span>
            <a href="?<?=http_build_query(array_filter(['filter_role'=>$filterRole,'filter_school'=>$filterSchool,'filter_class'=>$filterClass,'filter_active'=>'active']))?>" class="filter-chip <?=$filterActive==='active'?'active-green':''?>"><i class="fas fa-check-circle"></i> Actifs</a>
            <a href="?<?=http_build_query(array_filter(['filter_role'=>$filterRole,'filter_school'=>$filterSchool,'filter_class'=>$filterClass,'filter_active'=>'inactive']))?>" class="filter-chip <?=$filterActive==='inactive'?'active-red':''?>"><i class="fas fa-ban"></i> Inactifs</a>
            <?php if ($filterActive): ?>
            <a href="?<?=http_build_query(array_filter(['filter_role'=>$filterRole,'filter_school'=>$filterSchool,'filter_class'=>$filterClass]))?>" class="filter-chip" style="font-size:.78rem;">Effacer filtre</a>
            <?php endif; ?>
            <?php if (isSuperAdmin()): ?>
            <select name="filter_school" onchange="if(this.value) window.location='?filter_school='+this.value+<?= json_encode($filterRole ? '&filter_role='.$filterRole : '') ?>+<?= json_encode($filterActive ? '&filter_active='.$filterActive : '') ?>; else window.location='users.php';" style="margin-left:auto;padding:.4rem .7rem;border:1px solid #D1D5DB;border-radius:6px;font-size:.85rem;">
                <option value="">— Filtrer par école —</option>
                <?php foreach ($schools as $sc): ?>
                <option value="<?= $sc['id'] ?>" <?= $filterSchool == $sc['id'] ? 'selected' : '' ?>><?= e($sc['name']) ?></option>
                <?php endforeach; ?>
            </select>
            <?php endif; ?>
            <?php if ($filterRole === 'student'): ?>
            <select name="filter_class" onchange="var params=new URLSearchParams(window.location.search);params.set('filter_class',this.value);window.location='?'+params.toString();" style="padding:.4rem .7rem;border:1px solid #D1D5DB;border-radius:6px;font-size:.85rem;">
                <option value="">— Toutes les classes —</option>
                <?php foreach ($classes as $cl): ?>
                <option value="<?=$cl['id']?>" <?=$filterClass==$cl['id']?'selected':''?>><?=e($cl['name'])?></option>
                <?php endforeach; ?>
            </select>
            <?php endif; ?>
        </div>

        <div class="card card-table">
            <form method="POST" id="bulkFormUsers">
            <?= csrfField() ?>
            <input type="hidden" name="bulk_action" id="bulkAction" value="">
            <div class="table-wrapper">
            <table>
                <thead>
                    <tr>
                        <?php if (isSuperAdmin()): ?>
                        <th style="width:36px;"><input type="checkbox" onchange="document.querySelectorAll('#bulkFormUsers .cb').forEach(c=>c.checked=this.checked)"></th>
                        <?php endif; ?>
                        <th><?= sortTh('name','Nom',$sort) ?></th>
                        <th><?= sortTh('email','Email',$sort) ?></th>
                        <th><?= sortTh('role','Rôle',$sort) ?></th>
                        <th><?= sortTh('class_name','Classe',$sort) ?></th>
                        <th><?= sortTh('birth_date','Naissance / Fonction',$sort) ?></th>
                        <th><?= sortTh('school_name','École',$sort) ?></th>
                        <th><?= sortTh('active','Statut',$sort) ?></th>
                        <th><?= sortTh('created_at','Créé le',$sort) ?></th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($users as $u):
                    $isActive = isset($u['active']) ? (bool)$u['active'] : true;
                ?>
                <tr class="<?= $isActive ? '' : 'user-inactive' ?>">
                    <?php if (isSuperAdmin()): ?>
                    <td><input type="checkbox" name="user_ids[]" value="<?= $u['id'] ?>" class="cb" <?= $u['id'] === (int)$_SESSION['user_id'] ? 'disabled' : '' ?>></td>
                    <?php endif; ?>
                    <td><div class="user-cell"><?= userPhotoImg($u['photo']??null, $u['name'], 'small') ?><span class="user-icons"><?php if (!empty($u['director_id'])): ?><?php $dirTitle = ($u['director_gender']??$u['gender']) === 'F' ? 'Directrice' : 'Directeur'; ?><i class="fas fa-user-tie" style="color:#667eea;" title="<?=$dirTitle?>"></i> <?php endif; ?><?php if (!empty($u['student_id_linked'])): ?><i class="fas fa-user-graduate" style="color:#38a169;" title="Élève"></i> <?php endif; ?><?php if (!empty($u['teacher_id_linked'])): ?><i class="fas fa-chalkboard-teacher" style="color:#805ad5;" title="Enseignant"></i> <?php endif; ?><?php if ($u['gender']??''): ?><?php if ($u['gender']==='F'): ?><i class="fas fa-female" style="color:#d53f8c;" title="Féminin"></i><?php elseif ($u['gender']==='M'): ?><i class="fas fa-male" style="color:#3182ce;" title="Masculin"></i><?php else: ?><i class="fas fa-venus-mars" style="color:#718096;" title="Autre"></i><?php endif; ?> <?php endif; ?>
                            <?php if (!empty($u['director_id'])): ?>
                            <strong><?=$dirTitle?></strong> <?=e($u['director_last_name'].' '.$u['director_first_name'])?>
                            <?php elseif (!empty($u['teacher_id_linked'])): ?>
                            <strong>Ens.</strong> <?=e($u['name'])?>
                            <?php elseif (!empty($u['student_id_linked'])): ?>
                            <strong>Élève</strong> <?=e(($u['student_last_name'] ?? '') . ' ' . ($u['student_first_name'] ?? $u['name']))?>
                            <?php else: ?>
                            <?=e($u['name'])?>
                            <?php endif; ?>
                        </span></div></td>
                    <td><?= e($u['email']) ?></td>
                    <td>
                            <span class="badge badge-<?= $u['role'] ?>"><?= getRoleLabel($u['role']) ?></span>
                            <?php if (!empty($u['director_id'])): ?>
                            <span style="display:inline-flex;align-items:center;gap:3px;margin-left:3px;background:#EBF4FF;color:#2B6CB0;font-size:.7rem;padding:1px 6px;border-radius:10px;white-space:nowrap;"
                                  title="Directeur(trice) : <?= e($u['director_last_name'].' '.$u['director_first_name']) ?>">
                                <i class="fas fa-user-tie" style="font-size:.65rem;"></i>
                                Dir.
                            </span>
                            <?php endif; ?>
                        </td>
                    <td>
                            <?php if (!empty($u['student_id_linked']) && !empty($u['class_name'])): ?>
                            <span style="display:inline-flex;align-items:center;gap:3px;background:#F0FFF4;color:#276749;font-size:.82rem;padding:2px 8px;border-radius:10px;white-space:nowrap;">
                                <i class="fas fa-school" style="font-size:.7rem;"></i>
                                <?=e($u['class_name'])?>
                            </span>
                            <?php else: ?>
                            <span style="color:#9CA3AF;">—</span>
                            <?php endif; ?>
                        </td>
                    <td>
                            <?php if (!empty($u['director_id'])): ?>
                            <span style="font-size:.85rem;color:#6B7280;">
                                <?php if ($u['director_diploma']): ?><i class="fas fa-graduation-cap" style="color:#667eea;"></i> <?=e($u['director_diploma'])?><?php endif; ?>
                                <?php if ($u['director_start_date']): ?>
                                <br><small style="color:#9CA3AF;"><i class="far fa-calendar-alt"></i> depuis <?=e(formatDate($u['director_start_date']))?></small>
                                <?php endif; ?>
                            </span>
                            <?php elseif (!empty($u['teacher_id_linked'])): ?>
                            <span style="font-size:.85rem;color:#6B7280;">
                                <?php if ($u['teacher_diploma']): ?><i class="fas fa-graduation-cap" style="color:#805ad5;"></i> <?=e($u['teacher_diploma'])?><?php endif; ?>
                                <?php if ($u['teacher_subject']): ?><br><small><i class="fas fa-book" style="color:#805ad5;"></i> <?=e($u['teacher_subject'])?></small><?php endif; ?>
                            </span>
                            <?php elseif (!empty($u['student_id_linked'])): ?>
                            <span style="font-size:.85rem;color:#6B7280;">
                                <?php if ($u['birth_date']): ?><i class="fas fa-birthday-cake" style="color:#d53f8c;"></i> <?=e(formatDate($u['birth_date']))?><br><?php endif; ?>
                                <?php if ($u['student_parent_name']): ?><small><i class="fas fa-user-friends" style="color:#667eea;"></i> <?=e($u['student_parent_name'])?></small><?php endif; ?>
                                <?php if ($u['student_parent_phone']): ?> <small style="color:#9CA3AF;"><?=e($u['student_parent_phone'])?></small><?php endif; ?>
                            </span>
                            <?php else: ?>
                            <?= $u['birth_date'] ? e(formatDate($u['birth_date'])) : '<span style="color:#9CA3AF;">—</span>' ?>
                            <?php endif; ?>
                        </td>
                    <td>
                            <?php if (!empty($u['school_logo'])): ?>
                            <img src="<?= e(logoUrl($u['school_logo'])) ?>" alt="" style="width:28px;height:28px;object-fit:contain;border-radius:4px;" title="<?= e($u['school_name'] ?? '') ?>">
                            <?php else: ?>
                            <span style="color:#9CA3AF;font-size:.8rem;">—</span>
                            <?php endif; ?>
                        </td>
                    <td>
                        <?php if ($isActive): ?>
                        <span class="status-badge status-active"><i class="fas fa-check-circle"></i> Actif</span>
                        <?php else: ?>
                        <span class="status-badge status-inactive"><i class="fas fa-ban"></i> Inactif</span>
                        <?php endif; ?>
                    </td>
                    <td><?= formatDate($u['created_at']) ?></td>
                    <td style="white-space:nowrap;">
                        <?php if (isSuperAdmin()): ?>
                        <a href="user_detail.php?id=<?= $u['id'] ?>" class="btn btn-light" title="Détail" style="padding:.35rem .6rem;font-size:.75rem;"><i class="fas fa-eye"></i></a>
                        <?php endif; ?>
                        <?php if (hasPermission('users','edit') && canManageUser($u)): ?>
                        <a href="?action=edit&id=<?= $u['id'] ?>" class="btn btn-light" title="Modifier" style="padding:.35rem .6rem;font-size:.75rem;"><i class="fas fa-edit"></i></a>
                        <?php if (!empty($u['director_id'])): ?>
                        <a href="directors.php?action=edit&id=<?=$u['director_id']?>" class="btn btn-light" title="Profil directeur" style="padding:.35rem .6rem;font-size:.75rem;"><i class="fas fa-user-tie"></i></a>
                        <?php endif; ?>
                        <?php if (!empty($u['student_id_linked'])): ?>
                        <a href="students.php?action=edit&id=<?=$u['student_id_linked']?>" class="btn btn-light" title="Profil élève" style="padding:.35rem .6rem;font-size:.75rem;"><i class="fas fa-user-graduate"></i></a>
                        <?php endif; ?>
                        <?php if (!empty($u['teacher_id_linked'])): ?>
                        <a href="teachers.php?action=edit&id=<?=$u['teacher_id_linked']?>" class="btn btn-light" title="Profil enseignant" style="padding:.35rem .6rem;font-size:.75rem;"><i class="fas fa-chalkboard-teacher"></i></a>
                        <?php endif; ?>
                        <!-- Bouton activer/désactiver -->
                        <?php if ($u['id'] !== (int)$_SESSION['user_id']): ?>
                        <form method="POST" action="?action=toggle_active&id=<?= $u['id'] ?>" style="display:inline"
                              title="<?= $isActive ? 'Désactiver' : 'Activer' ?>">
                            <?= csrfField() ?>
                            <button type="submit" class="btn btn-light" style="padding:.35rem .6rem;font-size:.75rem;">
                                <i class="fas fa-<?= $isActive ? 'toggle-on' : 'toggle-off' ?>"></i>
                            </button>
                        </form>
                        <?php endif; ?>
                        <?php endif; ?>
                        <?php if (isSuperAdmin() && hasPermission('users','delete') && $u['id'] !== (int)$_SESSION['user_id']): ?>
                        <form method="POST" action="?action=delete&id=<?= $u['id'] ?>" style="display:inline"
                              onsubmit="return confirm('Supprimer cet utilisateur ?')">
                            <?= csrfField() ?>
                            <button type="submit" class="btn btn-danger" style="padding:.35rem .6rem;font-size:.75rem;"><i class="fas fa-trash"></i></button>
                        </form>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($users)): ?>
                <tr><td colspan="<?= isSuperAdmin() ? 10 : 9 ?>" style="text-align:center;color:#9CA3AF;padding:3rem;">Aucun utilisateur trouvé.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
            </div>
            <?php if (isSuperAdmin() && count($users) > 0): ?>
            <div class="bulk-actions">
                <button type="button" class="btn btn-outline" style="font-size:.8rem;" onclick="document.getElementById('bulkAction').value='deactivate'; if(confirm('Désactiver les utilisateurs sélectionnés ?')) document.getElementById('bulkFormUsers').submit();">
                    <i class="fas fa-user-slash"></i> Désactiver
                </button>
                <button type="button" class="btn btn-danger" style="font-size:.8rem;" onclick="document.getElementById('bulkAction').value='delete'; if(confirm('Supprimer les utilisateurs sélectionnés ?')) document.getElementById('bulkFormUsers').submit();">
                    <i class="fas fa-trash-alt"></i> Supprimer la sélection
                </button>
            </div>
            <?php endif; ?>
            </form>
        </div>
        <?php endif; ?>
    </div>
</div>

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

<script>
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; ?>

const roleSelect = document.getElementById('roleSelect');
if (roleSelect) {
    function toggleRoleFields() {
        const role = roleSelect.value;
        document.getElementById('studentLinkField').style.display = role === 'student' ? '' : 'none';
        document.getElementById('parentLinkField').style.display  = role === 'parent'  ? '' : 'none';
    }
    roleSelect.addEventListener('change', toggleRoleFields);
    toggleRoleFields();
}
function togglePasswordVisibility() {
    const f = document.getElementById('passwordField');
    const b = f.nextElementSibling;
    if (f.type === 'password') {
        f.type = 'text';
        b.innerHTML = '<i class="fas fa-eye-slash"></i>';
    } else {
        f.type = 'password';
        b.innerHTML = '<i class="fas fa-eye"></i>';
    }
}
function generatePassword() {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
    let p = '';
    for (let i = 0; i < 6; i++) p += chars[Math.floor(Math.random() * chars.length)];
    p += 'ABCDEFGHJKLMNPQRSTUVWXYZ'[Math.floor(Math.random() * 26)];
    p += String(Math.floor(Math.random() * 100)).padStart(2, '0');
    p += '@';
    p += 'abcdefghjkmnpqrstuvwxyz'[Math.floor(Math.random() * 26)];
    p += 'abcdefghjkmnpqrstuvwxyz'[Math.floor(Math.random() * 26)];
    const f = document.getElementById('passwordField');
    f.type = 'text';
    f.value = p;
    f.nextElementSibling.innerHTML = '<i class="fas fa-eye-slash"></i>';
}
function toggleAutoGen(cb) {
    const emailInput  = document.querySelector('input[name="email"]');
    const passInput   = document.querySelector('input[name="password"]');
    if (cb.checked) {
        emailInput.removeAttribute('required');
        emailInput.disabled = true;
        passInput.removeAttribute('required');
        passInput.disabled = true;
        emailInput.value = '(Généré automatiquement)';
        passInput.value = '';
        passInput.placeholder = '(Généré automatiquement)';
    } else {
        emailInput.required = true;
        emailInput.disabled = false;
        emailInput.value = '';
        passInput.required = true;
        passInput.disabled = false;
        passInput.placeholder = 'Min. 12 caractères';
    }
}
</script>
</body>
</html>
