<?php
/**
 * ITSWEBER CMS – Page Builder Admin Form: Before/After Comparison
 * Loaded via AJAX into section cards.
 * Migrated from plugins/before-after-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'] ?? '';
$description      = $data['description'] ?? '';
$colorScheme      = $data['color_scheme'] ?? '';
$columns          = $data['columns'] ?? '2';
$items            = (isset($data['items']) && is_array($data['items'])) ? $data['items'] : [];

$sectionId = (int) $section['id'];
$containerId = 'bas-items-container-' . $sectionId;
$addBtnId    = 'bas-add-item-' . $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.ba_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.ba_ph_subtitle') ?>">
</div>

<div class="form-group">
    <label class="form-label"><?= __('admin.section.description') ?></label>
    <textarea name="description" class="form-control" rows="2" placeholder="<?= __('admin.section.ba_ph_text') ?>"><?= $esc($description) ?></textarea>
</div>

<!-- Before/After Items Repeater -->
<div class="form-group">
    <label class="form-label"><?= __('admin.section.ba_items_label') ?></label>
    <div class="section-items-sortable" id="<?= $containerId ?>">
        <?php foreach ($items as $idx => $item): ?>
        <div class="section-item-sortable" style="margin-bottom: 1rem; padding: 1rem; background: #f9fafb; border-radius: 8px; border: 1px solid #e5e7eb;">
            <div style="display: flex; gap: 0.5rem; margin-bottom: 0.75rem; align-items: center;">
                <div class="item-move-buttons" style="display: flex; gap: 0.25rem;">
                    <button type="button" class="btn btn-xs item-move-up" title="<?= __('admin.section.move_up') ?>">&#9650;</button>
                    <button type="button" class="btn btn-xs item-move-down" title="<?= __('admin.section.move_down') ?>">&#9660;</button>
                </div>
                <strong style="flex: 1; font-size: 0.9rem;"><?= str_replace(':num', $idx + 1, __('admin.section.ba_item_label')) ?></strong>
                <button type="button" class="btn btn-xs btn-danger bas-remove-item">&#10005; <?= __('admin.section.remove_item') ?></button>
            </div>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem;">
                <div class="form-group">
                    <label><?= __('admin.section.title') ?></label>
                    <input type="text" name="bas_title[]" class="form-control" value="<?= $esc($item['title'] ?? '') ?>" placeholder="<?= __('admin.section.ba_ph_item_title') ?>">
                </div>
                <div class="form-group">
                    <label><?= __('admin.section.ba_before_label') ?></label>
                    <input type="text" name="bas_before_label[]" class="form-control" value="<?= $esc($item['before_label'] ?? 'Before') ?>" placeholder="Before">
                </div>
                <div class="form-group" style="grid-column: 1 / -1;">
                    <label><?= __('admin.section.description') ?></label>
                    <textarea name="bas_description[]" class="form-control" rows="2" placeholder="Optional description"><?= $esc($item['description'] ?? '') ?></textarea>
                </div>
                <div class="form-group">
                    <label><?= __('admin.section.ba_after_label') ?></label>
                    <input type="text" name="bas_after_label[]" class="form-control" value="<?= $esc($item['after_label'] ?? 'After') ?>" placeholder="After">
                </div>
                <div class="form-group">
                    <label><?= __('admin.section.ba_before_image') ?></label>
                    <div class="section-media-field-wrap">
                        <input type="text" name="bas_before_image[]" value="<?= $esc($item['before_image'] ?? '') ?>" class="section-media-input form-control" placeholder="Select or upload an image" readonly>
                        <div style="display:flex;gap:0.5rem;margin-top:0.5rem;">
                            <button type="button" class="btn btn-sm section-media-browse"><?= __('admin.section.ba_browse_media') ?></button>
                            <button type="button" class="btn btn-sm btn-danger section-media-remove"><?= __('admin.section.ba_remove_image') ?></button>
                        </div>
                        <div class="section-media-preview" style="margin-top:0.5rem;<?= empty($item['before_image']) ? 'display:none;' : '' ?>">
                            <img src="<?= $esc($item['before_image'] ?? '') ?>" style="max-height:120px;border-radius:4px;">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label><?= __('admin.section.ba_after_image') ?></label>
                    <div class="section-media-field-wrap">
                        <input type="text" name="bas_after_image[]" value="<?= $esc($item['after_image'] ?? '') ?>" class="section-media-input form-control" placeholder="Select or upload an image" readonly>
                        <div style="display:flex;gap:0.5rem;margin-top:0.5rem;">
                            <button type="button" class="btn btn-sm section-media-browse"><?= __('admin.section.ba_browse_media') ?></button>
                            <button type="button" class="btn btn-sm btn-danger section-media-remove"><?= __('admin.section.ba_remove_image') ?></button>
                        </div>
                        <div class="section-media-preview" style="margin-top:0.5rem;<?= empty($item['after_image']) ? 'display:none;' : '' ?>">
                            <img src="<?= $esc($item['after_image'] ?? '') ?>" style="max-height:120px;border-radius:4px;">
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <button type="button" class="btn btn-secondary btn-sm" id="<?= $addBtnId ?>" style="margin-top: 0.75rem;"><?= __('admin.section.add_item') ?></button>
</div>

<script>
(function() {
    var container = document.getElementById('<?= $containerId ?>');
    if (!container) return;

    function itemHTML(idx) {
        return '<div style="display:flex;gap:0.5rem;margin-bottom:0.75rem;align-items:center;">' +
            '<div class="item-move-buttons" style="display:flex;gap:0.25rem;">' +
                '<button type="button" class="btn btn-xs item-move-up">&#9650;</button>' +
                '<button type="button" class="btn btn-xs item-move-down">&#9660;</button>' +
            '</div>' +
            '<strong style="flex:1;font-size:0.9rem;"><?= str_replace(':num', "' + (idx + 1) + '", __('admin.section.ba_item_label')) ?></strong>' +
            '<button type="button" class="btn btn-xs btn-danger bas-remove-item">&#10005; <?= __('admin.section.remove_item') ?></button>' +
        '</div>' +
        '<div style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;">' +
            '<div class="form-group"><label><?= __('admin.section.title') ?></label><input type="text" name="bas_title[]" class="form-control" placeholder="<?= __('admin.section.ba_ph_item_title') ?>"></div>' +
            '<div class="form-group"><label><?= __('admin.section.ba_before_label') ?></label><input type="text" name="bas_before_label[]" class="form-control" value="Before" placeholder="Before"></div>' +
            '<div class="form-group" style="grid-column:1/-1;"><label><?= __('admin.section.description') ?></label><textarea name="bas_description[]" class="form-control" rows="2" placeholder="Optional description"></textarea></div>' +
            '<div class="form-group"><label><?= __('admin.section.ba_after_label') ?></label><input type="text" name="bas_after_label[]" class="form-control" value="After" placeholder="After"></div>' +
            '<div class="form-group"><label><?= __('admin.section.ba_before_image') ?></label><div class="section-media-field-wrap"><input type="text" name="bas_before_image[]" class="section-media-input form-control" placeholder="Select or upload an image" readonly><div style="display:flex;gap:0.5rem;margin-top:0.5rem;"><button type="button" class="btn btn-sm section-media-browse"><?= __('admin.section.ba_browse_media') ?></button><button type="button" class="btn btn-sm btn-danger section-media-remove"><?= __('admin.section.ba_remove_image') ?></button></div><div class="section-media-preview" style="margin-top:0.5rem;display:none;"><img src="" style="max-height:120px;border-radius:4px;"></div></div></div>' +
            '<div class="form-group"><label><?= __('admin.section.ba_after_image') ?></label><div class="section-media-field-wrap"><input type="text" name="bas_after_image[]" class="section-media-input form-control" placeholder="Select or upload an image" readonly><div style="display:flex;gap:0.5rem;margin-top:0.5rem;"><button type="button" class="btn btn-sm section-media-browse"><?= __('admin.section.ba_browse_media') ?></button><button type="button" class="btn btn-sm btn-danger section-media-remove"><?= __('admin.section.ba_remove_image') ?></button></div><div class="section-media-preview" style="margin-top:0.5rem;display:none;"><img src="" style="max-height:120px;border-radius:4px;"></div></div></div>' +
        '</div>';
    }

    document.getElementById('<?= $addBtnId ?>').addEventListener('click', function() {
        var count = container.querySelectorAll('.section-item-sortable').length;
        if (count >= 12) { alert('<?= __('admin.section.ba_max_hint') ?>'); return; }
        var div = document.createElement('div');
        div.className = 'section-item-sortable';
        div.style.cssText = 'margin-bottom:1rem;padding:1rem;background:#f9fafb;border-radius:8px;border:1px solid #e5e7eb';
        div.innerHTML = itemHTML(count);
        container.appendChild(div);
        attachHandlers(div);
        if (typeof initSectionMediaFields === 'function') {
            initSectionMediaFields(div);
        } else {
            var _dynRetry = setInterval(function () {
                if (typeof initSectionMediaFields === 'function') {
                    initSectionMediaFields(div);
                    clearInterval(_dynRetry);
                }
            }, 80);
            setTimeout(function () { clearInterval(_dynRetry); }, 5000);
        }
    });

    container.querySelectorAll('.section-item-sortable').forEach(attachHandlers);

    // Re-initialise media fields for server-rendered items.
    function _basInitMedia() {
        if (typeof initSectionMediaFields === 'function') {
            initSectionMediaFields(container);
            return true;
        }
        return false;
    }
    if (!_basInitMedia()) {
        var _basRetry = setInterval(function () {
            if (_basInitMedia()) clearInterval(_basRetry);
        }, 80);
        setTimeout(function () { clearInterval(_basRetry); }, 5000);
    }

    function attachHandlers(item) {
        var up = item.querySelector('.item-move-up');
        var dn = item.querySelector('.item-move-down');
        var rm = item.querySelector('.bas-remove-item');
        if (up) up.addEventListener('click', function(e) { e.preventDefault(); var p = item.previousElementSibling; if (p && p.classList.contains('section-item-sortable')) container.insertBefore(item, p); });
        if (dn) dn.addEventListener('click', function(e) { e.preventDefault(); var n = item.nextElementSibling; if (n && n.classList.contains('section-item-sortable')) container.insertBefore(n, item); });
        if (rm) rm.addEventListener('click', function(e) { e.preventDefault(); item.remove(); });
    }
})();
</script>

<?php admin_section_separator() ?>

<?php admin_field_grid_open(3) ?>
    <?php admin_color_scheme_field($data['color_scheme'] ?? '') ?>
    <?php render_section_text_color_field($data) ?>
    <?php admin_field('select', 'columns', __('admin.section.columns'), $data['columns'] ?? '2', [
        'options' => ['1' => __('admin.section.columns_1'), '2' => __('admin.section.columns_2'), '3' => __('admin.section.columns_3')],
        'wrap_style' => 'margin:0;',
    ]) ?>
<?php admin_field_grid_close() ?>
