<?php

class RepeaterUtils {
    public function repeater_manage($oldValue, $hook) {
        $oldValue = is_array($oldValue) ? $oldValue : [];
        $postType = isset($oldValue['post_type']) ? $oldValue['post_type'] : '';
        $acfKey   = isset($oldValue['acf_key']) ? $oldValue['acf_key'] : '';
        $oldCombo = "{$postType}|{$acfKey}";

        // Build ACF choices and subFieldsMap (no change)
        $choices = [];
        $subFieldsMap = [];
        foreach (acf_get_field_groups() as $group) {
            foreach ((array) acf_get_fields($group['key']) as $f) {
                if (!$f || $f['type'] !== 'repeater') continue;
                foreach ($group['location'] as $rg) {
                    foreach ($rg as $rule) {
                        if ($rule['param'] === 'post_type') {
                            $key = "{$rule['value']}|{$f['name']}";
                            $choices[$key] = "{$rule['value']} → {$f['label']}";
                            $subFieldsMap[$key] = array_map(function($sf) {
                                return ['name' => $sf['name'], 'label' => $sf['label']];
                            }, $f['sub_fields']);
                        }
                    }
                }
            }
        }

        $subFieldsMapJson = wp_json_encode($subFieldsMap);
        ?>
        <!-- ACF repeater selector, layout selector, repeater fields UI -->
        <label>Choose ACF Repeater</label>
        <select id="acf-repeater-list" style="width:100%;margin:6px 0;">
            <option value="" disabled>Choose ACF Repeater field</option>
            <?php foreach ($choices as $key => $label): ?>
                <option value="<?= esc_attr($key) ?>" <?= $key === $oldCombo ? 'selected' : '' ?>>
                    <?= esc_html($label) ?>
                </option>
            <?php endforeach; ?>
        </select>

        <hr style="margin: 10px 0px;">

        <label>Choose layout</label>
        <select id="layout-select" style="width:100%;margin:6px 0;">
            <?php 
                $displayType = isset($oldValue['display_type']) && trim($oldValue['display_type']) !== '' ? trim($oldValue['display_type']) : 'Plain Table';
                foreach (['Plain Table','Borderless Table', 'Card Grid (Pro)', 'Carousel (Pro)'] as $l): 
                    $isSelected = ($l === $displayType) ? 'selected' : '';
            ?>
                <option value="<?= esc_attr($l) ?>" <?= $isSelected ?>>
                    <?= esc_html($l) ?>
                </option>
            <?php endforeach; ?>

        </select>

        <hr style="margin: 10px 0px;">

        <label>Repeater Fields</label>
        <ul id="repeater-fields" style="
            list-style:none;
            margin-top:6px;
            max-height: 120px;
            padding: 6px 12px;
            border: 1px solid #fafafa60;
            border-radius: 6px;
            overflow: auto;"></ul>
        <button id="add-field" type="button" class="button" style="font-size: 22px; padding: 4px; width: 36px; margin-top: 8px;">+</button>

        <hr style="margin: 10px 0px;">

        <button id="save-settings" type="button" class="button button-primary" style="width: 100%; padding: 10px 0px; font-size: 16px; margin-top: 12px;">Save Settings</button>

        <script>
            jQuery(function($) {
                const oldValue = <?= wp_json_encode($oldValue) ?>;
                const subFieldsMap = <?= $subFieldsMapJson ?>;
                const $fieldsList = $('#repeater-fields');
                const $acfSelect = $('#acf-repeater-list');
                const $layoutSelect = $('#layout-select');
                const $saveBtn = $('#save-settings');
                let currentCombo = $acfSelect.val();

                function buildFieldSelect(val = '') {
                    const key = $acfSelect.val();
                    const options = (subFieldsMap[key] || []).map(f =>
                        `<option value="${f.name}" ${f.name === val ? 'selected' : ''}>${f.label}</option>`
                    ).join('');
                    return `<select class="repeater-select" style="flex:1;"><option value="">— choose —</option>${options}</select>`;
                }

                function appendField(val) {
                    const li = $(`<li style="display:flex;align-items:center;margin-bottom:8px;gap:8px;">${buildFieldSelect(val)}<button type="button" class="remove-field button" style="padding: 0 8px;">×</button></li>`);
                    li.find('.remove-field').on('click', () => li.remove());
                    $fieldsList.append(li);
                }

                function renderFields(arr) {
                    $fieldsList.empty();
                    arr.forEach(val => appendField(val));
                }

                // Initial repeater fields
                renderFields(oldValue.repeater_fields || []);
                // Set layout
                $layoutSelect.val(oldValue.display_type || '');

                // Clear fields when ACF repeater changes
                $acfSelect.on('change', function() {
                    const newCombo = $(this).val();
                    if (newCombo !== currentCombo) {
                        currentCombo = newCombo;
                        renderFields([]);
                    }
                });

                // Add Field button
                $('#add-field').off('click').on('click', () => appendField(''));

                // Save button click handler
                $saveBtn.on('click', function() {
                    try {
                        const selectedCombo = $acfSelect.val();
                        if (!selectedCombo) throw new Error("Please select an ACF Repeater field.");

                        const [postType, acfKey] = selectedCombo.split('|');
                        const displayType = $layoutSelect.val();

                        const repeaterFields = [];
                        $('#repeater-fields .repeater-select').each(function() {
                            const val = $(this).val();
                            if (val) repeaterFields.push(val);
                        });

                        const returnVal = JSON.stringify({
                            post_type: postType,
                            acf_key: acfKey,
                            display_type: displayType,
                            repeater_fields: repeaterFields
                        }, null, 4); // pretty print with 4 spaces indent

                        const panelView = elementor.getPanelView();
                        const model = panelView?.getCurrentPageView?.()?.model;
                        if (!model) throw new Error("Widget model not found.");

                        model.setSetting('<?= $hook ?>', returnVal);
                        model.trigger('change:settings');
                        model.trigger('change');
                        model.trigger('dirty');

                        const hiddenInput = $('input[data-setting="<?= $hook ?>"]');
                        hiddenInput.val(returnVal).trigger('input');

                        $('#trfx-layout-modal').fadeOut(200);
                    } catch (err) {
                        alert(err.message);
                    }
                });

            });
        </script>

        <?php
    }
}
