<?php
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']);

$schoolFilter = currentSchoolId();
if (isSuperAdmin() && !empty($_GET['school_id'])) {
    $schoolFilter = (int)$_GET['school_id'];
}

// ── Sauvegarde ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_all'])) {
    verifyCsrf();
    foreach ($_POST['titulaire'] ?? [] as $classId => $tid) {
        $classId = (int)$classId;
        $tid = $tid !== '' ? (int)$tid : null;
        $pdo->prepare("UPDATE classes SET titulaire_id=? WHERE id=?")->execute([$tid, $classId]);
    }
    flashMessage('success', 'Titulaires mis à jour.');
    header('Location: class_teachers.php' . ($schoolFilter ? '?school_id='.$schoolFilter : ''));
    exit;
}

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

// ── Classes (filtrées par école via les élèves) ──
if ($schoolFilter) {
    $clStmt = $pdo->prepare("
        SELECT DISTINCT c.id, c.name, c.titulaire_id
        FROM classes c
        JOIN students s ON s.class_id = c.id
        WHERE s.school_id = ?
        ORDER BY " . getClassSortSQL('c') . "
    ");
    $clStmt->execute([$schoolFilter]);
} else {
    $clStmt = $pdo->query("
        SELECT c.id, c.name, c.titulaire_id
        FROM classes c
        ORDER BY " . getClassSortSQL('c') . "
    ");
}
$classes = $clStmt->fetchAll();

// ── Enseignants (filtrés par école) ──
if ($schoolFilter) {
    $tStmt = $pdo->prepare("
        SELECT id, first_name, last_name, school_id
        FROM teachers
        WHERE school_id = ?
        ORDER BY last_name, first_name
    ");
    $tStmt->execute([$schoolFilter]);
} else {
    $tStmt = $pdo->query("
        SELECT id, first_name, last_name, school_id
        FROM teachers
        ORDER BY last_name, first_name
    ");
}
$allTeachers = $tStmt->fetchAll();

// ── Build lookup id→name ──
$teacherNames = [];
foreach ($allTeachers as $t) {
    $teacherNames[$t['id']] = 'M. ' . strtoupper($t['last_name']) . ' ' . $t['first_name'];
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Titulaires de classe - 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">
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-user-tie"></i> Titulaires de classe'; include '../includes/topbar.php'; ?>
        <?= showFlash() ?>

        <?php if (isSuperAdmin()): ?>
        <div class="card" style="margin-bottom:1.25rem;padding:1rem 1.5rem;">
            <form method="GET" style="display:flex;gap:.75rem;align-items:end;flex-wrap:wrap;">
                <div class="form-group" style="margin:0;flex:0 0 220px;">
                    <label style="font-weight:600;color:var(--primary);font-size:.85rem;">École</label>
                    <select name="school_id" onchange="this.form.submit()" style="width:100%;padding:.5rem;border:1px solid #D1D5DB;border-radius:6px;">
                        <option value="">Toutes les écoles</option>
                        <?php foreach ($schools as $sc): ?>
                        <option value="<?= $sc['id'] ?>" <?= $schoolFilter==$sc['id']?'selected':'' ?>><?= e($sc['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <a href="class_teachers.php" class="btn-action btn-view" style="padding:.5rem 1rem;"><i class="fas fa-undo"></i> Réinitialiser</a>
            </form>
        </div>
        <?php endif; ?>

        <?php if (empty($classes)): ?>
        <div class="card" style="text-align:center;padding:3rem;color:#999;">
            <i class="fas fa-school" style="font-size:3rem;display:block;margin-bottom:1rem;"></i>
            Aucune classe trouvée pour <?= $schoolFilter ? 'cette école' : 'cette sélection' ?>.
        </div>
        <?php else: ?>
        <form method="POST">
            <?= csrfField() ?>
            <div class="card" style="overflow-x:auto;">
                <div class="card-header">
                    <span class="card-title">
                        <i class="fas fa-users"></i> Classes
                        <span style="font-weight:400;font-size:.82rem;color:#718096;margin-left:.5rem;">(<?= count($classes) ?>)</span>
                    </span>
                    <button type="submit" name="save_all" class="btn-submit" style="width:auto;padding:.5rem 1.5rem;">
                        <i class="fas fa-save"></i> Enregistrer tout
                    </button>
                </div>
                <div class="data-table-wrapper">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>Classe</th>
                            <th style="text-align:center;min-width:250px;">Titulaire actuel</th>
                            <th style="text-align:center;min-width:300px;">Nouveau titulaire</th>
                            <th style="text-align:center;width:100px;">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($classes as $cl): ?>
                        <tr>
                            <td><strong><?= e($cl['name']) ?></strong></td>
                            <td style="text-align:center;">
                                <?php if ($cl['titulaire_id'] && isset($teacherNames[$cl['titulaire_id']])): ?>
                                <span style="display:inline-block;padding:.2rem .6rem;border-radius:4px;background:#c6f6d5;color:#22543d;font-weight:600;font-size:.85rem;">
                                    <i class="fas fa-check-circle"></i> <?= e($teacherNames[$cl['titulaire_id']]) ?>
                                </span>
                                <?php else: ?>
                                <span style="color:#a0aec0;font-style:italic;">— Non défini —</span>
                                <?php endif; ?>
                            </td>
                            <td style="text-align:center;">
                                <select name="titulaire[<?= $cl['id'] ?>]"
                                        style="min-width:260px;padding:.4rem;border:1px solid #e2e8f0;border-radius:6px;font-size:.85rem;">
                                    <option value="">— Aucun —</option>
                                    <?php foreach ($allTeachers as $t):
                                        $selected = ($t['id'] == $cl['titulaire_id']) ? 'selected' : '';
                                    ?>
                                    <option value="<?= $t['id'] ?>" <?= $selected ?>>
                                        <?= e('M. ' . strtoupper($t['last_name']) . ' ' . $t['first_name']) ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                            <td style="text-align:center;">
                                <?php if ($cl['titulaire_id']): ?>
                                <button type="button" class="btn-action btn-view" style="padding:.3rem .6rem;font-size:.75rem;"
                                        onclick="if(confirm('Retirer le titulaire de cette classe ?')){this.closest('tr').querySelector('select').value='';}">
                                    <i class="fas fa-undo"></i> Retirer
                                </button>
                                <?php else: ?>
                                <span style="color:#a0aec0;">—</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                </div>
            </div>
            <div style="text-align:right;margin-top:1rem;">
                <button type="submit" name="save_all" class="btn-submit" style="width:auto;padding:.75rem 2.5rem;font-size:1rem;">
                    <i class="fas fa-save"></i> Enregistrer tous les titulaires
                </button>
            </div>
        </form>
        <?php endif; ?>
    </div>
</div>
</body>
</html>
