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

{% block title %} 
    {% if app.request.get('id') %}
        {{ 'Edit Prepared Response' | trans }}
    {% else %}
        {{ 'Add Prepared Response' | trans }}
    {% endif %}
{% endblock %}

{% block internalcss %}
    @media(max-width: 767px) {
        #company-workflow > .steps {
            display: none;
        }
    }

    @media(max-width: 579px) {
        #company-workflow > h3 {
            margin-right: 80px;
        }

        #company-workflow > h3 > a {
            position: absolute;
            top: 0px;
            right: 10px;
        }
    }

    .has-error button.btn {
        border-color: #cc5965;
    }
{% endblock %}

{% block pageContent %}
    <style>
        .workflow-conditions-body .workflow-condition:first-child .uv-workflow-hr-plank {
            display: none;
        }
    </style>
    <!-- Inner Section -->
    <div class="uv-inner-section">
        {# Append Panel Aside #}
		{% set asideTemplate = 'Webkul\\UVDesk\\CoreFrameworkBundle\\Dashboard\\AsideTemplate' %}
		{% set asideSidebarReference = 'Webkul\\UVDesk\\CoreFrameworkBundle\\UIComponents\\Dashboard\\Panel\\Sidebars\\Productivity' %}

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

        <!-- View -->
        <div class="uv-view {% if app.request.cookies and app.request.cookies.get('uv-asideView') %}uv-aside-view{% endif %}">
            <!-- Form -->
            {% if app.request.get('id') is not empty %}
                <h1>{{ 'Edit Prepared Response'|trans }}</h1>
                <form class="workflow-form" name="form-workflow" method="POST" action="{{ path('prepare_response_editaction', {'id': app.request.get('id')}) }}">
            {% else %}
                <h1>{{ 'New Prepared Response'|trans }}</h1>
                <form class="workflow-form" name="form-workflow" method="POST" action="{{ path('prepare_response_addaction') }}">
            {% endif %}
                <!-- Prepared Response Description Section -->
                <div class="uv-element-block">
                    <label class="uv-field-label">{{ 'Name'|trans }}</label>
                    <div class="uv-field-block">
                        <input name="name" class="uv-field" type="text" value="{{ formData.name is defined ? formData.name : '' }}">
                        <p class="uv-field-message">{% if error.name is defined %}{{ error.name }}{% endif %}</p>
                    </div>
                </div>

                <div class="uv-element-block">
                    <label class="uv-field-label">{{ 'Description'|trans }}</label>
                    <div class="uv-field-block">
                        <textarea name="description" class="uv-field">{{ formData.description is defined ? formData.description : '' }}</textarea>
                        <p class="uv-field-message">{% if error.description is defined %}{{ error.description }}{% endif %}</p>
                    </div>
                </div>

                <div class="uv-element-block">
                    <label class="uv-field-label">{{ 'Prepared Response Status'|trans }}</label>
                    <div class="uv-element-block">
                        <label>
                            <div class="uv-checkbox">
                                <input name="status" type="checkbox" {{ formData.status is defined and formData.status == 'on' ? 'checked' : '' }}>
                                <span class="uv-checkbox-view"></span>
                            </div>
                            <span class="uv-checkbox-label">{{ 'Prepared Response is Active'|trans }}</span>
                        </label>
                    </div>
                </div>
                {% if user_service.isAccessAuthorized('ROLE_ADMIN') %}
                    <div class="uv-hr"></div>
                
                    <!-- Field -->
                    <div class="uv-element-block">
                        <label class="uv-field-label">{{ 'Groups'|trans }}</label>
                        <div class="uv-field-block" id="group-filter">
                            <input type="hidden" name="tempGroups" class="uv-field" value="" />
                            <input name="groups" class="uv-field uv-dropdown-other preloaded" type="text" id="group-filter-input" value="">
                            <span class="uv-field-info">{{ 'Share prepared response with user(s) in these group(s)'|trans }}</span>
                            <div class="uv-dropdown-list uv-bottom-left">
                                <div class="uv-dropdown-container">
                                    <label>{{ 'Filter With'|trans }}</label>
                                    <ul class="">
                                        {% for group in user_service.getSupportGroups() %}
                                            <li data-id="{{group.id}}">
                                                {{group.name}}
                                            </li>
                                        {% endfor %}
                                        <li class="uv-no-results" style="display: none;">
                                            {{ 'No result found'|trans }}
                                        </li>
                                    </ul>
                                </div>
                            </div>
                            <div class="uv-filtered-tags">
                                {% if formData.groups is defined and formData.groups %}
                                    {% for group in formData.groups %}
                                        {% if group.isActive %}
                                            <a class="uv-btn-small default" href="#" data-id="{{group.id }}">
                                                {{ group.name }}
                                                <span class="uv-icon-remove"></span>
                                            </a>
                                        {% endif %}
                                    {% endfor %}
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    <!-- //Field -->

                    <!-- Field -->
                    <div class="uv-element-block">
                        <label class="uv-field-label">{{ 'Teams'|trans }}</label>
                        <div class="uv-field-block" id="team-filter">
                            <input type="hidden" name="tempTeams" class="uv-field" value="" />
                            <input class="uv-field uv-dropdown-other preloaded" type="text" id="team-filter-input">
                            <span class="uv-field-info">{{ 'Share prepared response with user(s) in these teams(s)'|trans }}</span>
                            <div class="uv-dropdown-list uv-bottom-left">
                                <div class="uv-dropdown-container">
                                    <label>{{ 'Filter With'|trans }}</label>
                                    <ul class="">
                                        {% for team in user_service.getSupportTeams() %}
                                            <li data-id="{{team.id}}">
                                                {{team.name}}
                                            </li>
                                        {% endfor %}
                                        <li class="uv-no-results" style="display: none;">
                                            {{ 'No result found'|trans }}
                                        </li>
                                    </ul>
                                </div>
                            </div>
                            <div class="uv-filtered-tags">
                                {% if formData.teams is defined and formData.teams %}
                                    {% for team in formData.teams %}
                                        {% if team.isActive %}
                                            <a class="uv-btn-small default" href="#" data-id="{{team.id }}">
                                                {{ team.name }}
                                                <span class="uv-icon-remove"></span>
                                            </a>
                                        {% endif %}
                                    {% endfor %}
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    <!-- //Field --> 
                {% endif %}
                <div class="uv-hr"></div>
                <!-- // Prepared Response Description Section -->


                <!-- Prepared Response Actions Section -->
                <div id="actions" class="uv-element-block uv-field-workflow">
                    <label class="uv-field-label">{{ 'Actions'|trans }}</label>
                    <span class="uv-field-info">{{ 'An action not only reduces the workload but also makes it quite easier for ticket automation'|trans }}</span>

                    <div class="workflow-action-body"></div>
                    <div class="uv-workflow-buttons">
                        <a class="uv-btn-tag btn-add" href="#">
                            <span class="uv-icon-add-dark"></span> {{ 'Add More'|trans }}
                        </a>
                    </div>
                </div>
                <!-- // Prepared Response Actions Section -->


                <!-- CTA -->
                {# <input type="submit" class="uv-btn" href="#" value="Save Prepared Response"> #}
                <button type="submit" name="submit" class="uv-btn" href="#" {% if forcedActions is defined and forcedActions %}disabled="disabled" date-toggle="tooltip" title="{{ "You don't have premission to edit this Prepared response"|trans }} " {% endif %} >{% if app.request.get('id') is not empty %}{{ 'Save Prepared Response'|trans }}{% else %}{{ 'Add Prepared Response'|trans }}{% endif %}</button>
                <!-- // CTA -->
            </form>
            <!-- Form -->
        </div>
        <!-- // View -->
    </div>
    <!-- // Inner Section -->
{% endblock %}

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

    <script type="text/javascript">
        _.extend(Backbone.Validation.patterns, {
          stringPattern: /[a-z0-9]/i,
        });

        _.extend(Backbone.Validation.callbacks, {
            valid : function (view, attr, selector) {
                console.log($('[name="'+attr+'"]').closest('.uv-field-block'));
                $('[name="'+attr+'"]').closest('.uv-field-block').find('.uv-field-message').html('').fadeOut(0);
            },
            invalid : function (view, attr, error, selector) {
                console.log($('[name="'+attr+'"]').closest('.uv-field-block'));
                $('[name="'+attr+'"]').closest('.uv-field-block').find('.uv-field-message').html(error).fadeIn(0);
            }
        });

        if(typeof(sB) == 'undefined'){
          var sB = {};
        }

        sB.WorkflowCollection = Backbone.Collection.extend({
            baseUrl: "{{ path('ajax_service_call') }}",
            fetchResult: function(dataMatch) {
            this.url = this.baseUrl;
            return this.fetch({ 'data' : {
                'service': 'email.service',
                'call': 'getEmailPlaceHolders',
                'options': { 'match': dataMatch },
            }});
        }});
        sB.workflowCollection = new sB.WorkflowCollection();

        sB.WorkflowModel = Backbone.Model.extend({
            validation: {
                name: {
                    required: true,
                    pattern: 'stringPattern',
                    msg: "{{ 'Please enter a valid name.'|trans }}"
                },
            },
			{% if not(forcedActions is defined and forcedActions) %}
                validateSelect: function(value, attr, computedState) {
                    var currentSelectValue = $('select[name="'+ attr + '"]').prev().find('.selected').length;
                    if (!value) {
                        return "{{ 'Please select a value.'|trans }}";
                    }
                },
                validateSelectMultiple: function(value, attr, computedState) {
                    var currentSelectValue = $('[name="'+ attr + '"]').length;
                    if (!value) {
                        return "{{ 'Please select a value.'|trans }}";
                    }
                },
                validateSelectText: function(value, attr, computedState) {
                    if (!value) {
                        return "{{ 'Please add a value.'|trans }}";
                    }
                }
			{% endif %}            
        });

        sB.WorkflowView = Backbone.View.extend({
            el: '.uv-view',
            initialize: function() {
                this.model = new sB.WorkflowModel();
                Backbone.Validation.bind(this);
                this.setAddedIds('#group-filter');
                this.setAddedIds('#team-filter');
            },
            events: {
                'submit form[name="form-workflow"]': 'processWorlfow',
                'click .workflow-form .uv-dropdown-list li': 'addEntity',
                'click .workflow-form .uv-filtered-tags .uv-btn-small': 'removeEntity'                
            },
            processWorlfow: function(e) {
                this.model.set(this.$el.find('form').serializeObject());

                var self = this;
                filterArray = ['name'];
                // Populate Filter Array - Events and Actions are required fields
                
                // Actions
                this.$('.wfAction').each(function(key, value) {
                    filterArray.push($(value).attr('name'));
                    self.model.validation[$(value).attr('name')] = 'validateSelect';
                });
                this.$('.wfActionMultiple').each(function(key, value) {
                    filterArray.push($(value).attr('name'));
                    self.model.validation[$(value).attr('name')] = 'validateSelectMultiple';
                });
                this.$('.wfActionValue').each(function(key, value) {
                    if ($(this).attr('name') == undefined) {
                        return;
                    }

                    filterArray.push($(value).attr('name'));
                    self.model.validation[$(value).attr('name')] = 'validateSelectText';
                });

                if (this.validateData(filterArray)) {
                    return true;
                } else {
                    e.preventDefault();
                }
            },
            validateData: function(filterArray) {
                return this.model.isValid(filterArray);
            },
            updateActive: function(e){
                this.$('div.step-info').each(function() {
                    $(this).addClass('active');
                    if ($(this).attr('data-href') == self.$(e.target).attr('href'))
                        return false;
                });
            },
            addEntity: function(e) {
                currentElement = Backbone.$(e.currentTarget);
                if(id = currentElement.attr("data-id")) {
                    parent = currentElement.parents(".uv-field-block");
                    parent.find('input').val('')
                    parent.find("li:not(.uv-no-results)").show();

                    if(!parent.find(".uv-filtered-tags a[data-id='" + id + "']").length) {
                        parent.find('.uv-filtered-tags').append("<a class='uv-btn-small default' href='#' data-id='" + id + "'>"+currentElement.text()+"<span class='uv-icon-remove'></span></a>")
                        this.setAddedIds("#" + parent.attr('id'))
                    }
                }
            },
            removeEntity: function(e) {
                var parent = Backbone.$(e.currentTarget).parents(".uv-field-block")
                Backbone.$(e.currentTarget).remove()
                this.setAddedIds("#" + parent.attr('id'))
            },
            setAddedIds: function(selector) {
                var ids = [];
                $(selector).find('.uv-filtered-tags .uv-btn-small').each(function() {
                    ids.push($(this).attr('data-id'))
                });

                $(selector).find("input[type='hidden']").val(ids.join(','))

                return ids;
            },            
        });
        sB.workflowView = new sB.WorkflowView();

        $.fn.serializeObject = function () {
            "use strict";
            var a = {}, b = function (b, c) {
                var d = a[c.name];
                "undefined" != typeof d && d !== null ? $.isArray(d) ? d.push(c.value) : a[c.name] = [d, c.value] : a[c.name] = c.value
            };
            return $.each(this.serializeArray(), b), a
        };
    </script>
    
    {{ include('@UVDeskAutomation//PreparedResponse//actions.html.twig') }}
{% endblock %}