<?php
ob_start();
$isEdit = !empty($page);
$isSystem = $isEdit && \App\Models\Page::isSystemPage($page);
$systemTypes = \App\Models\Page::systemPageTypes();
$typeLabels = [
    'home' => 'Homepage', 'contact' => 'Contact', 'gallery' => 'Gallery',
    'blog' => 'Blog', 'events' => 'Events', 'downloads' => 'Downloads',
];
?>
<link rel="stylesheet" href="/admin/assets/editor/jodit.min.css">

<div class="content-header">
    <div class="content-header-left">
        <div class="content-header-icon"><?= icon('file-text', 20) ?></div>
        <h2><?= $isEdit ? __('admin.pages.edit') : __('admin.pages.create') ?></h2>
    </div>
    <div class="header-actions">
        <?php if ($isEdit): ?>
        <a href="<?= admin_url('preview/page/' . (int) $page['id']) ?>" target="_blank" class="btn btn-secondary btn-sm"><?= __('admin.common.preview') ?></a>
        <?php endif; ?>
        <?php if ($isEdit && ($page['status'] ?? '') === 'published' && !empty($page['slug'])): ?>
        <a href="/<?= e($page['slug']) ?>" target="_blank" class="btn btn-secondary btn-sm"><?= __('admin.pages.view_page') ?></a>
        <?php endif; ?>
        <?php if ($isEdit && setting('content_revisions_enabled', '1') === '1'): ?>
        <button type="button" class="btn btn-secondary btn-sm" onclick="loadRevisions('page', <?= (int) $page['id'] ?>)">
            <?= icon('history', 14) ?> <?= __('admin.revisions.title') ?>
        </button>
        <?php endif; ?>
        <a href="<?= admin_url('pages') ?>" class="btn btn-secondary"><?= __('admin.pages.back') ?></a>
    </div>
</div>

<?php if ($isSystem): ?>
<div class="alert alert-info" style="margin-bottom:1rem;">
    <strong><?= e($typeLabels[$page['page_type']] ?? ucfirst($page['page_type'])) ?> – System Page</strong><br>
    This is a system/module page. You can edit the title, intro content, SEO fields, and the show-title setting. The slug and template are managed by the CMS core.
</div>
<?php endif; ?>

<form method="POST" action="<?= $isEdit ? admin_url('pages/update/' . (int)$page['id']) : admin_url('pages/store') ?>" class="admin-form" id="pageForm">
    <?= $csrf->field() ?>

    <div class="form-grid">
        <div class="form-main">
            <div class="form-group">
                <label for="title"><?= __('admin.pages.page_title') ?> <span class="required">*</span></label>
                <input type="text" id="title" name="title"
                       value="<?= e($page['title'] ?? '') ?>"
                       required
                       placeholder="<?= __('admin.pages.page_title_placeholder') ?>">
            </div>

            <div class="form-group">
                <label for="slug"><?= __('admin.common.slug') ?></label>
                <div class="slug-preview-wrap">
                    <span class="slug-prefix">/</span>
                    <input type="text" id="slug" name="slug"
                           value="<?= e($page['slug'] ?? '') ?>"
                           placeholder="<?= __('admin.pages.slug_placeholder') ?>"
                           <?= $isSystem ? 'readonly style="background:#f0f0f0;cursor:not-allowed;"' : '' ?>>
                </div>
                <?php if ($isSystem): ?>
                <small class="form-hint">The slug of a system page cannot be changed.</small>
                <?php else: ?>
                <small class="form-hint"><?= __('admin.pages.slug_help') ?></small>
                <?php endif; ?>
            </div>

            <div class="form-group">
                <label for="content"><?= __('admin.pages.content') ?></label>
                <textarea id="content" name="content" rows="15"><?= e($page['content'] ?? '') ?></textarea>
                <div class="editor-footer-row">
                    <small class="form-hint editor-hint"><?= __('admin.pages.content_help') ?></small>
                    <button type="button" class="btn btn-secondary btn-sm media-picker-btn" id="mediaPickerBtn" data-media-picker data-editor-target="content"><?= __('admin.pages.insert_from_library') ?></button>
                </div>
            </div>
        </div>

        <div class="form-sidebar">
            <div class="form-card">
                <h4><?= __('admin.pages.publishing') ?></h4>
                <div class="form-group">
                    <label for="status"><?= __('admin.common.status') ?></label>
                    <select id="status" name="status">
                        <option value="draft"     <?= ($page['status'] ?? 'draft') === 'draft'     ? 'selected' : '' ?>><?= __('admin.common.draft') ?></option>
                        <option value="published" <?= ($page['status'] ?? '') === 'published'       ? 'selected' : '' ?>><?= __('admin.common.published') ?></option>
                        <?php if (setting('content_scheduling_enabled', '1') === '1'): ?>
                        <option value="scheduled" <?= ($page['status'] ?? '') === 'scheduled'       ? 'selected' : '' ?>><?= __('admin.common.scheduled') ?></option>
                        <?php endif; ?>
                    </select>
                </div>
                <?php if (setting('content_scheduling_enabled', '1') === '1'): ?>
                <div class="form-group scheduling-field" id="publishAtGroup" style="<?= ($page['status'] ?? 'draft') === 'scheduled' || !empty($page['publish_at']) ? '' : 'display:none;' ?>">
                    <label for="publish_at"><?= __('admin.pages.publish_at') ?></label>
                    <input type="datetime-local" id="publish_at" name="publish_at"
                           value="<?= !empty($page['publish_at']) ? date('Y-m-d\TH:i', strtotime($page['publish_at'])) : '' ?>">
                    <small class="form-hint"><?= __('admin.pages.publish_at_help') ?></small>
                </div>
                <div class="form-group scheduling-field" id="unpublishAtGroup">
                    <label for="unpublish_at"><?= __('admin.pages.unpublish_at') ?></label>
                    <input type="datetime-local" id="unpublish_at" name="unpublish_at"
                           value="<?= !empty($page['unpublish_at']) ? date('Y-m-d\TH:i', strtotime($page['unpublish_at'])) : '' ?>">
                    <small class="form-hint"><?= __('admin.pages.unpublish_at_help') ?></small>
                </div>
                <?php endif; ?>
                <?php if (!$isSystem): ?>
                <div class="form-group">
                    <label for="template"><?= __('admin.pages.template') ?></label>
                    <select id="template" name="template">
                        <option value="page"    <?= ($page['template'] ?? 'page') === 'page'    ? 'selected' : '' ?>><?= __('admin.pages.template_default') ?></option>
                        <option value="home"    <?= ($page['template'] ?? '') === 'home'         ? 'selected' : '' ?>><?= __('admin.pages.template_home') ?></option>
                        <option value="contact" <?= ($page['template'] ?? '') === 'contact'      ? 'selected' : '' ?>><?= __('admin.pages.template_contact') ?></option>
                    </select>
                    <small class="form-hint"><?= __('admin.pages.template_help') ?></small>
                </div>
                <?php else: ?>
                <input type="hidden" name="template" value="<?= e($page['template'] ?? 'page') ?>">
                <?php endif; ?>
                <div class="form-group">
                    <label for="sort_order"><?= __('admin.pages.order') ?></label>
                    <input type="number" id="sort_order" name="sort_order"
                           value="<?= (int)($page['sort_order'] ?? 0) ?>"
                           min="0" step="1">
                    <small class="form-hint"><?= __('admin.pages.sort_help') ?></small>
                </div>
                <?php if (!$isSystem || ($page['page_type'] ?? '') === 'home'): ?>
                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="is_homepage" value="1" <?= !empty($page['is_homepage']) ? 'checked' : '' ?>>
                        <?= __('admin.pages.set_homepage') ?>
                    </label>
                </div>
                <?php endif; ?>
                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="hidden" name="show_title" value="0">
                        <input type="checkbox" name="show_title" value="1" <?= ($page['show_title'] ?? 1) ? 'checked' : '' ?>>
                        <?= __('admin.pages.show_title') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.pages.show_title_help') ?></small>
                </div>
                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="hidden" name="pagebuilder_enabled" value="0">
                        <input type="checkbox" name="pagebuilder_enabled" value="1" <?= ($page['pagebuilder_enabled'] ?? 0) ? 'checked' : '' ?>>
                        Page Builder
                    </label>
                    <small class="form-hint">Use the page builder instead of the content editor.</small>
                </div>
                <?php if ($isEdit && !empty($page['pagebuilder_enabled'])): ?>
                <a href="<?= admin_url('pages/' . (int) $page['id'] . '/pagebuilder') ?>" class="btn btn-secondary btn-full" style="margin-top:0.25rem;">
                    <?= icon('page-builder', 16) ?> Open Page Builder
                </a>
                <?php endif; ?>
                <button type="submit" class="btn btn-primary btn-full" style="margin-top:0.5rem;">
                    <?= $isEdit ? __('admin.pages.update_page') : __('admin.pages.create_page') ?>
                </button>
            </div>

            <div class="form-card">
                <h4><?= __('admin.pages.seo') ?></h4>
                <div class="form-group">
                    <label for="seo_title"><?= __('admin.pages.seo_title') ?></label>
                    <input type="text" id="seo_title" name="seo_title"
                           value="<?= e($page['seo_title'] ?? '') ?>"
                           placeholder="<?= __('admin.pages.seo_title_default') ?>"
                           maxlength="120">
                    <div class="seo-counter" id="seo_title_counter">
                        <span id="seo_title_len">0</span><?= __('admin.pages.seo_title_hint') ?>
                    </div>
                </div>
                <div class="form-group">
                    <label for="seo_description"><?= __('admin.pages.seo_description') ?></label>
                    <textarea id="seo_description" name="seo_description" rows="3"
                              placeholder="<?= __('admin.pages.seo_description_default') ?>"
                              maxlength="320"><?= e($page['seo_description'] ?? '') ?></textarea>
                    <div class="seo-counter" id="seo_desc_counter">
                        <span id="seo_desc_len">0</span><?= __('admin.pages.seo_description_hint') ?>
                    </div>
                </div>
            </div>

            <?php if (setting('extended_seo_enabled', '1') === '1'): ?>
            <div class="form-card">
                <h4><?= __('admin.pages.extended_seo') ?></h4>
                <div class="form-group">
                    <label for="og_image"><?= __('admin.pages.og_image') ?></label>
                    <div class="media-picker-field">
                        <input type="hidden" id="og_image" name="og_image"
                               value="<?= e($page['og_image'] ?? '') ?>">
                        <div class="media-picker-preview" id="og_image_preview">
                            <?php if (!empty($page['og_image'])): ?>
                            <img src="<?= e($page['og_image']) ?>" alt="OG Image" style="max-width:200px;max-height:120px;">
                            <?php endif; ?>
                        </div>
                        <button type="button" class="btn btn-sm btn-secondary" onclick="openMediaPicker('og_image')">
                            <?= icon('image', 14) ?> <?= __('admin.common.select') ?>
                        </button>
                        <?php if (!empty($page['og_image'])): ?>
                        <button type="button" class="btn btn-sm btn-ghost" onclick="document.getElementById('og_image').value='';document.getElementById('og_image_preview').innerHTML='';">
                            <?= icon('x', 14) ?> <?= __('admin.common.remove') ?>
                        </button>
                        <?php endif; ?>
                    </div>
                    <small class="form-hint"><?= __('admin.pages.og_image_help') ?></small>
                </div>
                <div class="form-group">
                    <label for="robots_meta"><?= __('admin.pages.robots_meta') ?></label>
                    <select id="robots_meta" name="robots_meta">
                        <option value=""><?= __('admin.pages.robots_default') ?></option>
                        <option value="index, follow" <?= ($page['robots_meta'] ?? '') === 'index, follow' ? 'selected' : '' ?>>index, follow</option>
                        <option value="noindex, follow" <?= ($page['robots_meta'] ?? '') === 'noindex, follow' ? 'selected' : '' ?>>noindex, follow</option>
                        <option value="index, nofollow" <?= ($page['robots_meta'] ?? '') === 'index, nofollow' ? 'selected' : '' ?>>index, nofollow</option>
                        <option value="noindex, nofollow" <?= ($page['robots_meta'] ?? '') === 'noindex, nofollow' ? 'selected' : '' ?>>noindex, nofollow</option>
                    </select>
                    <small class="form-hint"><?= __('admin.pages.robots_meta_help') ?></small>
                </div>
                <div class="form-group">
                    <label for="canonical_url"><?= __('admin.pages.canonical_url') ?></label>
                    <input type="url" id="canonical_url" name="canonical_url"
                           value="<?= e($page['canonical_url'] ?? '') ?>"
                           placeholder="<?= __('admin.pages.canonical_url_placeholder') ?>">
                    <small class="form-hint"><?= __('admin.pages.canonical_url_help') ?></small>
                </div>
            </div>
            <?php endif; ?>

            <?php if (setting('custom_css_js_enabled', '1') === '1'): ?>
            <div class="form-card">
                <h4><?= __('admin.pages.custom_code') ?></h4>
                <div class="form-group">
                    <label for="custom_css"><?= __('admin.pages.custom_css') ?></label>
                    <textarea id="custom_css" name="custom_css" rows="6"
                              style="font-family:monospace;font-size:13px;"
                              placeholder="/* Custom CSS */"><?= e($page['custom_css'] ?? '') ?></textarea>
                    <small class="form-hint"><?= __('admin.pages.custom_css_help') ?></small>
                </div>
                <div class="form-group">
                    <label for="custom_js"><?= __('admin.pages.custom_js') ?></label>
                    <textarea id="custom_js" name="custom_js" rows="6"
                              style="font-family:monospace;font-size:13px;"
                              placeholder="// Custom JavaScript"><?= e($page['custom_js'] ?? '') ?></textarea>
                    <small class="form-hint"><?= __('admin.pages.custom_js_help') ?></small>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</form>

<!-- ── Media Picker Modal ──────────────────────────────────────────────── -->
<div id="mediaPickerOverlay" class="media-picker-overlay" style="display:none;" role="dialog" aria-modal="true" aria-label="Image Library">
    <div class="media-picker-modal">
        <div class="media-picker-header">
            <h3><?= __('admin.pages.insert_image_title') ?></h3>
            <button type="button" class="media-picker-close" id="mediaPickerClose" aria-label="Close">&times;</button>
        </div>
        <div id="mediaPickerBody">
            <p class="text-muted" style="text-align:center; padding:2rem;"><?= __('admin.common.loading') ?></p>
        </div>
        <div class="media-picker-footer">
            <small class="form-hint"><?= __('admin.pages.insert_image_help') ?></small>
        </div>
    </div>
</div>

<script src="/admin/assets/editor/jodit.min.js"></script>
<script>
(function () {
    // ── Jodit WYSIWYG Editor ──────────────────────────────────────────────
    var contentTextarea = document.getElementById('content');
    var joditEditor     = null;
    if (contentTextarea && typeof Jodit !== 'undefined') {
        joditEditor = Jodit.make(contentTextarea, {
            height: 480,
            language: 'en',
            toolbarSticky: true,
            toolbarStickyOffset: 56, // admin topbar height
            buttons: [
                'bold', 'italic', 'underline', 'strikethrough', 'eraser',
                '|',
                'paragraph', 'fontsize',
                '|',
                'ul', 'ol', 'indent', 'outdent',
                '|',
                'superscript', 'subscript',
                '|',
                'link', 'image',
                '|',
                'table', 'hr',
                '|',
                'align',
                '|',
                'undo', 'redo',
                '\n',
                'find',
                '|',
                'source',
                '|',
                'fullsize'
            ],
            // HTML Preservation – do not strip or modify existing HTML
            cleanHTML: {
                fillEmptyParagraph: false,
                replaceNBSP: false,
                removeEmptyElements: false,
                allowTags: false,
                denyTags: false
            },
            enter: 'P',
            allowResizeX: false,
            allowResizeY: true,
            minHeight: 300,
            // Keep HTML intact when pasting
            processPasteHTML: false,
            askBeforePasteHTML: false,
            askBeforePasteFromWord: false,
            defaultActionOnPaste: 'insert_as_html'
        });
        // Store instance on the element so admin.js can reach it via
        // [data-editor-target] without relying on a global variable.
        contentTextarea._joditEditor = joditEditor;
    }

    // ── Slug Auto-Generation ─────────────────────────────────────────────
    var titleInput = document.getElementById('title');
    var slugInput  = document.getElementById('slug');

    <?php if (!$isEdit): ?>
    if (titleInput && slugInput) {
        titleInput.addEventListener('input', function () {
            if (!slugInput._userEdited) {
                slugInput.value = slugifyTitle(this.value);
            }
        });
        slugInput.addEventListener('input', function () {
            this._userEdited = (this.value.trim() !== '');
        });
    }
    <?php endif; ?>

    function slugifyTitle(str) {
        var map = {
            'ä':'ae','ö':'oe','ü':'ue','Ä':'ae','Ö':'oe','Ü':'ue','ß':'ss',
            'à':'a','á':'a','â':'a','ã':'a','å':'a','æ':'ae',
            'ç':'c','è':'e','é':'e','ê':'e','ë':'e',
            'ì':'i','í':'i','î':'i','ï':'i',
            'ñ':'n','ò':'o','ó':'o','ô':'o','õ':'o','ø':'o',
            'ù':'u','ú':'u','û':'u',
            'ý':'y','þ':'th','ÿ':'y'
        };
        return str
            .replace(/[äöüÄÖÜßàáâãåæçèéêëìíîïñòóôõøùúûýþÿ]/g, function (c) { return map[c] || c; })
            .toLowerCase()
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-+|-+$/g, '');
    }

    // ── SEO Character Counters ───────────────────────────────────────────
    function updateCounter(inputId, lenId, limit) {
        var el  = document.getElementById(inputId);
        var len = document.getElementById(lenId);
        if (!el || !len) return;
        function update() {
            var n = el.value.length;
            len.textContent = n;
            len.className = n > limit ? 'seo-over' : (n > limit * 0.9 ? 'seo-warn' : '');
        }
        el.addEventListener('input', update);
        update();
    }

    updateCounter('seo_title',       'seo_title_len', 60);
    updateCounter('seo_description', 'seo_desc_len',  160);

    // ── Scheduling: show/hide publish_at based on status ────────────────
    var statusSelect    = document.getElementById('status');
    var publishAtGroup  = document.getElementById('publishAtGroup');
    if (statusSelect && publishAtGroup) {
        statusSelect.addEventListener('change', function () {
            publishAtGroup.style.display = (this.value === 'scheduled') ? '' : 'none';
        });
    }

    // Media Picker is wired up by admin.js after it loads, via the
    // [data-media-picker] / [data-editor-target] attributes on the button.
})();
</script>

<?php $content = ob_get_clean(); include dirname(__DIR__) . '/layouts/admin.php'; ?>
