<?php

use Illuminate\Support\Arr;
use WSDesk\Settings\SettingsItem;
use WSDesk\Settings\SettingsRepository;
use WSDesk\Tickets\TicketRepository;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

$repo     = new TicketRepository();
$settings = new SettingsRepository();

$ticket_filters_with_count = $repo->get_available_views();

$avail_labels_wf = array_values( $settings->getLabels() );
$avail_labels_f  = array_values( $settings->getFilterableLabels() );

$avail_tags_wf   = array_values( $settings->getTags() );
$avail_tags_f    = array_values( $settings->getFilterableTags() );
$avail_templates = array_values( $settings->getTemplates() );

$available_views_f = $settings->getFilterableViews();
$selected_views    = eh_crm_get_settingsmeta( 0, 'selected_views' );

if ( ! $avail_templates ) {
	$avail_templates = array();
}
$user_roles_default = array( 'WSDesk_Agents', 'WSDesk_Supervisor', 'administrator' );
$user_caps_default  = array( 'reply_tickets', 'delete_tickets', 'manage_tickets' );
$users              = get_users(
	array(
		'role__in' => $user_roles_default,
		'orderby'  => 'display_name',
	)
);
$users_data         = array();

$users_data = array_map(
	function ( $user ) {
		$users_data['id']    = $user->ID;
		$users_data['name']  = $user->display_name;
		$users_data['caps']  = $user->caps;
		$users_data['email'] = $user->user_email;
		return $users_data ;
	},
	$users
);

/****
 * Ticket Filters
 */
$ticket_filters_with_count = array_map(
	function ( $filter ) use ( $avail_labels_f, $avail_tags_f, $available_views_f, $users_data, $selected_views ) {
		if ( 'Labels' === $filter['title'] ) {
			$filter['items'] = $avail_labels_f;
		}

		if ( 'Tags' === $filter['title'] ) {
			$filter['items'] = $avail_tags_f;
		}

		if ( 'Views' === $filter['title'] ) {
			$filter['items'] = array_filter(
				$available_views_f,
				function ( $view ) use ( $selected_views ) {
					return \Illuminate\Support\Str::startsWith( $view['slug'], 'view_' ) && in_array( $view['slug'], $selected_views , true );
				}
			);

			$filter['items'] = Arr::sort(
				$filter['items'],
				function ( $view ) use ( $selected_views ) {
					return array_search( $view['slug'], $selected_views, true );
				}
			);

		}

		if ( 'Agents' === $filter['title'] ) {
			$filter['items']   = array_map(
				function ( $user ) {
				return array(
					'slug'  => $user['id'],
					'title' => $user['name'],
				);
				},
				$users_data
			);
			$filter['items'][] = array(
				'slug'  => 'null',
				'title' => 'Unassigned',
			);
		}

		if ( 'Users' === $filter['title'] ) {
			$filter['items'] = array(
				array(
					'slug'  => 'registered',
					'title' => 'Registered Users',
				),
				array(
					'slug'  => 'guest',
					'title' => 'Guest Users',
				),
			);
		}

		return $filter;
	},
	$ticket_filters_with_count
);

$avail_fields             = array_values( $settings->getFields() );
$active_fields            = eh_crm_get_settingsmeta( '0', 'selected_fields' );
$all_tickets_page_columns = eh_crm_get_settingsmeta( '0', 'all_ticket_page_columns' );

// TODO: Sort based on the all_tickets_page_columns
$columns = [];
foreach ( $avail_fields as $key => $field ) {
	if ( strpos( $field['slug'], 'request_' ) !== 0 && in_array( $field['slug'], $active_fields, true ) && in_array( $field['slug'], $all_tickets_page_columns , true ) ) {
		$field     = new SettingsItem( $field );
		$columns[] = [
			'data'       => $field['slug'],
			'field_type' => $field->get_meta()->get( 'field_type' ),
			'title'      => $field['title'],
		];
	}
}

$active_fields = array_map(
	function ( $f ) {
	return str_replace( 'request_', 'ticket_', $f );
	},
	$active_fields
);

$avail_caps  = array( 'reply_tickets', 'delete_tickets', 'manage_tickets', 'manage_templates' );
$access      = array();
$logged_user = wp_get_current_user();

if ( ! in_array( 'administrator', $logged_user->roles , true ) ) {
	$access = array_intersect( $avail_caps, $logged_user->caps );
} else {
	$access = $avail_caps;
}

// ob_start();

?>
<div class="container">
	<div class="row" style="margin-top: 10px;">
		<div class="col-md-12">
			<div class="full_row filter_div" id="dev-table-action-bar" >
				<div class="filter-each"><input type="checkbox" class="ticket_select_all"></div>
				<div class="filter-each" id="refresh_tickets" style="cursor:pointer;">
					<div  class="ticket-refresh-button" data-placement="top" data-toggle="wsdesk_tooltip" title="<?php esc_html_e( 'Refresh', 'wsdesk' ); ?>">
						<span class="glyphicon glyphicon-refresh"></span>
					</div>
				</div>
				<?php
				if ( in_array( 'delete_tickets', $access ) ) {
					echo '<div class="filter-each ticket-delete-btn multiple_ticket_unarchive_action" id="delete_tickets" style="display: none;"><div  class="ticket-delete-button" data-placement="top" data-toggle="wsdesk_tooltip" title="' . esc_html__( 'Restore the ticket(s)', 'wsdesk' ) . '"><span class="glyphicon glyphicon-folder-open"></span></div></div>';
				}
				?>

			</div>
		</div>
	</div>
	<div class="row" style="margin-top: 10px;">

		<div class="col-md-12" style="padding-right:0px;">
			<input type="hidden" name="view_type"/>
			<input type="hidden" name="view_slug"/>
			<div class="panel panel-default" >
				<div class="panel-body">
			<table class="table" id="archive_tickets_table_v2">
			</table>
		</div>
		</div>
		</div>
	</div>
</div>
<script>
(function (){
	//window.onload = initDataTable;
	dt_columns = <?php echo json_encode( $columns ); ?>;
	dt_page_columns = <?php echo json_encode( array_values( $all_tickets_page_columns ) ); ?>;
	var agents = <?php echo json_encode( $users_data ); ?>;
	var tags = <?php echo json_encode( $avail_tags_wf ); ?>;
	var actions = <?php echo json_encode( $avail_labels_wf ); ?>;
	templates = <?php echo json_encode( $avail_templates ); ?>;
	accesses = <?php echo json_encode( array_values( $access ) ); ?>;
	dt_available_fields = <?php echo json_encode( array_values( $avail_fields ) ); ?>;
	dt_active_fields = <?php echo json_encode( array_values( $active_fields ) ); ?>;

	for (var i = 0;i < dt_columns.length; i++) {
		dt_columns[i].orderable = false;
		dt_columns[i].render = function (data, type, row, meta) {
			if (meta.settings.aoColumns[meta.col].field_type === 'file' && row.ticket_attachment) {
				return row.ticket_attachment;
			}

			return data || '-';
		}
	}

	var stop = false;
	function tryNavigateToEloberateTab(ticket_id) {
		var tab = jQuery('ul.elaborate li#tab_' + ticket_id);
		if (tab.length === 0) {
			return false;
		}


		if(jQuery("ul.collapse_ul > li#tab_" + ticket_id).length!=0)
		{
			jQuery('.elaborate > li').last().before(ticket_id);
			collapse_tab();
		}
		tab.children('a').click();
		return true;
	}

	window.loadSingleTicketTab = function (ticket_id) {
				if (stop || tryNavigateToEloberateTab(ticket_id)) {
					return false;
				}

				jQuery(".table_loader").css("display", "inline");
				stop = true;
				jQuery.ajax({
					type: 'post',
					url: ajaxurl,
					data: {
						action: 'eh_crm_ticket_single_view_archive',
						ticket_id: ticket_id,
						nonce: js_obj.nonce,
						pagination_id : jQuery("#pagination_ids_traverse").val()
					},
					success: function (data) {
						jQuery(".table_loader").css("display", "none");
						var parse = jQuery.parseJSON(data);
						var tab_head = '<li role="presentation" class="visible_tab ticket_tab_open" id="tab_' + ticket_id + '" style="min-width:200px;">' + parse.tab_head + '</li>';
						var tab_content = '<div class="tab-pane new-style-tab-pane" id="tab_content_' + ticket_id + '">' + parse.tab_content + '</div>';
						jQuery('.elaborate > li').last().before(tab_head);
						jQuery('.tab-content').append(tab_content);
						trigger_load_single_ticket(ticket_id);
						jQuery('.visible_tab a#tab_content_a_'+ticket_id).click();
						// setURLFunc(ticket_id);
						collapse_tab();
						stop = false;
					},
					error: function (jqXHR, textStatus, errorThrown) {
						console.log(textStatus, errorThrown);
					}
				});
	};

	jQuery('#archive_tickets_table_v2').on('click', 'a.ticket_row_item', function (e) {
		e.preventDefault();
		loadSingleTicketTab(this.innerText);
	});
	jQuery('#archive_tickets_table_v2').on('deselect.dt', function () {
		jQuery('#delete_tickets').hide();
		dtFilter.selectAll = false;

		if (jQuery(this).find('tr.selected .select-checkbox').length || dtFilter.selectAll) {
			jQuery('#delete_tickets').show();
		}

	});
	jQuery('#archive_tickets_table_v2').on('xhr.dt', function (e, settings, json) {
		// jQuery('[data-toggle="wsdesk_tooltip"]').wstooltip({trigger : 'hover'});
		if (dtFilter.selectAll) {
			setTimeout(() => {
				dtTable.rows().select();
			}, 400);
		} else {
			const selectBtn = jQuery('#selectCurrentPageRows');
			if (selectBtn.prop('checked')) {
				selectBtn.click();
			}
		}
	});
	jQuery('#archive_tickets_table_v2').on('select.dt', function () {
		jQuery('#delete_tickets').show();
	});

	window.toggleRowSelection = function (selected) {
		selected ? dtTable.rows().select() : dtTable.rows().deselect();
		dtFilter.ticket_id = selected ? dtTable.column(2).data() : [];
	}

	function generateTicketCountView(views) {
		var html = '';
		views.forEach(function (view) {
			var viewDom = document.createElement('div');
			//viewDom.id = view.title;

			var header = document.createElement('h4');
			header.innerText = view.title;
			viewDom.append(header);

			var list = document.createElement('ul');
			list.id = view.title.toLowerCase();
			list.className = "nav nav-pills nav-stacked side-bar-filter";

			view.data.forEach(function (item) {
				list.innerHTML += '<li data-slug="'+item.slug+'" id="view_item_'+item.slug+'"><a href="#"><span class="view_item_count badge pull-right"></span>'+item.title+'</a></li>';
			});

			viewDom.append(list);
			viewDom.innerHTML += '<hr />';
			document.getElementById('ticket_views_count').append(viewDom);
		});
	}

	jQuery('#all_tickets_v2_left_bar').on('click', 'ul li', function (e) {
		e.preventDefault();
		dtFilter.view = {};
		var view = jQuery(this).parent().attr('id');
		dtFilter.view[view] = [];

		dtFilter.view[view].push(this.getAttribute('data-slug'));
		if (this.getAttribute('id') === 'view_item_all_tickets') {
			dtTable.rows().deselect();
			reset_dtfilter();
			loadCount();
		}

		if (this.getAttribute('data-slug') && this.getAttribute('data-slug').indexOf('view_') === 0 ) {
			loadCount({views_only: dtFilter.view});
		}

		updateFilterActiveStatus();
		dtTable.draw();

	});

	function getChildRowHtml(data) {
		data.last_message = data.last_message || {
			display_name: 'admin',
			ticket_email: data.ticket_email,
			ticket_date: data.ticket_date,
			ticket_content: data.ticket_content
		};
		var html = '<div >';
		html += '<div style="padding:5px 0px;">' +
						'<small class="glyphicon glyphicon-user"></small> <small style="opacity:0.7;">'+ data.last_message.display_name +'</small>' +
						'| <small class="glyphicon glyphicon-envelope"></small> <small style="opacity:0.7;">'+ data.last_message.ticket_email +'</small>' +
						'| <small class="glyphicon glyphicon-calendar"></small> <small style="opacity:0.7;">'+ data.last_message.ticket_date +'</small>' +
					'</div>';

		html += '<hr>';
		html += '<p>' + data.last_message.ticket_content + '</p>';

		html += '<table class="table table-striped">';
		html += '<thead>';
		html += '<tr>'+
					'<th>Actions</th>'+
					'<th>Assignee</th>'+
					'<th>Reply Requester</th>'+
					'<th>Raiser Voices</th>'+
					'<th>Agent Voices</th>'+
					'<th>Tags</th>'+
					'<th>Source</th>'+
				'</tr>';
		html += '</thead>';
		html += '<tbody>';
		html += '<tr>'+
					'<td>'+ getActionBtnDropdown(data) +'</td>'+
					'<td>'+ getAssingeesBtnDropdown(data) +'</td>'+
					'<td><a href="#reply_'+data.ticket_id+'" data-toggle="modal"  title="<?php echo esc_html__( 'Compose Reply', 'wsdesk' ); ?>">' +
						data.ticket_email +
					'</a></td>'+
					'<td>'+ (data.reply_count.raiser_reply || 0) +'</td>'+
					'<td>'+ (data.reply_count.agent_reply || 0) +'</td>'+
					'<th>'+ getTagsLabel(data.ticket_tags) +'</th>'+
					'<td>'+ data.ticket_source +'</td>'+
				'</tr>';
		html += '</tbody>';
		html += '</div>';

		return html;
	}

	function getActionBtnDropdown(data, isMultiAction) {
		var html = '<div class="btn-group '+(isMultiAction ? 'ml-1': '')+'">'+
		  '<button disabled type="button" '+ (isMultiAction ? 'disabled' : '') +' class="btn btn-default dropdown-toggle '+(isMultiAction ? 'mulitple_ticket_action_button' : '')+'" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">'+
			'Action <span class="caret"></span>'+
		  '</button>'+
		  '<ul class="dropdown-menu">'+
			actions.map(function (action) {
				return '<li id="'+ data.ticket_id +'">'+
						'<a href="#" class="' +(isMultiAction ? '' : 'single_ticket_action_button')+ '" data-ticket_id="'+data.ticket_id+'" data-action="'+action.slug+'" id="'+action.slug+'">Mark as '+action.title+'</a>'+
					'</li>';
			}).join('') +
			'<li role="separator" class="divider"></li>';
		if (isMultiAction) {
			html +='<li><a href="#" data-action="archive_tickets">Archive Tickets</a></li>';
		} else {
			html += '<li class="text-center"><small class="text-muted text-sm">Select label to assign</small></li>';
		}
		  html+= '</ul>'+
		'</div>';

		return html;
	}
	function getAssingeesBtnDropdown(data) {
		var html = '<div class="btn-group">'+
		  '<button disabled type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">'+
			'Assignee <span class="caret"></span>'+
		  '</button>'+
		  '<ul class="dropdown-menu">'+
			agents.map(function (assignee) {
				return '<li id="'+ data.ticket_id +'">'+
						'<a href="#" class="single_ticket_assignee" id="'+assignee.id+'">'+assignee.name+'</a>'+
					'</li>';
			}).join('') +
			'<li role="separator" class="divider"></li>'+
			'<li class="text-center"><small class="text-muted text-sm">Select assignee to assign</small></li>'+
		  '</ul>'+
		'</div>';

		return html;
	}

	function getTagsLabel(slugs) {
		if (!slugs) return '';

		slugs = Object.values(slugs);

		var filteredSlugs = tags.filter(function (tag) {
			return slugs.indexOf(tag.slug) > -1;
		});

		return filteredSlugs.map(function (tag) {
			return '<span class="label label-info">#' + tag.title + '</span>';
		}).join(' ');
	}

	jQuery('#archive_tickets_table_v2').on('click', 'button.btn_quick_view_ticket', function () {
		var row = dtTable.row(jQuery(this).parents('tr'));
		var icon = jQuery(this).find('span');

		if (row.child.isShown()) {
			row.child.hide();
			jQuery(icon).removeClass('glyphicon-eye-close');
			jQuery(icon).addClass('glyphicon-eye-open');
		} else {
			row.child(getChildRowHtml(row.data())).show();
			jQuery(icon).removeClass('glyphicon-eye-open');
			jQuery(icon).addClass('glyphicon-eye-close');
		}
	});
	jQuery('#all_tickets_tab_header').click(function () {
		if (jQuery(this).parent().hasClass('active') === false) {
			loadCount();
			dtTable.draw();
		}
	});

})();
</script>
<?php
// return ob_get_clean();
