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

checkRole(['super_admin']);

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

define('LOGO_DIR',      dirname(__DIR__) . '/uploads/logos/');
define('LOGO_MAX_SIZE', 2 * 1024 * 1024);
define('LOGO_ALLOWED',  ['image/jpeg', 'image/png', 'image/gif', 'image/webp']);
define('LOGO_EXT',      ['jpg', 'jpeg', 'png', 'gif', 'webp']);

// schools.php utilise logoUrl() définie dans includes/functions.php
// La définition locale ci-dessous est supprimée pour éviter la redéfinition fatale.

// ── Suppression logo seul ─────────────────────────────────────────────────────
if ($action === 'delete_logo' && $id) {
    verifyCsrf();
    if (!isSuperAdmin()) { flashMessage('error','Action réservée au super administrateur.'); header('Location: schools.php'); exit; }
    checkDeleteAllowed();
    $stmt = $pdo->prepare("SELECT logo FROM schools WHERE id = ?");
    $stmt->execute([$id]);
    $row = $stmt->fetch();
    if ($row && $row['logo']) {
        $file = LOGO_DIR . basename($row['logo']);
        if (file_exists($file)) unlink($file);
        $pdo->prepare("UPDATE schools SET logo = NULL WHERE id = ?")->execute([$id]);
        flashMessage('success', 'Logo supprimé.');
    }
    header('Location: schools.php'); exit;
}

// ── Suppression école ─────────────────────────────────────────────────────────
if ($action === 'delete' && $id) {
    verifyCsrf();
    if (!isSuperAdmin()) { flashMessage('error','Action réservée au super administrateur.'); header('Location: schools.php'); exit; }
    checkDeleteAllowed();
    $stmt = $pdo->prepare("SELECT logo FROM schools WHERE id = ?");
    $stmt->execute([$id]);
    $row = $stmt->fetch();
    if ($row && $row['logo']) {
        $file = LOGO_DIR . basename($row['logo']);
        if (file_exists($file)) unlink($file);
    }
    $pdo->prepare("DELETE FROM schools WHERE id = ?")->execute([$id]);
    flashMessage('success', 'École supprimée avec succès.');
    header('Location: schools.php'); exit;
}

// ── Session : définir/réinitialiser filtres ──
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: schools.php'); exit;
}
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: schools.php'); exit;
}

// ── Ajout / Modification ──────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $name    = trim($_POST['name']    ?? '');
    $address = trim($_POST['address'] ?? '');
    $phone   = trim($_POST['phone']   ?? '');
    $email   = trim($_POST['email']   ?? '');

    if (empty($name)) $error = "Le nom de l'école est requis.";
    elseif (!empty($email) && !validateEmail($email)) $error = 'Adresse email invalide.';

    $logoFilename = null;
    if (!empty($_FILES['logo']['name'])) {
        $file     = $_FILES['logo'];
        $tmpPath  = $file['tmp_name'];
        $mimeType = mime_content_type($tmpPath);
        $ext      = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

        if ($file['error'] !== UPLOAD_ERR_OK) $error = "Erreur lors de l'upload du fichier.";
        elseif ($file['size'] > LOGO_MAX_SIZE) $error = 'Le logo ne doit pas dépasser 2 Mo.';
        elseif (!in_array($mimeType, LOGO_ALLOWED, true) || !in_array($ext, LOGO_EXT, true)) $error = 'Format non autorisé. Utilisez JPG, PNG, GIF ou WEBP.';
        else {
            $logoFilename = 'school_' . ($id ?? 'new') . '_' . uniqid() . '.' . $ext;
            if ($id) {
                $oldStmt = $pdo->prepare("SELECT logo FROM schools WHERE id = ?");
                $oldStmt->execute([$id]);
                $oldRow = $oldStmt->fetch();
                if ($oldRow && $oldRow['logo']) { $oldFile = LOGO_DIR . basename($oldRow['logo']); if (file_exists($oldFile)) unlink($oldFile); }
            }
            if (!move_uploaded_file($tmpPath, LOGO_DIR . $logoFilename)) {
                $error = 'Impossible de sauvegarder le logo.';
                $logoFilename = null;
            }
        }
    }

    if (empty($error)) {
        if ($id) {
            if ($logoFilename !== null) {
                $pdo->prepare("UPDATE schools SET name=?, address=?, phone=?, email=?, logo=? WHERE id=?")->execute([$name, $address, $phone, $email, $logoFilename, $id]);
            } else {
                $pdo->prepare("UPDATE schools SET name=?, address=?, phone=?, email=? WHERE id=?")->execute([$name, $address, $phone, $email, $id]);
            }
            flashMessage('success', 'École mise à jour.');
        } else {
            $pdo->prepare("INSERT INTO schools (name, address, phone, email, logo) VALUES (?,?,?,?,?)")->execute([$name, $address, $phone, $email, $logoFilename]);
            flashMessage('success', 'École ajoutée.');
        }
        header('Location: schools.php'); exit;
    }
}

// ── Chargement pour édition ───────────────────────────────────────────────────
$school = null;
if ($action === 'edit' && $id) {
    $stmt = $pdo->prepare("SELECT * FROM schools WHERE id = ?");
    $stmt->execute([$id]);
    $school = $stmt->fetch();
    if (!$school) { flashMessage('error', 'École introuvable.'); header('Location: schools.php'); exit; }
}

$sessionYear   = $_SESSION['active_academic_year'] ?? '';
$sessionPeriod = getActivePeriod();
$schoolFilter = currentSchoolId();
$sessionSchool = $_SESSION['active_school_filter'] ?? $schoolFilter;
$years = $pdo->query("SELECT DISTINCT year FROM academic_years ORDER BY year DESC")->fetchAll(PDO::FETCH_COLUMN);
$ecoles = $pdo->query("SELECT id, name FROM schools ORDER BY name")->fetchAll();

// ── Tri ───────────────────────────────────────────────────────────────────────
$sortAllowed = ['name', 'address', 'phone', 'email', 'created_at'];
$sort = resolveSort($sortAllowed, 'created_at', 'desc');
$sortMap = [
    'name'       => 'name',
    'address'    => 'address',
    'phone'      => 'phone',
    'email'      => 'email',
    'created_at' => 'created_at',
];
$orderExpr = ($sortMap[$sort['col']] ?? 'created_at') . ' ' . $sort['dir'];
$schools = $pdo->query("SELECT * FROM schools ORDER BY $orderExpr")->fetchAll();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Écoles - 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;
  }

  .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;
    white-space: nowrap;
  }
  .prog-table th a {
    color: white;
    text-decoration: none;
  }
  .prog-table th a:hover {
    text-decoration: underline;
  }
  .prog-table td {
    padding: .7rem 1rem;
    border-bottom: 1px solid #E5E7EB;
    font-size: .85rem;
    vertical-align: middle;
  }
  .prog-table tbody tr:hover {
    background: #F9FAFB;
  }

  .btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: .55rem 1.25rem;
    border: none;
    border-radius: 6px;
    font-size: .82rem;
    font-weight: 600;
    cursor: pointer;
    transition: all .2s;
    text-decoration: none;
  }
  .btn-primary { background: var(--primary); color: white; }
  .btn-primary:hover { background: #163a5c; }
  .btn-light { background: #E5E7EB; color: #374151; }
  .btn-light:hover { background: #D1D5DB; }
  .btn-danger { background: #DC2626; color: white; }
  .btn-danger:hover { background: #B91C1C; }

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

  .form-group { margin-bottom: 1.1rem; }
  .form-group label { display: block; font-weight: 600; color: var(--primary); font-size: .85rem; margin-bottom: 5px; }
  .form-group input, .form-group select { width: 100%; padding: .55rem .75rem; border: 1px solid #D1D5DB; border-radius: 6px; font-size: .85rem; transition: border .2s; box-sizing: border-box; }
  .form-group input:focus, .form-group select:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px rgba(46,117,182,0.15); }

  .logo-upload-zone {
    border: 2px dashed #D1D5DB;
    border-radius: 8px;
    padding: 1.5rem;
    text-align: center;
    cursor: pointer;
    transition: all .2s;
    position: relative;
  }
  .logo-upload-zone:hover { border-color: var(--accent); background: #F9FAFB; }
  .logo-upload-zone.dragover { border-color: var(--accent); background: #EFF6FF; }
  .logo-upload-zone i { font-size: 2rem; color: var(--accent); display: block; margin-bottom: .5rem; }
  .logo-upload-zone small { display: block; color: #999; margin-top: 4px; }
  .logo-upload-zone input { position: absolute; inset: 0; opacity: 0; cursor: pointer; }
  .logo-preview-wrap { display: flex; align-items: center; gap: .75rem; margin-bottom: .75rem; }
  .logo-preview { max-width: 100px; max-height: 60px; border-radius: 6px; border: 1px solid #E5E7EB; }
  .logo-preview-label { font-size: .78rem; color: #666; }

  @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; }
  }
</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-school"></i> Gestion des écoles'; include '../includes/topbar.php'; ?>

        <?php if ($error): ?>
        <script>document.addEventListener('DOMContentLoaded',function(){showToast(<?= json_encode($error) ?>,'error');});</script>
        <?php endif; ?>
        <?php
        $__flash = $_SESSION['flash'] ?? null;
        unset($_SESSION['flash']);
        ?>

        <!-- ═══ Header ═══ -->
        <div class="prog-header">
            <div>
                <h1>🏫 Écoles</h1>
                <p>Gérez les établissements scolaires</p>
            </div>
            <div style="display:flex;gap:.5rem;flex-wrap:wrap;">
                <?php if ($action !== 'add' && $action !== 'edit'): ?>
                <a href="?action=add" class="btn btn-primary"><i class="fas fa-plus"></i> Ajouter une école</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 ($years 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 ?> Trimestre</option>
                        <?php endfor; ?>
                    </select>
                </div>
                <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 --</option>
                        <?php foreach ($ecoles as $ec): ?>
                        <option value="<?= $ec['id'] ?>" <?= ($sessionSchool && $sessionSchool == $ec['id']) ? 'selected' : '' ?>><?= e($ec['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <a href="?action=clear_session&csrf_token=<?= csrfToken() ?>" class="btn btn-light"><i class="fas fa-undo-alt"></i></a>
                </div>
            </div>
        </form>

        <!-- ═══ Formulaire ajout/édition ═══ -->
        <?php if ($action === 'add' || $action === 'edit'): ?>
        <div class="table-card" style="max-width:640px;">
            <div class="tc-header">
                <div class="tc-title"><?= $school ? 'Modifier' : 'Ajouter' ?> une école</div>
            </div>
            <div style="padding:1.5rem;">
                <form method="POST" enctype="multipart/form-data">
                    <?= csrfField() ?>
                    <div class="form-group">
                        <label>Logo de l'école</label>
                        <?php if (!empty($school['logo'])): ?>
                        <div class="logo-preview-wrap">
                            <img src="<?= e(logoUrl($school['logo'])) ?>" alt="Logo actuel" class="logo-preview">
                            <span class="logo-preview-label">Logo actuel</span>
                        </div>
                        <?php endif; ?>
                        <div class="logo-upload-zone" id="logoUploadZone">
                            <i class="fas fa-cloud-upload-alt"></i>
                            <span id="logoUploadText"><?= !empty($school['logo']) ? 'Choisir un nouveau logo' : 'Cliquer ou glisser une image ici' ?></span>
                            <small>JPG, PNG, GIF, WEBP — max 2 Mo</small>
                            <input type="file" name="logo" id="logoInput" accept="image/*">
                        </div>
                        <div id="newLogoPreview" style="display:none;margin-top:.75rem;">
                            <img id="newLogoImg" src="" alt="Aperçu" class="logo-preview">
                            <span class="logo-preview-label" id="newLogoName"></span>
                        </div>
                    </div>
                    <div class="form-group"><label>Nom <span style="color:red">*</span></label><input type="text" name="name" required value="<?= e($school['name'] ?? '') ?>"></div>
                    <div class="form-group"><label>Adresse</label><input type="text" name="address" value="<?= e($school['address'] ?? '') ?>"></div>
                    <div class="form-group"><label>Téléphone</label><input type="text" name="phone" value="<?= e($school['phone'] ?? '') ?>"></div>
                    <div class="form-group"><label>Email</label><input type="email" name="email" value="<?= e($school['email'] ?? '') ?>"></div>
                    <div style="display:flex;gap:.75rem;">
                        <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Enregistrer</button>
                        <a href="schools.php" class="btn btn-light">Annuler</a>
                    </div>
                </form>
                <?php if (!empty($school['logo']) && isSuperAdmin()): ?>
                <form method="POST" action="?action=delete_logo&id=<?= $school['id'] ?>" style="margin-top:1rem;" onsubmit="return confirm('Supprimer le logo ?')">
                    <?= csrfField() ?>
                    <button type="submit" class="btn btn-danger"><i class="fas fa-image"></i> Supprimer le logo</button>
                </form>
                <?php endif; ?>
            </div>
        </div>

        <!-- ═══ Liste ═══ -->
        <?php else: ?>
        <div class="table-card">
            <div class="tc-header">
                <div class="tc-title"><i class="fas fa-list"></i> Liste des écoles</div>
                <span style="background:var(--light);color:var(--primary);padding:3px 10px;border-radius:20px;font-size:.75rem;font-weight:600;"><?= count($schools) ?> école(s)</span>
            </div>
            <?php if (empty($schools)): ?>
            <div style="text-align:center;padding:3rem 1rem;color:#9CA3AF;">
                <div style="font-size:2.5rem;margin-bottom:.5rem;"><i class="fas fa-school"></i></div>
                <p>Aucune école enregistrée.</p>
                <a href="?action=add" class="btn btn-primary" style="margin-top:1rem;">Ajouter une école</a>
            </div>
            <?php else: ?>
            <table class="prog-table" id="schoolsTable">
                <thead>
                    <tr>
                        <th>École</th>
                        <th><?= sortTh('address',    'Adresse',    $sort) ?></th>
                        <th><?= sortTh('phone',      'Téléphone',  $sort) ?></th>
                        <th><?= sortTh('email',      'Email',      $sort) ?></th>
                        <th><?= sortTh('created_at', 'Créée le',   $sort) ?></th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($schools as $s): ?>
                    <tr>
                        <td>
                            <div style="display:flex;align-items:center;gap:.8rem;">
                            <?php if (!empty($s['logo'])): ?>
                            <img src="<?= e(logoUrl($s['logo'])) ?>" alt="Logo <?= e($s['name']) ?>" style="width:48px;height:48px;object-fit:contain;border-radius:8px;">
                            <?php else: ?>
                            <div style="width:48px;height:48px;display:flex;align-items:center;justify-content:center;background:var(--light);border-radius:8px;color:var(--primary);font-size:1.2rem;"><i class="fas fa-school"></i></div>
                            <?php endif; ?>
                            <strong><?= e($s['name']) ?></strong>
                            </div>
                        </td>
                        <td><?= e($s['address'] ?? '-') ?></td>
                        <td><?= e($s['phone']   ?? '-') ?></td>
                        <td><?= e($s['email']   ?? '-') ?></td>
                        <td><?= formatDate($s['created_at']) ?></td>
                        <td>
                            <a href="?action=edit&id=<?= $s['id'] ?>" class="btn btn-light" style="padding:.3rem .6rem;font-size:.75rem;" title="Modifier"><i class="fas fa-edit"></i></a>
                            <?php if (isSuperAdmin()): ?>
                            <form method="POST" action="?action=delete&id=<?= $s['id'] ?>" style="display:inline" onsubmit="return confirm('Supprimer cette école et toutes ses données ?')">
                                <?= csrfField() ?>
                                <button type="submit" class="btn btn-danger" style="padding:.3rem .6rem;font-size:.75rem;border:none;"><i class="fas fa-trash"></i></button>
                            </form>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </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: '✅', warning: '⚠️', error: '❌' };
    toast.innerHTML = '<span>' + (icons[type] || 'ℹ️') + '</span><span>' + message + '</span>';
    container.appendChild(toast);
    setTimeout(() => toast.remove(), 4000);
}

// ── Logo upload ──
const input = document.getElementById('logoInput');
const zone  = document.getElementById('logoUploadZone');
const preview = document.getElementById('newLogoPreview');
const previewImg  = document.getElementById('newLogoImg');
const previewName = document.getElementById('newLogoName');
const uploadText  = document.getElementById('logoUploadText');
if (input) {
    zone.addEventListener('click', () => input.click());
    zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('dragover'); });
    zone.addEventListener('dragleave', () => zone.classList.remove('dragover'));
    zone.addEventListener('drop', e => { e.preventDefault(); zone.classList.remove('dragover'); if (e.dataTransfer.files.length) { input.files = e.dataTransfer.files; showPreview(e.dataTransfer.files[0]); } });
    input.addEventListener('change', () => { if (input.files.length) showPreview(input.files[0]); });
    function showPreview(file) {
        uploadText.textContent = 'Fichier sélectionné :';
        previewName.textContent = file.name;
        const reader = new FileReader();
        reader.onload = e => { previewImg.src = e.target.result; preview.style.display = 'flex'; };
        reader.readAsDataURL(file);
    }
}

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