<?php
/**
 * ITSWEBER CMS – Page Builder Admin Form: HTML / Editor Section
 * Loaded via AJAX into section cards.
 * Migrated from plugins/html-section.
 *
 * @author  Benny Weber
 * @copyright ITSWEBER, www.itsweber.de
 *
 * @var array $data    Decoded JSON content
 * @var array $section DB row (id, section_type, instance_label, ...)
 */

$esc = fn(string $v): string => htmlspecialchars($v, ENT_QUOTES, 'UTF-8');

$title       = $data['title'] ?? '';
$subtitle    = $data['subtitle'] ?? '';
$contentHtml = $data['content_html'] ?? '';
$colorScheme = $data['color_scheme'] ?? '';
$textAlign   = $data['text_align'] ?? '';
$maxWidth    = $data['max_width'] ?? '';

// Unique IDs for this section instance
$sectionId  = (int) $section['id'];
$editorId   = 'hs_editor_' . $sectionId;
$pickerId   = 'hs_picker_overlay_' . $sectionId;
$pickerBtn  = 'hs_picker_btn_' . $sectionId;
?>

<div class="form-group">
    <label class="form-label"><?= __('admin.section.heading') ?></label>
    <input type="text" name="title" class="form-control" value="<?= $esc($title) ?>" placeholder="<?= __('admin.section.html_ph_title') ?>">
</div>

<div class="form-group">
    <label class="form-label"><?= __('admin.section.subtitle') ?></label>
    <input type="text" name="subtitle" class="form-control" value="<?= $esc($subtitle) ?>" placeholder="<?= __('admin.section.html_ph_subtitle') ?>">
</div>

<div class="form-group">
    <label class="form-label"><?= __('admin.section.content') ?></label>
    <textarea id="<?= $editorId ?>" name="content_html" class="form-control" rows="14" style="min-height:200px;"><?= $esc($contentHtml) ?></textarea>
    <div style="display:flex;gap:0.5rem;margin-top:0.5rem;align-items:center;">
        <button type="button" class="btn btn-secondary btn-sm" id="<?= $pickerBtn ?>">&#128247; <?= __('admin.section.html_insert_image') ?></button>
        <small class="form-help" style="margin:0;"><?= __('admin.section.html_editor_hint') ?></small>
    </div>
</div>

<!-- Jodit CSS + JS: loaded once per page, guarded against double-loading -->
<link rel="stylesheet" href="/admin/assets/editor/jodit.min.css" id="joditCssHs">
<script>
if (!window._joditJsLoaded) {
    window._joditJsLoaded = true;
    var s = document.createElement('script');
    s.src = '/admin/assets/editor/jodit.min.js';
    s.onload = function() { window._hsInitEditor_<?= $sectionId ?>(); };
    document.head.appendChild(s);
} else if (typeof Jodit !== 'undefined') {
    // Jodit already loaded (e.g. from blog form or another html-section)
    document.addEventListener('DOMContentLoaded', function() {
        window._hsInitEditor_<?= $sectionId ?>();
    });
}

window._hsInitEditor_<?= $sectionId ?> = function() {
    var ta = document.getElementById('<?= $editorId ?>');
    if (!ta || ta._joditEditor) return;
    if (typeof Jodit === 'undefined') return;

    var editor = Jodit.make(ta, {
        height: 450,
        language: 'en',
        toolbarSticky: false,
        buttons: [
            'bold', 'italic', 'underline', 'strikethrough', 'eraser',
            '|',
            'paragraph', 'fontsize',
            '|',
            'ul', 'ol', 'indent', 'outdent',
            '|',
            'link', 'image',
            '|',
            'table', 'hr',
            '|',
            'align',
            '|',
            'brush',
            '|',
            'undo', 'redo',
            '|',
            'source', 'fullsize'
        ],
        cleanHTML: {
            fillEmptyParagraph: false,
            replaceNBSP: false,
            removeEmptyElements: false,
            allowTags: false,
            denyTags: false
        },
        enter: 'P',
        allowResizeX: false,
        allowResizeY: true,
        minHeight: 250,
        processPasteHTML: false,
        askBeforePasteHTML: false,
        askBeforePasteFromWord: false,
        defaultActionOnPaste: 'insert_as_html'
    });

    ta._joditEditor = editor;
};

// If Jodit was already available (script cached), init immediately
if (typeof Jodit !== 'undefined') {
    window._hsInitEditor_<?= $sectionId ?>();
}
</script>

<!-- Media Picker Modal for this editor instance -->
<div id="<?= $pickerId ?>" class="media-picker-overlay" style="display:none;" role="dialog" aria-modal="true" aria-label="Insert Image">
    <div class="media-picker-modal" style="max-width:860px;">
        <div class="media-picker-header">
            <h3><?= __('admin.section.html_insert_image') ?></h3>
            <button type="button" class="media-picker-close hs-picker-close" aria-label="Close">&times;</button>
        </div>
        <div class="hs-picker-toolbar" style="display:flex;gap:0.75rem;padding:0.75rem 1.25rem;border-bottom:1px solid #e5e7eb;align-items:center;">
            <input type="text" class="form-control hs-picker-search" placeholder="<?= __('admin.section.html_search_images') ?>" style="flex:1;" autocomplete="off">
            <label class="btn btn-secondary btn-sm" style="cursor:pointer;margin:0;">
                &#8679; <?= __('admin.section.html_upload') ?>
                <input type="file" class="hs-picker-upload" accept="image/jpeg,image/png,image/gif,image/webp,image/svg+xml" style="display:none;">
            </label>
        </div>
        <div class="hs-picker-grid" style="padding:1rem;max-height:420px;overflow-y:auto;">
            <p style="text-align:center;color:#6b7280;padding:2rem;"><?= __('admin.section.html_loading') ?></p>
        </div>
    </div>
</div>

<script>
(function() {
    var overlay   = document.getElementById('<?= $pickerId ?>');
    var openBtn   = document.getElementById('<?= $pickerBtn ?>');
    var closeBtn  = overlay.querySelector('.hs-picker-close');
    var searchInp = overlay.querySelector('.hs-picker-search');
    var uploadInp = overlay.querySelector('.hs-picker-upload');
    var grid      = overlay.querySelector('.hs-picker-grid');
    var loaded    = false;

    function getEditor() {
        var ta = document.getElementById('<?= $editorId ?>');
        return ta ? ta._joditEditor : null;
    }

    // -- Open / Close --
    openBtn.addEventListener('click', function(e) {
        e.preventDefault();
        overlay.style.display = '';
        document.body.classList.add('iw-modal-open');
        if (!loaded) loadImages();
    });
    closeBtn.addEventListener('click', closePicker);
    overlay.addEventListener('click', function(e) { if (e.target === overlay) closePicker(); });
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && overlay.style.display !== 'none') closePicker();
    });

    function closePicker() {
        overlay.style.display = 'none';
        document.body.classList.remove('iw-modal-open');
    }

    // -- Search filter --
    searchInp.addEventListener('input', function() {
        var q = this.value.toLowerCase();
        overlay.querySelectorAll('.hs-img-item').forEach(function(item) {
            item.style.display = (!q || (item.dataset.name || '').toLowerCase().indexOf(q) !== -1) ? '' : 'none';
        });
    });

    // -- Upload --
    uploadInp.addEventListener('change', function() {
        if (!this.files || !this.files[0]) return;
        var formData = new FormData();
        formData.append('file', this.files[0]);
        var csrfEl = document.querySelector('input[name="_csrf_token"]');
        if (csrfEl) formData.append('_csrf_token', csrfEl.value);

        grid.innerHTML = '<p style="text-align:center;color:#6b7280;padding:2rem;"><?= __('admin.section.html_uploading') ?></p>';

        fetch('/admin/media/upload', { method:'POST', body: formData })
            .then(function(r) { return r.json(); })
            .then(function(d) {
                if (d.success && d.url) {
                    insertImage(d.url, d.alt || d.name || '');
                    closePicker();
                } else {
                    loaded = false;
                    loadImages();
                }
            })
            .catch(function() {
                grid.innerHTML = '<p style="text-align:center;color:#dc2626;padding:2rem;"><?= __('admin.section.html_upload_failed') ?></p>';
            });
        this.value = '';
    });

    // -- Load images --
    function loadImages() {
        grid.innerHTML = '<p style="text-align:center;color:#6b7280;padding:2rem;"><?= __('admin.section.html_loading') ?></p>';
        fetch('/admin/media/picker-images')
            .then(function(r) { return r.json(); })
            .then(function(d) {
                loaded = true;
                var imgs = d.images || d || [];
                if (!imgs.length) {
                    grid.innerHTML = '<p style="text-align:center;color:#6b7280;padding:2rem;"><?= __('admin.section.html_no_images') ?></p>';
                    return;
                }
                var h = '<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(100px,1fr));gap:0.5rem;">';
                imgs.forEach(function(img) {
                    var url = esc(img.url||''), thumb = esc(img.thumb_url||img.url||''), name = esc(img.name||img.title||''), alt = esc(img.alt||img.name||'');
                    h += '<div class="hs-img-item" data-url="'+url+'" data-alt="'+alt+'" data-name="'+name+'" '
                       + 'style="cursor:pointer;border:2px solid transparent;border-radius:6px;overflow:hidden;aspect-ratio:1;background:#f3f4f6;" '
                       + 'title="'+name+'">'
                       + '<img src="'+thumb+'" alt="'+name+'" loading="lazy" style="width:100%;height:100%;object-fit:cover;">'
                       + '</div>';
                });
                h += '</div>';
                grid.innerHTML = h;

                grid.querySelectorAll('.hs-img-item').forEach(function(item) {
                    item.addEventListener('click', function() {
                        insertImage(item.dataset.url, item.dataset.alt);
                        closePicker();
                    });
                });
            })
            .catch(function() {
                grid.innerHTML = '<p style="text-align:center;color:#dc2626;padding:2rem;"><?= __('admin.section.html_load_failed') ?></p>';
            });
    }

    // -- Insert image into Jodit editor --
    function insertImage(url, alt) {
        var ed = getEditor();
        if (ed) {
            ed.selection.insertHTML('<img src="' + url + '" alt="' + esc(alt) + '" style="max-width:100%;height:auto;">');
        } else {
            // Fallback: append to textarea
            var ta = document.getElementById('<?= $editorId ?>');
            if (ta) ta.value += '\n<img src="' + url + '" alt="' + esc(alt) + '">\n';
        }
    }

    function esc(s) {
        return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    }
})();
</script>

<?php admin_section_separator() ?>

<?php admin_field_grid_open(4) ?>
    <?php admin_color_scheme_field($data['color_scheme'] ?? '') ?>
    <?php render_section_text_color_field($data) ?>
    <?php admin_field('select', 'text_align', __('admin.section.text_align'), $data['text_align'] ?? '', [
        'options' => ['' => __('admin.section.align_default'), 'left' => __('admin.section.align_left'), 'center' => __('admin.section.align_center'), 'right' => __('admin.section.align_right')],
        'wrap_style' => 'margin:0;',
    ]) ?>
    <?php admin_field('select', 'max_width', __('admin.section.text_width'), $data['max_width'] ?? '', [
        'options' => ['' => __('admin.section.width_default'), 'sm' => __('admin.section.width_sm'), 'md' => __('admin.section.width_md'), 'lg' => __('admin.section.width_lg')],
        'wrap_style' => 'margin:0;',
    ]) ?>
<?php admin_field_grid_close() ?>
