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

use Magento\Framework\App\TemplateTypesInterface;

// @codingStandardsIgnoreFile

/* @var $block \Magento\Newsletter\Block\Adminhtml\Template\Edit */

?>
<form action="<?= $block->escapeUrl($block->getSaveUrl()) ?>" method="post" id="newsletter_template_edit_form">
    <?= $block->getBlockHtml('formkey') ?>
    <div class="no-display">
        <input type="hidden" id="change_flag_element" name="_change_type_flag" value="" />
        <input type="hidden" id="save_as_flag" name="_save_as_flag" value="<?= $block->escapeHtmlAttr($block->getSaveAsFlag()) ?>" />
    </div>
    <?= /* @noEscape */ $block->getForm() ?>
</form>
<form action="<?= $block->escapeUrl($block->getPreviewUrl()) ?>" method="get" id="newsletter_template_preview_form" target="_blank">
    <div class="no-display">
        <input type="hidden" id="preview_type" name="type" value="<?= /* @noEscape */ $block->isTextType() ? 1 : 2 ?>" />
        <input type="hidden" id="preview_text" name="text" value="" />
        <input type="hidden" id="preview_styles" name="styles" value="" />
        <input type="hidden" id="preview_id" name="id" value="" />
    </div>
</form>
<script>
require([
    'jquery',
    'wysiwygAdapter',
    'Magento_Ui/js/modal/prompt',
    'Magento_Ui/js/modal/confirm',
    'mage/mage',
    'prototype'
], function (jQuery, wysiwyg, prompt, confirm) {

//<![CDATA[
    jQuery('#newsletter_template_edit_form').mage('form').mage('validation');
    jQuery('#newsletter_template_preview_form').mage('form').mage('validation');
    var templateControl = {

        unconvertedText: '',
        typeChange: false,
        templateName: false,
        id: 'text',

        events: {
            'click [data-role=template-save]': 'save',
            'click [data-role=template-save-as]': 'saveAs',
            'click [data-role=template-preview]': 'preview',
            'click [data-role=template-unstrip]': 'unStripTags',
            'click [data-role=template-strip]': 'stripTags',
            'click [data-role=template-delete]': 'deleteTemplate'
        },

        init: function () {
            if ($('convert_button_back')) {
                $('convert_button_back').hide();
            }

            wysiwyg.id = this.id;

            this.bindEvents();
        },

        bindEvents: function () {
            var events = this.events,
                eventName,
                selector,
                callback,
                key;

            for (key in events) {
                if (!events.hasOwnProperty(key)) {
                    continue;
                }

                callback    = this[events[key]];
                key         = key.split(' ');

                eventName   = key[0];
                selector    = key.slice(1).join(' ');

                jQuery(selector).on(eventName, jQuery.proxy(callback, this));
            }
        },

        stripTags: function () {
            var self = this;

            confirm({
                content: "<?= $block->escapeJs($block->escapeHtml(__('Are you sure that you want to strip all tags?'))) ?>",
                actions: {
                    confirm: function () {
                        if (wysiwyg.activeEditor()) {
                            wysiwyg.turnOff();
                            wysiwyg.getToggleButton().hide();
                        }
                        self.unconvertedText = $(self.id).value;
                        $('convert_button').hide();
                        $('convert_button_back').show();
                        $(self.id).value =  $(self.id).value.stripScripts().stripTags();
                        $('field_template_styles').hide();
                        self.typeChange = true;
                    }
                }
            });

        },

        unStripTags: function () {
            $('convert_button').show();
            $('convert_button_back').hide();
            $(this.id).value = this.unconvertedText;
            if (wysiwyg.activeEditor()) {
                wysiwyg.turnOn();
                wysiwyg.getToggleButton().show();
            }
            this.typeChange = false;
            $('field_template_styles').show();
            return false;
        },

        save: function () {
            if (this.typeChange) {
                $('change_flag_element').value = '1';
            }

            // Temporary solution will be replaced after refactoring of newsletter functionality
            jQuery('#newsletter_template_edit_form').triggerHandler('save');
            return false;
        },

        saveAs: function () {
            var self = this;

            if (this.typeChange) {
                $('change_flag_element').value = '1';
            }

            if ($F('code').blank() || $F('code') == templateControl.templateName) {
                prompt({
                    content: '<?= $block->escapeJs($block->escapeHtml(__('Please enter a new template name.'))) ?>',
                    value: templateControl.templateName + '<?= $block->escapeJs(__(' Copy')) ?>',
                    actions: {
                        confirm: function (value) {
                            $('code').value = value;
                            self._saveAs();

                            return false;
                        },
                        cancel: function () {
                            $('code').value = '';
                            // Temporary solution will be replaced after refactoring of newsletter functionality
                            jQuery('#newsletter_template_edit_form').triggerHandler('save');
                            self._saveAs();

                            return false;
                        }
                    }
                });
            }
        },

        _saveAs: function () {
            $('save_as_flag').value = '1';

            // Temporary solution will be replaced after refactoring of newsletter functionality
            jQuery('#newsletter_template_edit_form').triggerHandler('save');
            return false;
        },

        preview: function () {
            if (this.typeChange) {
                $('preview_type').value = <?= $block->escapeJs(TemplateTypesInterface::TYPE_TEXT) ?>;
            } else {
                $('preview_type').value = <?= $block->escapeJs($block->getTemplateType()) ?>;
            }

            if (wysiwyg.activeEditor()) {
                $('preview_text').value = wysiwyg.getContent();
            } else {
                $('preview_text').value = $(this.id).value;
            }

            if ($('template_styles') != undefined) {
                $('preview_styles').value = $('template_styles').value;
            }

            if ($('id') != undefined) {
                $('preview_id').value = $('id').value;
            }

            // Temporary solution will be replaced after refactoring of newsletter functionality
            jQuery('#newsletter_template_preview_form').triggerHandler('save');
            return false;
        },

        deleteTemplate: function () {
            confirm({
                content: "<?= $block->escapeJs($block->escapeHtml(__('Are you sure you want to delete this template?'))) ?>",
                actions: {
                    confirm: function () {
                        window.location.href = '<?= $block->escapeUrl($block->getDeleteUrl()) ?>';
                    }
                }
            });
        }
    };

    templateControl.init();
    templateControl.templateName = "<?= $block->escapeJs($block->getJsTemplateName()) ?>";
//]]>

});
</script>
