<div class="col-12">
    <div id="widgetEditForm">
        <h5 class="mt-0">{$lang.datatable.edit_pay_widget}:</h5>
        <form method="post" action="/?pWidget/edit">

            <div class="col-4 mb-2">
                <label for="langSelect">Язык текстовых инпутов виджета</label>
                <select id="langSelect" class="form-select mb-3">
                    {foreach $langs as $langAssoc}
                        <option data-name="{$langAssoc.code}" value="{$langAssoc.code}">
                            {$langAssoc.name}
                        </option>
                    {/foreach}
                </select>
            </div>
            <small>Выбрано <b id="selectedLanguage">Chinese</b></small>

            <input type="hidden" name="id" value="{$pageId}" id="hiddenId">

            <div class="tab-content mt-2">
                {foreach $langs as $langAssoc}
                    <div class="tab-pane fade {if $langAssoc@first}show active{/if}"
                         id="{$langAssoc.code}">

                        <div class="row">
                            <div class="col-6 mb-2">
                                <label>{$lang.datatable.widget_name}:</label>
                                <input type="text" class="form-control" name="translations[{$langAssoc.code}][name]" placeholder="{$lang.datatable.widget_name}">
                            </div>
                            <div class="col-6 mb-2">
                                <label>{$lang.datatable.btn_text}</label>
                                <input type="text" class="form-control" name="translations[{$langAssoc.code}][btn_name]" placeholder="{$lang.datatable.btn_text}">
                            </div>

                        </div>

                    </div>
                {/foreach}
                <div class="row">
                    <div class="col-4 mb-2">
                        <label>{$lang.datatable.price}:</label>
                        <input type="text" class="form-control" name="price" placeholder="{$lang.datatable.price}">
                    </div>
                    <div class="col-3 mb-2" id="super_donater_sum" style="display: none">
                        <label>{$lang.datatable.top_donat_sum}:</label>
                        <input type="number" class="form-control" name="super_donater_sum" placeholder="{$lang.datatable.top_donat_sum}">
                    </div>
                    <div class="col-6 mb-2">
                        <label>{$lang.datatable.pay_typing}:</label>
                        <select class="form-select form-control" name="price_model">
                            <option value="1">{$lang.datatable.to_country}</option>
                            <option selected value="0">{$lang.datatable.to_static}</option>
                        </select>
                    </div>
                    <div class="col-6 mb-2">
                        <label>{$lang.datatable.widget_type}:</label>
                        <select class="form-select form-control" id="w_type" name="w_type">
                            <option value="sale">{$lang.datatable.sale}</option>
                            <option value="pay_for_hidden_data">{$lang.datatable.pay_hidden_data}</option>
                            <option value="donate">{$lang.datatable.donate}</option>
                            <option value="subscription">{$lang.datatable.subscription}</option>
                        </select>
                    </div>
                    <div class="col-6 mb-2">
                        <label>{$lang.datatable.pay_type}:</label>
                        <select class="form-select form-control" name="p_type">
                            <option value="one_time">{$lang.datatable.one_time}</option>
                            <option value="recurring">{$lang.datatable.reccuring}</option>
                        </select>
                    </div>
                    <div class="col-6 mb-2">
                        <label>{$lang.datatable.periodicity}:</label>
                        <select class="form-select form-control" name="period">
                            <option value="once">{$lang.datatable.one_time}</option>
                            <option value="yearly">{$lang.datatable.every_year}</option>
                            <option value="daily" disabled hidden="hidden">Ежедневно</option>
                            <option value="weekly" disabled hidden="hidden">Еженедельно</option>
                            <option value="monthly" disabled hidden="hidden">Ежемесячно</option>
                        </select>
                    </div>
                    <div class="col-6 mb-2">
                        <label>{$lang.datatable.notification_frequency}:</label>
                        <select class="form-select form-control" name="notify_fr">
                            <option value="once">{$lang.datatable.once_after_payment}</option>
                            <option value="daily">{$lang.datatable.ten_to_ten}</option>
                            <option value="weekly">{$lang.datatable.four_to_four}</option>
                        </select>
                    </div>
                    <div class="col-6 mb-2">
                        <label>{$lang.datatable.operations_limit}:</label>
                        <input type="number" class="form-control" name="limit" placeholder="{$lang.datatable.operations_limit}">
                    </div>
                </div>
                <div class="row">
                    <div class="col-6 mb-2">

                        <label>{$lang.datatable.select_template}:</label>
                        <select class="form-select form-control" id="filesE" name="template_name">
                            <option>Загрузка...</option>
                        </select>
                    </div>

                    <div class="col-6 mb-2">
                        <label>{$lang.datatable.success_url}:</label>
                        <input type="text" class="form-control" name="success_url" placeholder="URL">
                    </div>
                </div>
                <div class="row">
                    <div class="col-6 mb-2">
                        <label>{$lang.datatable.error_url}:</label>
                        <input type="text" class="form-control" name="error_url" placeholder="URL">
                    </div>
                    <div class="col-6 mb-2">
                        <label>{$lang.datatable.input_api_key}:</label>
                        <input type="text" class="form-control" name="api_key" placeholder="API">
                    </div>
                </div>
                <div class="row">
                    <div class="col-12 mb-2" id="email_templates">
                        <label>{$lang.datatable.email_template}:</label>
                        <select class="form-select form-control" name="email_template">
                            <option value="">{$lang.datatable.auto}</option>
                            {foreach $emailTemplates as $emailTemplate}
                                <option value="{$emailTemplate.name}">{$emailTemplate.name}</option>
                            {/foreach}
                        </select>
                    </div>
                    <div class="col-6 mb-2 hidden" id="group_field">
                        <label>{$lang.datatable.group}:</label>
                        <select class="form-select form-control" name="group">
                            <option value="" selected>{$lang.datatable.no_use}</option>
                            {foreach $groups as $group}
                                <option value="{$group}">{$group}</option>
                            {/foreach}
                        </select>
                    </div>
                </div>
                <div class="row">
                    <div class="col-3 col-md-3 mb-2">
                        <label for="disable_promo" class="col-form-label">{$lang.datatable.off_promo}:</label>
                        <div class="form-check form-switch">
                            <input type="hidden" name="home_tpl" value="false">
                            <input class="form-check-input offlineswitcher" type="checkbox" role="switch" name="disable_promo" id="disable_promo" value="true">
                        </div>
                    </div>
                    <div class="col-3 col-md-3 mb-2">
                        <label for="disable_delivery" class="col-form-label">{$lang.datatable.off_delivery}:</label>
                        <div class="form-check form-switch">
                            <input type="hidden" name="home_tpl" value="false">
                            <input class="form-check-input offlineswitcher" type="checkbox" role="switch" name="disable_delivery" id="disable_delivery" value="true">
                        </div>
                    </div>
                    <div class="col-3 col-md-3 mb-2">
                        <label for="statistic_counter" class="col-form-label">{$lang.datatable.on_statistic}:</label>
                        <div class="form-check form-switch">
                            <input type="hidden" name="home_tpl" value="false">
                            <input class="form-check-input offlineswitcher" type="checkbox" role="switch" name="statistic_counter" id="statistic_counter" value="true">
                        </div>
                    </div>
                    <div class="col-3 col-md-3 mb-2">
                        <label for="account_required" class="col-form-label">{$lang.datatable.required_authorize}:</label>
                        <div class="form-check form-switch">
                            <input type="hidden" name="home_tpl" value="false">
                            <input class="form-check-input offlineswitcher" type="checkbox" role="switch" name="account_required" id="account_required" value="true">
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-3 col-md-3 mb-2">
                        <label for="disable_title" class="col-form-label">{$lang.datatable.hide_title}:</label>
                        <div class="form-check form-switch">
                            <input type="hidden" name="home_tpl" value="false">
                            <input class="form-check-input offlineswitcher" type="checkbox" role="switch" name="disable_title" id="disable_title" value="true">
                        </div>
                    </div>
                    <div class="col-3 col-md-3 mb-2">
                        <label for="pay_with_redirect" class="col-form-label">{$lang.datatable.redirect_payment}:</label>
                        <div class="form-check form-switch">
                            <input type="hidden" name="home_tpl" value="false">
                            <input class="form-check-input offlineswitcher" type="checkbox" role="switch" name="pay_with_redirect" id="pay_with_redirect" value="true">
                        </div>
                    </div>
                    <div class="col-3 col-md-3 mb-2">
                        <label for="disable_sum_input" class="col-form-label">{$lang.datatable.hide_sum_input}:</label>
                        <div class="form-check form-switch">
                            <input type="hidden" name="home_tpl" value="false">
                            <input class="form-check-input offlineswitcher" type="checkbox" role="switch" name="disable_sum_input" id="disable_sum_input" value="true">
                        </div>
                    </div>
                    <div class="col-3 col-md-3 mb-2" id="redirect_to_registration_block">
                        <label for="redirect_to_registration" class="col-form-label">{$lang.datatable.redirect_to_registration}:</label>
                        <div class="form-check form-switch">
                            <input type="hidden" name="home_tpl" value="false">
                            <input class="form-check-input offlineswitcher" type="checkbox" role="switch" name="redirect_to_registration" id="redirect_to_registration" value="true">
                        </div>
                    </div>
                </div>
                <br>
            </div>


            <button type="submit" class="btn btn-primary w-100">{$lang.datatable.edit_pay_widget}</button>
        </form>
    </div>

</div>

<script>
    {literal}
    $(document).ready(function() {
        // Универсальная функция для управления формой виджета
        function initWidgetForm(formSelector) {
            const $form = $(formSelector);
            const $wType = $form.find('[name="w_type"]');
            const $files = $form.find('[name="template_name"]');
            const $emailTemplate = $form.find('[name="email_template"]');
            const $groupField = $form.find('[name="group_field"], [name="group"]');
            const $superDonater = $form.find('#super_donater_sum');

            function updateFormBlocks(type) {
                if(type === "donate") {
                    $superDonater.show();
                    $groupField.hide();
                    $emailTemplate.parent().removeClass('col-6').addClass('col-12');
                } else if(type === "subscription") {
                    $superDonater.hide();
                    $groupField.show();
                    $emailTemplate.parent().removeClass('col-12').addClass('col-6');
                } else {
                    $superDonater.hide();
                    $groupField.hide();
                    $emailTemplate.parent().removeClass('col-6').addClass('col-12');
                }
            }

            function loadWidgetFiles(type) {
                $.post('engine/ajax/lib/widget/widget-types-select.php',
                    { action: 'select', selectedObjectType: type },
                    function(resp) {
                        if(resp.error) return alert(resp.error);
                        $files.empty();
                        resp.forEach(f => $files.append(new Option(f, f)));
                    }, 'json'
                );
            }

            function loadEmailTemplates(type) {
                $.post('engine/ajax/lib/widget/widget-email-template.php',
                    { selectedObjectType: type },
                    function(resp) {
                        if(resp.error) return alert(resp.error);
                        //$emailTemplate.empty().append(new Option("{$lang.datatable.auto}", ""));
                        resp.forEach(t => $emailTemplate.append(new Option(t.value, t.text)));
                    }, 'json'
                );
            }

            // Событие смены типа виджета
            $wType.on('change', function() {
                const type = $(this).val();
                updateFormBlocks(type);
                loadWidgetFiles(type);
                loadEmailTemplates(type);
            });

            // Инициализация по умолчанию
            updateFormBlocks($wType.val());
            loadWidgetFiles($wType.val());
            loadEmailTemplates($wType.val());
        }

        // Инициализируем обе формы
        initWidgetForm('#widgetEditForm');

        const id = $("#hiddenId").val();

        if (id) {
            $.post('engine/ajax/lib/widget/widget-handler.php', { id: id, action: 'edit' }, function(resp) {
                const $form = $('#widgetEditForm');

                resp.translations.forEach(function (t) {
                    debugger;
                    let fieldName = `translations[${t.lang_code}][${t.name}]`;

                    $form.find(`[name="${fieldName}"]`).val(t.value);
                });

                $form.find('[name="id"]').val(resp.id);
                // $form.find('[name="name"]').val(resp.name);
                $form.find('[name="price"]').val(resp.price);
                $form.find('[name="price_model"]').val(resp.price_model ? 1 : 0);
                $form.find('[name="w_type"]').val(resp.w_type).trigger('change');
                $form.find('[name="p_type"]').val(resp.p_type);
                $form.find('[name="period"]').val(resp.period);
                $form.find('[name="notify_fr"]').val(resp.notify_fr);
                $form.find('[name="limit"]').val(resp.limit);
                $form.find('[name="template_name"]').val(resp.template_name);
                //$form.find('[name="btn_name"]').val(resp.btn_text);
                $form.find('[name="email_template"]').val(resp.settings.email_template || "");
                $form.find('[name="success_url"]').val(resp.settings.success_url);
                $form.find('[name="error_url"]').val(resp.settings.error_url);
                $form.find('[name="api_key"]').val(resp.settings.api_key);

                // чекбоксы
                ['statistic_counter','redirect_to_registration','account_required','disable_promo','disable_delivery','disable_title','pay_with_redirect','disable_sum_input'].forEach(function(name){
                    $form.find(`[name="${name}"]`).prop('checked', !!resp.settings[name]);
                });

                $form.find('[name="group"]').val(resp.settings.group_field || "");
            }, 'json');
        }
        document.getElementById('langSelect').addEventListener('change', function () {
            const value = this.value;
            $("#selectedLanguage").html(value);
            document.querySelectorAll('.tab-pane').forEach(p => {
                p.classList.remove('show', 'active');
            });
            document.getElementById(value).classList.add('show', 'active');
        });
    });

    var wabSection = document.getElementById('wabSection');
    wabSection.classList.add('active');
    var widgetsAndBanners = document.getElementById('widgetsAndBanners');
    widgetsAndBanners.classList.add('show');

    $("#paymentWidgets").addClass("active");
    {/literal}
</script>
