{% extends "@UVDeskCoreFramework//Templates//layout.html.twig" %}

{% block title %}Email Settings{% endblock %}

{% block pageContent %}
    <div class="uv-inner-section">
        {# Append Panel Aside #}
		{% set asideTemplate = 'Webkul\\UVDesk\\CoreFrameworkBundle\\Dashboard\\AsideTemplate' %}
		{% set asideSidebarReference = 'Webkul\\UVDesk\\CoreFrameworkBundle\\UIComponents\\Dashboard\\Panel\\Sidebars\\Settings' %}

		{{ uvdesk_extensibles.getRegisteredComponent(asideTemplate).renderSidebar(asideSidebarReference) | raw }}

        <div class="uv-view">
            <div class="uv-action-bar">
                <div class="uv-action-bar-col-lt">
                    <h1>
                        {{ 'Email Settings'|trans }}
                    </h1>
                </div>
            </div>
            <div id="email-settings">
			</div>
		</div>
    </div>
{% endblock %}

{% block footer %}
	{{ parent() }}

    <script id="email-settings-form-tempplate" type="text/template">
        <form id="email-settings-form">			
            <!-- .fade-out-white -->
            <div style="width: 500px;max-width: 80%;">
                <!-- .jelly-out -->
                <div class="uv-element-block">
                    <label class="uv-field-label">{{ 'Email Id'|trans }}</label>
                    <div class="uv-field-block">
                        <input class="uv-field" type="text" name="id" value='<%= (typeof(id) !== "undefined") ? id : "" %>'>
                    </div>
                </div>
                <div class="uv-element-block">
                    <label class="uv-field-label">{{ 'Name'|trans }}</label>
                    <div class="uv-field-block">
                        <input class="uv-field" type="text" name="name" value='<%= (typeof(name) !== "undefined") ? name : "" %>'>
                    </div>
                </div>

                <div class="uv-element-block">
                    <label class="uv-field-label">{{ 'Choose configuration for sending mails'|trans }}</label>
                    <div class="uv-field-block">
                        <select name="smtp[transport]" id="mailboxOutgoingTransportType" class="uv-select">
                            <option value="" <% if (typeof(mailer_type) == "undefined" || mailer_type == "") { %>selected<% } %>>{{ 'None Selected'|trans }}</option>
                            <option value="outlook" <% if (mailer_type == "outlook") { %>selected<% } %>>{{ 'Outlook'|trans }}</option>
                            <option value="swiftmailer_id" <% if (mailer_type == "swiftmailer_id") { %>selected<% } %>>{{ 'Swift Mailer'|trans }}</option>
                        </select>
                    </div>
                </div>

                <div class="smtp-setting-references"></div>

                <div class="uv-pop-up-actions">
                    <button type="submit" class="uv-btn save-email-settings">{{ 'Proceed'|trans }}</button>
                </div>
            </div>
        </form>
    </script>

    <script id="swift_mailer_configuration_template" type="text/template">
        <div class="uv-element-block">
			 <label class="uv-field-label">{{ 'Swiftmailer id (Select from drop down)'|trans }}</label>
            <div class="uv-field-block">
                <select name="mailer_id" class="uv-select" type="text" value='<%= (typeof(mailer_id) !== "undefined") ? mailer_id : "" %>'>
                    <% if (typeof(mailer_id) == "undefined") { %>
                        <option>Select swiftmailer</option>
                    <% } %>

                    {% for swiftmailer in swiftmailers %}
                        <option <%= typeof(mailer_id) !== 'undefined'  && mailer_id == "{{swiftmailer}}"? selected="selected" : "" %>>{{ swiftmailer }}</option>
                    {% endfor %}
                </select>
            </div>
		</div>
	</script>

    <script id="outlook_oauth_smtp_configuration_template" type="text/template">
        <div class="uv-element-block">
			 <label class="uv-field-label">{{ 'Outlook standard (Select from drop down)'|trans }}</label>
            <div class="uv-field-block">
                <select name="mailer_id" class="uv-select" type="text" value='<%= (typeof(mailer_id) !== "undefined") ? mailer_id : "" %>'>
                    <% if (typeof(mailer_id) == "undefined") { %>
                        <option>Select outlook mailbox</option>
                    <% } %>

                    {% for outlook in outlooks %}
                        <option <%= typeof(mailer_id) !== 'undefined' && mailer_id == "{{outlook}}" ? selected="selected" : "" %>>{{ outlook }}</option>
                    {% endfor %}
                </select>
            </div>
		</div>
	</script>

    <script type="text/javascript">
        var emailSettingsModel = Backbone.Model.extend({
            defaults: {
                'id': "{{ email_settings.id }}",
                'name': "{{ email_settings.name }}",                
                'mailer_id': "{{ email_settings.mailer_id }}",
                'mailer_type': "{{ email_settings.mailer_type }}",
            },
            validation: {
                'id': [
                    {
						pattern: 'email',
						msg: '{{ "Please enter a valid e-mail id"|trans }}'
					},
                ],
                "smtp[transport]": function(value) {
                    if ('' == value) {
                        if (value == undefined || value == '') {
                            return "Please select one active mailbox transport for sending mails";
                        }
                    }
                },
                'name': [
                    {
                        required: true,
						msg: '{{ "Please enter a mailer id"|trans }}'
                    },
                ],
                "mailer_id": function (id) {
					if (id == "Select swiftmailer" || id == "Select outlook mailbox" || id == "Select outlook app mailbox")
						return '{{ "Please select an active mailbox or swift mailer id"|trans }}';
				},
            }
        });

        var emailSettingsForm = Backbone.View.extend({
            el: '#email-settings',
            model: new emailSettingsModel(),
            email_settings_form_template: _.template($('#email-settings-form-tempplate').html()),
            outlook_smtp_configuration_template: _.template($("#outlook_oauth_smtp_configuration_template").html()),
            swift_mailer_configuration_template: _.template($("#swift_mailer_configuration_template").html()),
		    events : {
		    	'click .save-email-settings' : 'saveEmailSettings',
                'change #mailboxOutgoingTransportType': 'changeOutgoingTransportType',
		    },
            initialize: function () {
                this.render();
                const transport = '{{ email_settings.mailer_type|default("") }}'; // Safely retrieve the transport type

                if (transport) {
                    this.renderOutgoingTransportConfigurations(transport, true); // Render based on transport type
                }
            },
            render: function () {
                this.$el.html(this.email_settings_form_template(this.model.toJSON()));
            },
            changeOutgoingTransportType: function(e) {
                let transport = $(e.target).val();

                transport == '' ? $('.smtp-setting-references').hide() : $('.smtp-setting-references').show();
                this.renderOutgoingTransportConfigurations(transport);
            },
            renderOutgoingTransportConfigurations: function (transport,isInialize = false) {
                let data = this.model.toJSON(); // Get the current model data
                
                switch (transport) {
                    case 'outlook':
                        $('.smtp-setting-references').html(this.outlook_smtp_configuration_template(data));
                        break;
                    case 'swiftmailer_id':
                        $('.smtp-setting-references').html(this.swift_mailer_configuration_template(data));
                        break;
                    default:
                        $('.smtp-setting-references').html(''); // Clear if no valid transport
                        break;
                }
            },
            saveEmailSettings: function (event) {
                event.preventDefault();
                Backbone.Validation.bind(this);
                var data = this.$el.find('#email-settings-form').serializeObject();

                this.model.set(data);
                if (this.model.isValid(true)) {
					app.appView.showLoader();
                    this.model.save({}, {
                        url: "{{ path('helpdesk_member_update_emails_settings_xhr') }}",
                        success: function (model, response, options) {
        					app.appView.hideLoader();
                            this.model.attributes = response.email_settings;
                            app.appView.renderResponseAlert(response);
                        }.bind(this),
                        error: function (model, response, options) {
        					app.appView.hideLoader();
                        }
                    });
                }
            }
        });

        new emailSettingsForm();
    </script>
{% endblock %}
