<?php
/**
 * Reclassement des élèves — promotion / redoublement
 */
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('students', 'edit');

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

$error = '';

// ── Traitement ────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['apply'])) {
    verifyCsrf();
    $targetYear = trim($_POST['target_year'] ?? '');
    $assignments = $_POST['class_id'] ?? [];

    if (empty($targetYear)) {
        $error = 'Année cible requise.';
    } elseif (empty($assignments)) {
        $error = 'Aucun élève sélectionné.';
    } else {
        $count = 0; $univCount = 0;
        foreach ($assignments as $studentId => $newClassId) {
            $studentId = (int)$studentId;
            $newClassId = (int)$newClassId;
            if ($studentId && $newClassId > 0) {
                $chk = $pdo->prepare("SELECT id FROM classes WHERE id=?");
                $chk->execute([$newClassId]);
                if ($chk->fetch()) {
                    $pdo->prepare("UPDATE students SET class_id=? WHERE id=?")->execute([$newClassId, $studentId]);
                    $count++;
                }
            } elseif ($studentId && $newClassId === -1) {
                $pdo->prepare("UPDATE students SET class_id=NULL WHERE id=?")->execute([$studentId]);
                $univCount++;
            }
        }
        $msg = '';
        if ($count) $msg = "$count élève(s) reclassé(s)";
        if ($univCount) $msg .= ($msg ? ', ' : '') . "$univCount élève(s) passé(s) en Université";
        flashMessage('success', $msg ?: 'Aucune modification effectuée.');
        header('Location: promotion.php?' . http_build_query(['source_year'=>$_GET['source_year']??$defaultAy,'target_year'=>$_GET['target_year']??$targetYear,'school_id'=>$_GET['school_id']??null]));
        exit;
    }
}

// ── Données ───────────────────────────────────────────────────────────────────

$years = $pdo->query("SELECT DISTINCT year FROM academic_years WHERE school_id=" . (int)($schoolFilter ?: 0))->fetchAll(PDO::FETCH_COLUMN);
if (empty($years)) {
    $years = $pdo->query("SELECT DISTINCT year FROM academic_years ORDER BY year DESC")->fetchAll(PDO::FETCH_COLUMN);
}
if (empty($years)) { $years = []; }
$years = array_unique(array_merge($years, [date('Y') . '-' . (date('Y')+1)]));
$defaultAy = getDefaultAcademicYear($pdo, $schoolFilter);
$sourceYear = $_GET['source_year'] ?? $defaultAy;
$nextAy = explode('-', $defaultAy);
$targetYear = $_GET['target_year'] ?? (count($nextAy)==2 ? ((int)$nextAy[0]+1).'-'.((int)$nextAy[1]+1) : '2026-2027');

$stmt = $pdo->prepare("
    SELECT c.id, c.name, c.level
    FROM classes c
    WHERE c.academic_year = ?
    ORDER BY " . getClassSortSQL('c') . "
");
$stmt->execute([$sourceYear]);
$sourceClasses = $stmt->fetchAll();

$stmt2 = $pdo->prepare("
    SELECT c.id, c.name, c.level
    FROM classes c
    WHERE c.academic_year = ?
    ORDER BY " . getClassSortSQL('c') . "
");
$stmt2->execute([$targetYear]);
$targetClasses = $stmt2->fetchAll();

// Regrouper les classes cibles par niveau
$targetByLevel = [];
foreach ($targetClasses as $tc) {
    $targetByLevel[$tc['level']][] = $tc;
}

// Niveaux ordonnés pour suggestion de promotion
$levelOrder = ['6ème','5ème','4ème','3ème','2nde','1ère','Tle'];
function nextLevel(string $current): ?string {
    global $levelOrder;
    $idx = array_search($current, $levelOrder);
    if ($idx !== false && isset($levelOrder[$idx + 1])) {
        return $levelOrder[$idx + 1];
    }
    return null;
}

// Regrouper les élèves par classe source
$studentsByClass = [];
foreach ($sourceClasses as $sc) {
    $sid = $sc['id'];
    $studentsByClass[$sid] = [
        'class' => $sc,
        'students' => [],
    ];
}

if (!empty($sourceClasses)) {
    $classIds = array_column($sourceClasses, 'id');
    $placeholders = implode(',', array_fill(0, count($classIds), '?'));
    $params = $classIds;
    $schoolFilterSql = '';
    if ($schoolFilter) {
        $schoolFilterSql = 'AND s.school_id=?';
        $params[] = $schoolFilter;
    }
    $stmt = $pdo->prepare("
        SELECT s.id, s.first_name, s.last_name, s.class_id
        FROM students s
        WHERE s.class_id IN ($placeholders) $schoolFilterSql
        ORDER BY s.last_name, s.first_name
    ");
    $stmt->execute($params);
    $students = $stmt->fetchAll();

    foreach ($students as $st) {
        $studentsByClass[$st['class_id']]['students'][] = $st;
    }
}

// Filtrer les classes sans élèves
$studentsByClass = array_filter($studentsByClass, fn($g) => !empty($g['students']));

// Écoles (pour filtre super_admin)
$schools = $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>Reclassement des élèves - 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>
        .promo-class-group {
            background: #fff;
            border-radius: 12px;
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
            overflow: hidden;
        }
        .promo-class-header {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: .75rem 1.25rem;
            font-weight: 700;
            font-size: 1rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .promo-class-header .batch-actions {
            display: flex;
            gap: .5rem;
        }
        .promo-class-header .batch-actions button {
            font-size: .75rem;
            padding: .3rem .6rem;
            border: 1px solid rgba(255,255,255,.4);
            background: rgba(255,255,255,.15);
            color: white;
            border-radius: 6px;
            cursor: pointer;
            transition: background .2s;
        }
        .promo-class-header .batch-actions button:hover {
            background: rgba(255,255,255,.3);
        }
        .promo-table {
            width: 100%;
            border-collapse: collapse;
        }
        .promo-table th {
            background: #f7fafc;
            padding: .6rem .75rem;
            font-size: .75rem;
            text-transform: uppercase;
            letter-spacing: .5px;
            color: #718096;
            text-align: left;
            border-bottom: 2px solid #e2e8f0;
        }
        .promo-table td {
            padding: .5rem .75rem;
            font-size: .85rem;
            border-bottom: 1px solid #f0f0f0;
            vertical-align: middle;
        }
        .promo-table tr:last-child td {
            border-bottom: none;
        }
        .promo-table select {
            padding: .35rem .5rem;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            font-size: .8rem;
            background: #f7fafc;
            min-width: 130px;
        }
        .promo-table select.promote { border-color: #38a169; background: #f0fff4; }
        .promo-table select.repeat  { border-color: #ed8936; background: #fffaf0; }
        .student-name {
            font-weight: 600;
            color: #2d3748;
        }
        .promo-summary {
            display: flex;
            gap: 1.5rem;
            flex-wrap: wrap;
            margin-bottom: 1rem;
            font-size: .85rem;
        }
        .promo-summary span {
            background: #edf2f7;
            padding: .4rem .8rem;
            border-radius: 8px;
        }
        .promo-summary .count-promote { background: #c6f6d5; color: #22543d; }
        .promo-summary .count-repeat  { background: #fefcbf; color: #744210; }
        @media (max-width: 768px) {
            .card-header { flex-direction: column; align-items: flex-start; gap: .5rem; }
            .promo-summary { flex-wrap: wrap; gap: .4rem; }
        }
    </style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-arrows-alt"></i> Reclassement des élèves'; include '../includes/topbar.php'; ?>
        <?= showFlash() ?>
        <?php if ($error): ?><div class="error-message"><?= e($error) ?></div><?php endif; ?>

        <!-- Filtres -->
        <div class="card no-print">
            <div class="card-header"><span class="card-title"><i class="fas fa-filter"></i> Période de reclassement</span></div>
            <form method="GET" style="display:flex;gap:.75rem;flex-wrap:wrap;align-items:end;padding:.5rem 0;">
                <?php if (isSuperAdmin()): ?>
                <div class="form-group" style="margin:0;">
                    <label>École</label>
                    <select name="school_id" onchange="this.form.submit()">
                        <option value="">Toutes</option>
                        <?php foreach ($schools as $sc): ?>
                        <option value="<?= $sc['id'] ?>" <?= $schoolFilter==$sc['id']?'selected':'' ?>><?= e($sc['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <div class="form-group" style="margin:0;">
                    <label>Année source</label>
                    <select name="source_year" onchange="this.form.submit()">
                        <?php foreach ($years as $y): ?>
                        <option value="<?= e($y) ?>" <?= $y===$sourceYear?'selected':'' ?>><?= e($y) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group" style="margin:0;">
                    <label>Année cible</label>
                    <select name="target_year" onchange="this.form.submit()">
                        <?php foreach ($years as $y): ?>
                        <option value="<?= e($y) ?>" <?= $y===$targetYear?'selected':'' ?>><?= e($y) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <button type="submit" class="btn-action btn-view"><i class="fas fa-search"></i> Charger</button>
            </form>
        </div>

        <?php if (empty($studentsByClass)): ?>
        <div class="card" style="text-align:center;padding:3rem;color:#999;">
            <i class="fas fa-users" style="font-size:3rem;margin-bottom:1rem;"></i><br>
            Aucun élève trouvé pour l'année source sélectionnée.
        </div>
        <?php else: ?>
        <!-- Résumé -->
        <?php
        $totalStudents = 0;
        foreach ($studentsByClass as $g) { $totalStudents += count($g['students']); }
        ?>
        <div class="promo-summary">
            <span><strong><?= $totalStudents ?></strong> élève(s) · <strong><?= count($studentsByClass) ?></strong> classe(s)</span>
            <span><?= $sourceYear ?> → <?= $targetYear ?></span>
        </div>

        <!-- Formulaire de reclassement -->
        <form method="POST">
            <?= csrfField() ?>
            <input type="hidden" name="target_year" value="<?= e($targetYear) ?>">

            <?php foreach ($studentsByClass as $groupId => $group): 
                $sc = $group['class'];
                $nextLvl = nextLevel($sc['level']);
            ?>
            <div class="promo-class-group">
                <div class="promo-class-header">
                    <span><i class="fas fa-school"></i> <?= e($sc['name']) ?> (<?= e($sc['level']) ?>)</span>
                    <div class="batch-actions">
                        <button type="button" onclick="batchSelect(<?= $groupId ?>, 'promote')" title="Promouvoir tous au niveau supérieur"><i class="fas fa-arrow-up"></i> Promouvoir</button>
                        <button type="button" onclick="batchSelect(<?= $groupId ?>, 'repeat')" title="Faire redoubler tous"><i class="fas fa-undo"></i> Redoubler</button>
                    </div>
                </div>
                <div style="overflow-x:auto;">
                <table class="promo-table">
                    <thead>
                        <tr>
                            <th style="width:40%;">Élève</th>
                            <th style="width:30%;">Classe actuelle</th>
                            <th style="width:30%;">Nouvelle classe <small style="font-weight:400;color:#a0aec0;">(<?= $targetYear ?>)</small></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $manualLevels = ['3ème', 'Tle'];
                        $isManual = in_array($sc['level'], $manualLevels);
                        foreach ($group['students'] as $st): 
                            // Suggestion : promotion au niveau supérieur si possible, sinon redoublement
                            $suggestedLevel = $nextLvl ?? $sc['level'];
                            $suggestedClasses = $targetByLevel[$suggestedLevel] ?? [];
                            // Classe de redoublement (même niveau dans année cible)
                            $repeatClasses = $targetByLevel[$sc['level']] ?? [];
                            $allOptions = array_merge($suggestedClasses, $repeatClasses);
                            // Déduplication par id
                            $seen = [];
                            $uniqueOptions = [];
                            foreach ($allOptions as $opt) {
                                if (!isset($seen[$opt['id']])) {
                                    $seen[$opt['id']] = true;
                                    $uniqueOptions[] = $opt;
                                }
                            }
                            $defaultId = !empty($suggestedClasses) ? $suggestedClasses[0]['id'] : (!empty($repeatClasses) ? $repeatClasses[0]['id'] : 0);
                        ?>
                        <tr>
                            <td><span class="student-name"><?= e($st['last_name']) ?> <?= e($st['first_name']) ?></span></td>
                            <td><?= e($sc['name']) ?></td>
                            <td>
                                <select name="class_id[<?= $st['id'] ?>]" class="<?= !empty($suggestedClasses) && $defaultId === $suggestedClasses[0]['id'] ? 'promote' : 'repeat' ?>">
                                    <option value="">— Non reclassé —</option>
                                    <?php if (!empty($suggestedClasses)): ?>
                                    <optgroup label="Promotion (<?= $suggestedLevel ?>)">
                                        <?php foreach ($suggestedClasses as $tc): ?>
                                        <option value="<?= $tc['id'] ?>" <?= $tc['id']===$defaultId?'selected':'' ?>><?= e($tc['name']) ?></option>
                                        <?php endforeach; ?>
                                    </optgroup>
                                    <?php endif; ?>
                                    <?php if (!empty($repeatClasses)): ?>
                                    <optgroup label="Redoublement (<?= $sc['level'] ?>)">
                                        <?php foreach ($repeatClasses as $tc): ?>
                                        <option value="<?= $tc['id'] ?>"><?= e($tc['name']) ?></option>
                                        <?php endforeach; ?>
                                    </optgroup>
                                    <?php endif; ?>
                                    <?php if ($isManual): ?>
                                    <?php if ($sc['level'] === 'Tle'): ?>
                                    <optgroup label="Fin de cycle">
                                        <option value="-1">🎓 Université</option>
                                    </optgroup>
                                    <?php endif; ?>
                                    <optgroup label="Autres classes">
                                        <?php foreach ($targetClasses as $tc): 
                                            if (!isset($seen[$tc['id']])): $seen[$tc['id']] = true; ?>
                                        <option value="<?= $tc['id'] ?>"><?= e($tc['name']) ?> (<?= e($tc['level']) ?>)</option>
                                        <?php endif; endforeach; ?>
                                    </optgroup>
                                    <?php endif; ?>
                                </select>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                </div>
            </div>
            <?php endforeach; ?>

            <div style="display:flex;gap:.75rem;align-items:center;" class="no-print">
                <button type="submit" name="apply" class="btn-submit" style="font-size:1rem;padding:.75rem 2rem;">
                    <i class="fas fa-check-double"></i> Appliquer le reclassement
                </button>
                <span style="color:#718096;font-size:.85rem;">Les élèves sans sélection seront ignorés.</span>
            </div>
        </form>
        <?php endif; ?>
    </div>
</div>

<script>
function batchSelect(classGroupId, action) {
    const prefix = 'class_id[';
    const btn = event.target.closest('button');
    const container = btn.closest('.promo-class-group');
    const groupSelects = container.querySelectorAll('select[name^="' + prefix + '"]');
    groupSelects.forEach(function(sel) {
        if (action === 'repeat') {
            const optgroup = sel.querySelector('optgroup[label^="Redoublement"]');
            if (optgroup && optgroup.options.length > 0) {
                sel.value = optgroup.options[0].value;
            }
        } else if (action === 'promote') {
            const optgroup = sel.querySelector('optgroup[label^="Promotion"]');
            if (optgroup && optgroup.options.length > 0) {
                sel.value = optgroup.options[0].value;
            }
        }
        updateSelectClass(sel);
    });
}

function updateSelectClass(sel) {
    sel.classList.remove('promote', 'repeat');
    if (sel.value) {
        const opt = sel.querySelector('option[value="' + sel.value + '"]');
        if (opt) {
            const parent = opt.closest('optgroup');
            if (parent) {
                if (parent.label.startsWith('Promotion')) {
                    sel.classList.add('promote');
                } else if (parent.label.startsWith('Redoublement')) {
                    sel.classList.add('repeat');
                }
            }
        }
    }
}

// Attach change handlers
document.addEventListener('change', function(e) {
    if (e.target.matches('select[name^="class_id["]')) {
        updateSelectClass(e.target);
    }
});
</script>
</body>
</html>
