<?php
/**
 * Maho
 *
 * @category    design
 * @package     default_default
 * @copyright   Copyright (c) 2006-2020 Magento, Inc. (https://magento.com)
 * @copyright   Copyright (c) 2021-2024 The OpenMage Contributors (https://openmage.org)
 * @copyright   Copyright (c) 2024 Maho (https://mahocommerce.com)
 * @license     https://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

/** @var Mage_Adminhtml_Block_System_Email_Template_Edit $this */
?>
<div class="content-header">
    <h3><?= $this->getHeaderText() ?></h3>
    <p class="content-buttons form-buttons">
                <?= $this->getBackButtonHtml() ?>
                <?= $this->getResetButtonHtml() ?>
                <?php if($this->getEditMode()): ?>
                <?= $this->getDeleteButtonHtml() ?>
                <?php endif ?>
                <?php if(!$this->isTextType()): ?>
                <?= $this->getToPlainButtonHtml() ?>
                <?= $this->getToHtmlButtonHtml() ?>
                <?php endif ?>
                <?= $this->getPreviewButtonHtml() ?>
                <?= $this->getSaveButtonHtml() ?>
    </p>
</div>
<?php if (!$this->getEditMode()): ?>
<form action="<?= $this->getLoadUrl() ?>" method="post" id="email_template_load_form">
    <?= $this->getBlockHtml('formkey') ?>
    <div class="entry-edit">
        <div class="entry-edit-head">
            <h4>
            <?= Mage::helper('adminhtml')->__('Load default template') ?>
            </h4>
            <div class="form-buttons"></div>
        </div>
        <div class="fieldset">
            <table class="form-list" cellspacing="0">
                <tbody>
                    <tr>
                        <td class="label">
                            <label for="template_select">
                            <?= Mage::helper('adminhtml')->__('Template') ?>
                            <span class="required">*</span>
                            </label>
                        </td>
                        <td class="value">
                            <select id="template_select" name="code" class="select required-entry">
                                <?php foreach ($this->getTemplateOptions() as $_option): ?>
                                <option value="<?= $_option['value'] ?>"<?= $this->getOrigTemplateCode() == $_option['value'] ? ' selected="selected"' : '' ?>><?= $_option['label'] ?></option>
                                <?php endforeach ?>
                            </select>
                        </td>
                        <td></td>
                    </tr>
                    <tr>
                        <td class="label">
                            <label for="locale_select">
                            <?= Mage::helper('adminhtml')->__('Locale') ?>
                            <span class="required">*</span>
                            </label>
                        </td>
                        <td class="value">
                            <select id="locale_select" name="locale" class="select required-entry">
                                <?php foreach ($this->getLocaleOptions() as $_option): ?>
                                <option value="<?= $_option['value'] ?>"<?php if ($_option['value']==$this->getCurrentLocale()): ?> selected="selected"<?php endif ?>><?= $_option['label'] ?></option>
                                <?php endforeach ?>
                            </select>
                        </td>
                        <td></td>
                    </tr>
                    <tr>
                        <td class="label">
                            <label>&nbsp;</label>
                        </td>
                        <td class="value">
                            <?= $this->getLoadButtonHtml() ?>
                        </td>
                        <td></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</form>
<?php endif ?>
<form action="<?= $this->getSaveUrl() ?>" method="post" id="email_template_edit_form">
    <?= $this->getBlockHtml('formkey') ?>
    <fieldset>
        <input type="hidden" id="change_flag_element" name="_change_type_flag" value="" />
        <input type="hidden" id="orig_template_code" name="orig_template_code" value="<?= $this->getOrigTemplateCode() ?>" />
        <?= $this->getFormHtml() ?>
    </fieldset>
</form>
<form action="<?= $this->getPreviewUrl() ?>" method="post" id="email_template_preview_form" target="_blank">
    <?= $this->getBlockHtml('formkey') ?>
    <div class="no-display">
        <input type="hidden" id="preview_type" name="type" value="<?= $this->isTextType()?1:2 ?>" />
        <input type="hidden" id="preview_text" name="text" value="" />
        <input type="hidden" id="preview_styles" name="styles" value="" />
    </div>
</form>
<script type="text/javascript">
//<![CDATA[
    var templateForm = new varienForm('email_template_edit_form');
    var templatePreviewForm = new varienForm('email_template_preview_form');
    var templateControl = {
        unconvertedText: '',
        typeChange: false,
        variables: null,
        init: function () {
            if ($('convert_button_back')) {
                $('convert_button_back').hide();
            }
            this.renderPaths(<?= $this->getUsedDefaultForPaths() ?>, 'used_default_for');
            this.renderPaths(<?= $this->getUsedCurrentlyForPaths() ?>, 'used_currently_for');
        },
        stripTags: function () {
            if(!window.confirm("<?= Mage::helper('core')->jsQuoteEscape($this->__('Are you sure that you want to strip tags?')) ?>")) {
                return false;
            }
            this.unconvertedText = $('template_text').value;
            $('convert_button').hide();
            $('template_text').value =  $('template_text').value.stripScripts().replace(
                new RegExp('<style[^>]*>[\\S\\s]*?</style>', 'img'), ''
            ).stripTags().strip();
            $('convert_button_back').show();
            $('field_template_styles').hide();
            this.typeChange = true;
            return false;
        },
        unStripTags: function () {
            $('convert_button').show();
            $('convert_button_back').hide();
            $('template_text').value =  this.unconvertedText;
            $('field_template_styles').show();
            this.typeChange = false;
            return false;
        },
        save: function() {
            if (this.typeChange) {
                $('change_flag_element').value = '1';
            }
            templateForm.submit();
            return false;
        },
        preview: function() {
            if (this.typeChange) {
                $('preview_type').value = 1;
            } else {
                $('preview_type').value = 2;
            }
            if (typeof tinymce == 'undefined' || !tinymce.get('template_text')) {
                $('preview_text').value = $('template_text').value;
            } else {
                $('preview_text').value = tinymce.get('template_text').getContent();
            }

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

            templatePreviewForm.submit();
            return false;
        },

        deleteTemplate: function() {
            if(window.confirm("<?= Mage::helper('core')->jsQuoteEscape($this->__('Are you sure that you want to delete this template?')) ?>")) {
                   window.location.href = '<?= $this->getDeleteUrl() ?>';
            }
        },

        load: function() {
            var form = new varienForm('email_template_load_form');

            if (!form.validator.validate()) {
                return;
            }

            this.variables = null;

            new Ajax.Request($('email_template_load_form').action, {
               parameters: Form.serialize($('email_template_load_form'), true),
               area: $('email_template_load_form'),
               onComplete: function (transport) {
                   if (transport.responseText.isJSON()) {
                       var fields = $H(transport.responseText.evalJSON());
                       fields.each(function(pair) {
                          if ($(pair.key)) {
                              $(pair.key).value = pair.value.strip();
                          }
                          if (pair.key == 'template_type') {
                              if (pair.value == 1) {
                                  this.typeChange = true;
                                  $('convert_button').hide();
                                  $('convert_button_back').hide();
                              } else {
                                  this.typeChange = false;
                                  $('convert_button_back').hide();
                                  $('convert_button').show();
                              }
                          }
                          if (pair.key == 'orig_template_used_default_for') {
                               if(pair.value.length){
                                   $('used_default_for').show();
                                   this.renderPaths(pair.value, 'used_default_for');
                               }
                               else{
                                   $('used_default_for').hide();
                               }
                          }
                       }.bind(this));
                   }
               }.bind(this)
            });

        },

        renderPaths: function(paths, fieldId){
            var field = $(fieldId);
            if(field){
                field.down('td').next('td').update(this.parsePath(paths, '<span class="path-delimiter">&nbsp;-&gt;&nbsp;</span>', '<br />'));
            }
        },

        parsePath: function (value, pathDelimiter, lineDelimiter) {
            if (Object.isArray(value)) {
                var result = [];
                for (var i = 0, len = value.length; i < len; i++) {
                    result.push(this.parsePath(value[i], pathDelimiter, pathDelimiter));
                }
                return result.join(lineDelimiter);
            }

            if(!Object.isString(value) && value.title) {
                value = (value.url ? '<a href="' + value.url + '">' + value.title + '</a>' : value.title) + (value.scope ? '&nbsp;&nbsp;<span class="path-scope-label">(' + value.scope + ')</span>' : '');
            }

            return value;
        },

        openVariableChooser: function() {
            Variables.init('template_text');
            if (this.variables == null) {
                Variables.resetData();
                this.variables = $('variables').value.evalJSON();
                var templateVariablesValue = $('template_variables').value;
                if (this.variables && templateVariablesValue) {
                    if (templateVariables = templateVariablesValue.evalJSON()) {
                        this.variables.push(templateVariables);
                    }
                }
            }
            if (this.variables) {
                Variables.openVariableChooser(this.variables);
            }
        }
    };

    templateControl.init();
//]]>
</script>
