<?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_filter       =
	array(
		'role__in' => $user_roles_default,
		'orderby'  => 'display_name',
	);
if ( wsdesk_can_access_other_tickets() === false ) {
	$users_filter['include'] = array( get_current_user_id() );
}

$users      = get_users(
	$users_filter
);
$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, $filter ) {
					return \Illuminate\Support\Str::startsWith( $view['slug'], 'view_' ) && in_array( $view['slug'], $selected_views , true ) && in_array( $view['slug'], Arr::get( $filter, 'data', array() ), 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' );
$active_fields            = is_array( $active_fields ) ? $active_fields : array( $active_fields );
$all_tickets_page_columns = wsdesk_get_all_tickets_page_fields();

// 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, array_keys( $logged_user->caps ) );
} else {
	$access = $avail_caps;
}

// ob_start();

?>
<div class="container">
	<div class="row" style="margin-top: 10px;">
		<div class="col-md-3" id="all_tickets_v2_left_bar" style="max-height: 100vh;overflow: auto;overflow-x: hidden;min-height: 100px;">
			<ul class="nav nav-pills nav-stacked side-bar-filter" id="v2_all_tickets_section">
				<li class="active" id="view_item_all_tickets"><a href="#" id="all"><span class="badge pull-right"><?php echo esc_html( $repo->count() ); ?></span> <?php esc_html_e( 'All Tickets', 'wsdesk' ); ?> <?php require 'eh_crm_table_loader.php'; ?></a></li>
			</ul>
			<hr>
			<div id="ticket_views_count">
				<?php
				if ( is_array( $ticket_filters_with_count ) && ! empty( $ticket_filters_with_count ) && isset( $ticket_filters_with_count ) ) {
					foreach ( $ticket_filters_with_count as $view ) {
						?>
					<div >
						<h4><?php echo esc_html__( $view['title'], 'wsdesk' ); ?></h4>
						<ul class="nav nav-pills nav-stacked side-bar-filter" id="<?php echo esc_html( strtolower( $view['title'] ) ); ?>">
								<?php foreach ( $view['items'] as $item ) { ?>
							<li data-slug="<?php echo esc_html( $item['slug'] ); ?>" id="view_item_<?php echo esc_html( $item['slug'] ); ?>"><a href="#" id="all"><span  class="badge pull-right">...</span> <?php echo esc_html__( $item['title'], 'wsdesk' ); ?></a></li>
							<?php } ?>
						</ul>
						<hr />
					</div>
					<?php
					}
				}
				?>
			</div>
		</div>

		<div class="col-md-9" 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="all_tickets_table_v2">
			</table>
		</div>
		</div>
		</div>
	</div>
</div>
		<div class="modal fade" id="edit_tickets_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
			<div class="modal-dialog" role="document">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
						<h4 class="modal-title" style="padding-left: 15px;"><?php esc_html_e( 'Edit', 'wsdesk' ); ?> <span class="number_of_tickets"></span> <?php esc_html_e( 'Ticket', 'wsdesk' ); ?>(s)</h4>
						<input type="hidden" name="ticket_ids" id="edit_ticket_ids" value="">
						<input type="hidden" name="ticket_select_all" id="edit_ticket_select_all" value="">
					</div>
					<div class="modal-body">
						<div class="row">
							<div class="col-md-4 left-modal-body">
								<div class="row bulk-edit-row">
									<label class="edit_tickets_label"><?php esc_html__( 'Assignee', 'wsdesk' ); ?></label>
									<select id="assignee_ticket_edit" class="form-control" aria-describedby="helpBlock" multiple="multiple">
										<?php
										foreach ( $users_data as $i => $user ) {
											if ( in_array( 'administrator', array_keys( $users_data[ $i ]['caps'] ), true ) ) {
												?>
													<option value="<?php echo esc_html( $user['id'] ); ?>">
														<?php echo esc_html( $user['name'] ) . ' | ' . esc_html__( 'Administrator', 'wsdesk' ); ?>
													</option>
												<?php
											} elseif ( in_array( 'WSDesk_Supervisor', array_keys( $users_data[ $i ]['caps'] ), true ) ) {
												?>
													<option value="<?php echo esc_html( $user['id'] ); ?>">
													<?php echo esc_html( $user['name'] ) . ' | ' . esc_html__( 'Supervisor', 'wsdesk' ); ?>
													</option>
												<?php
											} elseif ( in_array( 'WSDesk_Agents', array_keys( $users_data[ $i ]['caps'] ) , true ) ) {
												?>
													<option value="<?php echo esc_html( $user['id'] ); ?>">
														<?php echo esc_html( $user['name'] ) . ' | ' . esc_html__( 'Agent', 'wsdesk' ); ?>
													</option>
												<?php
											}
										}
										?>
									</select>
								</div>
								<div class="row bulk-edit-row">
									<label class="edit_tickets_label"><?php esc_html__( 'Labels', 'wdesk' ); ?></label>
									<select id="label_ticket_edit" class="form-control" aria-describedby="helpBlock">
										<option value=''> <?php echo esc_html__( 'Select Status', 'wsdesk' ); ?> </option>
										<?php
										foreach ( $avail_labels_f as $label ) {
											?>
												<option value="<?php echo esc_html( $label['slug'] ); ?>">
													<?php echo esc_html( $label['title'] ); ?>
												</option>
											<?php
										}
										?>
									</select>
								</div>
								<div class="row bulk-edit-row">
									<label class="edit_tickets_label"> <?php esc_html__( 'Tags', 'wsdesk' ); ?></label>
									<select id="tags_ticket_edit" class="form-control" aria-describedby="helpBlock" multiple="multiple">
										<?php
										foreach ( $avail_tags_f as $tag_item ) {
											?>
												<option value="<?php echo esc_html( $tag_item['slug'] ); ?>">
													<?php echo esc_html( $tag_item['title'] ); ?>
												</option>
											<?php
										}
										?>
									</select>
								</div>
								<center>
								<button type="button" class="btn btn-primary" id="bulk_edit_save"><?php echo esc_html__( 'Save Properties', 'wsdesk' ); ?></button>
								</center>
							</div>
							<div class="col-md-7 right-modal-body">
								<div class="row bulk-edit-row">
									<label class="edit_tickets_label"><?php esc_html_e( 'Subject' , 'wsdesk' ); ?></label>
									<input type="text" placeholder="<?php esc_html_e( 'No Change', 'wsdesk' ); ?>" id="title_ticket_edit" class="form-control">
								</div>
								<div class="row bulk-edit-row">
									<label class="edit_tickets_label"><?php esc_html_e( 'Bulk Reply', 'wsdesk' ); ?></label>
									<div class="textarea" style="width: 100% !important; height: 200px;" class="reply_textarea" id="reply_textarea_edit" name="reply_textarea_edit"></div>
								</div>
								<div class="row bulk-edit-row">
									<span class="btn btn-primary fileinput-button">
										<i class="glyphicon glyphicon-plus"></i>
										<span><?php esc_html_e( 'Attachment', 'wsdesk' ); ?></span>
										<input type="file" name="files" id="files_edit" class="attachment_reply"  media="all" multiple="">
									</span>
									<span class="glyphicon glyphicon-info-sign" style="color:lightgray;font-size:x-small;vertical-align:baseline;" data-toggle="wsdesk_tooltip" title="<?php esc_html_e( 'Text in the body of the reply is mandatory to submit attachemnts.', 'wsdesk' ); ?>" data-container="body"></span>
								</div>
								<div class="row">
									<div class="upload_preview_edit"></div>
								</div>
							</div>
						</div>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-default" data-dismiss="modal"><?php esc_html_e( 'Close', 'wsdesk' ); ?></button>
						<button type="button" class="btn btn-primary" id="bulk_edit_submit"><?php esc_html_e( 'Submit', 'wsdesk' ); ?></button>
					</div>
				</div>
			</div>
		</div>

		<div class="modal fade" id="new_template_model" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
		  <div class="modal-dialog" role="document">
			<div class="modal-content">
			  <div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
				<h4 class="modal-title"><?php esc_html_e( 'New Template', 'wsdesk' ); ?></h4>
			  </div>
			  <div class="modal-body">
				<p style="margin-top: 5px;font-size: 16px;">
					<label for=""><small><?php esc_html_e( 'Template title to identify', 'wsdesk' ); ?></small></label>
					<input type="text" placeholder="<?php esc_html_e( 'Enter Title', 'wsdesk' ); ?>" class="form-control template_title_editable" id="new_template_title">
				</p>
				<div class="panel-group" id="email_auto_role" style="margin-bottom: 10px !important;">
					<div class="panel panel-default">
						<div class="panel-heading collapsed" style="padding:10px;cursor: pointer;" data-toggle="collapse" data-parent="#email_auto_role" data-target="#content_email_auto">
							<span class ="email-reply-toggle"></span>
							<h4 class="panel-title">
								<?php esc_html_e( 'Code for template', 'wsdesk' ); ?>
							</h4>
						</div>
						<div id="content_email_auto" class="panel-collapse collapse">
							<div class="panel-body">
								<div class="col-md-12">
									<div class="row">
										<div class="col-md-3">
										   <?php esc_html_e( '[name]', 'wsdesk' ); ?>
										</div>
										<div class="col-md-9">
											<?php esc_html_e( 'To insert ticket raiser name in the template', 'wsdesk' ); ?>
										</div>
									</div>
									<span class="crm-divider"></span>
									<div class="row">
										<div class="col-md-3">
											<?php esc_html_e( '[id]', 'wsdesk' ); ?>
										</div>
										<div class="col-md-9">
											<?php esc_html_e( 'To insert ticket number in the template', 'wsdesk' ); ?>
										</div>
									</div>
									<?php
										$selected_fields = eh_crm_get_settingsmeta( 0, 'selected_fields' );
									if ( empty( $selected_fields ) ) {
										$selected_fields = array();
									}
									foreach ( $avail_fields as $field ) {
										if ( 'google_captcha' === $field['slug'] || ! in_array( $field['slug'], $selected_fields ) ) {
											continue;
										}
										echo '
                                                <span class="crm-divider"></span>
                                                <div class="row">
                                                    <div class="col-md-3">
                                                        [' . esc_html( $field['slug'] ) . ']
                                                    </div>
                                                    <div class="col-md-9">
                                                       ' . esc_html__( 'To insert ', 'wsdesk' ) . ' ' . esc_html( $field['title'] ) . ' ' . esc_html__( 'field value in the template', 'wsdesk' ) . '
                                                    </div>
                                                </div>';
									}
									?>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="textarea" style="height: 100px" id="new_template_content"></div>
			  </div>
			  <div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal"><?php esc_html_e( 'Close', 'wsdesk' ); ?></button>
				<button type="button" class="btn btn-primary" id="create_new_template"><?php esc_html_e( 'Create', 'wsdesk' ); ?></button>
			  </div>
			</div>
		  </div>
		</div>
		<div id="update_template_model_display"></div>
		<div id="preview_template_model_display"></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;
			}
            if (data && typeof data === 'string' && (dt_columns[meta.col].data === 'ticket_title' || dt_columns[meta.col].data === 'ticket_email')) {
                return escapeHtml(data);
            }
			return data || '-';
		}
	}

    function escapeHtml(text) {
        if (text === null || text === undefined) return '';
        return String(text)
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

	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',
						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) {
					}
				});
	};

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

		var selectedRows = dtTable.rows({selected: true}).data();

		if (selectedRows.length !== 0) {
			return false;
		}

		dtTable.button(3).disable();
		dtTable.button(4).disable();
		jQuery('.mulitple_ticket_action_button, #reply_template_button').attr('disabled', true);
		jQuery('#selectCurrentPageRows').prop('checked', false);
		jQuery('button.buttons-select-all').removeClass('hidden')
		jQuery('button.buttons-select-none').addClass('hidden')
	});
	jQuery('#all_tickets_table_v2').on('xhr.dt', function (e, settings, json) {
		if (!json) return;

		if (!dtFilter.view.views) {
			var activeItem = jQuery('.side-bar-filter').find('li.active');
			if (activeItem.attr('id') !== 'view_item_all_tickets') {
				activeItem.find('span.badge').text(json.recordsFiltered);
			}
		} else {
			setTimeout(function () {
				jQuery('#all_tickets_table_v2').find('thead > tr').find('th[class^=sorting]').removeClass('sorting sorting_asc sorting_desc');
			}, 500);
		}

		// jQuery('[data-toggle="wsdesk_tooltip"]').wstooltip({trigger : 'hover'});
		if (dtFilter.view.views ) {
			dtTable.rowGroup().enable();
		} else {
			dtTable.rowGroup().disable();
		}

		if (dtFilter.selectAll) {
			setTimeout(() => {
				dtTable.rows().select();
			}, 400);
		} else {
			const selectBtn = jQuery('#selectCurrentPageRows');
			if (selectBtn.prop('checked')) {
				selectBtn.click();
			}
		}
	});
	jQuery('#all_tickets_table_v2').on('select.dt', function () {
		if (User().can('delete_tickets')) {
			dtTable.button(3).enable();
		}
		if (User().can('manage_tickets')) {
			dtTable.button(4).enable();
			jQuery('.mulitple_ticket_action_button').attr('disabled', false);
		}
		if (User().can('reply_tickets')) {
			jQuery('#reply_template_button').attr('disabled', false);
		}
		jQuery('button.buttons-select-all').addClass('hidden')
		jQuery('button.buttons-select-none').removeClass('hidden')
	});
	jQuery('#all_tickets_table_v2').on('preInit.dt', function () {
		jQuery('#all_tickets_advanced_filters').append('' +
			'<div class="col-md-3">'+
			'<div class="form-group">'+
			'<label>Ticket ID</label>'+
			'<input class="form-control" name="ticket_id" placeholder="Ticket ID"/>'+
			'</div>'+
			'</div>'+
			'<div class="col-md-3">'+
			'<div class="form-group">'+
			'<label>Requestor</label>'+
			'<input class="form-control" name="requestor" placeholder="Requestor Email"/>'+
			'</div>'+
			'</div>'+
			'<div class="col-md-3">'+
			'<div class="form-group">'+
			'<label>Subject</label>'+
			'<input class="form-control" name="subject" placeholder="Subject"/>'+
			'</div>'+
			'</div>'+
			'<div class="col-md-3 text-right">'+
			'<label></label>'+
			'<br>'+
			'<button class="btn btn-primary" id="all_tickets_advanced_filters_submit">Filter</button>'+
			'</div>'+
			'');
		jQuery('#all_tickets_action_buttons').append(getActionBtnDropdown({}, true));
		jQuery('#all_tickets_action_buttons').append(getTemplatesBtn());
	});

	jQuery('#all_tickets_table_v2').on('init.dt', function () {
		jQuery('#all_tickets_advanced_filters').on('click', 'button#all_tickets_advanced_filters_submit', function () {
			dtTable.draw();
		});
		jQuery('button.buttons-select-all').removeClass('hidden')
		jQuery('button.buttons-select-none').addClass('hidden')
	});
	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();

		if (window.history) {
			const newUrl = new URL(window.location);

			const filter = getTicketsFilter();
			newUrl.searchParams.set('filter', crypto_enc(JSON.stringify(filter)));

			window.history.pushState(filter, '', newUrl);
		}
	});

	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;">'+ escapeHtml(data.last_message.display_name) +'</small>' +
						'| <small class="glyphicon glyphicon-envelope"></small> <small style="opacity:0.7;">'+ escapeHtml(data.last_message.ticket_email) +'</small>' +
						'| <small class="glyphicon glyphicon-calendar"></small> <small style="opacity:0.7;">'+ escapeHtml(data.last_message.ticket_date) +'</small>' +
					'</div>';

		html += '<hr>';
		// ticket_content contains HTML, assuming it is sanitized by wp_kses_post on save
		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>'+ ( User().can('manage_tickets') ? getActionBtnDropdown(data) : getActionBtnDropdown(data, true)) +'</td>'+
					'<td>'+ ( User().can('manage_tickets') ? getAssingeesBtnDropdown(data) : getAssingeesBtnDropdown(data, true)) +'</td>'+
					'<td><a href="#reply_'+data.ticket_id+'" data-toggle="modal"  title="<?php echo esc_html__( 'Compose Reply', 'wsdesk' ); ?>">' +
						escapeHtml(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>'+ escapeHtml(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 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('');
		if (isMultiAction) {
		} else {
			html += '<li role="separator" class="divider"></li>';
			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, isDisabled) {
		var html = '<div class="btn-group '+(isDisabled ? 'ml-1': '')+'">'+
		  '<button type="button" '+ (isDisabled ? 'disabled' : '') +' 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">#' + escapeHtml(tag.title) + '</span>';
		}).join(' ');
	}

	jQuery('#all_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();
		}
	});

	jQuery(document).on('click', '.ticket_action_refresh', function () {
		const ticket_id = jQuery(this).data('id');
		jQuery.ajax({
					type: 'post',
					url: ajaxurl,
					data: {
						action: 'eh_crm_ticket_single_view',
						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);
						jQuery('#tab_content_' + ticket_id).html(parse.tab_content);
						trigger_load_single_ticket(ticket_id);
						collapse_tab();
					},});
	});

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