<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/** @var $block \Magento\Tax\Block\Adminhtml\Rule\Edit\Form */
/** @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer */
?>
<?php $formElementId = /* @noEscape */ \Magento\Tax\Block\Adminhtml\Rate\Form::FORM_ELEMENT_ID;
$jsId = /* @noEscape */ $block->getJsId();
//phpcs:ignore Magento2.SQL.RawQuery
$scriptString = <<<script
require([
    'jquery',
    'Magento_Ui/js/modal/alert',
    'Magento_Ui/js/modal/confirm',
    "jquery/ui",
    'mage/multiselect',
    "mage/mage",
    'Magento_Ui/js/modal/modal'
], function($, alert, confirm) {

    $.widget("adminhtml.dialogRates", $.mage.modal, {
        options: {
            itemRate: {},
            itemRateDefault: {}
        },
        _create: function() {
            this._super();
            this._getFormData(this.options.itemRateDefault);
        },
        openModal: function() {
            var zipIsRange = this.modal.find('#zip_is_range');

            this._applyItem(this.options.itemRateDefault);
            if (this.options.itemRate && !$.isEmptyObject(this.options.itemRate)) {
                this._applyItem(this.options.itemRate);
            }
            zipIsRange.attr('checked', zipIsRange.val() == 1);
            zipIsRange.trigger('change');
            updater.update();
            this._super();
        },
        closeModal: function() {
            this._super();
        },
        _applyItem: function(rate) {
            var dialogElement = this.modal;

            $.each(rate, function(key, value) {
                if (!value) {
                    value = '';
                }
                dialogElement.find('[name="' + key + '"]').attr('value', value);
            });
        },
        updateItemRate: function() {
            this._getFormData(this.options.itemRate);
        },
        _getFormData: function(data) {
            $.each(this.modal.find(':input'), function() {
                if (this.name) {
                    data[this.name] = this.value
                }
            });
        }
    });

    TaxRateEditableMultiselect = function (settings) {
        this.settings = settings || {};
        this.isEntityEditable = this.settings.is_entity_editable || false;

        this.edit = function() {
            var listItem = $(this).closest('.mselect-list-item');
            var that = listItem.children('.mselect-edit');
            var id = listItem.find('input[type="checkbox"]').attr('value'),
                item;

            $('body').trigger('processStart');
            $.ajax({
                type: "POST",
                data: {id:id},
                url: '{$block->escapeJs($block->getTaxRateLoadUrl())}',
                success: function(result, status) {
                    $('body').trigger('processStop');
                    if (result.success) {
                        item=result.result;
                        item.itemElement = that.prev();
                        $('#tax-rate-form')
                            .dialogRates({itemRate: item})
                            .dialogRates('openModal');

                    } else {
                        if (result.error_message)
                            alert({
                                content: result.error_message
                            });
                        else
                            alert({
                                content: '{$block->escapeJs(__('An error occurred'))}'
                            });
                    }
                },
                error: function () {
                    $('body').trigger('processStop');
                    alert({
                        content: '{$block->escapeJs(__('An error occurred'))}'
                    });
                },
                dataType: "json"
            });
        };

        TaxRateEditableMultiselect.prototype.init = function () {
            var options = {
                mselectContainer: '#tax_rate + section.mselect-list',
                toggleAddButton:false,
                addText: '{$block->escapeJs(__('Add New Tax Rate'))}',
                parse: null,
                nextPageUrl: '{$block->escapeJs($block->getTaxRatesPageUrl())}',
                selectedValues: this.settings.selected_values,
                mselectInputSubmitCallback: function (value, options) {
                    var select = $('#tax_rate');
                        select.append('<option value="" selected="selected">' + value + '</option>');
                    var mselectItemHtml = $(options.item.replace(/%value%|%label%/gi, value)
                        .replace(/%mselectCheckedClass%|%mselectDisabledClass%|%iseditable%|%isremovable%/gi, '')
                        .replace(/%checked%|%disabled%/gi, '')
                        .replace(/%mselectListItemClass%/gi, options.mselectListItemClass))
                        .find('[type=checkbox]')
                        .attr('checked', true)
                        .addClass(options.mselectCheckedClass)
                        .end();
                    var itemsWrapper = select.nextAll('section.block:first')
                        .find('.' + options.mselectItemsWrapperClass + '');
                    itemsWrapper.children('.' + options.mselectListItemClass + '').length
                        ? itemsWrapper.children('.' + options.mselectListItemClass + ':last').after(mselectItemHtml)
                        : itemsWrapper.prepend(mselectItemHtml);
                }
            };
            var taxRate = $('#tax_rate'),
                taxRateField = taxRate.parent(),
                taxRateForm = $('#tax-rate-form'),
                taxRateFormElement = $('#{$formElementId}');

            if (!this.isEntityEditable) {
                // Override default layout of editable multiselect
                options['layout'] = '<section class="block %mselectListClass%">'
                        + '<div class="block-content"><div class="%mselectItemsWrapperClass%">'
                        + '%items%'
                        + '</div></div>'
                        + '<div class="%mselectInputContainerClass%">'
                        + '<input type="text" class="%mselectInputClass%" title="%inputTitle%"/>'
                        + '<span class="%mselectButtonCancelClass%" title="%cancelText%"></span>'
                        + '<span class="%mselectButtonSaveClass%" title="Add"></span>'
                        + '</div>'
                        + '</section>';
                options['mselectInputSubmitCallback'] = null;
            }

            taxRate.multiselect2(options);

            taxRateField.find('.mselect-button-add').off('click');

            taxRateField.find('.mselect-list')
                    .on('click.mselect-edit', '.mselect-edit', this.edit)
                    .on("click.mselect-delete", ".mselect-delete", function () {
                        var that = $(this),

script;
                            // phpcs:ignore Magento2.SQL.RawQuery
                            $scriptString .= "select = that.closest('.mselect-list').prev()," . PHP_EOL;
                            $scriptString .= <<<script

                            rateValue = that.parent().find('input[type="checkbox"]').val();

                        confirm({
                            content: '{$block->escapeJs(__('Do you really want to delete this tax rate?'))}',
                            actions: {
                                /**
                                 * Confirm action.
                                 */
                                confirm: function () {
                                    $('body').trigger('processStart');
                                    var ajaxOptions = {
                                        type: 'POST',
                                        data: {
                                            tax_calculation_rate_id: rateValue,
                                            form_key: $('input[name="form_key"]').val()
                                        },
                                        dataType: 'json',
                                        url: '{$block->escapeJs($block->getTaxRateDeleteUrl())}',
                                        success: function(result, status) {
                                            $('body').trigger('processStop');
                                            if (result.success) {
                                                that.parent().remove();
                                                select.find('option').each(function() {
                                                    if (this.value === rateValue) {
                                                        $(this).remove();
                                                    }
                                                });
                                                select.trigger('change.hiddenSelect');
                                            } else {
                                                if (result.error_message)
                                                    alert({
                                                        content: result.error_message
                                                    });
                                                else
                                                    alert({
                                                        content: '{$block->escapeJs(__('An error occurred'))}'
                                                    });
                                            }
                                        },
                                        error: function () {
                                            $('body').trigger('processStop');
                                            alert({
                                                content: '{$block->escapeJs(__('An error occurred'))}'
                                            });
                                        }
                                    };
                                    $.ajax(ajaxOptions);
                                }
                            }
                        });
                    })
                    .on('click.mselectAdd', '.mselect-button-add', function () {
                        taxRateForm
                                .dialogRates({itemRate: {}})
                                .dialogRates('openModal');
                    })
                    .on('click.mselect-checked', '.mselect-list-item input', function (event) {
                        var el = $(this),
                                checkedClassName = 'mselect-checked';
                        el[el.is(':checked') ? 'addClass' : 'removeClass'](checkedClassName);
                    })
                    .on('dblclick.mselect-list-item', '.mselect-list-item label span', this.edit);
            taxRateFormElement.mage('form').mage('validation');

            taxRateForm.dialogRates({
                title: '{$block->escapeJs(__('Tax Rate'))}',
                type: 'slide',
                id: '{$jsId}',
                modalClass: 'tax-rate-popup',
                closed: function () {
                    taxRateFormElement.data('validation').clearError();
                },
                buttons: [{
                    text: '{$block->escapeJs(__('Save'))}',
                    'class': 'action-save action-primary',
                    click: function() {
                        this.updateItemRate();
                        var itemRate = this.option('itemRate'),
                            itemRateData = $.extend({}, itemRate);

                        if (itemRateData.itemElement) {

script;
                            //phpcs:ignore Magento2.SQL.RawQuerys
                            $scriptString .= ' delete itemRateData.itemElement;';
$scriptString.= <<<script

                        }

                        if (!taxRateFormElement.validation().valid()) {
                            return;
                        }
                        $('.tax-rate-popup').trigger('processStart');
                        $('.loading-mask').css('z-index','1004');
                        var ajaxOptions = {
                            type: 'POST',
                            data: itemRateData,
                            dataType: 'json',
                            url: '{$block->escapeJs($block->getTaxRateSaveUrl())}',
                            success: function(result, status) {
                                $('body').trigger('processStop');
                                if (result.success) {
                                    itemRate.code = result.code;
                                    if (itemRate.tax_calculation_rate_id) {
                                        itemRate.itemElement.find('span').html(itemRate.code);
                                    } else {
                                        itemRate.tax_calculation_rate_id = result.tax_calculation_rate_id;
                                        taxRateField.find('.mselect-input').val(itemRate.code);
                                        taxRateField.find('.mselect-save').trigger('mousedown');
                                        taxRateField.find('option[value=""]:last')
                                            .val(itemRate.tax_calculation_rate_id);
                                        taxRateField.find('input[type="checkbox"][value="' + itemRate.code + '"]')
                                            .val(itemRate.tax_calculation_rate_id);
                                        taxRateField.find('select').trigger('change.hiddenSelect');
                                    }
                                    taxRateForm.dialogRates('closeModal');
                                } else {
                                    if (result.error_message)
                                        alert({
                                            content: result.error_message
                                        });
                                    else
                                        alert({
                                            content: '{$block->escapeJs(__('An error occurred'))}'
                                        });
                                }
                            },
                            error: function () {
                                $('body').trigger('processStop');
                                alert({
                                    content: '{$block->escapeJs(__('An error occurred'))}'
                                });
                            }
                        };
                        $.ajax(ajaxOptions);
                    }
                }]
            });
            $('.grid-loading-mask').hide();
        }
    };

    window.TaxRateEditableMultiselect = TaxRateEditableMultiselect;
});
script;
?>
<?= /* @noEscape */ $secureRenderer->renderTag('script', [], $scriptString, false) ?>
