<main id="main-content">

    <div class="admin-list-toolbar">
        <h1>Accès étudiant·e</h1>
        <div class="admin-list-toolbar__right">
            <button type="button" class="admin-btn admin-btn--sm" id="open-create-dialog">
                ＋ Créer un lien
            </button>
        </div>
    </div>

    <?php if (empty($links)): ?>
        <p class="admin-empty">Aucun lien d'accès créé. Cliquez sur « Créer un lien » pour générer un lien partageable.</p>
    <?php else: ?>
    <table>
        <thead>
            <tr>
                <th scope="col">Lien</th>
                <th scope="col">Statut</th>
                <th scope="col">Mot de passe</th>
                <th scope="col">Utilisations</th>
                <th scope="col">Expiration</th>
                <th scope="col">Créé le</th>
                <th scope="col">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($links as $link): ?>
                <?php
                    $isExpired = $link['expires_at'] !== null && strtotime($link['expires_at']) < time();
                    $isActive  = (bool)$link['is_active'] && !$isExpired;
                    $statusLabel = $isExpired ? 'Expiré' : ($link['is_active'] ? 'Actif' : 'Désactivé');
                    if ($isExpired) {
                        $statusClass = 'status-badge status-pending';
                    } elseif ($link['is_active']) {
                        $statusClass = 'status-badge status-published';
                    } else {
                        $statusClass = 'status-badge';
                        $statusClass .= ' style="background:var(--error-muted-bg);color:var(--error);"';
                    }
                    $fullUrl = $baseUrl . '/partage/' . htmlspecialchars($link['slug']);
                    $created = date('d/m/Y H:i', strtotime($link['created_at']));
                    $expires = $link['expires_at'] ? date('d/m/Y', strtotime($link['expires_at'])) : '—';
                    $hasPassword = !empty($link['password_hash']);
                ?>
                <tr>
                    <td>
                        <code style="font-size:var(--step--2);color:var(--text-secondary);"><?= htmlspecialchars($link['slug']) ?></code>
                        <input type="hidden" id="url-<?= $link['id'] ?>" value="<?= $fullUrl ?>">
                    </td>
                    <td>
                        <?php if ($isExpired): ?>
                            <span class="status-badge status-pending"><?= $statusLabel ?></span>
                        <?php elseif ($link['is_active']): ?>
                            <span class="status-badge status-published"><?= $statusLabel ?></span>
                        <?php else: ?>
                            <span style="display:inline-block;padding:var(--space-3xs) var(--space-2xs);border-radius:3px;font-size:var(--step--2);font-weight:500;letter-spacing:0.04em;background:var(--error-muted-bg);color:var(--error);"><?= $statusLabel ?></span>
                        <?php endif; ?>
                    </td>
                    <td><?= $hasPassword ? '🔒 Oui' : 'Non' ?></td>
                    <td style="text-align:center;"><?= intval($link['usage_count']) ?></td>
                    <td><?= $expires ?></td>
                    <td><?= $created ?></td>
                    <td>
                        <div class="admin-actions">
                            <a href="/partage/<?= urlencode($link['slug']) ?>" target="_blank" rel="noopener"
                               class="admin-btn-sm admin-btn-visit" title="Visiter le formulaire">
                                👁 Visiter
                            </a>
                            <button type="button" class="admin-btn-sm admin-btn-view"
                                    onclick="copyUrl(<?= $link['id'] ?>)" title="Copier l'URL">
                                Copier
                            </button>
                            <form method="post" action="actions/acces-etudiante.php" class="publish-form">
                                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
                                <input type="hidden" name="action" value="toggle">
                                <input type="hidden" name="id" value="<?= $link['id'] ?>">
                                <button type="submit"
                                        class="admin-btn-sm <?= $link['is_active'] ? 'admin-btn-unpublish' : 'admin-btn-publish' ?>"
                                        title="<?= $link['is_active'] ? 'Désactiver' : 'Activer' ?>">
                                    <?= $link['is_active'] ? '⏸' : '▶' ?>
                                </button>
                            </form>
                            <button type="button" class="admin-btn-sm admin-btn-edit"
                                    onclick="openPasswordDialog(<?= $link['id'] ?>, <?= $hasPassword ? 'true' : 'false' ?>)"
                                    title="Modifier le mot de passe">
                                🔑
                            </button>
                            <form method="post" action="actions/acces-etudiante.php" class="publish-form"
                                  onsubmit="return confirm('Supprimer ce lien ? Les soumissions via ce lien seront bloquées.')">
                                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?= $link['id'] ?>">
                                <button type="submit" class="admin-btn-sm admin-btn-delete" title="Supprimer">
                                    🗑
                                </button>
                            </form>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>
</main>

<!-- ═══════════════════════ CREATE DIALOG ═══════════════════════ -->
<dialog id="create-dialog" class="admin-dialog" aria-labelledby="create-dialog-title">
    <div class="admin-dialog__header">
        <h2 id="create-dialog-title">Créer un lien d'accès</h2>
        <button type="button" class="admin-dialog__close" aria-label="Fermer"
                onclick="document.getElementById('create-dialog').close()">&#x2715;</button>
    </div>
    <form method="post" action="actions/acces-etudiante.php" class="admin-form">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
        <input type="hidden" name="action" value="create">
        <div>
            <label for="create-password">Mot de passe (optionnel)</label>
            <input type="password" id="create-password" name="password" autocomplete="new-password">
            <small>Laissez vide pour un lien sans mot de passe.</small>
        </div>
        <div>
            <label for="create-expires">Expiration (optionnel)</label>
            <input type="datetime-local" id="create-expires" name="expires_at">
            <small>Laissez vide pour qu'il n'expire jamais.</small>
        </div>
        <div class="admin-form-footer">
            <button type="submit" class="admin-btn">Créer le lien</button>
            <button type="button" class="admin-btn-secondary"
                    onclick="document.getElementById('create-dialog').close()">Annuler</button>
        </div>
    </form>
</dialog>

<!-- ═══════════════════════ PASSWORD DIALOG ═══════════════════════ -->
<dialog id="password-dialog" class="admin-dialog" aria-labelledby="password-dialog-title">
    <div class="admin-dialog__header">
        <h2 id="password-dialog-title">Mot de passe</h2>
        <button type="button" class="admin-dialog__close" aria-label="Fermer"
                onclick="document.getElementById('password-dialog').close()">&#x2715;</button>
    </div>
    <form method="post" action="actions/acces-etudiante.php" class="admin-form">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
        <input type="hidden" name="action" value="set_password">
        <input type="hidden" name="id" id="password-link-id" value="">
        <div>
            <label for="password-input">Nouveau mot de passe</label>
            <input type="password" id="password-input" name="password" autocomplete="new-password">
            <small>Laissez vide pour supprimer le mot de passe.</small>
            <p id="password-current-info" style="font-size:var(--step--2);color:var(--text-secondary);margin-top:var(--space-2xs);"></p>
        </div>
        <div class="admin-form-footer">
            <button type="submit" class="admin-btn">Enregistrer</button>
            <button type="button" class="admin-btn-secondary"
                    onclick="document.getElementById('password-dialog').close()">Annuler</button>
        </div>
    </form>
</dialog>

<script>
document.getElementById('open-create-dialog').addEventListener('click', () => {
    document.getElementById('create-dialog').showModal();
});

function copyUrl(id) {
    const input = document.getElementById('url-' + id);
    navigator.clipboard.writeText(input.value).then(() => {
        const btn = event.target.closest('button');
        const orig = btn.textContent;
        btn.textContent = '✓ Copié';
        setTimeout(() => { btn.textContent = orig; }, 1200);
    });
}

function openPasswordDialog(id, hasPassword) {
    document.getElementById('password-link-id').value = id;
    const info = document.getElementById('password-current-info');
    info.textContent = hasPassword
        ? 'Un mot de passe est actuellement configuré. Entrez-en un nouveau ou laissez vide pour le supprimer.'
        : 'Aucun mot de passe configuré.';
    document.getElementById('password-dialog').showModal();
}
</script>
