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

/**
 * @var $block \Magento\Catalog\Block\Adminhtml\Product\Edit
 * @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer
 */
?>
<div class="admin__scope-old">
    <div class="product-actions">
        <div id="product-template-suggest-container" class="suggest-expandable">
            <div class="action-dropdown">
                <button type="button" class="action-toggle" data-mage-init='{"dropdown":{}}' data-toggle="dropdown">
                    <span><?= $block->escapeHtml($block->getAttributeSetName()) ?></span>
                </button>
                <ul class="dropdown-menu">
                    <li><input type="text" id="product-template-suggest" class="search"
                           placeholder="<?= $block->escapeHtmlAttr(__('start typing to search template')) ?>"/></li>
                </ul>
            </div>
        </div>

        <div class="switcher" onselectstart='return false;'>
            <input type="checkbox" id="product-online-switcher" name="product-online-switcher" />
            <label class="switcher-label"
                   for="product-online-switcher"
                   data-text-on="<?= $block->escapeHtmlAttr(__('Product online')) ?>"
                   data-text-off="<?= $block->escapeHtmlAttr(__('Product offline')) ?>"
                   title="<?= $block->escapeHtmlAttr(__('Product online status')) ?>"></label>
        </div>

        <?php if ($block->getProductId()):?>
            <?= $block->getDeleteButtonHtml() ?>
        <?php endif; ?>
        <?php if ($block->getProductSetId()):?>
            <?= $block->getChangeAttributeSetButtonHtml() ?>
            <?= $block->getSaveSplitButtonHtml() ?>
        <?php endif; ?>
        <?= $block->getBackButtonHtml() ?>
    </div>
</div>
<?php if ($block->getUseContainer()): ?>
<form action="<?= $block->escapeUrl($block->getSaveUrl()) ?>" method="post" enctype="multipart/form-data"
      data-form="edit-product" data-product-id="<?= $block->escapeHtmlAttr($block->getProduct()->getId()) ?>">
<?php endif; ?>
    <?= $block->getBlockHtml('formkey') ?>
    <div data-role="tabs" id="product-edit-form-tabs"></div>
    <?php /* @TODO: remove id after elimination of setDestElementId('product-edit-form-tabs') */?>
    <?= $block->getChildHtml('product-type-tabs') ?>
    <input type="hidden" id="product_type_id"
           value="<?= $block->escapeHtmlAttr($block->getProduct()->getTypeId()) ?>"/>
    <input type="hidden" id="attribute_set_id"
           value="<?= $block->escapeHtmlAttr($block->getProduct()->getAttributeSetId()) ?>"/>
    <button type="submit" class="hidden"></button>
<?php if ($block->getUseContainer()):?>
</form>
<?php endif; ?>
<?php
/** @var \Magento\Framework\Json\Helper\Data $jsonHelper */
$jsonHelper = $block->getData('jsonHelper');
$jsonFieldsAutogenerationMasks  = /* @noEscape */ $jsonHelper->jsonEncode($block->getFieldsAutogenerationMasks());
$jsonAttributesAllowedForAutogeneration = /* @noEscape */ $jsonHelper->jsonEncode(
    $block->getAttributesAllowedForAutogeneration()
);
$scriptString = <<<scriptStr
require([
    "jquery",
    "Magento_Catalog/catalog/type-events",
    "underscore",
    "mage/mage",
    "mage/backend/tabs",
    "domReady!"
], function($, TypeSwitcher){
    var \$form = $('[data-form=edit-product]');
    \$form.data('typeSwitcher', TypeSwitcher.init());

    var scriptTagManager = (function($) {
        var hiddenPrefix = 'hidden',
            scriptTypeRegExp = /((java|ecma)script)/gi,
            hiddenScriptType = 'text/' + hiddenPrefix + 'javascript',
            changeScriptsType = function(source, callback) {
                var isString = (typeof source === 'string'),
                    div = document.createElement('div'),
                    scripts,
                    scriptsLength;
                div.innerHTML = isString ? source : $(source).clone().wrap('<p>').parent().html();
                scripts = div.getElementsByTagName('script');
                scriptsLength = scripts.length;
                for (var i = 0; i < scriptsLength; i++) {
                    scripts[i].type = callback(scripts[i].type);
                }
                return isString ? div.innerHTML : $(div.innerHTML);
            },
            disableScripts = function(source) {
                enableScripts(source);
                return changeScriptsType(source, function(type) {
                    return type ? type.replace(scriptTypeRegExp, hiddenPrefix + '$1') : hiddenScriptType;
                });
            },
            enableScripts = function(source) {
                return changeScriptsType(source, function(type) {
                    return type.replace(hiddenPrefix, '');
                });
            };
        return {
            'disableScripts' : disableScripts,
            'enableScripts' : enableScripts
        }
    })($);

    $('#meta_description').on('change keyup paste', function () {
        var maxLength = $(this).data('maxLength') || 255;
        if ($(this).val().length >= maxLength) {
            $(this).val($(this).val().substr(0, maxLength));
        }
    });
    \$form.mage('form', {
        handlersData: {
            save: {},
            saveAndContinueEdit: {
                action: {
                    args: {back: 'edit'}
                }
            },
            saveAndNew: {
                action: {
                    args: {back: 'new'}
                }
            },
            saveAndDuplicate: {
                action: {
                    args: {back: 'duplicate'}
                }
            }
        }
    });
    \$form.mage('validation', {validationUrl: '{$block->escapeJs($block->getValidationUrl())}'});

    var masks = {$jsonFieldsAutogenerationMasks};
    var availablePlaceholders = {$jsonAttributesAllowedForAutogeneration};
    var Autogenerator = function(masks) {
        this._masks = masks || {};
        this._fieldReverseIndex = this._buildReverseIndex(this._masks);
        this.form = $('[data-form=edit-product], #drawer-form');
    };

    $.extend(Autogenerator.prototype, {
        varRegexp: /{{([\w_]+?)}}/,
        varsRegexp: new RegExp('{{(' + availablePlaceholders.join('|') + ')}}', 'g'),
        data: {
            disabled: 'autogenerator-disabled'
        },
        bindAll: function(events) {
            var self = this;
            var elementSelector = _(this._masks).keys().map(function(key) {
                return '#' + key;
            }).join(',');
            var disabler = function() {
                this.form.on(
                    'change init',
                    elementSelector,
                    $.proxy(function(event) {
                        var \$element = $(event.target);
                        if (event.type == 'init' && \$element.data('disablerInited')) {
                            return;
                        } else {
                            \$element.data('disablerInited', true);
                        }
                        \$element.data(this.data.disabled, \$element.val().replace(/\s/g, '') != '');
                    }, this)
                ).find(elementSelector).trigger('init');
            };
            disabler.call(this);
            $("#product_info_tabs").on("tabscreate tabsactivate", $.proxy(disabler, this));

            $.each(this._masks, function(field, mask) {
                var \$field = $('#' + field);
                if (!\$field.val() && mask && mask.length > 0 && !self.varRegexp.test(mask)) {
                    \$field.val(mask);
                }
                \$field.trigger('change');
            });

            $.each(self._fieldReverseIndex, function(field) {
                var fields = this, \$field = $('#' + field);
                var filler = function(onlyText) {
                    $.each(fields, function() {
                        var \$el = $('#' + this);
                        if (\$el.data(self.data.disabled)) {
                            return;
                        }
                        if (onlyText === true && self.varRegexp.test(self._masks[this])) {
                            return;
                        }
                        var value = self._masks[this].replace(self.varsRegexp, function(maskfieldName) {
                            return $('#' + maskfieldName.slice(2, -2)).val();
                        });
                        \$el.val(value);
                    });
                };
                if (\$field.length) {
                    self.form.on('keyup change blur click paste', '#' + field, filler);
                    \$field.trigger('change');
                }
            });
        },
        _buildReverseIndex: function(masks) {
            var self = this;
            var fieldReverseIndex = {};
            $.each(masks, function(field, mask) {
                if (mask) {
                    $.each(mask.toString().match(self.varsRegexp) || [], function (key, maskName) {
                        var fieldName = maskName.slice(2, -2);
                        if (!(fieldName in fieldReverseIndex)) {
                            fieldReverseIndex[fieldName] = [];
                        }
                        fieldReverseIndex[fieldName].push(field);
                    })
                }
            });
            return fieldReverseIndex;
        }
    });

    \$form.data('autogenerator', new Autogenerator(masks).bindAll());

    $('.widget-button-save .item-default').parent().hide();

    $('#product-online-switcher')
        .prop('checked', $('#status').val() == '1')
        .trigger('change');

    $('#product-online-switcher').on('change', function(event) {
        $('#status').val($(this).prop('checked') ? '1' : '2');
    });

    \$form.on('changeAttributeSet', function(event, data) {
        if (data.label) {
            $('#product-template-suggest-container .action-toggle>span').text(data.label);
            $('[data-role=affected-attribute-set-selector] [data-role=name-container]').text(data.label);
        }
        $('#product-template-suggest').suggest('option', "currentlySelected", data.id).val('');

        var uri = document.location.href.replace(/(\/|&|\?)?\bset(\/|=)\d+/g, '').replace(/#[^#]*$/, '');
        uri += /\?/.test(uri) ? '&' : '?';
        uri += 'set=' + window.encodeURIComponent(data.id);

        var \$form = $('[data-form=edit-product]');
        \$form.attr('action', \$form.attr('action').replace(/(\/|&|\?)?\bset(\/|=)\d+/g, ''));
        \$form.find('#attribute_set_id').attr('name', 'set').val(data.id);
        $.ajax({
            url: uri.replace('/edit/', '/new/') + '&popup=1',
            type: 'post',
            data: \$form.serializeArray(),
            dataType: 'html',
            context: $('body'),
            showLoader: true
        }).done(function(data) {
            //Hide all js scripts to prevent removing them during jQuery object creation
            data = scriptTagManager.disableScripts(data);
            var removedElementClass = 'removed';

            var \$page = $('body');
            var \$newPage = $(data);

            var nameMapper = function() {
                return $(this).attr('name');
            };
            var activeTabId = $('.ui-tabs-active>a').attr('id');
            //add new tab tabs or reorder
            \$page.find('#product_info_tabs .tabs').each(function(i, tabContainer) {
                \$newPage.find('#product_info_tabs .tabs').each(function(j, newTabContainer) {
                    if (i != j) {
                        return;
                    }
                    var \$tabContainer = $(tabContainer);
                    $(tabContainer).find('li').removeClass(removedElementClass);
                    var \$tabs = $(tabContainer)
                        .find('li:not(.' + removedElementClass + ')  .tab-item-link.user-defined:not(.ajax)');
                    var \$newTabs = $(newTabContainer).find('.tab-item-link.user-defined:not(.ajax)'),
                        tabsNames = \$tabs.map(nameMapper).toArray();

                    //hide not exists elements
                    $.each(
                        _.difference(tabsNames, \$newTabs.map(nameMapper).toArray()),
                        function(index, tabName) {
                            \$tabContainer.find('[name=' + tabName + ']').closest('li')
                                .addClass(removedElementClass);
                            \$page.find('#' + tabName)
                                .addClass(removedElementClass)
                                .addClass('ignore-validate');
                        }
                    );

                    $(newTabContainer).find('.tab-item-link.user-defined:not(.ajax)').each(function(index, tab) {
                        var \$tab = $(tab),
                            tabName = nameMapper.apply(\$tab),
                            \$tabsContent = \$tab.closest('li').clone();
                        \$tabsContent.find('.fieldset>.field').remove();
                        if (nameMapper.apply(\$tabs.eq(index)) == tabName) {
                            return true;
                        }
                        var \$tabToMove = $.inArray(tabName, tabsNames) !== -1
                            ? \$tabs.filter(function() {
                            return nameMapper.apply(this) === tabName;
                        }).closest('li')
                            : \$tabsContent;
                        if (index === 0) {
                            \$tabToMove.prependTo(\$tabContainer);
                        } else {
                            \$tabToMove.insertAfter(\$tabs.eq(index - 1).closest('li'));
                        }
                        \$tabToMove.removeClass(removedElementClass).removeClass('ignore-validate');
                        \$tabs = \$tabContainer
                        .find('li:not(.' + removedElementClass + ')  .tab-item-link.user-defined:not(.ajax)');
                    });
                });
            });

            //add new fieldsets or reorder
            \$newPage.find('#product_info_tabs .fieldset.user-defined').each(function(index, newFieldset) {
                var fieldsetContainer, newFieldsetContainer, sourceContainer, destinationContainer;
                newFieldsetContainer = $(newFieldset).parents('[data-ui-id*=-tab-content-]').first();
                if (\$page.find('[data-ui-id=' + newFieldsetContainer.data('uiId') + ']').length === 0) {
                    fieldsetContainer = newFieldsetContainer
                        .clone()
                        .removeClass(removedElementClass)
                        .removeClass('ignore-validate');
                    //Enable hidden js scripts in node. These scripts will be performed after inserting into page
                    fieldsetContainer = scriptTagManager.enableScripts(fieldsetContainer);
                } else {
                    fieldsetContainer = \$page.find('[data-ui-id=' + newFieldsetContainer.data('uiId') + ']').first();
                }
                sourceContainer = newFieldsetContainer.parents('[data-ui-id*=-tab-content-]').first();
                destinationContainer = \$page.find('[data-ui-id=' + sourceContainer.data('uiId') + ']').first();
                fieldsetContainer.appendTo(destinationContainer);
            });

            var nameDataMapper = function() {
                return $(this).data('attributeCode');
            };
            //add new element elements or reorder
            \$page.find('[data-form=edit-product] [data-role=tabs] .fieldset, #product_info_tabs .fieldset')
                .removeClass('ignore-validate')
                .removeClass(removedElementClass)
                .each(function(i, fieldSet) {
                var updateFieldsetElements = function(index, newFieldSet) {
                    if ($(fieldSet).attr('id') != $(newFieldSet).attr('id')) {
                        return
                    }
                    var \$elements = $(fieldSet).find('>.field:not(.' + removedElementClass + ')');
                    var \$newFieldSet = $(newFieldSet);
                    var \$newElements = \$newFieldSet.find('>.field');

                    \$elements.removeClass(removedElementClass);

                    var elementNames = \$elements.map(nameDataMapper).toArray();

                    //hide not exists elements
                    $.each(
                        _.difference(elementNames, \$newElements.map(nameDataMapper).toArray()),
                        function(index, elementId) {
                            \$page.find('#attribute-' + elementId + '-container')
                                .addClass(removedElementClass)
                                .addClass('ignore-validate');
                        }
                    );

                    \$newElements.each(function(index, element) {
                        var \$element = $(element),
                            elementId = nameDataMapper.apply(\$element);
                        if (nameDataMapper.apply(\$elements.get(index)) == elementId) {
                            return true;
                        }
                        var \$elementToMove = $('.fieldset>.field[data-attribute-code="' + elementId + '"]');
                        if (\$elementToMove.length === 0) {
                            \$elementToMove = \$element.clone();
                        }
                        if (index === 0) {
                            \$elementToMove.prependTo(fieldSet);
                        } else {
                            \$elementToMove.insertAfter(\$elements.get(index - 1))
                        }
                        \$elementToMove.trigger('contentUpdated');
                        \$elementToMove.removeClass(removedElementClass).removeClass('.ignore-validate');
                        \$elements = $(fieldSet).find('>.field:not(.' + removedElementClass + ')');
                    });
                };

                \$newPage.find('#product_info_tabs .fieldset').each(updateFieldsetElements);

                fieldsetContainer = $(fieldSet).parents('[data-ui-id*=-tab-content-]').first();
                var newFieldsetContainer = \$newPage.find('[data-ui-id=' + $(fieldsetContainer).data('uiId') + ']');
                if (newFieldsetContainer.length == 0) {
                    $(fieldsetContainer).find('fieldset .field')
                        .addClass('ignore-validate')
                        .addClass(removedElementClass);
                    $(fieldsetContainer).addClass(removedElementClass);
                } else {
                    $(newFieldsetContainer).find('fieldset').each(updateFieldsetElements);
                    $(fieldsetContainer).removeClass(removedElementClass);
                }
            });
            $('#product_info_tabs').tabs('refresh');
            if (!$('#' + activeTabId).closest('li').hasClass(removedElementClass)) {
                $('#' + activeTabId).trigger('click');
            } else {
                $('#product_info_tabs').tabs("option", "active", 0);
            }
        });

    });
});
scriptStr;
?>
<?= /* @noEscape */ $secureRenderer->renderTag('script', [], $scriptString, false) ?>
<script type="text/x-magento-init">
    {
        "*": {
            "Magento_Catalog/js/product/weight-handler": {},
            "Magento_Catalog/catalog/apply-to-type-switcher": {}
        }
    }
</script>
