<?php include __DIR__ . '/../header.php'; ?>

<div class="container-fluid py-4">

    <!-- PAGE HEADER -->
    <div class="d-flex justify-content-between align-items-start mb-4">
        <div>
            <h3 class="mb-1">
                <i class="bi bi-file-earmark-text me-2"></i>
                <?= isset($page)
                    ? __('pages.form.edit_title', 'Edit Page')
                    : __('pages.form.create_title', 'Create Page')
                ?>
            </h3>
            <small class="text-muted">
                <?= __('sidebar.manage_site', 'Manage Site') ?>
                →
                <?= __('pages.title', 'Pages') ?>
            </small>
        </div>

        <!-- BACK BUTTON -->
        <a href="/admin/pages" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left me-1"></i>
            <?= __('actions.back', 'Back') ?>
        </a>
    </div>

    <form method="POST"
          action="<?= isset($page)
              ? '/admin/pages/update/' . (int)$page['id']
              : '/admin/pages/store'
          ?>">
        <?= \Core\System\Csrf::field(); ?>

        <div class="card shadow-sm border-0">

            <!-- TABS -->
            <div class="card-header bg-white border-bottom">
                <ul class="nav nav-tabs card-header-tabs" role="tablist">

                    <li class="nav-item" role="presentation">
                        <button class="nav-link active"
                                id="tab-content-btn"
                                data-bs-toggle="tab"
                                data-bs-target="#tab-content"
                                type="button"
                                role="tab"
                                aria-controls="tab-content"
                                aria-selected="true">
                            <i class="bi bi-pencil-square me-1"></i>
                            <?= __('pages.tab.content', 'Content') ?>
                        </button>
                    </li>

                    <li class="nav-item" role="presentation">
                        <button class="nav-link"
                                id="tab-seo-btn"
                                data-bs-toggle="tab"
                                data-bs-target="#tab-seo"
                                type="button"
                                role="tab"
                                aria-controls="tab-seo"
                                aria-selected="false">
                            <i class="bi bi-search me-1"></i>
                            <?= __('pages.tab.seo', 'SEO') ?>
                        </button>
                    </li>

                    <li class="nav-item" role="presentation">
                        <button class="nav-link"
                                id="tab-settings-btn"
                                data-bs-toggle="tab"
                                data-bs-target="#tab-settings"
                                type="button"
                                role="tab"
                                aria-controls="tab-settings"
                                aria-selected="false">
                            <i class="bi bi-gear me-1"></i>
                            <?= __('pages.tab.settings', 'Settings') ?>
                        </button>
                    </li>

                </ul>
            </div>

            <div class="card-body">
                <div class="tab-content">

                    <!-- CONTENT TAB -->
                    <div class="tab-pane fade show active"
                         id="tab-content"
                         role="tabpanel"
                         aria-labelledby="tab-content-btn"
                         tabindex="0">

                        <div class="row g-3">

                            <div class="col-md-6">
                                <label class="form-label">
                                    <?= __('pages.title', 'Title') ?>
                                </label>
                                <input type="text"
                                       id="page-title"
                                       name="title"
                                       class="form-control"
                                       value="<?= htmlspecialchars($page['title'] ?? '') ?>"
                                       required>
                            </div>

                            <div class="col-md-6">
                                <div class="d-flex justify-content-between align-items-center">
                                    <label class="form-label mb-0">
                                        <?= __('pages.slug', 'Slug') ?>
                                    </label>

                                    <!-- SLUG MODE -->
                                    <div class="d-flex align-items-center gap-3">
                                        <div class="form-check form-check-inline mb-0">
                                            <input class="form-check-input"
                                                   type="radio"
                                                   name="slug_mode"
                                                   id="slug-mode-auto"
                                                   value="auto"
                                                   <?= empty($page['slug']) ? 'checked' : '' ?>>
                                            <label class="form-check-label" for="slug-mode-auto">
                                                <?= __('pages.slug_mode.auto', 'Auto') ?>
                                            </label>
                                        </div>

                                        <div class="form-check form-check-inline mb-0">
                                            <input class="form-check-input"
                                                   type="radio"
                                                   name="slug_mode"
                                                   id="slug-mode-manual"
                                                   value="manual"
                                                   <?= !empty($page['slug']) ? 'checked' : '' ?>>
                                            <label class="form-check-label" for="slug-mode-manual">
                                                <?= __('pages.slug_mode.manual', 'Manual') ?>
                                            </label>
                                        </div>
                                    </div>
                                </div>

                                <input type="text"
                                       id="page-slug"
                                       name="slug"
                                       class="form-control mt-2"
                                       value="<?= htmlspecialchars($page['slug'] ?? '') ?>"
                                       required>

                                <small class="text-muted">
                                    <?= __('pages.slug_hint', 'Choose Auto to generate it from the title, or Manual to write your own.') ?>
                                </small>
                            </div>

                            <div class="col-12">
                                <label class="form-label">
                                    <?= __('pages.content', 'Content') ?>
                                </label>
                                <textarea name="content"
                                          id="editor"
                                          rows="12"
                                          class="form-control"><?= htmlspecialchars($page['content'] ?? '') ?></textarea>
                            </div>

                        </div>

                    </div>

                    <!-- SEO TAB -->
                    <div class="tab-pane fade"
                         id="tab-seo"
                         role="tabpanel"
                         aria-labelledby="tab-seo-btn"
                         tabindex="0">

                        <div class="mb-3">
                            <label class="form-label">
                                <?= __('seo.meta_title', 'Meta Title') ?>
                            </label>
                            <input type="text"
                                   name="meta_title"
                                   class="form-control"
                                   value="<?= htmlspecialchars($page['meta_title'] ?? '') ?>">
                        </div>

                        <div class="mb-3">
                            <label class="form-label">
                                <?= __('seo.meta_description', 'Meta Description') ?>
                            </label>
                            <textarea name="meta_description"
                                      rows="3"
                                      class="form-control"><?= htmlspecialchars($page['meta_description'] ?? '') ?></textarea>
                        </div>

                    </div>

                    <!-- SETTINGS TAB -->
                    <div class="tab-pane fade"
                         id="tab-settings"
                         role="tabpanel"
                         aria-labelledby="tab-settings-btn"
                         tabindex="0">

                        <div class="row g-3">

                            <div class="col-md-4">
                                <label class="form-label">
                                    <?= __('pages.status', 'Status') ?>
                                </label>
                                <select name="status" class="form-select">
                                    <option value="draft" <?= (($page['status'] ?? '') === 'draft') ? 'selected' : '' ?>>
                                        <?= __('pages.status.draft', 'Draft') ?>
                                    </option>
                                    <option value="published" <?= (($page['status'] ?? '') === 'published') ? 'selected' : '' ?>>
                                        <?= __('pages.status.published', 'Published') ?>
                                    </option>
                                </select>
                            </div>

                            <div class="col-md-5 d-flex align-items-end">
                                <div class="form-check">
                                    <input class="form-check-input"
                                           type="checkbox"
                                           name="show_in_menu"
                                           value="1"
                                        <?= !empty($page['show_in_menu']) ? 'checked' : '' ?>>
                                    <label class="form-check-label">
                                        <?= __('pages.show_in_menu', 'Show in menu') ?>
                                    </label>
                                </div>
                            </div>

                        </div>

                    </div>

                </div>
            </div>

            <div class="card-footer bg-white border-top d-flex justify-content-between align-items-center">
                <a href="/admin/pages" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-left me-1"></i>
                    <?= __('actions.back', 'Back') ?>
                </a>

                <button class="btn btn-primary px-4">
                    <i class="bi bi-save me-1"></i>
                    <?= __('actions.save', 'Save') ?>
                </button>
            </div>

        </div>

    </form>

</div>

<!-- CKEditor 4 Full — with Subresource Integrity -->
<script src="https://cdn.ckeditor.com/4.22.1/full/ckeditor.js"
        integrity="sha384-N9X0dNobzHBx+FYlGqJepLLqWJl7Lhf+lAG/8B2OwLJpCjSqkAjx0X5kvCqDLq5"
        crossorigin="anonymous"></script>
<script>
window.CKEDITOR && (CKEDITOR.config.versionCheck = false);
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {

    // Helpers
    function makeSlug(str) {
        return (str || '')
            .toLowerCase()
            .replace(/[^a-z0-9\u0600-\u06FF]+/g, '-')
            .replace(/(^-|-$)/g, '');
    }

    var titleEl = document.getElementById('page-title');
    var slugEl  = document.getElementById('page-slug');

    var autoRadio   = document.getElementById('slug-mode-auto');
    var manualRadio = document.getElementById('slug-mode-manual');

    function isAutoMode() {
        return autoRadio && autoRadio.checked;
    }

    function updateSlugModeUI() {
        if (!slugEl) return;

        if (isAutoMode()) {
            slugEl.readOnly = true;
            slugEl.classList.add('bg-light');
            if (titleEl) slugEl.value = makeSlug(titleEl.value);
        } else {
            slugEl.readOnly = false;
            slugEl.classList.remove('bg-light');
        }
    }

    // Init slug mode
    updateSlugModeUI();

    // Change mode
    if (autoRadio) autoRadio.addEventListener('change', updateSlugModeUI);
    if (manualRadio) manualRadio.addEventListener('change', updateSlugModeUI);

    // Auto Slug only in auto mode
    if (titleEl && slugEl) {
        titleEl.addEventListener('input', function () {
            if (!isAutoMode()) return;
            slugEl.value = makeSlug(this.value);
        });
    }

    // Init CKEditor 4
    if (window.CKEDITOR && document.getElementById('editor')) {

        // prevent double init
        if (!CKEDITOR.instances.editor) {
            CKEDITOR.replace('editor', {
                language: '<?= (isset($currentLangCode) && $currentLangCode === "ar") ? "ar" : "en" ?>',
                height: 360,
                filebrowserUploadUrl: '/admin/upload/image',
                filebrowserUploadMethod: 'form',
                toolbar: [
                    { name: 'document', items: ['Source','-','Preview','Print'] },
                    { name: 'clipboard', items: ['Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo'] },
                    { name: 'editing', items: ['Find','Replace','-','SelectAll'] },
                    { name: 'basicstyles', items: ['Bold','Italic','Underline','Strike','Subscript','Superscript','RemoveFormat'] },
                    { name: 'paragraph', items: ['NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'] },
                    { name: 'links', items: ['Link','Unlink','Anchor'] },
                    { name: 'insert', items: ['Image','Table','HorizontalRule','SpecialChar','Iframe'] },
                    { name: 'styles', items: ['Styles','Format','Font','FontSize'] },
                    { name: 'colors', items: ['TextColor','BGColor'] },
                    { name: 'tools', items: ['Maximize'] }
                ]
            });
        }

        // When returning to content tab, force editor resize
        var contentBtn = document.getElementById('tab-content-btn');
        if (contentBtn) {
            contentBtn.addEventListener('shown.bs.tab', function () {
                if (CKEDITOR.instances.editor) {
                    CKEDITOR.instances.editor.resize('100%', 360);
                }
            });
        }
    }

});
</script>

<?php include __DIR__ . '/../footer.php'; ?>
