

<?php $__env->startSection('head'); ?>
    <script type="text/javascript">
        $(function() {
            <?php if(isset($availableVariables)): ?>
                var availableVariables = <?php echo json_encode($availableVariables); ?>;
            <?php else: ?>
                var availableVariables = [];
            <?php endif; ?>

            App.Binder.bindTinymce({ 
                setup: function(editor) {
                    var me = this;
                    var highlighted = false;

                    var highlight = function() {
                        var content = me.getContent();

                        var joinedAvailableVariables = "";
                        $.each(availableVariables, function(key, val) {
                            joinedAvailableVariables += key + "|";
                        });

                        if(joinedAvailableVariables.endsWith('|')) {
                            joinedAvailableVariables = joinedAvailableVariables.substr(0, joinedAvailableVariables.length-1);
                        }

                        var pattern = "#" + "(" + joinedAvailableVariables +")(("+ "," + "([a-zA-Z0-9_.]+))*)" + "#";
                        console.log(pattern);
                        var newContent = content.replace(new RegExp(pattern, 'g'), '<span class="tinmce-highlighted-variable" style="background-color: yellow;">#$1#</span>');

                        var bookmark = editor.selection.getBookmark(2, true);
                        me.setContent(newContent);
                        editor.selection.moveToBookmark(bookmark);

                        highlighted = true;
                    };

                    var removeHighlight = function() {
                        var content = me.getContent();
                        var pattern = '<span class="tinmce-highlighted-variable" style="background-color: yellow;">(#[a-zA-Z0-9-_,]+#)<\\/span>';

                        var newContent = content.replace(new RegExp(pattern, 'g'), '$1');

                        var bookmark = editor.selection.getBookmark(2, true);
                        me.setContent(newContent);
                        editor.selection.moveToBookmark(bookmark);

                        highlighted = false;
                    }

                    var blurBlock = false;
                    var clickUnhighlight = false;
                    editor.addButton('email_template_variable_highlighter', {
                        text: 'Podświetl zmienne',
                        icon: false,
                        onclick: function(e) {
                            if(highlighted == true) {
                                removeHighlight();
                            } else {
                                highlight();

                                blurBlock = true;
                                tinymce.activeEditor.getBody().blur();
                                clickUnhighlight = true;
                                blurBlock = false;
                            }
                        }
                    });

                    editor.on('focus blur', function() {
                        if(blurBlock == false) {
                            removeHighlight();
                        }
                    });

                    editor.on('click', function() {
                        if(clickUnhighlight == true) {
                            removeHighlight();
                            clickUnhighlight = false;
                        }
                    });

                    $("#template-form").bind("submit", function() {
                        removeHighlight();
                    });
                }
            });

            tinymce.init({
                readonly:1,
                selector: "#be_emte_footer_preview",
                toolbar: false,
                menubar:false,
                statusbar:false,
                height:180,
                init_instance_callback: function() {
                    footerChange();
                }
            });

            $("#show-available-variables-button").bind("click", function(e) {
                e.preventDefault();

                $("#available-variables-list").toggle();
            });

            var footerSelect = $("#be_emte_emte_id");

            var footerChange = function() {
                if(footerSelect.val() == '') {
                    App.Helper.hideBootstrapFormField($("#be_emte_footer_preview"));
                } else {
                    App.Helper.showBootstrapFormField($("#be_emte_footer_preview"));

                    tinymce.get("be_emte_footer_preview").setContent(<?php echo json_encode("<b>" . trans("GlobalTranslations::common.loading_please_wait") . "</b>"); ?>);

                    footerSelect.addClass('disabled');

                    var url = <?php echo json_encode(route('backend_xhr_get_email_template')); ?>;
                    $.ajax({
                        url: url,
                        data: {id: footerSelect.val()}
                    }).done(function(response) {
                        tinymce.get("be_emte_footer_preview").setContent(response.be_emte_content);
                    }).always(function() {
                        footerSelect.removeClass('disabled');
                    });
                }
            };

            $("#be_emte_emte_id").bind("change", footerChange);

            <?php if(isset($eventName) && ! is_null($data)): ?>
                function templateAttachmentsLoading() {
                    $("#email-template-attachments").fadeTo(200, 0.6);
                }

                function templateAttachmentsReady() {
                    $("#email-template-attachments").fadeTo(1, 1);
                }

                function deleteTemplateAttachment(id) {
                    templateAttachmentsLoading();

                    $.ajax({
                        url: <?php echo json_encode(route('backend_xhr_delete_email_template_attachment')); ?>,
                        type: "POST",
                        data: {be_emtat_id: id, _token: <?php echo json_encode(csrf_token()); ?> }
                    }).done(function(response) {
                        if(typeof response.success_message != "undefined") {
                            App.successMessage(null, response.success_message);

                            templateAttachmentsReady();
                            getTemplateAttachments();
                        } else {
                            App.errorMessage(null, response.error_message)
                        }
                    });
                }

                function getTemplateAttachments() {
                    templateAttachmentsLoading();

                    $.ajax({
                        url: <?php echo json_encode(route('backend_xhr_get_email_template_attachments')); ?>,
                        type: "GET",
                        data: {be_emte_id: <?php echo json_encode($data->getKey()); ?> }
                    }).done(function(response) {
                        var attachmentsTemplate = $("#attachments-template").html();
                        var attachmentsHTML = Mustache.render(attachmentsTemplate, {attachments: response});
                        $("#email-template-attachments").html(attachmentsHTML).find('.delete-template-attachment').bind('click', function(e) {
                                e.preventDefault();

                                deleteTemplateAttachment($(this).data('attachment-id'));
                        });

                        templateAttachmentsReady();
                    });
                }

                getTemplateAttachments();

                $(document).on('chooseFile-attach-file-to-email-template', function(e) {
                    App.FileManager.close();
                    $("#be_emtat_file_path").val(e.path);
                });

                $("#file-path-browse").bind('click', function(e) {
                    e.preventDefault();
                    App.FileManager.show('attach-file-to-email-template');
                });

                $("#attach-attachment-to-template").bind('click', function(e) {
                    e.preventDefault();

                    templateAttachmentsLoading();

                    $.ajax({
                        url: <?php echo json_encode(route('backend_xhr_attach_attachment_to_email_template')); ?>,
                        type: "POST",
                        data: {
                            _token: <?php echo json_encode(csrf_token()); ?>,
                            be_emte_id: <?php echo json_encode($data->getKey()); ?>,
                            be_emtat_file_path: $("#be_emtat_file_path").val()
                        }
                    }).done(function(response) {
                        if(typeof response.success_message != "undefined") {
                            $("#be_emtat_file_path").val('');
                            App.successMessage(null, response.success_message);
                            templateAttachmentsReady();
                            getTemplateAttachments();
                        } else if(response.validation_errors != "undefined") {
                            App.errorMessage(null, response.validation_errors["be_emtat_file_path"][0]);
                            templateAttachmentsReady();
                        }
                    });
                });
            <?php endif; ?>
        });
    </script>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
    <script type="mustache-template" id="attachments-template">
        <div class="alert alert-info">
            {{#attachments}}
                {{name}} <a href="#" class="delete-template-attachment" data-attachment-id="{{value}}"><i class="icon-trash"></i></a><br />
            {{/attachments}}

            {{^attachments}}
                Brak dołączonych załączników
            {{/attachments}}
        </div>
    </script>

    <?php echo HTML::widgetBox(['name' => $data ? trans('GlobalTranslations::common.edit') . (isset($templateName) ? ' (' . $templateName . ')' : null) : trans('GlobalTranslations::common.add') . (isset($templateName) ? ' (' . $templateName . ')' : null), 'icon' => 'icon-user'],
    [
        [
            'name' => trans('MailingEvents::common.show_available_variables'),
            'url' => '#',
            'attributes' => [
                'id' => 'show-available-variables-button',
            ],
            'icon' => 'icon-question-sign',
        ]
    ]); ?>


    <div id="available-variables-list" class="no-display alert alert-info no-border-radius no-margin">
        <?php if(isset($availableVariables)): ?>
            <?php foreach($availableVariables as $variable => $value): ?>
                <?php if($value['required'] == 0): ?>
                    <strong class="label label-info">#<?php echo e($variable); ?>#</strong>
                <?php else: ?>
                    <strong class="label label-danger">#<?php echo e($variable); ?># *</strong>
                <?php endif; ?>
            <?php endforeach; ?>

            <br /><br />
            <small><strong><span class="text-danger">*</span> - <?php echo trans("MailingEvents::common.variables_that_are_required_in_content"); ?></small></strong>
        <?php else: ?> 
            <?php echo trans('MailingEvents::common.no_variables_available'); ?>

        <?php endif; ?>
    </div>

        <?php echo Former::populate($data); ?>

        
        <?php echo Former::open()->id('template-form'); ?>


            <?php echo Former::text('be_emte_name'); ?>


            <?php echo Former::text('be_emte_subject'); ?>


            <?php echo Former::textarea('be_emte_content')->class('tinymce'); ?>


            <?php echo Former::select('be_emte_emte_id')->addOption('-', '')->fromQuery($emailTemplates, 'be_emte_name', 'be_emte_id'); ?>


            <?php echo Former::textarea('be_emte_footer_preview'); ?>


            <?php if(isset($eventName)): ?>
                <div class="form-group">
                    <label class="control-label col-lg-2 col-sm-4"><?php echo trans('MailingEvents::common.attachments'); ?></label>
                    <div class="col-lg-10 col-sm-8">
                        <div id="email-template-attachments">
                            <div class="alert alert-info">
                                <?php echo trans("GlobalTranslations::common.loading_please_wait"); ?>

                            </div>
                        </div>

                        <div class="input-group">
                            <span class="input-group-btn">
                                <span class="attached-button">
                                    <button id="file-path-browse">Przeglądaj</button>
                                </span>
                            </span>

                            <input class="form-control" id="be_emtat_file_path" type="text" name="be_emtat_file_path">

                            <span class="input-group-btn">
                                <span class="attached-button">
                                    <button id="attach-attachment-to-template"><strong><i class="text-success icon-paperclip"></i></button>
                                </span>
                            </span>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <?php echo Former::actions( Former::btn_primary_submit(trans('GlobalTranslations::common.save')), Former::default_reset(trans('GlobalTranslations::common.reset_changes'))->onclick('location.reload();')); ?>


        <?php echo Former::close(); ?>

        
    <?php echo HTML::widgetBox(false); ?>

<?php $__env->stopSection(); ?>
<?php echo $__env->make('Backend::layout', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>