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

{% block title %}Agents{% endblock %}

{% block templateCSS %}{% 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>{{ 'Agents'|trans }}</h1>
			<div class="uv-action-bar">
				<div class="uv-action-bar-col-lt">
					{# Sort Agents #}
					<div class="uv-dropdown sort">
						<div class="uv-dropdown-btn uv-vertical-align uv-margin-right-5">Sort By: Created At</div>
						<div class="uv-dropdown-list uv-bottom-left">
							<div class="uv-dropdown-container">
								<label>{{ 'Sort By'|trans }}</label>
								<ul></ul>
							</div>
						</div>
					</div>

					{# Filter Agents by Status #}
					<div class="uv-dropdown filter-by-status">
						<div class="uv-dropdown-btn uv-vertical-align uv-margin-right-5">Status: All</div>
						<div class="uv-dropdown-list uv-bottom-left">
							<div class="uv-dropdown-container">
								<label>{{ 'Status'|trans }}</label>
								<ul>
									<li class="uv-drop-list-active"><a href="#">All</a></li>
									<li><a href="#" data-id="1">Active</a></li>
									<li><a href="#" data-id="0">Disabled</a></li>
								</ul>
							</div>
						</div>
					</div>
				</div>

				<div class="uv-action-bar-col-rt">
					{# Search Agent #}
					<input type="text" class="uv-search-inline uv-vertical-align uv-margin-right-15" placeholder="{{ 'Search'|trans }}">

					{# Create New Agent #}
					<a href="{{ path('helpdesk_member_create_account') }}" type="button" class="uv-btn-action"><span class="uv-icon-add"></span> {{ 'New Agent'|trans }}</a>
				</div>
			</div>

			{# Agent Listicle #}
			<div class="uv-table uv-list-view">
				<table>
					<thead>
					<tr>
						<th>{{ 'Name'|trans }}</th>
						<th>{{ 'Email'|trans }}</th>
						<th>{{ 'Role'|trans }}</th>
						<th>{{ 'Status'|trans }}</th>
						<th class="uv-last">{{ 'Action'|trans }}</th>
					</tr>
					</thead>
					<tbody></tbody>
				</table>

				{# Pagintation #}
				<div class="navigation"></div>
			</div>
		</div>
	</div>
{% endblock %}

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

	{# Sorting Template #}
	<script id="agent_list_sorting_tmp" type="text/template">
		<li class="<% if(sort == 'userInstance.createdAt') { %>uv-drop-list-active<% } %>">
			<a href="#<% if(queryString != '') { %><%= queryString %>/<% } %><% if(page) { %>page/<%= page %><% } else { %>page/1<% } %>/sort/userInstance.createdAt/<% if(sort == 'userInstance.createdAt') { %><% if(direction) { %>direction/<%= direction %><% } else { %>direction/desc<% } %><% } else { %>direction/asc<% } %>" data-field="userInstance.createdAt">
				Created At
				<% if(sort == 'userInstance.createdAt') { %>
				<span class="uv-sorting <% if(direction == 'asc') { %> descend <% } else { %> ascend <% } %>"></span>
				<% } %>
			</a>
		</li>
		<li class="<% if(sort == 'user.firstName') { %>uv-drop-list-active<% } %>">
			<a href="#<% if(queryString != '') { %><%= queryString %>/<% } %><% if(page) { %>page/<%= page %><% } else { %>page/1<% } %>/sort/user.firstName/<% if(sort == 'user.firstName') { %><% if(direction) { %>direction/<%= direction %><% } else { %>direction/desc<% } %><% } else { %>direction/asc<% } %>" data-field="user.firstName">
				Name
				<% if(sort == 'user.firstName') { %>
				<span class="uv-sorting <% if(direction == 'asc') { %> descend <% } else { %> ascend <% } %>"></span>
				<% } %>
			</a>
		</li>
		<li class="<% if(sort == 'user.email') { %>uv-drop-list-active<% } %>">
			<a href="#<% if(queryString != '') { %><%= queryString %>/<% } %><% if(page) { %>page/<%= page %><% } else { %>page/1<% } %>/sort/user.email/<% if(sort == 'user.email') { %><% if(direction) { %>direction/<%= direction %><% } else { %>direction/desc<% } %><% } else { %>direction/asc<% } %>" data-field="user.email">
				Email
				<% if(sort == 'user.email') { %>
				<span class="uv-sorting <% if(direction == 'asc') { %> descend <% } else { %> ascend <% } %>"></span>
				<% } %>
			</a>
		</li>
	</script>
	{# Type list item template #}
	<script id="agent_list_item_tmp" type="text/template">
		<td data-value="Name">
			<% if (smallThumbnail != null) { %>
			<img src="{{ app.request.scheme ~'://' ~ app.request.httpHost ~ asset('') }}<%= smallThumbnail.slice(1) %>" alt=""/>
			<% } else { %>
			<img src="{{ asset(default_agent_image_path) }}" alt=""/>
			<% } %>
			<%- name %>
		</td>
		<td data-value="Email"><%- email %></td>
		<td data-value="Role">
		   <% if(role == "Agent") { %>
        		{% trans %} Agent {% endtrans %}
         	   <% } else if(role == "Account Owner"){ %>
			{% trans %} Account Owner {% endtrans %}
		   <%}else if(role == "Administrator"){ %>
			{% trans %} Administrator {% endtrans%}
		   <% } %>
		</td>
		<td data-value="Status">
			<% if (isActive) { %>
			<span class="uv-text-success">{{ 'Active'|trans }}</span>
			<% } else { %>
			<span class="uv-text-danger">{{ 'Disabled'|trans }}</span>
			<% } %>
		</td>
		<td data-value="Action" class="uv-last">
			<a href="<%- path.replace('replaceId', id) %>" class="uv-btn-stroke edit-agent">{{ 'Edit'|trans }}</a>
			<% if (roleCode == "ROLE_SUPER_ADMIN") { %>
			<div class="uv-btn-stroke" disabled="disabled">{{ 'Delete'|trans }}</div>
			<% } else { %>
			<div class="uv-btn-stroke delete-agent">{{ 'Delete'|trans }}</div>
			<% } %>
		</td>
	</script>

	<script type="text/javascript">
		var path = "{{ path('helpdesk_member_account', { 'agentId': 'replaceId' }) }}";
		var deletePath = "{{ path('helpdesk_member_account_xhr', { 'id': 'replaceId' }) }}";

		$(function () {
			var globalMessageResponse = "";

			var AgentModel = Backbone.Model.extend({
				idAttribute : "id"
			});

			var AgentCollection = AppCollection.extend({
				model : AgentModel,
				url : "{{ path('helpdesk_member_account_collection_xhr') }}",
				filterParameters : {
					"isActive" : "",
					"search" : ""
				},
				parseRecords: function (resp, options) {
					return resp.users;
				},
				syncData : function() {
					app.appView.showLoader();
					this.fetch({
						data : this.getValidParameters(),
						reset: true,
						success: function(model, response) {
							app.appView.hideLoader();
							var agentListView = new AgentList();
							app.pager.paginationData = response.pagination_data;

							var url = app.pager.paginationData.url;
							if(agentCollection.length == 0 && app.pager.paginationData.current != "0")
								router.navigate(url.replace('replacePage', app.pager.paginationData.last),{trigger: true});
							else {
								app.pager.render();
							}
							if(globalMessageResponse)
								app.appView.renderResponseAlert(globalMessageResponse);
							globalMessageResponse = null;
						},
						error: function (model, xhr, options) {
							if(url = xhr.getResponseHeader('Location'))
								window.location = url;
						}
					});
				}
			});

			var AgentItem = Backbone.View.extend({
				tagName : "tr",
				template : _.template($("#agent_list_item_tmp").html()),
				events : {
					'click .delete-agent' : "confirmRemove"
				},
				render : function() {
					this.$el.html(this.template(this.model.toJSON()));
					return this;
				},
				unrender : function(response) {
					if(response.alertMessage != undefined) {
						agentCollection.syncData();
						app.appView.renderResponseAlert(response)
					}
				},
				confirmRemove: function(e) {
					e.preventDefault();
					app.appView.openConfirmModal(this)
				},
				removeItem : function (e) {
					app.appView.showLoader();
					self = this;

					this.model.destroy({
						url: deletePath.replace('replaceId', this.model.get('id')),
						success : function (model, response, options) {
							app.appView.hideLoader();
							globalMessageResponse = response;
							agentCollection.syncData();
						},
						error: function (model, xhr, options) {
							if(url = xhr.getResponseHeader('Location'))
								window.location = url;
							var response = warningResponse;
							if(xhr.responseJSON)
								response = xhr.responseJSON;

							app.appView.hideLoader();
							app.appView.renderResponseAlert(response);
						}
					});
				}
			});

			var AgentList = Backbone.View.extend({
				el : $(".uv-list-view table tbody"),
				initialize : function() {
					this.render();
				},
				render : function () {
					this.$el.find("tr").remove();
					if(agentCollection.length) {
						_.each(agentCollection.models, function (item) {
							this.renderAgent(item);
						}, this);
					} else {
						this.$el.append("<tr style='text-align: center;'><td colspan='5'>{% trans %}No Record Found{% endtrans %}</td></tr>")
					}
				},
				renderAgent : function (item) {
					var agentItem = new AgentItem({
						model: item
					});
					this.$el.append(agentItem.render().el);
				}
			});

			var Filter = app.Filter.extend({
				defaultSortIndex: 'userInstance.createdAt',
				sortText: "{% trans %}Sort By:{% endtrans %} ",
				defaultSortText: "{% trans %}Sort By:{% endtrans %} {% trans %}Created At{% endtrans %}",
				template : _.template($("#agent_list_sorting_tmp").html())
			})

			var agentCollection = new AgentCollection();

			var filter = new Filter({
				collection : agentCollection
			});

			Router = Backbone.Router.extend({
				routes: {
					'page/:number(/sort/:sortField)(/direction/:order)' : 'paginate',
					'isActive/:status(/search/:query)(/page/:number)(/sort/:sortField)(/direction/:order)' : 'filterAgentByStatus',
					'search/:query(/page/:number)(/sort/:sortField)(/direction/:order)' : 'filterByQuery',
					'' : 'initializeList'
				},
				initializeList : function() {
					this.resetParams('', '');
					agentCollection.state.currentPage = null;
					filter.sortCollection();
					agentCollection.syncData();
				},
				paginate : function(number,sortField,order) {
					this.resetParams('', '');
					agentCollection.state.currentPage = number;
					filter.sortCollection(sortField,order);
					agentCollection.syncData();
				},
				filterAgentByStatus: function(status,query,number,sortField,order) {
					this.resetParams(status,query);
					agentCollection.state.currentPage = number;
					filter.sortCollection(sortField,order);
					agentCollection.syncData();
				},
				filterByQuery : function(query,number,sortField,order) {
					this.resetParams('',query);
					agentCollection.state.currentPage = number;
					filter.sortCollection(sortField,order);
					agentCollection.syncData();
				},
				resetParams : function(status, query) {
					if(query != null)
						query = query.replace(/\+/g,' ');
					agentCollection.filterParameters.isActive  = status;
					var statusText = status ? $(".filter-by-status a[data-id='" + status + "']").text() : "{% trans %}All{% endtrans %}";
					$(".filter-by-status .uv-dropdown-btn").text("{% trans %}Status:{% endtrans %} " + statusText);
					agentCollection.filterParameters.search = query;
					$(".uv-search-inline").val(query);
				}
			});

			router = new Router();
			Backbone.history.start({push_state:true});
		});
	</script>
{% endblock %}