<?php
/**
 * Redirections (Tabler).
 * @var list<array<string,mixed>> $redirects
 * @var ?string $flash
 * @var list<string> $errors
 */

use App\Core\Csrf;

$labels = [301 => '301 — Permanente', 302 => '302 — Temporaire', 410 => '410 — Supprimée'];
?>
<h2 class="h2 mb-3">Redirections</h2>

<?php if (!empty($errors)): ?><div class="alert alert-danger"><?php foreach ($errors as $er): ?><div><?= e($er) ?></div><?php endforeach; ?></div><?php endif; ?>

<div class="card mb-3"><div class="card-body">
    <form method="post" action="<?= e(base_url('admin/redirects')) ?>" class="row g-2 align-items-end">
        <?= Csrf::field() ?>
        <div class="col-md-4"><label class="form-label">Ancien chemin</label><input type="text" name="old_path" class="form-control" placeholder="/ancienne-url" required></div>
        <div class="col-md-4"><label class="form-label">Nouvelle cible</label><input type="text" name="new_path" class="form-control" placeholder="/nouvelle-url ou https://…"></div>
        <div class="col-md-2"><label class="form-label">Type</label><select name="code" class="form-select"><option value="301">301</option><option value="302">302</option><option value="410">410</option></select></div>
        <div class="col-md-2"><button class="btn btn-primary w-100"><i class="ti ti-plus me-1"></i>Ajouter</button></div>
    </form>
</div></div>

<?php if (empty($redirects)): ?>
    <div class="card"><div class="card-body text-secondary">Aucune redirection.</div></div>
<?php else: ?>
    <div class="card"><div class="table-responsive">
        <table class="table table-vcenter card-table">
            <thead><tr><th>Ancien</th><th>Cible</th><th>Type</th><th class="w-1"></th></tr></thead>
            <tbody>
            <?php foreach ($redirects as $rd): ?>
                <tr>
                    <td class="text-secondary"><?= e($rd['old_path']) ?></td>
                    <td><?= (int) $rd['code'] === 410 ? '<span class="text-secondary">—</span>' : e($rd['new_path']) ?></td>
                    <td><span class="badge bg-azure-lt"><?= e($labels[(int) $rd['code']] ?? $rd['code']) ?></span></td>
                    <td class="text-end">
                        <a href="#" class="btn btn-sm btn-icon btn-ghost-danger" title="Supprimer"
                           data-bs-toggle="modal" data-bs-target="#deleteModal"
                           data-delete-url="<?= e(base_url('admin/redirects/' . $rd['id'] . '/delete')) ?>"
                           data-delete-label="<?= e($rd['old_path']) ?>"><i class="ti ti-trash"></i></a>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div></div>
<?php endif; ?>
