<?php
$h = static fn(mixed $value): string => htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
$meetingCount = count($meetings);
$professorCount = count($professors);
?>
<section class="meeting-page">
    <header class="meeting-hero">
        <div>
            <span class="meeting-kicker">Direction · Organisation</span>
            <h2>Réunions des professeurs</h2>
            <p>Planifiez une réunion et ajoutez-la automatiquement au planning de chaque professeur invité.</p>
        </div>
        <div class="meeting-hero-actions">
            <span><strong><?= $professorCount ?></strong> professeur<?= $professorCount > 1 ? 's' : '' ?> actif<?= $professorCount > 1 ? 's' : '' ?></span>
            <a class="meeting-back" href="/public/espaces?espace=direction">← Retour</a>
        </div>
    </header>

    <div class="meeting-layout">
        <article class="meeting-panel meeting-compose">
            <div class="meeting-panel-title">
                <span class="meeting-step">1</span>
                <div><h3>Nouvelle réunion</h3><p>Renseignez la date, l’horaire et les participants.</p></div>
            </div>

            <form class="meeting-form" method="post" action="/public/direction/reunions/creer" data-meeting-form>
                <?= \App\Core\Csrf::field() ?>
                <label class="meeting-field meeting-field-wide">
                    <span>Objet de la réunion *</span>
                    <input name="titre" maxlength="190" placeholder="Ex. Réunion pédagogique de rentrée" required>
                </label>

                <div class="meeting-date-row">
                    <label class="meeting-field">
                        <span>Date *</span>
                        <input type="date" name="date_evenement" required>
                    </label>
                    <label class="meeting-field">
                        <span>Début *</span>
                        <input type="time" name="heure_debut" step="300" required>
                    </label>
                    <label class="meeting-field">
                        <span>Fin *</span>
                        <input type="time" name="heure_fin" step="300" required>
                    </label>
                </div>

                <fieldset class="meeting-guests">
                    <legend>Professeurs invités *</legend>
                    <div class="meeting-guest-toolbar">
                        <label class="meeting-search">
                            <span aria-hidden="true">⌕</span>
                            <input type="search" placeholder="Rechercher un professeur…" data-guest-search>
                        </label>
                        <button type="button" data-select-all>Tout sélectionner</button>
                        <span data-guest-count>0 sélectionné</span>
                    </div>
                    <div class="meeting-guest-grid" data-guest-grid>
                        <?php foreach ($professors as $professor):
                            $fullName = trim((string)$professor['prenom'].' '.(string)$professor['nom']);
                            $initials = mb_strtoupper(mb_substr((string)$professor['prenom'], 0, 1).mb_substr((string)$professor['nom'], 0, 1));
                        ?>
                        <label class="meeting-guest" data-guest-name="<?= $h(mb_strtolower($fullName)) ?>">
                            <input type="checkbox" name="professeur_ids[]" value="<?= (int)$professor['id'] ?>">
                            <span class="meeting-avatar"><?= $h($initials) ?></span>
                            <span class="meeting-guest-name"><?= $h($fullName) ?></span>
                            <span class="meeting-check">✓</span>
                        </label>
                        <?php endforeach; ?>
                    </div>
                    <?php if (!$professors): ?><p class="meeting-empty">Aucun professeur actif n’est disponible.</p><?php endif; ?>
                </fieldset>

                <label class="meeting-field meeting-field-wide">
                    <span>Informations complémentaires</span>
                    <textarea name="description" rows="4" maxlength="2000" placeholder="Ordre du jour, documents à prévoir, salle…"></textarea>
                </label>

                <button class="meeting-submit" type="submit" <?= !$professors ? 'disabled' : '' ?>>
                    <span>＋</span> Ajouter aux plannings
                </button>
            </form>
        </article>

        <article class="meeting-panel meeting-history">
            <div class="meeting-panel-title">
                <span class="meeting-step">2</span>
                <div><h3>Réunions enregistrées</h3><p><?= $meetingCount ?> réunion<?= $meetingCount > 1 ? 's' : '' ?> planifiée<?= $meetingCount > 1 ? 's' : '' ?></p></div>
            </div>

            <?php if (!$meetings): ?>
                <div class="meeting-empty-state">
                    <span>▣</span>
                    <strong>Aucune réunion enregistrée</strong>
                    <p>La première réunion apparaîtra ici avec sa date et ses participants.</p>
                </div>
            <?php else: ?>
                <div class="meeting-list">
                    <?php foreach ($meetings as $meeting): ?>
                    <article class="meeting-card">
                        <div class="meeting-date">
                            <strong><?= date('d', strtotime((string)$meeting['date_evenement'])) ?></strong>
                            <span><?= $h(mb_strtoupper(date('M', strtotime((string)$meeting['date_evenement'])))) ?></span>
                        </div>
                        <div class="meeting-card-body">
                            <h4><?= $h($meeting['titre']) ?></h4>
                            <p class="meeting-time"><?= substr((string)$meeting['heure_debut'], 0, 5) ?>–<?= substr((string)$meeting['heure_fin'], 0, 5) ?></p>
                            <p class="meeting-invites"><b>Invités :</b> <?= $h($meeting['invites']) ?></p>
                            <?php if (!empty($meeting['description'])): ?><p class="meeting-description"><?= nl2br($h($meeting['description'])) ?></p><?php endif; ?>
                            <details class="meeting-reinvite">
                                <summary>＋ Ajouter / réinviter des professeurs</summary>
                                <form method="post" action="/public/direction/reunions/invites/ajouter">
                                    <?= \App\Core\Csrf::field() ?>
                                    <input type="hidden" name="reunion" value="<?= $h($meeting['public_token']) ?>">
                                    <?php $already=array_flip(array_filter(array_map('intval',explode(',',(string)$meeting['invite_ids'])))); ?>
                                    <div class="meeting-guest-grid">
                                    <?php foreach($professors as $professor): $pid=(int)$professor['id']; ?>
                                        <label class="meeting-guest<?=isset($already[$pid])?' is-invited':''?>">
                                            <input type="checkbox" name="professeur_ids[]" value="<?=$pid?>" <?=isset($already[$pid])?'disabled':''?>>
                                            <span class="meeting-guest-name"><?=$h(trim($professor['prenom'].' '.$professor['nom']))?></span>
                                            <span class="meeting-check"><?=isset($already[$pid])?'Déjà invité':'✓'?></span>
                                        </label>
                                    <?php endforeach; ?>
                                    </div>
                                    <button class="meeting-submit" type="submit">Ajouter les nouveaux invités</button>
                                </form>
                            </details>
                        </div>
                    </article>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </article>
    </div>
</section>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const form = document.querySelector('[data-meeting-form]');
    if (!form) return;
    const boxes = [...form.querySelectorAll('input[name="professeur_ids[]"]')];
    const count = form.querySelector('[data-guest-count]');
    const all = form.querySelector('[data-select-all]');
    const search = form.querySelector('[data-guest-search]');
    const refresh = () => {
        const selected = boxes.filter(box => box.checked).length;
        count.textContent = selected + ' sélectionné' + (selected > 1 ? 's' : '');
        all.textContent = selected === boxes.length && boxes.length ? 'Tout désélectionner' : 'Tout sélectionner';
    };
    boxes.forEach(box => box.addEventListener('change', refresh));
    all?.addEventListener('click', () => {
        const visible = boxes.filter(box => !box.closest('[data-guest-name]').hidden);
        const select = visible.some(box => !box.checked);
        visible.forEach(box => box.checked = select);
        refresh();
    });
    search?.addEventListener('input', () => {
        const query = search.value.trim().toLocaleLowerCase('fr');
        form.querySelectorAll('[data-guest-name]').forEach(card => {
            card.hidden = query !== '' && !card.dataset.guestName.includes(query);
        });
    });
    form.addEventListener('submit', event => {
        if (!boxes.some(box => box.checked)) {
            event.preventDefault();
            count.textContent = 'Sélectionnez au moins un professeur';
            count.classList.add('is-error');
        }
    });
    refresh();
});
</script>
