<?php
/**
 * Édition d'une page (Tabler).
 * @var array<string,mixed> $p
 * @var array<string,string> $errors
 * @var ?string $flash
 */

use App\Core\Csrf;

$isHome   = ($p['slug'] ?? '') === 'home';
$isSystem = in_array(($p['slug'] ?? ''), ['home', 'mentions-legales'], true);
?>
<h2 class="h2 mb-3">Page &mdash; <?= e($p['title']) ?></h2>

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

<form method="post" action="<?= e(base_url('admin/pages/' . $p['id'])) ?>">
    <?= Csrf::field() ?>
    <div class="row row-cards">
        <div class="col-lg-8"><div class="card"><div class="card-body">
            <div class="mb-3"><label class="form-label required">Titre</label><input type="text" name="title" class="form-control" value="<?= e($p['title']) ?>" required></div>
            <div class="mb-3"><label class="form-label">URL</label><input type="text" class="form-control" value="<?= $isHome ? '/ (accueil)' : '/' . e($p['slug']) ?>" disabled></div>
            <div class="mb-1">
                <label class="form-label"><?= $isHome ? 'Texte d\'accueil (affiché au-dessus des galeries)' : 'Contenu' ?></label>
                <textarea id="body_html" name="body_html" class="form-control" rows="10"><?= e($p['body_html'] ?? '') ?></textarea>
            </div>
        </div></div></div>
        <div class="col-lg-4">
            <?php if ($isSystem): ?>
            <div class="card mb-3"><div class="card-body"><div class="text-secondary small"><i class="ti ti-lock me-1"></i>Page système — toujours publiée.</div></div></div>
            <?php else: ?>
            <div class="card mb-3"><div class="card-body"><div class="mb-0">
                <label class="form-label">Statut</label>
                <select name="status" class="form-select">
                    <option value="published" <?= ($p['status'] ?? '') === 'published' ? 'selected' : '' ?>>Publié</option>
                    <option value="draft" <?= ($p['status'] ?? '') === 'draft' ? 'selected' : '' ?>>Brouillon</option>
                </select>
                <div class="form-hint mt-1">« Publié » affiche la page + le lien en pied de page ; « Brouillon » → 404.</div>
            </div></div></div>
            <?php endif; ?>
            <div class="card"><div class="card-header"><h3 class="card-title">SEO</h3></div><div class="card-body">
                <div class="mb-3"><label class="form-label">Title SEO</label><input type="text" name="seo_title" class="form-control" value="<?= e($p['seo_title'] ?? '') ?>"></div>
                <div class="mb-3"><label class="form-label">Meta description</label><textarea name="seo_description" class="form-control" rows="2"><?= e($p['seo_description'] ?? '') ?></textarea></div>
                <label class="form-check"><input type="checkbox" class="form-check-input" name="seo_noindex" value="1" <?= !empty($p['seo_noindex']) ? 'checked' : '' ?>><span class="form-check-label">Ne pas indexer (noindex)</span></label>
            </div></div>
        </div>
    </div>
    <div class="d-flex gap-2 mt-3 justify-content-end">
        <a class="btn" href="<?= e(base_url('admin/pages')) ?>">Annuler</a>
        <button type="submit" class="btn btn-primary"><i class="ti ti-device-floppy me-1"></i>Enregistrer</button>
    </div>
</form>

<script src="https://cdn.jsdelivr.net/npm/tinymce@7.3.0/tinymce.min.js"></script>
<script>
if (window.tinymce) {
    var PAGE_IMG_UPLOAD = <?= json_encode(base_url('admin/pages/upload-image')) ?>;
    var __meta = document.querySelector('meta[name="csrf-token"]');
    var PAGE_CSRF = __meta ? __meta.getAttribute('content') : '';

    function pageUpload(file, filename) {
        var fd = new FormData();
        fd.append('_csrf', PAGE_CSRF);
        fd.append('file', file, filename);
        return fetch(PAGE_IMG_UPLOAD, { method: 'POST', body: fd, credentials: 'same-origin' })
            .then(function (r) { return r.json().then(function (d) { return { ok: r.ok, d: d }; }); });
    }

    tinymce.init({
        selector: '#body_html', menubar: false, plugins: 'lists link image code',
        toolbar: 'styles | bold italic superscript | bullist numlist | link image | removeformat | code',
        style_formats: [{ title: 'Paragraphe', format: 'p' }, { title: 'Titre 1', block: 'h1' }, { title: 'Titre 2', block: 'h2' }, { title: 'Titre 3', block: 'h3' }],
        height: 320, branding: false, license_key: 'gpl',
        valid_elements: '*[*]',
        content_css: [<?= json_encode(asset('vendor/bootstrap/bootstrap.min.css')) ?>, <?= json_encode(asset('css/app.css')) ?>],
        automatic_uploads: true, file_picker_types: 'image',
        images_upload_handler: function (blobInfo) {
            return new Promise(function (resolve, reject) {
                pageUpload(blobInfo.blob(), blobInfo.filename()).then(function (res) {
                    if (res.ok && res.d && res.d.location) { resolve(res.d.location); }
                    else { reject({ message: (res.d && res.d.error) || 'Téléversement échoué.', remove: true }); }
                }).catch(function () { reject({ message: 'Téléversement échoué.', remove: true }); });
            });
        },
        file_picker_callback: function (cb) {
            var input = document.createElement('input');
            input.type = 'file'; input.accept = 'image/*';
            input.onchange = function () {
                var file = input.files[0];
                if (!file) { return; }
                pageUpload(file, file.name).then(function (res) {
                    if (res.ok && res.d && res.d.location) { cb(res.d.location, { alt: file.name }); }
                    else { alert((res.d && res.d.error) || 'Téléversement échoué.'); }
                }).catch(function () { alert('Téléversement échoué.'); });
            };
            input.click();
        }
    });
}
</script>
