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

{% block title %}Create Agent{% endblock %}

{% block templateCSS %}
    <style>
        .uv-element-block .uv-element-block {
            margin: 6px 0;
        }
        
        .uv-tab-error {
            border-bottom: 3px solid #FF5656 !important;
        }
        
        .uv-paper .uv-view .uv-element-block .uv-error-message {
            color: #FF5656;
        }

        .uv-new-tab-link {
            width: 8px;
            height: 20px;
            display: inline-block;
            background-image: url(../../../bundles/uvdeskcoreframework/images/uvdesk-sprite.svg);
            background-position: 44px -158px;
            margin: 5px 0 0 10px;
            float: right;
            vertical-align: top;
        }

        .uv-xtra-info {
            font-weight: bold;
            margin-left: 6px;
            font-style: normal;
            cursor: help;
        }
    </style>
{% 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\\Users' %}

		{{ uvdesk_extensibles.getRegisteredComponent(asideTemplate).renderSidebar(asideSidebarReference) | raw }}
        
		<div class="uv-view {% if app.request.cookies and app.request.cookies.get('uv-asideView') %}uv-aside-view{% endif %}">
            <h1>{{ 'Create Agent'|trans }}</h1>

            {# Registration Form #}
			<form method="post" action="" id="user-form" enctype="multipart/form-data">
                {# Registration Form Tabs #}
                <div class="uv-tabs">
                    <ul>
                        <li for="profile" class="uv-tab-active">{{ 'General'|trans }}</li>
                        <li for="groups">{{ 'Groups'|trans }}</li>
                        {% if "ROLE_SUPER_ADMIN" not in user.roles %}
                            <li for="permission">{{ 'Permission'|trans }}</li>
                        {% endif %}
                    </ul>
                </div>

                {# Profile Tab #}
                <div class="uv-tab-view uv-tab-view-active" id="profile">
                    <div class="uv-image-upload-wrapper">
					    <div class="uv-image-upload-brick">
                            <input type="file" name="user_form[profileImage]" id="uv-upload-profile">
                            <div class="uv-image-upload-placeholder">
                                <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="48px" height="32px">
                                <path fill-rule="evenodd" d="M28.026,26.003 L19.964,26.003 L19.964,17.962 L13.964,17.962 L23.995,8.050 L34.025,17.962 L28.026,17.962 L28.026,26.003 ZM33.557,3.421 C30.806,1.146 27.619,0.008 23.995,0.008 C21.182,0.008 18.588,0.756 16.214,2.252 C13.838,3.749 11.996,5.712 10.683,8.143 C7.683,8.456 5.152,9.749 3.090,12.024 C1.027,14.300 -0.004,16.965 -0.004,20.019 C-0.004,23.324 1.168,26.144 3.512,28.481 C5.855,30.819 8.682,31.988 11.996,31.988 L37.963,31.988 C40.712,31.988 43.072,31.006 45.040,29.042 C47.009,27.079 47.993,24.726 47.993,21.983 C47.993,19.364 47.087,17.106 45.275,15.203 C43.461,13.302 41.275,12.258 38.713,12.071 C38.024,8.580 36.306,5.698 33.557,3.421 Z"></path>
                                </svg>
                            </div>
                            <img id="dynamic-image-upload">

                        </div>
                        <div class="uv-image-info-brick">
                            <span class="uv-field-info">{{ 'Upload a Profile Image (100px x 100px)<br> in PNG or JPG Format'|trans|raw }}</span>
                        </div>
                    </div>

                    <div class="uv-element-block">
                        <label class="uv-field-label">{{ 'First Name'|trans }}</label>
                        <div class="uv-field-block">
                            <input name="user_form[firstName]" class="uv-field" type="text" value="">
                        </div>
                    </div>

                    <div class="uv-element-block">
                        <label class="uv-field-label">{{ 'Last Name'|trans }}</label>
                        <div class="uv-field-block">
                            <input name="user_form[lastName]" class="uv-field" type="text" value="">
                        </div>
                    </div>

                    <div class="uv-element-block">
                        <label class="uv-field-label">{{ 'Email'|trans }}</label>
                        <div class="uv-field-block">
                            <input name="user_form[email]" class="uv-field" type="text" value="">
                        </div>
                    </div>

                    <div class="uv-element-block">
                        <label class="uv-field-label">{{ 'Designation'|trans }}</label>
                        <div class="uv-field-block">
                            <input name="user_form[designation]" class="uv-field" type="text" value="">
                        </div>
                    </div>

                    <div class="uv-element-block">
                        <label class="uv-field-label">{{ 'Contact Number'|trans }}</label>
                        <div class="uv-field-block">
                            <input name="user_form[contactNumber]" class="uv-field" type="text" value="">
                        </div>
                    </div>
                    <div class="uv-element-block">
                        <label class="uv-field-label">{{ 'Signature'|trans }}</label>
                        <div class="uv-field-block">
                            <textarea name="user_form[signature]" class="uv-field"></textarea>
                        </div>
                        <span class="uv-field-info">{{ 'User signature will be append in the bottom of ticket reply box'|trans }}</span>
                    </div>

                    <div class="uv-element-block">
                        <label class="uv-field-label">{{ 'Account Status'|trans }}</label>
                        <div class="uv-element-block">
                            <label>
                                <div class="uv-checkbox">
                                    <input type="checkbox" name="user_form[isActive]">
                                    <span class="uv-checkbox-view"></span>
                                </div>
                                <span class="uv-checkbox-label">{{ 'Account is Active'|trans }}</span>
                            </label>
                        </div>
                    </div>
                </div>
                
                {# Group Tab #}
                <div class="uv-tab-view" id="groups">
                    <div class="uv-scroll-plank">
                        <!-- Checkbox Block -->
                        <div class="uv-element-block">
                            <label class="uv-field-label">{{ 'Groups'|trans }}</label>
                            <span class="uv-field-info uv-margin-top-5">{{ 'Assigning group(s) to user to view tickets regardless assignment.'|trans }}</span>
                        </div>

                        <div>
                            <!--Block-->
                            <div class="uv-scroll-block" id="beauty-scroll">
                                {% set groups = user_service.getSupportGroups() %}
                                
                                {% if groups %}
                                    {% for group in groups %}
                                        <!-- / -->
                                        <div class="uv-element-block">
                                            <label>
                                                <div class="uv-checkbox">
                                                     <input name="user_form[groups][]" type="checkbox" value="{{ group.id }}">
                                                    <span class="uv-checkbox-view"></span>
                                                </div>
                                                <span class="uv-checkbox-label">{{ group.name }}</span>
                                            </label>
                                        </div>
                                        <!-- /// -->
                                    {% endfor %}
                                {% else %}
                                    <div class="uv-element-block">
                                        <a class="uv-error-message" href="{{path('helpdesk_member_support_group_collection')}}" target="_blank">{% trans %}No Group added, Please add Group(s) first !{% endtrans %}</a>
                                    </div>
                                {% endif %}
                            </div>
                            <!--//Block-->

                        </div>
                        <div class="uv-element-block">
                            <a href="#" class="select">{{ 'Select All'|trans }}</a>
                            <a href="#" class="deselect">{{ 'Remove All'|trans }}</a>
                        </div>
                    </div>

                    {% set userSubGroups = user_service.getUserSubGroupIds(user.id) %}
                    <div class="uv-scroll-plank">
                        <!-- Checkbox Block -->
                        <div class="uv-element-block">
                            <label class="uv-field-label">{{ 'Teams'|trans }}</label>
                            <span class="uv-field-info uv-margin-top-5">{{ 'Assigning team(s) to user to view tickets regardless assignment.'|trans }}</span>
                        </div>

                        <div>
                            <!--Block-->
                            <div class="uv-scroll-block" id="beauty-scroll">
                                {% set teams = user_service.getSupportTeams() %}
                                {% if teams %}
                                    {% for team in teams %}
                                        <!-- / -->
                                        <div class="uv-element-block">
                                            <label>
                                                <div class="uv-checkbox">
                                                    <input name="user_form[userSubGroup][]" type="checkbox" value="{{ team.id }}">
                                                    <span class="uv-checkbox-view"></span>
                                                </div>
                                                <span class="uv-checkbox-label">{{ team.name }}</span>
                                            </label>
                                        </div>
                                        <!-- /// -->
                                    {% endfor %}
                                {% else %}
                                    <div class="uv-element-block">
                                        <a href="{{path('helpdesk_member_support_team_collection')}}" target="_blank">{% trans %}No Team added !{% endtrans %}</a>
                                    </div>
                                {% endif %}

                            </div>
                            <!--//Block-->

                        </div>
                        <div class="uv-element-block">
                            <a href="#" class="select">{{ 'Select All'|trans }}</a>
                            <a href="#" class="deselect">{{ 'Remove All'|trans }}</a>
                        </div>
                    </div>
                </div>
                <!--//Tab View-->

                <!--Tab View-->
                <div class="uv-tab-view" id="permission">
                    {% if "ROLE_SUPER_ADMIN" not in user.roles %}
                        <!-- Field -->
                        <div class="uv-element-block">
                            <label class="uv-field-label">{{ 'Role'|trans }}</label>
                            <div class="uv-field-block">
                                <select name="user_form[role]" class="uv-select" id="user_form_role" {% if user and user.id == app.user.id %}disabled="disabled"{% endif %}>
                                   <option value="ROLE_ADMIN" {% if "ROLE_ADMIN" in user.roles %}selected{% endif %}>{% trans %} Administrator {% endtrans%}</option>
                                    <option value="ROLE_AGENT" {% if "ROLE_AGENT" in user.roles %}selected{% endif %}>{% trans %} Agent {% endtrans%}</option>
                                </select>
                            </div>
                            <span class="uv-field-info">{{ "Select agent role"|trans }}</span>
                        </div>
                        <!-- //Field -->

                        <!-- Role dependent fields -->
                        <div class="role-dependent-fields">
                            <div class="uv-scroll-plank">
                                <!-- Checkbox Block -->
                                <div class="uv-element-block">
                                    <label class="uv-field-label">{{ 'Agent Privileges'|trans }}</label>
                                    <span class="uv-field-info uv-margin-top-5">{{ 'Agent Privilege represents overall permissions in System.'|trans }}</span>
                                </div>

                                {% set privileges = user_service.getSupportPrivileges() %}
                                {% if privileges %}
                                    <div>
                                        <div class="uv-scroll-block" id="beauty-scroll">
                                            {% for privilege in privileges %}
                                                <div class="uv-element-block">
                                                    <label>
                                                        <div class="uv-checkbox">
                                                            <input name="user_form[agentPrivilege][]" type="checkbox" value="{{ privilege.id }}">
                                                            <span class="uv-checkbox-view"></span>
                                                        </div>
                                                        <span class="uv-checkbox-label">{{ privilege.name }}</span>
                                                    </label>
                                                    <a class="uv-new-tab-link" href="{{ path('helpdesk_member_update_privilege', {'supportPrivilegeId': privilege.id }) }}" target="_blank"></a> 
                                                </div>
                                            {% endfor %}
                                        </div>
                                    </div>

                                    <div class="uv-element-block">
                                        <a href="#" class="select">{{ 'Select All'|trans }}</a>
                                        <a href="#" class="deselect">{{ 'Remove All'|trans }}</a>
                                    </div>
                                {% else %}
                                    <div>
                                        <div class="uv-scroll-block" id="beauty-scroll">
                                            <div class="uv-element-block">
                                                <input name="user_form[agentPrivilege][]" type="hidden" value="">
                                            </div>
                                        </div>
                                    </div>
                                {% endif %}
							</div>

                            <div class="uv-element-block">
                                <label class="uv-field-label">{{ 'Ticket View'|trans }}</label>
                                <span class="uv-field-info">{{ 'User can view tickets based on selected scope.'|trans }}
                                    <span class="uv-xtra-info" data-toggle="tooltip" data-placement="top" title="{{ 'If individual access then user can View assigned Ticket(s) only, If Team access then user can view all Ticket(s) in team(s) he belongs to and so on'|trans }}">[?]</span>
                                </span>
                                <div class="uv-element-block" style="margin-top: 10px;">
                                    <label>
                                        <div class="uv-radio">
                                            <input name="user_form[ticketView]" value="1" type="radio">
                                            <span class="uv-radio-view"></span>
                                        </div>
                                        <span class="uv-radio-label">{{ 'Global Access'|trans }}</span>
                                    </label>
                                </div>
                                <div class="uv-element-block">
                                    <label>
                                        <div class="uv-radio">
                                            <input name="user_form[ticketView]" value="2" type="radio">
                                            <span class="uv-radio-view"></span>
                                        </div>
                                        <span class="uv-radio-label">{{ 'Group Access'|trans }}</span>
                                    </label>
                                </div>
                                <div class="uv-element-block">
                                    <label>
                                        <div class="uv-radio">
                                            <input name="user_form[ticketView]" value="3" type="radio">
                                            <span class="uv-radio-view"></span>
                                        </div>
                                        <span class="uv-radio-label">{{ 'Team Access'|trans }}</span>
                                    </label>
                                </div>
                                <div class="uv-element-block">
                                    <label>
                                        <div class="uv-radio">
                                            <input name="user_form[ticketView]" value="4" type="radio">
                                            <span class="uv-radio-view"></span>
                                        </div>
                                        <span class="uv-radio-label">{{ 'Individual Access'|trans }}</span>
                                    </label>
                                </div>
                            </div>
                        </div>
                    {% else %}
                        <input type="hidden" name="user_form[role]" value="ROLE_SUPER_ADMIN">
                    {% endif %}
                </div>

                <!-- CSRF token Field -->
                {# <input type="hidden" name="user_form[_token]" value="{{ default_service.generateCsrfToken('user_form') }}"/> #}

				<input class="uv-btn" href="#" value="{{ 'Save Changes'|trans }}" type="submit">
            </form>
		</div>
	</div>
{% endblock %}

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

	<script type="text/javascript">
		$(function () {
			var UserModel = Backbone.Model.extend({
				validation: {
					'user_form[firstName]': [{
                        required: true,
                        msg: '{{ "This field is mandatory" | trans}}'
                    }, {
                        pattern: /^[\p{L}]+$/u,
                        msg: '{{ "This field must have no space and characters only" | trans}}'
                    }, {
                        maxLength:40,
                        msg: '{{ "Maximum character length is 40" | trans}}'
                    }],
                    'user_form[lastName]': [{
                        required: true,
                        msg: '{{ "This field is mandatory" | trans}}'
                    }, {
                        pattern: /^[\p{L}]+$/u,
                        msg: '{{ "This field must have no space and characters only" | trans}}'
                    }, {
                        maxLength:40,
                        msg: '{{ "Maximum character length is 40" | trans}}'
                    }],
                    'user_form[email]': [{
                        required: true,
                        msg: '{{ "This field is mandatory" | trans}}'
                    }, {
                        pattern:  /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
                        msg: '{{ "This is not a valid email address" | trans}}'
                    }],
                    'user_form[contactNumber]': function(value) {
                        if(value != undefined && value !== '') {
                            if(!value.match('^[0-9]*$'))
                                return '{{ "This field must be a number" | trans}}';
                        }
                    },
                    'user_form[password][first]' : function(value) {
                        if(value != undefined && value !== '') {
                            if(value.length < 8)
                               return '{{ "Password must contains 8 Characters" | trans}}';
                        }
                    },
                    'user_form[password][second]': {
                        equalTo: 'user_form[password][first]',
                        msg: 'The passwords does not match'
                    },
                    'user_form[isActive][]': {
                        fn: function(value) {
                            return false;
                        },
                    },
                    'user_form[groups][]': {
                        required: true,
                        msg: '{{ "This field is mandatory" | trans}}'
                    },
                    'user_form[agentPrivilege][]' : {
                        fn: function(value) {
                            if ($("#user_form_role").val() == 'ROLE_AGENT') {
                                if (!value)
                                    return true;
                            }

                            return false;
                        },
                        msg: '{{ "This field is mandatory" | trans}}'
                    },
                    'user_form[ticketView]': {
                        fn: function(value) {
                            if($("#user_form_role").val() == 'ROLE_AGENT') {
                                if(!value)
                                    return true;
                            }

                            return false;
                        },
                        msg: '{{ "This field is mandatory" | trans}}'
                    },
				}
			});

			var UserForm = Backbone.View.extend({
				events : {
					'click .uv-btn' : "saveUser",
					'blur input, textarea': 'formChanged',
                    'change #user_form_role': 'roleChanged',
                    'click a.select': 'selectAll',
		            'click a.deselect': 'deselectAll',
				},
				initialize : function() {
					Backbone.Validation.bind(this);
					var jsonContext = JSON.parse('{{ errors|raw }}');
		    		for (var field in jsonContext) {
                        if (field == 'first') {
                            Backbone.Validation.callbacks.invalid(this, "user_form[password][" + field + "]", jsonContext[field], 'input');
                        } else {
		    			    Backbone.Validation.callbacks.invalid(this, "user_form[" + field + "]", jsonContext[field], 'input');
                        }
					}
                    {% if not user.id %}
                        /* guess timezone and select that one */
                        var timezone = Intl.DateTimeFormat().resolvedOptions().timeZone == 'Asia/Calcutta' ? 'Asia/Kolkata' : Intl.DateTimeFormat().resolvedOptions().timeZone;
                        if (timezone) {
                            var option = $('select[name="user_form[timezone]"]').find('option[value="'+ timezone +'"]');
                            if(option.length) {
                                option.prop('selected', true);
                            }
                        }
                    {% endif %}
				},
				formChanged: function(e) {
			    	var fieldName = Backbone.$(e.currentTarget).attr('name');
                    $(".uv-tabs li.uv-tab-active").removeClass('uv-tab-error')
                    if (fieldName == 'user_form[password][second]') {
                        if ($("input[name='user_form[password][first]']").val().length) {
                            this.model.set(fieldName, Backbone.$(e.currentTarget).val())
                            this.model.isValid([fieldName])
                        } else {
                            if ($("input[name='user_form[password][second]']").val().length) {
		    			        this.model.set(fieldName, Backbone.$(e.currentTarget).val())
                                this.model.isValid([fieldName])
                            } else {
		    			        Backbone.Validation.callbacks.valid(this, fieldName, 'input');
                            }
                        }
                    } else {
                        this.model.set(fieldName, Backbone.$(e.currentTarget).val())
                        this.model.isValid([fieldName])
                        if (fieldName == 'user_form[password][first]' && !$("input[name='user_form[password][second]']").val().length) {
		    			    Backbone.Validation.callbacks.valid(this, 'user_form[password][second]', 'input');
                        }
                    }
			    },
				saveUser : function (e) {
					e.preventDefault();
                    $(".uv-tabs li").removeClass('uv-tab-error')
                    this.model.unset('user_form[groups][]', { silent: true });
                    this.model.unset('user_form[agentPrivilege][]', { silent: true });
			        this.model.set(this.$el.serializeObject());
			        if (this.model.isValid(true)) {
                        if ($("#user_form_role").val() == 'ROLE_ADMIN') {
                            $('input[name="user_form[agentPrivilege][]"]').remove();
                            this.model.unset('user_form[agentPrivilege][]', { silent: true });
                        }
						this.$el.find('.uv-btn').attr('disabled', 'disabled');
			            this.$el.submit();
			        } else {
                        $('.uv-field-message').each(function(e) {
                            $(".uv-tabs li[for='" + $(this).parents('.uv-tab-view').attr('id') + "']:not(.uv-tab-active)").addClass('uv-tab-error')

                            if ($(".uv-tabs li[for='" + $(this).parents('.uv-tab-view').attr('id') + "']:not(.uv-tab-active)").length ) {
                                $('.uv-view').animate({
                                    scrollTop: 0
                                }, 'slow');
                            }
                        });
                    }
				},
                roleChanged: function(e) {
                    if ($(e.target).val() == 'ROLE_AGENT') {
		            	$('.role-dependent-fields').show();
		            } else {
		            	$('.role-dependent-fields').hide();
		            }
                },
                selectAll: function (e) {
                    e.preventDefault();
                    this.$(e.currentTarget).parents('.uv-scroll-plank')
                            .find('input')
                            .prop('checked', true)
                },
                deselectAll: function (e) {
                    e.preventDefault();
                    this.$(e.currentTarget).parents('.uv-scroll-plank')
                            .find('input')
                            .prop('checked', false);
		        },
			});

			new UserForm({
				el: $("#user-form"),
				model: new UserModel()
			});

            $('#user_form_role').trigger('change');
		});
	</script>
{% endblock %}