<?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'];
}
$error = $success = '';

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

// ── Upload ─────────────────────────────────────────────────────────────────
if ($action === 'upload' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $name = trim($_POST['name'] ?? '');
    if ($name === '') {
        flashMessage('error', 'Le nom du modèle est requis.');
        header('Location: bulletin_templates.php'); exit;
    }
    if (empty($_FILES['pdf_file']['name'])) {
        flashMessage('error', 'Aucun fichier sélectionné.');
        header('Location: bulletin_templates.php'); exit;
    }

    $file = $_FILES['pdf_file'];
    $maxSize = 20 * 1024 * 1024;
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

    if ($ext !== 'pdf') {
        flashMessage('error', 'Format non supporté (PDF requis).');
        header('Location: bulletin_templates.php'); exit;
    }
    if ($file['size'] > $maxSize) {
        flashMessage('error', 'Le fichier dépasse 20 MB.');
        header('Location: bulletin_templates.php'); exit;
    }

    $uploadDir = __DIR__ . '/../uploads/bulletin_templates/';
    $safeName = uniqid('tpl_', true) . '.pdf';
    $destPath = $uploadDir . $safeName;

    if (move_uploaded_file($file['tmp_name'], $destPath)) {
        $originalName = preg_replace('/[^a-zA-Z0-9._\-\s\(\)]/u', '', $file['name']);
        $pdo->prepare("INSERT INTO bulletin_templates (school_id, name, filename, original_name, file_size, uploaded_by, created_at) VALUES (?,?,?,?,?,?,NOW())")
            ->execute([$schoolFilter ?? 0, $name, $safeName, $originalName, $file['size'], $_SESSION['user_id'] ?? null]);
        flashMessage('success', 'Modèle "' . e($name) . '" importé avec succès.');
    } else {
        flashMessage('error', 'Erreur lors de l\'enregistrement du fichier.');
    }
    header('Location: bulletin_templates.php'); exit;
}

// ── Assigner ──────────────────────────────────────────────────────────────
if ($action === 'assign' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $template_id  = (int)($_POST['template_id'] ?? 0);
    $assignSchool = (int)($_POST['assign_school_id'] ?? 0);
    $assignClass  = (int)($_POST['assign_class_id'] ?? 0);
    $assignYear   = trim($_POST['assign_academic_year'] ?? '');

    if (!$template_id || !$assignSchool) {
        flashMessage('error', 'Veuillez sélectionner un modèle et une école.');
        header('Location: bulletin_templates.php'); exit;
    }

    // Vérifier que le template appartient à l'école ou est global (school_id=0)
    $check = $pdo->prepare("SELECT id FROM bulletin_templates WHERE id=? AND (school_id=? OR school_id=0)");
    $check->execute([$template_id, $assignSchool]);
    if (!$check->fetch()) {
        flashMessage('error', 'Modèle invalide pour cette école.');
        header('Location: bulletin_templates.php'); exit;
    }

    $schoolParam = $assignSchool ?: null;
    $classParam  = $assignClass ?: null;
    $yearParam   = $assignYear ?: null;

    // Supprimer l'ancienne assignation pour cette combo
    if ($classParam && $yearParam) {
        $pdo->prepare("DELETE FROM bulletin_template_assignments WHERE school_id=? AND class_id=? AND academic_year=?")->execute([$schoolParam, $classParam, $yearParam]);
    } elseif ($classParam) {
        $pdo->prepare("DELETE FROM bulletin_template_assignments WHERE school_id=? AND class_id=? AND academic_year IS NULL")->execute([$schoolParam, $classParam]);
    } elseif ($yearParam) {
        $pdo->prepare("DELETE FROM bulletin_template_assignments WHERE school_id=? AND class_id IS NULL AND academic_year=?")->execute([$schoolParam, $yearParam]);
    } else {
        $pdo->prepare("DELETE FROM bulletin_template_assignments WHERE school_id=? AND class_id IS NULL AND academic_year IS NULL")->execute([$schoolParam]);
    }

    $pdo->prepare("INSERT INTO bulletin_template_assignments (template_id, school_id, class_id, academic_year, created_at) VALUES (?,?,?,?,NOW())")
        ->execute([$template_id, $schoolParam, $classParam, $yearParam]);

    flashMessage('success', 'Assignation enregistrée.');
    header('Location: bulletin_templates.php'); exit;
}

// ── Supprimer assignation ────────────────────────────────────────────────
if ($action === 'unassign' && $id) {
    verifyCsrf();
    $pdo->prepare("DELETE FROM bulletin_template_assignments WHERE id=?")->execute([$id]);
    flashMessage('success', 'Assignation supprimée.');
    header('Location: bulletin_templates.php'); exit;
}

// ── Supprimer template ───────────────────────────────────────────────────
if ($action === 'delete' && $id) {
    verifyCsrf();
    $stmt = $pdo->prepare("SELECT filename FROM bulletin_templates WHERE id=?");
    $stmt->execute([$id]);
    $row = $stmt->fetch();
    if ($row) {
        $filepath = __DIR__ . '/../uploads/bulletin_templates/' . $row['filename'];
        if (file_exists($filepath)) unlink($filepath);
        $pdo->prepare("DELETE FROM bulletin_template_assignments WHERE template_id=?")->execute([$id]);
        $pdo->prepare("DELETE FROM bulletin_templates WHERE id=?")->execute([$id]);
        flashMessage('success', 'Modèle supprimé.');
    }
    header('Location: bulletin_templates.php'); exit;
}

// ── Données ──────────────────────────────────────────────────────────────
$schools = $pdo->query("SELECT id, name FROM schools ORDER BY name")->fetchAll();
$classes = $pdo->query("SELECT id, name FROM classes c ORDER BY " . getClassSortSQL('c'))->fetchAll();
$years   = $pdo->query("SELECT DISTINCT year FROM academic_years ORDER BY year DESC")->fetchAll(PDO::FETCH_COLUMN);
$currentYear = getDefaultAcademicYear($pdo, $schoolFilter);

$where = $schoolFilter ? "WHERE school_id=?" : "";
$params = $schoolFilter ? [$schoolFilter] : [];
$templates = $pdo->prepare("SELECT * FROM bulletin_templates $where ORDER BY created_at DESC");
$templates->execute($params);
$templates = $templates->fetchAll();

// Compter les affectations par template en une seule requête
$assignCounts = [];
$acSt = $pdo->query("SELECT template_id, COUNT(*) AS cnt FROM bulletin_template_assignments GROUP BY template_id");
foreach ($acSt as $ac) $assignCounts[$ac['template_id']] = (int)$ac['cnt'];

// Toutes les assignations (pour l'école courante ou globales)
$assignWhere = $schoolFilter ? "WHERE bta.school_id=?" : "";
$assignParams = $schoolFilter ? [$schoolFilter] : [];
$assignments = $pdo->prepare("
    SELECT bta.*, bt.name AS template_name, s.name AS school_name, c.name AS class_name
    FROM bulletin_template_assignments bta
    JOIN bulletin_templates bt ON bta.template_id = bt.id
    LEFT JOIN schools s ON bta.school_id = s.id
    LEFT JOIN classes c ON bta.class_id = c.id
    $assignWhere
    ORDER BY bta.school_id, bta.class_id, bta.academic_year
");
$assignments->execute($assignParams);
$assignments = $assignments->fetchAll();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Modèles de bulletins - 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;--bg:#F1F5F9;--white:#FFFFFF;--text:#1E293B;--success:#10B981;--warning:#F59E0B;--danger:#EF4444;--info:#3B82F6;}
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;background:var(--bg);color:var(--text);line-height:1.6;}
.main-content{padding-top:0;}
.content{padding:30px;}
.section{background:var(--white);border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,0.06);padding:24px 30px;margin-bottom:25px;}
.section-title{font-family:Georgia,serif;color:var(--primary);font-size:1.2rem;margin-bottom:20px;padding-bottom:10px;border-bottom:2px solid var(--light);display:flex;align-items:center;gap:10px;}
.grid-2{display:grid;grid-template-columns:1fr 1fr;gap:24px;}
@media(max-width:900px){.grid-2{grid-template-columns:1fr;}}

/* Upload */
.upload-box{border:2px dashed var(--accent);border-radius:12px;padding:30px;text-align:center;background:linear-gradient(180deg,#f8fbff,#eef4fc);cursor:pointer;position:relative;transition:all .3s;}
.upload-box:hover{border-color:var(--primary);background:linear-gradient(180deg,#f0f7ff,#e4eef8);}
.upload-box input[type=file]{position:absolute;left:0;top:0;width:100%;height:100%;opacity:0;cursor:pointer;}
.upload-box .icon{font-size:2.5rem;color:var(--primary);margin-bottom:8px;}
.upload-box .hint{color:#6B7280;font-size:.82rem;margin-top:6px;}

/* Form */
.form-row{display:flex;gap:12px;flex-wrap:wrap;margin-bottom:14px;align-items:end;}
.form-row .form-group{margin:0;flex:1;min-width:140px;}
.form-group{margin-bottom:14px;}
.form-group label{display:block;font-weight:600;color:var(--primary);font-size:.82rem;margin-bottom:4px;}
.form-group input,.form-group select{padding:9px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:.85rem;width:100%;}

/* Cards */
.tpl-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:16px;}
.tpl-card{background:white;border-radius:10px;border:1px solid #E5E7EB;overflow:hidden;transition:box-shadow .2s;}
.tpl-card:hover{box-shadow:0 4px 12px rgba(0,0,0,.1);}
.tpl-card .tpl-preview{height:160px;background:linear-gradient(135deg,#f0f4ff,#e8ecf4);display:flex;align-items:center;justify-content:center;font-size:2.5rem;color:var(--primary);border-bottom:1px solid #E5E7EB;position:relative;}
.tpl-card .tpl-body{padding:14px;}
.tpl-card .tpl-name{font-weight:700;color:var(--primary);font-size:.95rem;margin-bottom:4px;}
.tpl-card .tpl-meta{font-size:.78rem;color:#6B7280;margin-bottom:10px;}
.tpl-card .tpl-actions{display:flex;gap:6px;}
.tpl-card .tpl-actions a,.tpl-card .tpl-actions button{padding:5px 10px;border:none;border-radius:5px;font-size:.75rem;cursor:pointer;transition:all .2s;text-decoration:none;}
.act-assign{background:#FFF3E0;color:var(--warning);}
.act-assign:hover{background:#FFE0B2;}
.act-download{background:#E3F2FD;color:var(--info);}
.act-download:hover{background:#BBDEFB;}
.act-delete{background:#FEE2E2;color:var(--danger);}
.act-delete:hover{background:#FECACA;}
.act-view{background:#E8F5E9;color:var(--success);}
.act-view:hover{background:#C8E6C9;}

/* Assign table */
.assign-table{width:100%;border-collapse:collapse;margin-top:8px;}
.assign-table th,.assign-table td{padding:10px 12px;text-align:left;border-bottom:1px solid #E5E7EB;font-size:.85rem;}
.assign-table th{background:var(--primary);color:white;font-weight:600;}
.assign-table tr:hover{background:#F0F7FF;}
.badge-scope{display:inline-block;padding:3px 10px;border-radius:20px;font-size:.75rem;font-weight:600;}
.scope-school{background:#E3F2FD;color:var(--info);}
.scope-class{background:#E8F5E9;color:var(--success);}
.scope-year{background:#F3E5F5;color:#7B1FA2;}

/* Modal */
.modal-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:1500;align-items:center;justify-content:center;}
.modal-overlay.active{display:flex;}
.modal{background:white;border-radius:12px;width:90%;max-width:520px;padding:28px;box-shadow:0 8px 32px rgba(0,0,0,.2);animation:modalSlide .3s ease;max-height:90vh;overflow-y:auto;}
@keyframes modalSlide{from{transform:translateY(-30px);opacity:0;}to{transform:translateY(0);opacity:1;}}
.modal h3{color:var(--primary);font-size:1.1rem;margin-bottom:16px;display:flex;align-items:center;gap:8px;}
.modal-actions{display:flex;justify-content:flex-end;gap:10px;margin-top:20px;}
.modal-actions button{padding:9px 20px;border-radius:6px;border:none;font-size:.85rem;cursor:pointer;transition:all .2s;}
.btn-cancel{background:#E5E7EB;color:#374151;}
.btn-cancel:hover{background:#D1D5DB;}
.btn-save{background:var(--primary);color:white;}
.btn-save:hover{background:var(--accent);}
.btn-submit{padding:9px 18px;background:var(--primary);color:white;border:none;border-radius:6px;font-size:.85rem;font-weight:600;cursor:pointer;transition:all .2s;}
.btn-submit:hover{background:var(--accent);}
.empty-state{text-align:center;padding:40px 20px;}
.empty-state .icon{font-size:3rem;margin-bottom:12px;color:#CBD5E1;}
.empty-state h3{color:var(--primary);margin-bottom:6px;}
.empty-state p{color:#9CA3AF;font-size:.9rem;}

@media(max-width:768px){
.content{padding:16px;}
.form-row{flex-direction:column;}
.form-row .form-group{min-width:100%;}
}
</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-file-pdf"></i> Modèles de bulletins'; include '../includes/topbar.php'; ?>
        <?= showFlash() ?>

        <div class="content">

        <div class="section">
            <div class="section-title"><i class="fas fa-cloud-upload-alt"></i> Ajouter un modèle</div>
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="upload">
                <?= csrfField() ?>
                <div class="form-row">
                    <div class="form-group">
                        <label>Nom du modèle</label>
                        <input type="text" name="name" required placeholder="ex: Bulletin classique 2025">
                    </div>
                    <div class="form-group" style="flex:0 0 180px;">
                        <label>Fichier PDF</label>
                        <div class="upload-box" style="padding:16px 20px;">
                            <input type="file" name="pdf_file" accept=".pdf" required>
                            <span class="icon"><i class="fas fa-file-pdf"></i></span>
                            <span style="font-size:.85rem;color:#6B7280;">Cliquez ou glissez un PDF</span>
                            <div class="hint">Taille max : 20 MB</div>
                        </div>
                    </div>
                    <button type="submit" class="btn-submit" style="margin-bottom:14px;align-self:end;"><i class="fas fa-upload"></i> Importer</button>
                </div>
            </form>
        </div>

        <!-- Modèles disponibles -->
        <div class="section">
            <div class="section-title"><i class="fas fa-layer-group"></i> Modèles disponibles</div>
            <?php if (empty($templates)): ?>
            <div class="empty-state">
                <div class="icon"><i class="fas fa-file-pdf"></i></div>
                <h3>Aucun modèle</h3>
                <p>Importez un modèle PDF de bulletin ci-dessus.</p>
            </div>
            <?php else: ?>
            <div class="tpl-grid">
                <?php foreach ($templates as $t): ?>
                <div class="tpl-card">
                    <div class="tpl-preview">
                        <i class="fas fa-file-pdf"></i>
                        <?php $ac = $assignCounts[$t['id']] ?? 0; ?>
                        <?php if ($ac > 0): ?>
                        <span style="position:absolute;top:8px;right:8px;background:var(--success);color:white;padding:2px 8px;border-radius:12px;font-size:.7rem;font-weight:600;"><?= $ac ?> affectation(s)</span>
                        <?php endif; ?>
                    </div>
                    <div class="tpl-body">
                        <div class="tpl-name"><?= e($t['name']) ?></div>
                        <div class="tpl-meta">
                            <?= formatFileSize((int)$t['file_size']) ?> &middot;
                            <?= formatDate($t['created_at']) ?>
                        </div>
                        <div class="tpl-actions">
                            <a href="<?= BASE_URL ?>uploads/bulletin_templates/<?= rawurlencode($t['filename']) ?>" target="_blank" class="act-view" title="Voir"><i class="fas fa-eye"></i></a>
                            <a href="<?= BASE_URL ?>uploads/bulletin_templates/<?= rawurlencode($t['filename']) ?>" download class="act-download" title="Télécharger"><i class="fas fa-download"></i></a>
                            <button onclick="openAssignModal(<?= $t['id'] ?>)" class="act-assign" title="Assigner"><i class="fas fa-link"></i> Assigner</button>
                            <a href="?action=delete&id=<?= $t['id'] ?>&csrf=<?= $_SESSION['csrf_token'] ?>" class="act-delete" title="Supprimer" onclick="return confirm('Supprimer ce modèle ? Les assignations seront aussi supprimées.')"><i class="fas fa-trash"></i></a>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>

        <!-- Assignations -->
        <div class="section">
            <div class="section-title"><i class="fas fa-tasks"></i> Assignations actuelles</div>
            <?php if (empty($assignments)): ?>
            <div class="empty-state">
                <div class="icon"><i class="fas fa-unlink"></i></div>
                <h3>Aucune assignation</h3>
                <p>Assignez un modèle à une école ou une classe pour qu'il soit utilisé comme fond des bulletins générés.</p>
            </div>
            <?php else: ?>
            <div style="overflow-x:auto;">
            <table class="assign-table">
                <thead>
                    <tr><th>Modèle</th><th>Portée</th><th>Classe</th><th>Année</th><th>Action</th></tr>
                </thead>
                <tbody>
                    <?php foreach ($assignments as $a): ?>
                    <tr>
                        <td><strong><?= e($a['template_name']) ?></strong></td>
                        <td>
                            <?php if ($a['class_id']): ?>
                            <span class="badge-scope scope-class">Classe</span>
                            <?php else: ?>
                            <span class="badge-scope scope-school">École</span>
                            <?php endif; ?>
                        </td>
                        <td><?= e($a['class_name'] ?: '— Toutes —') ?></td>
                        <td><?= e($a['academic_year'] ?: '— Toutes —') ?></td>
                        <td>
                            <a href="?action=unassign&id=<?= $a['id'] ?>&csrf=<?= $_SESSION['csrf_token'] ?>" class="act-delete" style="padding:4px 10px;border:none;border-radius:5px;font-size:.75rem;cursor:pointer;text-decoration:none;display:inline-flex;align-items:center;gap:4px;" onclick="return confirm('Supprimer cette assignation ?')"><i class="fas fa-unlink"></i> Retirer</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            </div>
            <?php endif; ?>
            <p style="margin-top:14px;font-size:.82rem;color:#6B7280;">
                <i class="fas fa-info-circle"></i>
                Une assignation par école/classe/année. La priorité : classe+année &gt; classe seule &gt; école+année &gt; école seule.
            </p>
        </div>

        </div>
    </div>
</div>

<!-- ═══ MODAL ASSIGNER ═══ -->
<div class="modal-overlay" id="assignModal">
    <div class="modal">
        <h3><i class="fas fa-link"></i> Assigner le modèle</h3>
        <form method="POST">
            <input type="hidden" name="action" value="assign">
            <input type="hidden" name="template_id" id="assignTemplateId" value="">
            <?= csrfField() ?>
            <div class="form-group">
                <label>École</label>
                <select name="assign_school_id" id="assignSchool" required>
                    <option value="">Sélectionner</option>
                    <?php foreach ($schools as $s): ?>
                    <option value="<?= $s['id'] ?>" <?= $schoolFilter == $s['id'] ? 'selected' : '' ?>><?= e($s['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Classe <small style="color:#9CA3AF;font-weight:400;">(optionnel — toutes si vide)</small></label>
                <select name="assign_class_id">
                    <option value="">Toutes les classes</option>
                    <?php foreach ($classes as $c): ?>
                    <option value="<?= $c['id'] ?>"><?= e($c['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Année scolaire <small style="color:#9CA3AF;font-weight:400;">(optionnel — toutes si vide)</small></label>
                <select name="assign_academic_year">
                    <option value="">Toutes les années</option>
                    <?php foreach ($years as $y): ?>
                    <option value="<?= e($y) ?>" <?= $y === $currentYear ? 'selected' : '' ?>><?= e($y) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="modal-actions">
                <button type="button" class="btn-cancel" onclick="closeAssignModal()">Annuler</button>
                <button type="submit" class="btn-save"><i class="fas fa-save"></i> Assigner</button>
            </div>
        </form>
    </div>
</div>

<script>
function openAssignModal(templateId) {
    document.getElementById('assignTemplateId').value = templateId;
    document.getElementById('assignModal').classList.add('active');
}
function closeAssignModal() {
    document.getElementById('assignModal').classList.remove('active');
}
document.querySelectorAll('.modal-overlay').forEach(m => {
    m.addEventListener('click', e => { if (e.target === m) m.classList.remove('active'); });
});
</script>
</body>
</html>
