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

/**
 * @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer
 */
?>
<?php
/**
 * @methods
 *  getTitle() - string
 *  getSaveUrl() - string
 *  getSections() - array
 *  getForm() - html
 *  getConfigSearchParamsJson() - string
 */
?>

<?= /* @noEscape */ $secureRenderer->renderTag(
    'style',
    [],
    '.highlighted { background-color: #DFF7FF!important; }'
) ?>

<form action="<?= $block->escapeUrl($block->getSaveUrl()) ?>" method="post" id="config-edit-form"
      enctype="multipart/form-data">
    <?= $block->getBlockHtml('formkey') ?>
    <div class="accordion">
        <?= $block->getChildHtml('form') ?>
    </div>
</form>

<?php $scriptString = <<<script
require([
    "jquery",
    "uiRegistry",
    "Magento_Ui/js/modal/confirm",
    "mage/translate",
    "mage/mage",
    "prototype",
    "mage/adminhtml/form",
    "domReady!",
    "jquery/ui"
], function(jQuery, registry){

    var adminSystemConfig = {
        navigateToElement: function (searchRequest) {
            if ('section' in searchRequest) {
                var section = searchRequest.section;
            }
            if ('group' in searchRequest) {
                var group = searchRequest.group;
            }
            if ('field' in searchRequest) {
                var field = searchRequest.field;
            }
            if (typeof section === 'undefined') {
                return;
            }
            if (typeof group !== 'undefined') {
                var groupElement = jQuery('#' + section + '_' + group);

                var parentSection = groupElement.parents('.section-config');
                parentSection.addClass('highlighted');
                parentSection.addClass('active');
                setTimeout(function() {
                    parentSection.removeClass('highlighted', 2000, "easeInBack");
                }, 3000);
                if (!parentSection.hasClass('active')) {
                    if(section == 'payment') {
                        var openSection = jQuery('.open').first().attr('id');
                        var splitIdArray = openSection.split('_');
                        section = section + '_' + splitIdArray[1];
                    }
                    Fieldset.toggleCollapse(section + '_' + group);
                }
            }
        },
        getUp: function (element, tag) {
            var _element = Element.extend(element);
            if (typeof _element.upTag == 'undefined') {
                _element.upTag = {};
            }
            if (typeof _element.upTag[tag] == 'undefined') {
                _element.upTag[tag] = Element.extend(_element.up(tag));
            }
            return _element.upTag[tag];
        },
        getUpTd: function (element) {
            return this.getUp(element, 'td');
        },
        getUpTr: function (element) {
            return this.getUp(element, 'tr');
        },
        getScopeElement: function(element) {
            var _element = Element.extend(element);
            if (typeof _element.scopeElement == 'undefined') {
                var scopeElementName = element.getAttribute('name').replace(/\[value\]$/, '[inherit]');
                _element.scopeElement = this.getUpTr(element).select('input[name="' + scopeElementName + '"]')[0];
                if (typeof _element.scopeElement == 'undefined') {
                    _element.scopeElement = false;
                }
            }
            return _element.scopeElement;
        },
        getDeleteElement: function(element) {
            var _element = Element.extend(element);
            if (typeof _element.deleteElement == 'undefined') {
                _element.deleteElement = this.getUpTd(element)
                    .select('input[name="'+ element.getAttribute('name') + '[delete]"]')[0];
                if (typeof _element.deleteElement == 'undefined') {
                    _element.deleteElement = false;
                }
            }
            return _element.deleteElement;
        },
        mapClasses: function(element, full, callback, classPrefix) {
            if (typeof classPrefix == 'undefined') {
                classPrefix = 'shared'
            }
            element.classNames().each(function(className) {
                if (className.indexOf(classPrefix + '-') == 0
                    || (full && className.indexOf(classPrefix + '_') == 0)
                    ) {
                    callback(className);
                }
            });
        },
        getRegisteredEvents: function(element) {
            var events = [];
            var registry = Element.retrieve(Element.extend(element), 'prototype_event_registry');
            if (!registry) {
                return events;
            }
            registry.each(function(pair) {
                var eventName = pair.key;
                if (!eventName) {
                    return;
                }
                var responders = registry.get(eventName);
                if (!responders) {
                    return;
                }
                responders.each(function(responder) {
                    if (!responder.handler) {
                        return;
                    }
                    events.push({
                        'eventName': eventName,
                        'handler': responder.handler
                    });
                });
            });
            return events;
        },
        onchangeSharedElement: function(event) {
            var element = Element.extend(Event.element(event));
            adminSystemConfig.mapClasses(element, true, function(className) {
                $$('.' + className).each(function(el) {
                    if (element == el) {
                        return;
                    }

                    var tagName = el.tagName.toLowerCase();
                    if (tagName == 'input' && el.getAttribute('type') == 'file') {
                        var _el = Element.extend(el);
                        var events = adminSystemConfig.getRegisteredEvents(el);
                        _el.stopObserving('change');
                        var elId = _el.id;
                        _el.replace(_el.outerHTML);
                        events.each(function(event) {
                            Event.observe(
                                Element.extend(document.getElementById(elId)), event.eventName, event.handler
                            );
                        });
                    } else {
                        el.stopObserving('change', adminSystemConfig.onchangeSharedElement);
                        if (tagName == 'input' && el.getAttribute('type') == 'checkbox') {
                            if (el.checked != element.checked) {
                                Element.extend(el).click();
                            }
                        } else if (tagName == 'select') {
                            var _el = Element.extend(el);
                            Element.extend(element).select('option').each(function(option) {
                                var relatedOption = _el.select('option[value="' + option.value + '"]')[0];
                                if (typeof relatedOption != 'undefined') {
                                    relatedOption.selected = option.selected;
                                }
                            });
                        } else {
                            el.value = element.getValue();
                        }
                        if (Element.extend(el).requiresObj) {
                            Element.extend(el).requiresObj.indicateEnabled();
                        }
                        fireEvent(el, 'change');
                        Event.observe(el, 'change', adminSystemConfig.onchangeSharedElement);
                    }
                });
            });
        },
        checkRequired: function(element, callback) {
            var tagName = this.tagName.toLowerCase();
            if (tagName != 'fieldset') {
                if (adminSystemConfig.getUpTr(this).visible()) {

                    if (this.hasClassName('not-required')) {
                        return;
                    }

                    var typeAttr = null;
                    if (tagName == 'input') {
                        typeAttr = this.getAttribute('type').toLowerCase();
                    }
                    var valueIsEmpty = false;
                    var scopeElement = adminSystemConfig.getScopeElement(this);
                    if (!scopeElement || !scopeElement.checked) {
                        if (typeAttr == 'file') {
                            var deleteUploadedElement = adminSystemConfig.getDeleteElement(this);
                            valueIsEmpty = !deleteUploadedElement && this.value == ''
                                || deleteUploadedElement && deleteUploadedElement.checked;
                        }
                        valueIsEmpty = valueIsEmpty
                            || (typeAttr == 'text' || typeAttr == 'password') && this.value == ''
                            || (tagName == 'select') && (this.getAttribute('multiple') != null)
                            && this.getValue().length == 0
                            || (tagName == 'select') && (this.getAttribute('multiple') == null)
                            && this.getValue() == null;
                    }

                    if (valueIsEmpty) {
                        if (element.value != 0) {
                            element.value = 0;
                            fireEvent(element, 'change');
                        }
                        element.disable();
                    }
                }
            } else {
                this.select('input,select').each(function(inputElement) {
                    adminSystemConfig.checkRequired.call(Element.extend(inputElement), element, callback);
                });
            }
            callback(this);
        }
    };

    window.configForm = jQuery('#config-edit-form').mage('form').mage('validation', {
        submitHandler: function(form)
        {
            $$('.requires').each(function(element) {
                var scopeElement = adminSystemConfig.getScopeElement(element);
                if (!scopeElement || !scopeElement.checked) {
                    Element.extend(element).disabled = false;
                }
            });
            jQuery(form).trigger('afterValidate');
            form.submit();
        }
    });

    window.configForm.on('invalid-form.validate', function (event, validation) {
        if (validation.errorList.length === 0) {
            return;
        }

        jQuery.each(validation.errorList, function () {
            var element = jQuery(this.element || []);

            if (element.length) {
                jQuery(element.parents('.section-config')).each(function () {
                    if (!jQuery(this).hasClass('active')) {
                        Fieldset.toggleCollapse(jQuery(this).children('.config.admin__collapsible-block').attr('id'));
                    }
                });
            }
        });
    })

    $$('.shared').each(function(element){
        Event.observe(element, 'change', adminSystemConfig.onchangeSharedElement);

        // scope should be shared together with the field
        var scopeElement = adminSystemConfig.getScopeElement(element);
        if (scopeElement) {
            adminSystemConfig.mapClasses(element, false, function(className) {
                scopeElement.addClassName('shared_scope-' + className.substr(7));
            });
            Event.observe(scopeElement, 'change', adminSystemConfig.onchangeSharedElement);
        }

        // file fields should share deletion
        if (element.tagName.toLowerCase() == 'input' && element.getAttribute('type') == 'file') {
            var deleteUploadedElement = adminSystemConfig.getDeleteElement(element);
            if (deleteUploadedElement) {
                adminSystemConfig.mapClasses(element, false, function(className) {
                    deleteUploadedElement.addClassName('shared_delete-' + className.substr(7));
                });
                Event.observe(deleteUploadedElement, 'change', adminSystemConfig.onchangeSharedElement);
            }
        }

        // process situation, when control is complex
        adminSystemConfig.mapClasses(element, true, function(className) {
            var controls = adminSystemConfig.getUpTd(element).select('.' + className);
            if (controls.length < 2) {
                return;
            }

            var counter = 0;
            controls.each(function(controlElement) {
                controlElement.removeClassName(className);
                controlElement.addClassName('shared_' + counter + className.substr(6));
                counter++;
            });
        });
    });

    $$('.requires').each(function(element) {
        var eventObj = {
            'element': Element.extend(element),
            'requires': [],
            'callback': function(required) {},
            checkRequirements: function() {
                var scopeElement = adminSystemConfig.getScopeElement(eventObj.element);
                if (!scopeElement || !scopeElement.checked) {
                    eventObj.element.enable();
                    eventObj.requires.each(function(required) {
                        adminSystemConfig.checkRequired.call(
                            Element.extend(required), eventObj.element, eventObj.callback
                        );
                    }.bind(this));
                }
            },
            keydownCheckRequirements: function() {
                window.setTimeout(eventObj.checkRequirements, 1);
            },
            bindCheckingObserver: function(element) {
                if (element.tagName.toLowerCase() == 'fieldset') {
                    Element.extend(element).select('input,select').each(function(subElement) {
                        eventObj.bindCheckingObserver(subElement);
                    })
                } else {
                    var scopeElement = adminSystemConfig.getScopeElement(element);
                    if (scopeElement) {
                        Event.observe(scopeElement, 'click', eventObj.checkRequirements);
                    }
                    Event.observe(element, 'change', eventObj.checkRequirements);
                    Event.observe(element, 'keydown', eventObj.keydownCheckRequirements);
                }
            },
            indicateEnabled: function() {
                var labelElement = adminSystemConfig.getUpTr(eventObj.element).select('td.label label')[0];
                if (typeof labelElement != 'undefined') {
                    if (eventObj.element.value == 1) {
                        labelElement.addClassName('enabled');
                    } else {
                        labelElement.removeClassName('enabled');
                    }
                }
            }
        };

        // fill eventObj with required elements
        adminSystemConfig.mapClasses(element, false, function(className) {
            var requiredElement = Element.extend(document.getElementById(className.substr(9)));
            if (requiredElement) {
                eventObj.requires.push(requiredElement);
            }
        }, 'requires');
        Element.extend(element).requiresObj = eventObj;

        // replacing "Use Default" action with checking requirements
        var scopeElement = adminSystemConfig.getScopeElement(element);
        if (scopeElement) {
            Event.stopObserving(scopeElement, 'click');
            Event.observe(scopeElement, 'click', function(event) {
                toggleValueElements(scopeElement, Element.previous(scopeElement.parentNode));
                eventObj.checkRequirements();
            });
        }

        // binding events
        eventObj.requires.each(function(required) {
            eventObj.bindCheckingObserver(required);
        });
        Event.observe(eventObj.element, 'change', eventObj.indicateEnabled);
        eventObj.checkRequirements();
        eventObj.indicateEnabled();
    });

    var handleHash = function () {
        if (window.location.hash == '') {
            return false;
        }
        try {
            var hashString = window.location.hash.replace('#', ''),
                containerId = hashString.replace('-link', ''),
                state = jQuery('#' + containerId + '-state'),
                head = jQuery('#' + containerId + '-head');
            if (state.length) {
                state.val(1);
            }
            if (head.length) {
                head.collapsed = 0;
            }
            Fieldset.applyCollapse(containerId);
        } catch(err) {
        }
        return false;
    };

    window.addEventListener('hashchange', handleHash);
    handleHash();

    registry.set('adminSystemConfig', adminSystemConfig);
script;
$scriptString .= 'adminSystemConfig.navigateToElement(' . /* @noEscape */ $block->getConfigSearchParamsJson() . ');
});';

echo /* @noEscape */ $secureRenderer->renderTag('script', [], $scriptString, false);
