<?php
/**
 * Copyright 2014 Adobe
 * All Rights Reserved.
 */

/* @var $block \Magento\ConfigurableProduct\Block\Product\Configurable\AttributeSelector */
/** @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer */
?>

<?php $scriptString = <<<script
(function(){
    'use strict';

    var _form;

    require([
        'jquery',
        'jquery/ui',
        'Magento_Ui/js/modal/modal'
    ], function($){
        _form = $('[data-role=affected-attribute-set-selector]');
        var resetValidation = function() {
                _form.find('.messages .message.error').hide();
                _form.find('form').validation().data('validator').resetForm();
            },
            setAttributeSetId = function (id) {
                $('[data-role=new-variations-attribute-set-id]').val(id);
            },
            closeDialogAndProcessForm = function (form) {
                form.modal('closeModal').data('target').click();
            },
            newAttributeSetContainer = $('[data-role=affected-attribute-set-new-name-container]'),
            existingAttributeSetContainer = $('[data-role=affected-attribute-set-existing-name-container]');

        _form.find('input[type=text]').on('keypress',function(e){
            if(e.keyCode === 13){
                e.preventDefault();
                _form.closest('[data-role=modal]').find('button[data-action=confirm]').click();
            }
        });

        $('[data-form=edit-product]').append($('<input>', {
            type: 'hidden',
            name: 'new-variations-attribute-set-id',
            'data-role': 'new-variations-attribute-set-id'
        }));

        _form
            .modal({
                title: '{$block->escapeJs(__('Choose Affected Attribute Set'))}',
                closed: function () {
                    resetValidation();
                },
                buttons: [{
                    text: '{$block->escapeJs(__('Confirm'))}',
                    attr: {
                        'data-action': 'confirm'
                    },
                    'class': 'action-primary',
                    click: function() {
                        var affectedAttributeSetId = _form.find('input[name=affected-attribute-set]:checked').val();
                        if (affectedAttributeSetId == 'current') {
                            setAttributeSetId($('#attribute_set_id').val());
                            closeDialogAndProcessForm(_form);
                            return;
                        } else if (affectedAttributeSetId == 'existing') {
                            setAttributeSetId($('select', existingAttributeSetContainer).val());
                            closeDialogAndProcessForm(form);
                        }

                        _form.find('.messages .message.error').hide();
                        if (!_form.find('form').validation().valid()) {
                            _form.find('input[name=new-attribute-set-name]').focus();
                            return false;
                        }

                        $.ajax({
                            type: 'POST',
                            url: '{$block->escapeUrl($block->getAttributeSetCreationUrl())}',
                            data: {
                                gotoEdit: 1,
                                attribute_set_name: _form.find('input[name=new-attribute-set-name]').val(),
                                skeleton_set: $('#attribute_set_id').val(),
                                form_key: '{$block->escapeJs($block->getFormKey())}',
                                return_session_messages_only: 1
                            },
                            dataType: 'json',
                            showLoader: true,
                            context: _form
                        })
                            .done(function (data) {
                                if (!data.error) {
                                    setAttributeSetId(data.id);
                                    closeDialogAndProcessForm(_form);
                                } else {
                                    _form.find('.messages .message.error').replaceWith($(data.messages)
                                    .find('.message.error'));
                                }
                            });

                        return false;
                    }
                },{
                    text: '{$block->escapeJs(__('Cancel'))}',
                    id: '{$block->escapeJs($block->getJsId('close-button'))}',
                    'class': 'action-close',
                    click: function() {
                        _form.modal('closeModal');
                    }
                }]
            })
            .find('input[name=affected-attribute-set]').on('change', function() {
                var affectedAttributeSet = $(this).val();
                newAttributeSetContainer[affectedAttributeSet == 'new' ? 'show' : 'hide']();
                existingAttributeSetContainer[affectedAttributeSet == 'existing' ? 'show' : 'hide']();
                resetValidation();
                if (affectedAttributeSet == 'new') {
                    newAttributeSetContainer.find('input[name=new-attribute-set-name]').focus();
                }
            });
    });

    require([
        'jquery'
    ], function ($) {

        /**
         * Retrieve list of attributes
         *
         * @return {Array}
         */
        var getAttributes = function (_node) {
            return $.map(
                _node.find('[data-role=configurable-attributes-container] [data-role=attribute-info]') || [],
                function (attribute) {
                    var _attribute = $(attribute);

                    return {
                        id: _attribute.find('[name$="[attribute_id]"]').val(),
                        code: _attribute.find('[name$="[code]"]').val(),
                        label: _attribute.find('[name$="[label]"]').val(),
                        position: _attribute.find('[name$="[position]"]').val()
                    };
                }
            );
        };

        /**
         * This fix was made in order to properly handle 'stopImmediatePropagation'.
         */
        $('#save-split-button .item').on('click', function(event) {
            if ($('[data-role=new-variations-attribute-set-id]').val() != '') {
                return; // affected attribute set was already chosen
            }

            var extendingAttributes = [];

            $.each(getAttributes($('[data-role=product-variations-matrix]')), function () {
                if (!$('#attribute-' + this.code + '-container').length) {
                    extendingAttributes.push(this.id);
                }
            });
            if (!extendingAttributes.length) {
                $('[data-role=new-variations-attribute-set-id]').val($('#attribute_set_id').val());
                return; // all selected configurable attributes belong to current attribute set
            }
            if (!$('[data-role=product-variations-matrix] [data-column=entity_id]')
                .closest('tr').has('input[name$="[name]"]').length
            ) {
                return; // no new simple products to save from matrix: uniting attribute set is not needed
            }

            event.stopImmediatePropagation();

            _form.data('target', event.target).modal('openModal');
        });

    });

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

