<?php
/**
 * Gestion des programmations (années scolaires & périodes) — version moderne
 * Persistance globale de l'année, de la période et de l'école via session.
 */
require_once '../config/database.php';
require_once '../includes/auth_check.php';
require_once '../includes/functions.php';
header('Content-Type: text/html; charset=utf-8');

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

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

$schoolFilter = currentSchoolId();

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

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

// Valeurs de session pour les filtres
$sessionYear   = $_SESSION['active_academic_year'] ?? '';
$sessionPeriod = getActivePeriod();
$sessionSchool = $_SESSION['active_school_filter'] ?? $schoolFilter;

// ── Suppression d'une programmation (période) ──
if ($action === 'delete' && $id) {
    verifyCsrf();
    $pdo->prepare("DELETE FROM grading_periods WHERE id=? AND school_id=COALESCE(?,school_id)")
        ->execute([$id, $schoolFilter]);
    flashMessage('success', 'Programmation supprimée.');
    header('Location: academic_years.php'); exit;
}

// ── Suppression multiple ──
if (isset($_POST['bulk_delete'])) {
    verifyCsrf();
    $ids = isset($_POST['item_ids']) ? array_map('intval', (array)$_POST['item_ids']) : [];
    $count = 0;
    foreach ($ids as $pid) {
        $pdo->prepare("DELETE FROM grading_periods WHERE id=? AND school_id=COALESCE(?,school_id)")
            ->execute([$pid, $schoolFilter]);
        $count++;
    }
    flashMessage('success', "$count programmation(s) supprimée(s).");
    header('Location: academic_years.php'); exit;
}

// ── Ajout / Modification d'une programmation ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_programmation'])) {
    verifyCsrf();
    $pid           = (int)($_POST['item_id'] ?? 0);
    $school_id     = (int)($_POST['school_id'] ?? $schoolFilter);
    $academic_year = trim($_POST['academic_year'] ?? $sessionYear);
    $period_number = (int)($_POST['period_number'] ?? 1);
    $label         = trim($_POST['label'] ?? '');
    $start_date    = $_POST['start_date'] ?? '';
    $end_date      = $_POST['end_date'] ?? '';
    $is_open       = isset($_POST['is_open']) ? 1 : 0;

    if (empty($academic_year) || empty($start_date) || empty($end_date)) {
        $error = 'Année, date début et date fin sont requis.';
    } elseif ($period_number < 1 || $period_number > 3) {
        $error = 'Numéro de période invalide.';
    } elseif ($start_date > $end_date) {
        $error = 'La date de fin doit être postérieure à la date de début.';
    } else {
        if (!$label) {
            $label = match($period_number) {1=>'1er Trimestre',2=>'2ème Trimestre',3=>'3ème Trimestre',default=>"Trimestre $period_number"};
        }
        if ($pid) {
            $pdo->prepare("UPDATE grading_periods SET school_id=?,academic_year=?,period_type='trimestre',period_number=?,label=?,start_date=?,end_date=?,is_open=? WHERE id=?")
                ->execute([$school_id,$academic_year,$period_number,$label,$start_date,$end_date,$is_open,$pid]);
            flashMessage('success', 'Programmation mise à jour.');
        } else {
            try {
                $pdo->prepare("INSERT INTO grading_periods (school_id,academic_year,period_type,period_number,label,start_date,end_date,is_open) VALUES (?,?,'trimestre',?,?,?,?,?)")
                    ->execute([$school_id,$academic_year,$period_number,$label,$start_date,$end_date,$is_open]);
                flashMessage('success', 'Programmation ajoutée.');
            } catch (PDOException $e) {
                $error = $e->getCode() == 23000 ? 'Cette programmation existe déjà.' : 'Erreur : ' . $e->getMessage();
            }
        }
        if (empty($error)) {
            header('Location: academic_years.php'); exit;
        }
    }
}

// ── Édition ──
$editItem = null;
if ($action === 'edit' && $id) {
    $st = $pdo->prepare("SELECT gp.*, s.name AS school_name FROM grading_periods gp JOIN schools s ON gp.school_id=s.id WHERE gp.id=? AND gp.school_id=COALESCE(?,gp.school_id)");
    $st->execute([$id, $schoolFilter]);
    $editItem = $st->fetch();
    if (!$editItem) { flashMessage('error','Programmation introuvable.'); header('Location: academic_years.php'); exit; }
}

// ── Liste des programmations ──
$where = "1=1"; $params = [];
if ($schoolFilter) {
    $where .= " AND gp.school_id=?";
    $params[] = $schoolFilter;
}
if ($sessionYear) {
    $where .= " AND gp.academic_year=?";
    $params[] = $sessionYear;
}
if ($sessionSchool && !$schoolFilter) {
    $where .= " AND gp.school_id=?";
    $params[] = $sessionSchool;
}

$programmations = $pdo->prepare("
    SELECT gp.*, s.name AS school_name
    FROM grading_periods gp
    JOIN schools s ON gp.school_id = s.id
    WHERE $where
    ORDER BY gp.academic_year DESC, gp.period_number
");
$programmations->execute($params);
$programmations = $programmations->fetchAll();

// ── Données pour les listes déroulantes ──
$ecoles = $pdo->query("SELECT id, name FROM schools ORDER BY name")->fetchAll();
$academicYears = $pdo->query("SELECT DISTINCT year FROM academic_years WHERE school_id=" . (int)($schoolFilter?:0) . " ORDER BY year DESC")->fetchAll(PDO::FETCH_COLUMN);
if (empty($academicYears)) {
    $academicYears = $pdo->query("SELECT DISTINCT year FROM academic_years ORDER BY year DESC")->fetchAll(PDO::FETCH_COLUMN);
}
$yearsPool = [];
for ($y = 2015; $y <= 2030; $y++) {
    $yearsPool[] = $y . '-' . ($y + 1);
}
if (empty($academicYears)) $academicYears = $yearsPool;
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Programmations - Nukunu Mofiala</title>
<link rel="stylesheet" href="../assets/css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
  :root {
    --primary: #1F4E79;
    --accent: #2E75B6;
    --light: #D6E4F0;
  }

  .prog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.5rem;
    flex-wrap: wrap;
    gap: 1rem;
  }
  .prog-header h1 {
    font-family: Georgia, serif;
    color: var(--primary);
    font-size: 1.6rem;
  }
  .prog-header p {
    color: #666;
    font-size: .9rem;
  }

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

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

  .prog-table {
    width: 100%;
    border-collapse: collapse;
  }
  .prog-table thead {
    background: var(--primary);
    color: white;
  }
  .prog-table th {
    padding: .7rem 1rem;
    text-align: left;
    font-weight: 600;
    font-size: .78rem;
    text-transform: uppercase;
    letter-spacing: .4px;
  }
  .prog-table td {
    padding: .7rem 1rem;
    border-bottom: 1px solid #E5E7EB;
    font-size: .85rem;
    vertical-align: middle;
  }
  .prog-table tbody tr:hover {
    background: #F9FAFB;
  }
  .prog-table tbody tr.selected {
    background: #EFF6FF;
  }

  .badge-green { background: #D1FAE5; color: #065F46; }
  .badge-yellow { background: #FEF3C7; color: #92400E; }
  .badge-red { background: #FEE2E2; color: #991B1B; }

  .badge-p {
    display: inline-block;
    padding: 3px 8px;
    border-radius: 20px;
    font-size: .7rem;
    font-weight: 600;
  }

  .actions-footer {
    display: flex;
    justify-content: flex-end;
    gap: .75rem;
    margin-top: 1.25rem;
    flex-wrap: wrap;
  }

  .toast-container {
    position: fixed;
    bottom: 30px;
    right: 30px;
    z-index: 2000;
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  .toast {
    background: white;
    padding: 12px 18px;
    border-radius: 8px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.15);
    display: flex;
    align-items: center;
    gap: 10px;
    animation: slideIn .3s ease;
    border-left: 4px solid var(--primary);
    font-size: .9rem;
  }
  .toast-success { border-left-color: #10B981; }
  .toast-error { border-left-color: #EF4444; }
  @keyframes slideIn {
    from { transform: translateX(100%); opacity: 0; }
    to { transform: translateX(0); opacity: 1; }
  }

  .modal-overlay {
    display: none;
    position: fixed;
    top: 0; left: 0; right: 0; bottom: 0;
    background: rgba(0,0,0,0.4);
    z-index: 1500;
    align-items: center;
    justify-content: center;
  }
  .modal-overlay.open {
    display: flex;
  }
  .modal-box {
    background: white;
    border-radius: 12px;
    padding: 2rem;
    width: 90%;
    max-width: 540px;
    max-height: 90vh;
    overflow-y: auto;
    box-shadow: 0 10px 40px rgba(0,0,0,0.2);
  }
  .modal-box h2 {
    font-family: Georgia, serif;
    color: var(--primary);
    font-size: 1.2rem;
    margin-bottom: 1.25rem;
    display: flex;
    align-items: center;
    gap: .5rem;
  }
  .modal-box .form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: .75rem;
  }
  .modal-box .form-grid .full { grid-column: 1 / -1; }
  .modal-box .form-group { margin: 0; }
  .modal-box .form-group label { font-size: .8rem; }
  .modal-box .modal-actions {
    display: flex;
    gap: .75rem;
    margin-top: 1.25rem;
    justify-content: flex-end;
  }

  .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-warning { background: #F59E0B; color: white; }
  .btn-warning:hover { background: #D97706; }
  .btn-danger { background: #DC2626; color: white; }
  .btn-danger:hover { background: #B91C1C; }
  .btn-light { background: #E5E7EB; color: #374151; }
  .btn-light:hover { background: #D1D5DB; }

  @media (max-width: 768px) {
    .filters-row { flex-direction: column; }
    .filter-group { min-width: 100%; }
    .prog-table th, .prog-table td { padding: .5rem .6rem; font-size: .78rem; }
    .actions-footer { flex-direction: column; }
    .actions-footer .btn { width: 100%; justify-content: center; }
    .modal-box .form-grid { grid-template-columns: 1fr; }
  }
</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-calendar-alt"></i> Programmations'; include '../includes/topbar.php'; ?>

        <?php if ($error): ?>
        <script>document.addEventListener('DOMContentLoaded',function(){showToast(<?= json_encode($error) ?>,'error');});</script>
        <?php endif; ?>
        <?php
        // Supprimer le flash classique après l'avoir passé au toast
        $__flash = $_SESSION['flash'] ?? null;
        unset($_SESSION['flash']);
        ?>

        <!-- ═══ Header ═══ -->
        <div class="prog-header">
            <div>
                <h1><i class="fas fa-calendar-alt" style="color:var(--primary);"></i> Programmations</h1>
                <p>Gérez les années, périodes et écoles actives</p>
            </div>
            <div style="display:flex;gap:.5rem;flex-wrap:wrap;">
                <button class="btn btn-primary" onclick="openModal('add')">
                    <i class="fas fa-plus"></i> Ajouter une programmation
                </button>
                <?php if (isSuperAdmin()): ?>
                <a href="?action=manage_years" class="btn" style="background:white;border:1px solid #D1D5DB;color:var(--primary);">
                    <i class="fas fa-cog"></i> Gérer les années
                </a>
                <?php endif; ?>
            </div>
        </div>

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

        <!-- ═══ Tableau ═══ -->
        <div class="table-card">
            <div class="tc-header">
                <div class="tc-title"><i class="fas fa-list"></i> Liste des programmations</div>
                <span class="tc-count"><?= count($programmations) ?> programmation(s)</span>
            </div>
            <?php if (empty($programmations)): ?>
            <div style="text-align:center;padding:3rem 1rem;color:#9CA3AF;">
                <div style="font-size:2.5rem;margin-bottom:.5rem;"><i class="far fa-calendar-alt"></i></div>
                <p>Aucune programmation trouvée.</p>
                <button class="btn btn-primary" style="margin-top:1rem;" onclick="openModal('add')">Créer une programmation</button>
            </div>
            <?php else: ?>
            <form method="post" id="bulkForm">
            <input type="hidden" name="bulk_delete" value="1">
            <?= csrfField() ?>
            <table class="prog-table">
                <thead>
                    <tr>
                        <th style="width:36px;"><input type="checkbox" id="selectAll" onchange="toggleAll(this)"></th>
                        <th>Année scolaire</th>
                        <th>Période</th>
                        <th>École</th>
                        <th>Date début</th>
                        <th>Date fin</th>
                        <th>Statut</th>
                        <th style="width:80px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($programmations as $p):
                        $isOpen = (bool)$p['is_open'];
                        $now = date('Y-m-d');
                        if ($isOpen && $now >= $p['start_date'] && $now <= $p['end_date']) {
                            $statut = 'active'; $label = 'Active';
                        } elseif ($isOpen && $now < $p['start_date']) {
                            $statut = 'planifiee'; $label = 'Planifiée';
                        } else {
                            $statut = 'cloturee'; $label = 'Clôturée';
                        }
                    ?>
                    <tr onclick="toggleRow(this)">
                        <td class="checkbox-wrapper" onclick="event.stopPropagation()">
                            <input type="checkbox" name="item_ids[]" value="<?= $p['id'] ?>" class="row-check">
                        </td>
                        <td><strong><?= e($p['academic_year']) ?></strong></td>
                        <td><?= e($p['label']) ?></td>
                        <td><?= e($p['school_name']) ?></td>
                        <td><?= formatDate($p['start_date']) ?></td>
                        <td><?= formatDate($p['end_date']) ?></td>
                        <td><span class="badge-p badge-<?= $statut === 'active' ? 'green' : ($statut === 'planifiee' ? 'yellow' : 'red') ?>"><?= $label ?></span></td>
                        <td>
                            <a href="?action=edit&id=<?= $p['id'] ?>" class="btn btn-light" style="padding:.3rem .6rem;font-size:.75rem;" title="Modifier"><i class="fas fa-edit"></i></a>
                            <a href="?action=delete&id=<?= $p['id'] ?>&csrf_token=<?= csrfToken() ?>" class="btn btn-danger" style="padding:.3rem .6rem;font-size:.75rem;" title="Supprimer" onclick="return confirm('Supprimer cette programmation ?')"><i class="fas fa-trash"></i></a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            </form>
            <div style="padding:.75rem 1.25rem;border-top:1px solid #E5E7EB;">
                <button class="btn btn-danger" onclick="bulkDelete()" style="font-size:.78rem;padding:.4rem 1rem;">
                    <i class="fas fa-trash-alt"></i> Supprimer la sélection
                </button>
            </div>
            <?php endif; ?>
        </div>

        <?php if (!empty($programmations)): ?>
        <div class="actions-footer">
            <button class="btn btn-warning" onclick="editSelected()">
                <i class="fas fa-edit"></i> Modifier la sélection
            </button>
            <button class="btn btn-danger" onclick="bulkDelete()">
                <i class="fas fa-trash-alt"></i> Supprimer la sélection
            </button>
        </div>
        <?php endif; ?>

        <?php if ($action === 'manage_years' || $action === 'manage_year_edit' || $action === 'manage_year_add'): ?>
        <!-- ═══ Gestion des années scolaires ═══ -->
        <div style="margin-top:2rem;">
        <?php
        // Year CRUD
        $yearAction = $_GET['ya'] ?? 'list';
        $yearId     = isset($_GET['yid']) ? (int)$_GET['yid'] : null;
        $yearError  = '';

        // Delete year
        if ($yearAction === 'delete' && $yearId) {
            verifyCsrf();
            $chk = $pdo->prepare("SELECT is_current FROM academic_years WHERE id=?");
            $chk->execute([$yearId]); $row = $chk->fetch();
            if ($row && !$row['is_current']) {
                $pdo->prepare("DELETE FROM academic_years WHERE id=?")->execute([$yearId]);
                flashMessage('success', 'Année scolaire supprimée.');
            } else {
                flashMessage('error', 'Impossible de supprimer cette année.');
            }
            header('Location: academic_years.php?action=manage_years'); exit;
        }

        // Set current year
        if ($yearAction === 'set_current' && $yearId) {
            verifyCsrf();
            $sid = $pdo->prepare("SELECT school_id FROM academic_years WHERE id=?");
            $sid->execute([$yearId]); $sId = $sid->fetchColumn();
            if ($sId) {
                $pdo->prepare("UPDATE academic_years SET is_current=0 WHERE school_id=?")->execute([$sId]);
                $pdo->prepare("UPDATE academic_years SET is_current=1 WHERE id=?")->execute([$yearId]);
                $yr = $pdo->prepare("SELECT year FROM academic_years WHERE id=?");
                $yr->execute([$yearId]); $y = $yr->fetchColumn();
                if ($y) $_SESSION['active_academic_year'] = $y;
                flashMessage('success', 'Année courante mise à jour.');
            }
            header('Location: academic_years.php?action=manage_years'); exit;
        }

        // Save year
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_year'])) {
            verifyCsrf();
            $school_id  = (int)($_POST['school_id'] ?? $schoolFilter);
            $year       = trim($_POST['year'] ?? '');
            $label      = trim($_POST['label'] ?? '');
            $sd         = $_POST['start_date'] ?? '';
            $ed         = $_POST['end_date'] ?? '';
            $is_current = isset($_POST['is_current']) ? 1 : 0;
            $is_active  = isset($_POST['is_active']) ? 1 : 0;

            if (empty($year)) $yearError = 'L\'année est requise.';
            elseif (!preg_match('/^\d{4}-\d{4}$/', $year)) $yearError = 'Format attendu : ex. 2025-2026';

            if (empty($yearError)) {
                $sd = $sd ?: null; $ed = $ed ?: null;
                if ($yearId) {
                    $pdo->prepare("UPDATE academic_years SET school_id=?,year=?,label=?,start_date=?,end_date=?,is_active=? WHERE id=?")
                        ->execute([$school_id, $year, $label, $sd, $ed, $is_active, $yearId]);
                    if ($is_current) {
                        $pdo->prepare("UPDATE academic_years SET is_current=0 WHERE school_id=? AND id!=?")->execute([$school_id, $yearId]);
                        $pdo->prepare("UPDATE academic_years SET is_current=1 WHERE id=?")->execute([$yearId]);
                        $_SESSION['active_academic_year'] = $year;
                    }
                    flashMessage('success', 'Année mise à jour.');
                } else {
                    $dup = $pdo->prepare("SELECT id FROM academic_years WHERE school_id=? AND year=?");
                    $dup->execute([$school_id, $year]);
                    if ($dup->fetch()) {
                        $yearError = "L'année $year existe déjà.";
                    } else {
                        if ($is_current) $pdo->prepare("UPDATE academic_years SET is_current=0 WHERE school_id=?")->execute([$school_id]);
                        $pdo->prepare("INSERT INTO academic_years (school_id,year,label,start_date,end_date,is_current,is_active) VALUES (?,?,?,?,?,?,?)")
                            ->execute([$school_id, $year, $label, $sd, $ed, $is_current, $is_active]);
                        if ($is_current) $_SESSION['active_academic_year'] = $year;
                        flashMessage('success', 'Année ajoutée.');
                    }
                }
                if (empty($yearError)) { header('Location: academic_years.php?action=manage_years'); exit; }
            }
        }

        $editYear = null;
        if ($yearAction === 'edit' && $yearId) {
            $st = $pdo->prepare("SELECT * FROM academic_years WHERE id=?");
            $st->execute([$yearId]); $editYear = $st->fetch();
        }

        // Load years
        if ($schoolFilter) {
            $yList = $pdo->prepare("SELECT ay.*, s.name AS school_name FROM academic_years ay JOIN schools s ON ay.school_id=s.id WHERE ay.school_id=? ORDER BY ay.year DESC");
            $yList->execute([$schoolFilter]);
        } else {
            $yList = $pdo->query("SELECT ay.*, s.name AS school_name FROM academic_years ay JOIN schools s ON ay.school_id=s.id ORDER BY s.name, ay.year DESC");
        }
        $allYears = $yList->fetchAll();
        ?>
        <?php if ($yearError): ?><div class="error-message"><?= e($yearError) ?></div><?php endif; ?>

        <div class="table-card">
            <div class="tc-header">
                <div class="tc-title"><i class="fas fa-calendar-alt"></i> Années scolaires</div>
                <div>
                    <a href="?action=manage_year_add" class="btn btn-primary" style="padding:.4rem 1rem;font-size:.78rem;">
                        <i class="fas fa-plus"></i> Ajouter
                    </a>
                    <a href="academic_years.php" class="btn btn-light" style="padding:.4rem 1rem;font-size:.78rem;">
                        <i class="fas fa-arrow-left"></i> Retour
                    </a>
                </div>
            </div>
            <table class="prog-table">
                <thead><tr>
                    <th>Année</th><th>Libellé</th><th>Début</th><th>Fin</th><th>Statut</th><th>Actions</th>
                </tr></thead>
                <tbody>
                    <?php foreach ($allYears as $ay): ?>
                    <tr>
                        <td><strong><?= e($ay['year']) ?></strong></td>
                        <td><?= e($ay['label'] ?? '—') ?></td>
                        <td><?= $ay['start_date'] ? formatDate($ay['start_date']) : '—' ?></td>
                        <td><?= $ay['end_date'] ? formatDate($ay['end_date']) : '—' ?></td>
                        <td>
                            <?php if ($ay['is_current']): ?>
                            <span class="badge-p badge-green"><i class="fas fa-star"></i> En cours</span>
                            <?php elseif ($ay['is_active']): ?>
                            <span class="badge-p badge-yellow">Active</span>
                            <?php else: ?>
                            <span class="badge-p badge-red">Archivée</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <a href="?action=manage_year_edit&yid=<?= $ay['id'] ?>" class="btn btn-light" style="padding:.3rem .6rem;font-size:.75rem;"><i class="fas fa-edit"></i></a>
                            <?php if (!$ay['is_current']): ?>
                            <a href="?action=manage_years&ya=set_current&yid=<?= $ay['id'] ?>&csrf_token=<?= csrfToken() ?>" class="btn btn-warning" style="padding:.3rem .6rem;font-size:.75rem;" title="Définir comme année courante"><i class="fas fa-star"></i></a>
                            <a href="?action=manage_years&ya=delete&yid=<?= $ay['id'] ?>&csrf_token=<?= csrfToken() ?>" class="btn btn-danger" style="padding:.3rem .6rem;font-size:.75rem;" onclick="return confirm('Supprimer ?')"><i class="fas fa-trash"></i></a>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        </div>
        <?php endif; ?>

        <?php if ($action === 'manage_year_add' || $action === 'manage_year_edit'): ?>
        <div class="modal-overlay open">
            <div class="modal-box">
                <h2><i class="fas fa-<?= $editYear ? 'edit' : 'plus-circle' ?>"></i> <?= $editYear ? 'Modifier' : 'Ajouter' ?> une année</h2>
                <form method="post" action="?action=manage_years<?= $editYear ? '&ya=edit&yid='.$editYear['id'] : '&ya=add' ?>">
                    <?= csrfField() ?>
                    <input type="hidden" name="save_year" value="1">
                    <div class="form-grid">
                        <div class="form-group full">
                            <label>École</label>
                            <select name="school_id" required <?= $schoolFilter ? 'disabled' : '' ?>>
                                <?php foreach ($ecoles as $sc): ?>
                                <option value="<?= $sc['id'] ?>" <?= ($editYear['school_id'] ?? $schoolFilter) == $sc['id'] ? 'selected' : '' ?>><?= e($sc['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                            <?php if ($schoolFilter): ?><input type="hidden" name="school_id" value="<?= $schoolFilter ?>"><?php endif; ?>
                        </div>
                        <div class="form-group">
                            <label>Année scolaire</label>
                            <select name="year" required>
                                <option value="">Choisir...</option>
                                <?php foreach ($yearsPool as $y): ?>
                                <option value="<?= e($y) ?>" <?= ($editYear['year'] ?? '') === $y ? 'selected' : '' ?>><?= e($y) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Libellé</label>
                            <input type="text" name="label" value="<?= e($editYear['label'] ?? '') ?>" placeholder="ex: 2025-2026">
                        </div>
                        <div class="form-group">
                            <label>Date début</label>
                            <input type="date" name="start_date" value="<?= e($editYear['start_date'] ?? '') ?>">
                        </div>
                        <div class="form-group">
                            <label>Date fin</label>
                            <input type="date" name="end_date" value="<?= e($editYear['end_date'] ?? '') ?>">
                        </div>
                        <div class="form-group full" style="display:flex;gap:1.25rem;">
                            <label style="display:flex;align-items:center;gap:.4rem;cursor:pointer;">
                                <input type="checkbox" name="is_current" value="1" <?= ($editYear['is_current'] ?? 0) ? 'checked' : '' ?>>
                                <span>Année courante</span>
                            </label>
                            <label style="display:flex;align-items:center;gap:.4rem;cursor:pointer;">
                                <input type="checkbox" name="is_active" value="1" <?= ($editYear['is_active'] ?? 1) ? 'checked' : '' ?>>
                                <span>Active</span>
                            </label>
                        </div>
                    </div>
                    <div class="modal-actions">
                        <a href="?action=manage_years" class="btn btn-light">Annuler</a>
                        <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Enregistrer</button>
                    </div>
                </form>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- ═══ Modal Ajout/Modification programmation ═══ -->
<div class="modal-overlay" id="programmationModal">
    <div class="modal-box">
        <h2 id="modalTitle"><i class="fas fa-plus-circle"></i> Ajouter une programmation</h2>
        <form method="post">
            <?= csrfField() ?>
            <input type="hidden" name="save_programmation" value="1">
            <input type="hidden" name="item_id" id="itemId" value="0">
            <div class="form-grid">
                <div class="form-group full">
                    <label>École</label>
                    <select name="school_id" id="f_school" required <?= $schoolFilter ? 'disabled' : '' ?>>
                        <option value="">Choisir...</option>
                        <?php foreach ($ecoles as $sc): ?>
                        <option value="<?= $sc['id'] ?>"><?= e($sc['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <?php if ($schoolFilter): ?><input type="hidden" name="school_id" value="<?= $schoolFilter ?>"><?php endif; ?>
                </div>
                <div class="form-group">
                    <label>Année scolaire</label>
                    <select name="academic_year" id="f_year" required>
                        <option value="">Choisir...</option>
                        <?php foreach ($yearsPool as $y): ?>
                        <option value="<?= e($y) ?>" <?= $y === $sessionYear ? 'selected' : '' ?>><?= e($y) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Période</label>
                    <select name="period_number" id="f_period" required>
                        <option value="">Choisir...</option>
                        <?php for ($i = 1; $i <= 3; $i++): ?>
                        <option value="<?= $i ?>"><?= $i ?><?= $i === 1 ? 'er' : 'ème' ?> Trimestre</option>
                        <?php endfor; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Libellé</label>
                    <input type="text" name="label" id="f_label" placeholder="Ex: 1er Trimestre">
                </div>
                <div class="form-group">
                    <label>Date début</label>
                    <input type="date" name="start_date" id="f_start" required>
                </div>
                <div class="form-group">
                    <label>Date fin</label>
                    <input type="date" name="end_date" id="f_end" required>
                </div>
                <div class="form-group full" style="display:flex;gap:.5rem;align-items:center;">
                    <label style="display:flex;align-items:center;gap:.4rem;cursor:pointer;">
                        <input type="checkbox" name="is_open" value="1" id="f_open" checked>
                        <span>Période ouverte</span>
                    </label>
                </div>
            </div>
            <div class="modal-actions">
                <button type="button" class="btn btn-light" onclick="closeModal()">Annuler</button>
                <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Enregistrer</button>
            </div>
        </form>
    </div>
</div>

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

<script>
// ── Modal ──
function openModal(mode, data) {
    const modal = document.getElementById('programmationModal');
    const title = document.getElementById('modalTitle');
    if (mode === 'edit' && data) {
        title.innerHTML = '<i class="fas fa-edit"></i> Modifier la programmation';
        document.getElementById('itemId').value = data.id;
        document.getElementById('f_school').value = data.school_id;
        document.getElementById('f_year').value = data.academic_year;
        document.getElementById('f_period').value = data.period_number;
        document.getElementById('f_label').value = data.label;
        document.getElementById('f_start').value = data.start_date;
        document.getElementById('f_end').value = data.end_date;
        document.getElementById('f_open').checked = data.is_open == 1;
    } else {
        title.innerHTML = '<i class="fas fa-plus-circle"></i> Ajouter une programmation';
        document.getElementById('itemId').value = 0;
        document.getElementById('f_label').value = '';
        document.getElementById('f_start').value = '';
        document.getElementById('f_end').value = '';
        document.getElementById('f_open').checked = true;
        document.getElementById('f_school').value = '<?= $schoolFilter ?: '' ?>';
        document.getElementById('f_year').value = '<?= e($sessionYear) ?>';
    }
    modal.classList.add('open');
}
function closeModal() {
    document.getElementById('programmationModal').classList.remove('open');
}
// Close on overlay click
document.getElementById('programmationModal').addEventListener('click', function(e) {
    if (e.target === this) closeModal();
});

// ── Table selection ──
function toggleAll(cb) {
    document.querySelectorAll('.row-check').forEach(c => {
        c.checked = cb.checked;
        c.closest('tr').classList.toggle('selected', cb.checked);
    });
}
function toggleRow(tr) {
    const cb = tr.querySelector('.row-check');
    if (cb) {
        cb.checked = !cb.checked;
        tr.classList.toggle('selected', cb.checked);
    }
}

// ── Bulk actions ──
function bulkDelete() {
    const checked = document.querySelectorAll('.row-check:checked');
    if (checked.length === 0) { showToast('Sélectionnez des éléments d\'abord.', 'error'); return; }
    if (!confirm('Supprimer ' + checked.length + ' programmation(s) ?')) return;
    document.getElementById('bulkForm').submit();
}
function editSelected() {
    const checked = document.querySelectorAll('.row-check:checked');
    if (checked.length === 0) { showToast('Sélectionnez un élément à modifier.', 'error'); return; }
    if (checked.length > 1) { showToast('Sélectionnez un seul élément à modifier.', 'error'); return; }
    // Get the row data from the table
    const row = checked[0].closest('tr');
    const cells = row.querySelectorAll('td');
    // Parse data from the row (we'll redirect to edit action)
    const editLink = row.querySelector('.btn-light[href*="edit"]');
    if (editLink) window.location.href = editLink.href;
}

// ── Toast ──
function showToast(message, type) {
    const container = document.getElementById('toastContainer');
    const toast = document.createElement('div');
    toast.className = 'toast toast-' + type;
    const icons = { success: '✅', warning: '⚠️', error: '❌' };
    toast.innerHTML = '<span>' + (icons[type] || 'ℹ️') + '</span><span>' + message + '</span>';
    container.appendChild(toast);
    setTimeout(() => toast.remove(), 4000);
}

// ── Auto-open modal on edit ──
<?php if ($editItem): ?>
document.addEventListener('DOMContentLoaded', function() {
    openModal('edit', <?= json_encode($editItem) ?>);
});
<?php endif; ?>

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