
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
{*

<div class="col-12">
    <div class="col-12">
        <button class="btn btn-dark mb-0" onclick="largeModal('widgetAddForm')">{$lang.datatable.create_pay_widget}</button>
    </div>
</div>
*}

<div class="col-12">
    <table class="table">
        <thead>
            <tr>
                <th class="border-end text-center">#</th>
                <th class="border-end text-center" width="130px">{$lang.datatable.date}</th>
                <th class="border-end">{$lang.datatable.name}</th>
                <th class="border-end text-center">{$lang.datatable.price}</th>
                <th class="border-end text-center">{$lang.datatable.widget_type}</th>
                <th class="border-end text-center">{$lang.datatable.pay_type}</th>
                <th class="text-center" width="90px">{$lang.datatable.actions}</th>
            </tr>
        </thead>
        <tbody>


        {foreach $widgets as $widget}
            <tr>
                <td class="border-end border-bottom-0 text-center">{$widget.uniq_id}</td>
                <td class="border-end border-bottom-0 text-center">
                    <i class="fa fa-clock-o" title=""> {$widget.s_date}</i>
                </td>
                <td class="border-end border-bottom-0">{$widget.name}</td>
                <td class="border-end border-bottom-0 text-center">{$widget.price}</td>
                <td class="border-end border-bottom-0 text-center">{$widget.w_type}</td>
                <td class="border-end border-bottom-0 text-center">{$widget.p_type}</td>
                <td class="text-center border-bottom-0">
                    <div class="btn-group d-flex align-items-center justify-content-between">
                        <button class="btn btn-sm border border-default rounded" data-bs-toggle="collapse" data-bs-target="#details{$widget.id}" aria-expanded="false" aria-controls="details{$widget.id}">{$lang.datatable.details}</button>
                        <a href="#" id="copy-ico" data-copy='{$widget.include_copy}' class="mx-3 fa fa-copy"></a>
                        <a href="/admin?action=widgets/payments/edit&id={$widget.id}" {*id="edit-ico" *}data-id="{$widget.id}" {*onclick="largeModal('widgetEditForm')"*} class="mx-3"><i class="fa fa-edit"></i></a>
                        <a href="#" id="delete-ico" data-id="{$widget.id}" class="no-b px-0"><i class="fa fa-trash"></i></a>

                      {*  <form method="POST" action="#" style="display:inline;">
                            <input type="hidden" name="delete_widget_id" value="{$widget.id}">
                            <button type="submit" class="no-b px-0" onclick="return confirm('Удалить этот виджет?');">
                                <i class="fa fa-trash"></i>
                            </button>
                        </form>*}
                    </div>
                </td>
            </tr>
            <tr class="collapse-row">
                <td colspan="7" class="p-0">
                    <div id="details{$widget.id}" class="collapse">
                        <div class="p-3 body-color">
                            <div class="row">
                                <div class="col">
                                    <div class="card">
                                        <div class="card-body py-2 border-top border-success d-flex align-items-center justify-content-between fs-7">
                                            <strong>{$lang.datatable.uniq_name}:</strong>
                                            <span>{$widget.uniq_name}</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col">
                                    <div class="card">
                                        <div class="card-body py-2 border-top border-success d-flex align-items-center justify-content-between fs-7">
                                            <strong>{$lang.datatable.pay_typing}:</strong>
                                            <span>{$widget.price_model}</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col">
                                    <div class="card">
                                        <div class="card-body py-2 border-top border-success d-flex align-items-center justify-content-between fs-7">
                                            <strong>{$lang.datatable.periodicity}:</strong>
                                            <span>{$widget.period}</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col">
                                    <div class="card">
                                        <div class="card-body py-2 border-top border-success d-flex align-items-center justify-content-between fs-7">
                                            <strong>{$lang.header.notifications}:</strong>
                                            <span>{$widget.notify_fr}</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col">
                                    <div class="card">
                                        <div class="card-body py-2 border-top border-success d-flex align-items-center justify-content-between fs-7">
                                            <strong>{$lang.datatable.limit}:</strong>
                                            <span>{$widget.limit}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </td>
            </tr>
        {/foreach}



        </tbody>
    </table>
</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('#widgetAddForm');
        initWidgetForm('#widgetEditForm');

        // Универсальное копирование в буфер
        $(document).on('click', '#copy-ico', function() {
            const text = $(this).data('copy');
            navigator.clipboard.writeText(text).then(() => {
                $(this).removeClass('fa-copy').addClass('fa-check');
                setTimeout(() => $(this).removeClass('fa-check').addClass('fa-copy'), 2000);
            });
        });

        // Редактирование виджета
        $(document).on('click', '#edit-ico', function(e) {
            e.preventDefault();
            const id = $(this).data('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).on('click', '#delete-ico', function(e) {
            e.preventDefault();
            if(confirm("Вы уверены, что хотите удалить этот виджет?")) {
                const id = $(this).data('id');
                $.post('engine/ajax/lib/widget/widget-handler.php', { id: id, action: 'delete' }, function(){ location.reload(); }, 'json');
            }
        });
    });

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

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