<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of admistrator
 *
 * @author pc mart ltd
 */
class Tickets extends Admin_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->model('tickets_model');
		$this->load->model('common_model');
	}

	private function ticket_status_badge($status, $slot = '')
	{
		$tone = 'bg-slate-100 text-slate-700';
		if ($status === 'open') {
			$tone = 'bg-rose-50 text-rose-700';
		} elseif ($status === 'closed') {
			$tone = 'bg-emerald-50 text-emerald-700';
		} elseif ($status === 'in_progress') {
			$tone = 'bg-amber-50 text-amber-700';
		} elseif ($status === 'answered') {
			$tone = 'bg-blue-50 text-blue-700';
		}

		$slot_attr = !empty($slot) ? ' data-ticket-status-slot="' . html_escape($slot) . '"' : '';
		return '<span' . $slot_attr . ' class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold ' . $tone . '">' . lang($status) . '</span>';
	}


	public function tickets_state_report()
	{
		if (!$this->input->is_ajax_request()) {
			redirect('admin/dashboard');
		}
		$data = array();
		$pathonor_jonno['tickets_state_report_div'] = $this->load->view("admin/tickets/tickets_state_report", $data, true);
		echo json_encode($pathonor_jonno);
		exit;
	}


	public function index($action = NULL, $id = NULL)
	{
		// get permission user by menu id
		$data['permission_user'] = $this->tickets_model->all_permission_user('6');

		$data['title'] = "Tickets Details"; //Page title      
		$data['page_title'] = lang('tickets');
		$data['page_description'] = lang('all_tickets');

		$data['dataTables'] = true;
		$data['datatable_preload'] = $this->capture_datatable_preload(function () {
			$this->ticketsList();
		});
		$data['ticket_statuses'] = get_result('tbl_status');
		if (!empty(can_action(6, 'created')) || !empty(can_action(6, 'edited'))) {
			$data['header_actions'] = array(
				array(
					'label' => lang('new_ticket'),
					'icon' => 'plus',
					'href' => base_url('admin/tickets/create'),
					'style' => 'primary',
				),
			);
		}
		$ticket_filter_items = array(
			array('label' => lang('all'), 'active' => true, 'attrs' => array('data-ticket-filter-action' => '1', 'data-ticket-filter' => '', 'data-ticket-filter-label' => lang('all'))),
			array('label' => lang('assigned_to_me'), 'attrs' => array('data-ticket-filter-action' => '1', 'data-ticket-filter' => 'assigned_to_me', 'data-ticket-filter-label' => lang('assigned_to_me'))),
			array('label' => lang('open'), 'attrs' => array('data-ticket-filter-action' => '1', 'data-ticket-filter' => 'open', 'data-ticket-filter-label' => lang('open'))),
			array('label' => lang('in_progress'), 'attrs' => array('data-ticket-filter-action' => '1', 'data-ticket-filter' => 'in_progress', 'data-ticket-filter-label' => lang('in_progress'))),
			array('label' => lang('answered'), 'attrs' => array('data-ticket-filter-action' => '1', 'data-ticket-filter' => 'answered', 'data-ticket-filter-label' => lang('answered'))),
			array('label' => lang('closed'), 'attrs' => array('data-ticket-filter-action' => '1', 'data-ticket-filter' => 'closed', 'data-ticket-filter-label' => lang('closed'))),
		);
		if (admin()) {
			$ticket_filter_items[] = array(
				'label' => lang('assigned_to') . ' ' . lang('everyone'),
				'attrs' => array('data-ticket-filter-action' => '1', 'data-ticket-filter' => 'everyone', 'data-ticket-filter-label' => lang('assigned_to') . ' ' . lang('everyone')),
			);
		}
		$data['header_filters'] = array(
			array(
				'label' => 'Filters',
				'icon' => 'sliders-horizontal',
				'selected_label' => lang('all'),
				'attrs' => array('id' => 'tickets-header-filter'),
				'items' => array_merge(
					$ticket_filter_items,
					array(
						array(
							'label' => lang('project'),
							'icon' => 'briefcase',
							'divider_before' => true,
							'items' => array(
								array('label' => lang('all') . ' ' . lang('project'), 'attrs' => array('data-ticket-filter-action' => '1', 'data-ticket-filter' => '', 'data-ticket-search' => 'by_project', 'data-ticket-filter-label' => lang('all') . ' ' . lang('project'))),
							),
							'lookup' => array(
								'endpoint' => base_url('admin/common/project_lookup'),
								'limit' => 12,
								'min_length' => 0,
								'action_attrs' => array('data-ticket-filter-action' => '1', 'data-ticket-search' => 'by_project'),
								'filter_attr' => 'data-ticket-filter',
								'label_attr' => 'data-ticket-filter-label',
								'label_prefix' => lang('project') . ': ',
								'placeholder' => lang('search') . ' ' . lang('project'),
								'cache_key' => 'tickets_project_lookup',
							),
						),
						array(
							'label' => lang('reporter'),
							'icon' => 'user',
							'items' => array(
								array('label' => lang('all') . ' ' . lang('reporter'), 'attrs' => array('data-ticket-filter-action' => '1', 'data-ticket-filter' => '', 'data-ticket-search' => 'by_reported', 'data-ticket-filter-label' => lang('all') . ' ' . lang('reporter'))),
							),
							'lookup' => array(
								'endpoint' => base_url('admin/common/user_lookup'),
								'limit' => 12,
								'min_length' => 0,
								'action_attrs' => array('data-ticket-filter-action' => '1', 'data-ticket-search' => 'by_reported'),
								'filter_attr' => 'data-ticket-filter',
								'label_attr' => 'data-ticket-filter-label',
								'label_prefix' => lang('reporter') . ': ',
								'placeholder' => lang('search') . ' ' . lang('reporter'),
								'cache_key' => 'tickets_reporter_lookup',
							),
						),
						array(
							'label' => lang('department'),
							'icon' => 'layers',
							'items' => array(
								array('label' => lang('all') . ' ' . lang('department'), 'attrs' => array('data-ticket-filter-action' => '1', 'data-ticket-filter' => '', 'data-ticket-search' => 'by_department', 'data-ticket-filter-label' => lang('all') . ' ' . lang('department'))),
							),
							'lookup' => array(
								'endpoint' => base_url('admin/common/department_lookup'),
								'limit' => 12,
								'min_length' => 0,
								'action_attrs' => array('data-ticket-filter-action' => '1', 'data-ticket-search' => 'by_department'),
								'filter_attr' => 'data-ticket-filter',
								'label_attr' => 'data-ticket-filter-label',
								'label_prefix' => lang('department') . ': ',
								'placeholder' => lang('search') . ' ' . lang('department'),
								'cache_key' => 'tickets_department_lookup',
							),
						),
					)
				),
			),
		);
		$data['header_filter_extras_html'] = '';

		$data['page'] = lang('tickets');
		$data['sub_active'] = lang('all_tickets');

		if ($action == 'tickets_details') {
			$data['tickets_info'] = $this->tickets_model->check_by(array('tickets_id' => $id), 'tbl_tickets');
			$subview = 'tickets_details';
		} elseif ($action == 'download_file') {
			$this->load->helper('download');
			$file = $this->uri->segment(6);
			if ($id) {
				$down_data = file_get_contents('uploads/' . $file); // Read the file's contents
				force_download($file, $down_data);
			} else {
				$type = "error";
				$message = 'Operation Fieled !';
				set_message($type, $message);
				if (empty($_SERVER['HTTP_REFERER'])) {
					redirect('admin/tickets');
				} else {
					redirect($_SERVER['HTTP_REFERER']);
				}
			}
		}

		if (empty($subview)) {
			$subview = 'tickets';
		}
		$data['active'] = 1;
		$data['subview'] = $this->load->view('admin/tickets/' . $subview, $data, TRUE);
		$this->load->view('admin/_layout_main', $data); //page load
	}

	public function tickets_details($id = null)
	{
		$data['title'] = "Tickets Details"; //Page title
		$data['tickets_info'] = $this->tickets_model->check_by(array('tickets_id' => $id), 'tbl_tickets');
		$can_edit = $this->tickets_model->can_action('tbl_tickets', 'edit', array('tickets_id' => $id));
		$edited = can_action(6, 'edited');
		if (!empty($can_edit) && !empty($edited)) {
			$data['tickets_info'] = $this->tickets_model->check_by(array('tickets_id' => $id), 'tbl_tickets');
		} else {
			$type = "error";
			$message = 'No Record Found';
			set_message($type, $message);
			redirect('admin/tickets');
		}
		$data['dropzone'] = true;
		$data['page_title'] = '[' . $data['tickets_info']->ticket_code . '] ' . $data['tickets_info']->subject;
		$department = get_row('tbl_departments', array('departments_id' => $data['tickets_info']->departments_id));
		$department_label = !empty($department->deptname) ? $department->deptname : lang('unknown');
		$data['page_description'] = $department_label . ' . ' . lang('priority') . ': ' . $data['tickets_info']->priority . ' . ' . lang('status') . ': ' . lang($data['tickets_info']->status);
		$data['header_badge'] = array(
			'label' => $data['tickets_info']->ticket_code,
			'tone' => $data['tickets_info']->status === 'closed' ? 'success' : ($data['tickets_info']->status === 'in_progress' ? 'warning' : 'primary'),
		);
		$data['header_actions'] = array();
		if (!empty($can_edit) && !empty($edited)) {
			$data['header_actions'][] = array(
				'label' => lang('edit'),
				'icon' => 'pencil',
				'href' => base_url('admin/tickets/create/edit_tickets/' . $data['tickets_info']->tickets_id),
			);
		}
		$data['header_filters'] = array();
		$subview = 'tickets_details';
		$data['subview'] = $this->load->view('admin/tickets/' . $subview, $data, TRUE);
		$this->load->view('admin/_layout_main', $data); //page load
	}


	public
	function create($action = NULL, $id = NULL)
	{

		$data['permission_user'] = $this->tickets_model->all_permission_user('6');

		$data['title'] = "Tickets Details"; //Page title
		$this->load->helper('string');
		$data['default_priority'] = config_item('default_priority');
		$data['default_department'] = config_item('default_department');
		$data['priority_options'] = array();
		$priority_rows = $this->db->get('tbl_priority')->result();
		if (!empty($priority_rows)) {
			foreach ($priority_rows as $priority) {
				$data['priority_options'][$priority->priority] = $priority->priority;
			}
		}
		$data['department_options'] = array();
		$department_rows = $this->db->get('tbl_departments')->result();
		if (!empty($department_rows)) {
			foreach ($department_rows as $dept) {
				$data['department_options'][$dept->departments_id] = $dept->deptname;
			}
		}
		$data['selected_reporter_id'] = '';
		$data['selected_reporter_label'] = '';
		$data['selected_project_id'] = '';
		$data['selected_project_label'] = '';
		$data['ticket_code_default'] = strtoupper(random_string('alnum', 7));
		if (!empty($id)) {
			if (is_numeric($id)) {
				$can_edit = $this->tickets_model->can_action('tbl_tickets', 'edit', array('tickets_id' => $id));
				$edited = can_action(6, 'edited');
				if (!empty($can_edit) && !empty($edited)) {
					$data['tickets_info'] = $this->tickets_model->check_by(array('tickets_id' => $id), 'tbl_tickets');
					if (!empty($data['tickets_info']->reporter)) {
						$data['selected_reporter_id'] = $data['tickets_info']->reporter;
					}
					if (!empty($data['tickets_info']->project_id)) {
						$data['selected_project_id'] = $data['tickets_info']->project_id;
					}
				}
			}
		}
		$data['dropzone'] = true;
		if ($action == 'edit_tickets' || $action == 'project_tickets') {
			$project_id = $this->uri->segment(6);
			if (!empty($project_id)) {
				$project_info = get_row('tbl_project', array('project_id' => $project_id));
				if ($project_info->permission == 'all') {
					$data['permission_user'] = $this->tickets_model->allowed_user('57');
				} else {
					$data['permission_user'] = $this->tickets_model->permitted_allowed_user($project_info->permission);
				}
				if ($action == 'project_tickets' && empty($data['selected_project_id'])) {
					$data['selected_project_id'] = $project_id;
				}
			}
		}
		$reporter_id = $data['selected_reporter_id'];
		if (empty($reporter_id)) {
			$type = $this->uri->segment(5);
			if (!empty($type) && !is_numeric($type)) {
				$ex = explode('_', $type);
				if (!empty($ex[0]) && $ex[0] === 'c' && !empty($ex[1])) {
					$reporter_id = $ex[1];
				}
			}
		}
		if (!empty($reporter_id)) {
			$reporter = $this->db->where('user_id', $reporter_id)->get('tbl_account_details')->row();
			if (!empty($reporter)) {
				$data['selected_reporter_id'] = $reporter_id;
				$data['selected_reporter_label'] = $reporter->fullname;
			}
		}
		if (!empty($data['selected_project_id'])) {
			$project = $this->db->where('project_id', $data['selected_project_id'])->get('tbl_project')->row();
			if (!empty($project)) {
				$data['selected_project_label'] = $project->project_name;
			}
		}
		$data['active'] = 2;
		$data['page'] = lang('tickets');
		$data['sub_active'] = lang('all_tickets');
		if ($action == 'tickets_details') {
			$data['tickets_info'] = $this->tickets_model->check_by(array('tickets_id' => $id), 'tbl_tickets');
			$subview = 'tickets_details';
		} elseif ($action == 'download_file') {
			$this->load->helper('download');
			$file = $this->uri->segment(6);
			if ($id) {
				$down_data = file_get_contents('uploads/' . $file); // Read the file's contents
				force_download($file, $down_data);
			} else {
				$type = "error";
				$message = 'Operation Fieled !';
				set_message($type, $message);
				if (empty($_SERVER['HTTP_REFERER'])) {
					redirect('admin/tickets');
				} else {
					redirect($_SERVER['HTTP_REFERER']);
				}
			}
		} else {
			$subview = 'createtickets';
		}
		$data['subview'] = $this->load->view('admin/tickets/' . $subview, $data, TRUE);
		$this->load->view('admin/_layout_main', $data); //page load


	}

	public function changed_ticket_status($id = null)
	{
		$is_ajax = $this->input->is_ajax_request();
		$json_buffer_level = ob_get_level();
		if ($is_ajax) {
			ob_start();
		}
		$date = date('Y-m-d H:i:s');
		$status = $this->uri->segment(5);

		if (!empty($status)) {
			if ($status != 'closed' && config_item('notify_ticket_reopened') == 'TRUE') {
				$this->notify_ticket_reopened($id);
			}
			$this->tickets_model->set_action(array('tickets_id' => $id), array('status' => $status), 'tbl_tickets');
		}
		$this->tickets_model->set_action(array('tickets_id' => $id), array('last_reply' => $date), 'tbl_tickets');

		$rdata['body'] = $this->input->post('body', TRUE);

		$rdata['tickets_id'] = $id;
		$rdata['replierid'] = $this->session->userdata('user_id');

		$this->tickets_model->_table_name = 'tbl_tickets_replies';
		$this->tickets_model->_primary_key = 'tickets_replies_id';

		$rid = $this->tickets_model->save($rdata);
		// print('<pre>'.print_r($rid,true).'</pre>'); exit;


		$user_info = $this->db->where(array('user_id' => $rdata['replierid']))->get('tbl_users')->row();

		if ($user_info->role_id == '2') {
			$this->get_notify_ticket_reply('admin', $rdata); // Send email to admins
		} else {
			$this->get_notify_ticket_reply('client', $rdata); // Send email to client
		}
		// save into activities
		$activities = array(
			'user' => $this->session->userdata('user_id'),
			'module' => 'tickets',
			'module_field_id' => $id,
			'activity' => 'activity_reply_tickets',
			'icon' => 'fa-ticket',
			'link' => 'admin/tickets/tickets_details/' . $id,
			'value1' => $rdata['body'],
		);
		// Update into tbl_project
		$this->tickets_model->_table_name = "tbl_activities"; //table name
		$this->tickets_model->_primary_key = "activities_id";
		$this->tickets_model->save($activities);
		$response = array(
			'status' => 'success',
			'message' => lang('ticket_status_changed'),
			'reload_ticket_state_report' => true,
			'patch' => array(
				array(
					'selector' => '[data-ticket-status-slot="header"]',
					'html' => $this->ticket_status_badge($status, 'header'),
					'mode' => 'replace',
				),
				array(
					'selector' => '[data-ticket-status-slot="details"]',
					'html' => $this->ticket_status_badge($status, 'details'),
					'mode' => 'replace',
				),
			),
		);
		if ($is_ajax) {
			while (ob_get_level() > $json_buffer_level) {
				ob_end_clean();
			}
			$this->output
				->set_content_type('application/json')
				->set_output(json_encode($response));
			return;
		}
		echo json_encode($response);
		exit;
	}

	public function ticketsList($filterBy = null, $search_by = null)
	{
		if ($this->input->is_ajax_request()) {
			$this->load->model('datatables');
			$this->datatables->table = 'tbl_tickets';
			$this->datatables->join_table = array('tbl_departments');
			$this->datatables->join_where = array('tbl_departments.departments_id=tbl_tickets.departments_id');
			$this->datatables->column_order = array('ticket_code', 'subject', 'reporter', 'priority', 'tbl_departments.deptname', 'status', 'tags');
			$this->datatables->column_search = array('ticket_code', 'subject', 'reporter', 'priority', 'tbl_departments.deptname', 'status', 'tags');
			$this->datatables->order = array('tickets_id' => 'desc');
			$where = null;
			if (empty($filterBy) && !empty(admin())) {
				$where = array('status !=' => 'closed');
			}
			if (!empty($search_by)) {
				if ($search_by == 'by_reported') {
					$where = array('reporter' => $filterBy);
				}
				if ($search_by == 'by_project') {
					$where = array('project_id' => $filterBy);
				}
				if ($search_by == 'by_department') {
					$where = array('tbl_tickets.departments_id' => $filterBy);
				}
			} else {
				if ($filterBy == 'assigned_to_me') {
					$user_id = $this->session->userdata('user_id');
					$where = $user_id;
				} else if ($filterBy == 'everyone') {
					$where = array('permission' => 'all');
				} elseif (!empty($filterBy)) {
					$where = array('status' => $filterBy);
				}
			}
			// get all invoice
			$fetch_data = $this->datatables->get_tickets($filterBy, $search_by);

			$data = array();

			$edited = can_action('6', 'edited');
			$deleted = can_action('6', 'deleted');
			$status_info = get_result('tbl_status');
			$reporter_ids = array();
			foreach ($fetch_data as $ticket_row) {
				if (!empty($ticket_row->reporter)) {
					$reporter_ids[] = (int) $ticket_row->reporter;
				}
			}
			$reporter_ids = array_values(array_unique(array_filter($reporter_ids)));
			$reporters = array();
			if (!empty($reporter_ids)) {
				$reporter_rows = $this->db
					->select('user_id, fullname, avatar')
					->where_in('user_id', $reporter_ids)
					->get('tbl_account_details')
					->result();
				if (!empty($reporter_rows)) {
					foreach ($reporter_rows as $reporter_row) {
						$reporters[(int) $reporter_row->user_id] = $reporter_row;
					}
				}
			}
			foreach ($fetch_data as $_key => $v_tickets_info) {
				$action = null;
				$can_edit = $this->tickets_model->can_action('tbl_tickets', 'edit', array('tickets_id' => $v_tickets_info->tickets_id));
				$can_delete = $this->tickets_model->can_action('tbl_tickets', 'delete', array('tickets_id' => $v_tickets_info->tickets_id));
				if ($v_tickets_info->status == 'open') {
					$s_label = 'bg-rose-50 text-rose-700';
				} elseif ($v_tickets_info->status == 'closed') {
					$s_label = 'bg-emerald-50 text-emerald-700';
				} elseif ($v_tickets_info->status == 'in_progress') {
					$s_label = 'bg-amber-50 text-amber-700';
				} else {
					$s_label = 'bg-slate-100 text-slate-700';
				}
				$dept_name = !empty($v_tickets_info->deptname) ? $v_tickets_info->deptname : '-';

				$sub_array = array();
				if (!empty($deleted) && !empty($can_delete)) {
					$sub_array[] = '<div class="checkbox c-checkbox" ><label class="needsclick"> <input value="' . $v_tickets_info->tickets_id . '" type="checkbox"></label></div>';
				}
				$ticket_code = null;
				$ticket_code .= '<a class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300" href="' . base_url() . 'admin/tickets/tickets_details/' . $v_tickets_info->tickets_id . '">' . $v_tickets_info->ticket_code . '</a>';
				$sub_array[] = $ticket_code;

				$ticket_subject = null;
				$ticket_subject .= '<a class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300" href="' . base_url() . 'admin/tickets/tickets_details/' . $v_tickets_info->tickets_id . '">' . $v_tickets_info->subject . '</a>';
				$sub_array[] = $ticket_subject;
				$sub_array[] = display_date($v_tickets_info->created);
				if ($this->session->userdata('user_type') == '1') {
					$reporter_info = isset($reporters[(int) $v_tickets_info->reporter]) ? $reporters[(int) $v_tickets_info->reporter] : null;
					$reporter_name = !empty($reporter_info->fullname) ? $reporter_info->fullname : lang('undefined_user');
					$reporter_avatar = base_url() . ((!empty($reporter_info->avatar) && file_exists($reporter_info->avatar)) ? $reporter_info->avatar : 'assets/img/user/default_avatar.jpg');
					$reporter = '<div class="flex items-center gap-2">
                        <img class="h-8 w-8 rounded-full border border-border" src="' . $reporter_avatar . '" alt="' . html_escape($reporter_name) . '">
                        <span class="text-sm text-foreground">' . html_escape($reporter_name) . '</span>
                    </div>';
					$sub_array[] = $reporter;
				}
				$sub_array[] = '<span class="inline-flex rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-600">' . html_escape($dept_name) . '</span>';
				$sub_array[] = get_tags($v_tickets_info->tags, true);
				$sub_array[] = '<span class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold ' . $s_label . '">' . lang($v_tickets_info->status) . '</span>';

				$custom_form_table = custom_form_table(7, $v_tickets_info->tickets_id);
				if (!empty($custom_form_table)) {
					foreach ($custom_form_table as $c_label => $v_fields) {
						$sub_array[] = $v_fields;
					}
				}
				if (!empty($can_edit) && !empty($edited)) {
					$action .= btn_edit('admin/tickets/create/edit_tickets/' . $v_tickets_info->tickets_id) . ' ';
				}
				if (!empty($can_delete) && !empty($deleted)) {
					$action .= ajax_anchor(base_url("admin/tickets/delete/delete_tickets/$v_tickets_info->tickets_id"), '', array("class" => "", "title" => lang('delete'), "data-fade-out-on-success" => "#table_" . $_key)) . ' ';
				}
				$action .= btn_view('admin/tickets/tickets_details/' . $v_tickets_info->tickets_id) . ' ';

				$change_status = null;
				if (!empty($can_edit) && !empty($edited)) {
					$ch_url = base_url() . 'admin/tickets/change_status/';
					$items = '';
					if (!empty($status_info)) {
						foreach ($status_info as $v_status) {
							$is_active = ($v_status->status === $v_tickets_info->status);
							$active_class = $is_active
								? 'bg-slate-100 font-medium text-slate-900 dark:bg-gray-700 dark:text-white'
								: 'text-slate-700 dark:text-gray-300';
							$status_modal_url = $ch_url . $v_tickets_info->tickets_id . '/' . $v_status->status;
							$status_modal_url_attr = html_escape($status_modal_url);
							$status_modal_title = html_escape(lang('change_status'));
							$items .= '<li>
								<a class="block px-4 py-2 transition-colors hover:bg-slate-50 dark:hover:bg-gray-700 ' . $active_class . '" 
								   href="' . $status_modal_url_attr . '"
								   data-modal-url="' . $status_modal_url_attr . '"
								   data-modal-title="' . $status_modal_title . '"
								   data-modal-size="md"
								   data-no-instant-nav="1">
								   ' . html_escape(lang($v_status->status)) . '
								</a>
							   </li>';
						}
					}
					$change_status = '<details class="group relative inline-flex">
						<summary class="inline-flex cursor-pointer list-none items-center justify-center gap-1 rounded-md border border-slate-200 bg-white px-2 py-1.5 mb-1 text-slate-500 shadow-sm transition-colors hover:bg-slate-50 hover:text-slate-900 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-gray-200">
							<i data-lucide="chevron-down" class="h-3.5 w-3.5 transition-transform duration-200 group-open:rotate-180"></i>
						</summary>
						<ul class="absolute right-0 top-full z-50 mt-1 min-w-[160px] overflow-hidden rounded-lg border border-slate-200 bg-white py-1 text-xs shadow-lg dark:border-gray-700 dark:bg-gray-800">
							' . $items . '
						</ul>
					</details>';
					$action .= $change_status;
				}

				$sub_array[] = '<div class="erp-table-actions">' . $action . '</div>';
				$data[] = $sub_array;
			}
			render_table($data, $where);
		} else {
			redirect('admin/dashboard');
		}
	}

	public function create_tickets($id = NULL)
	{

		$data = $this->tickets_model->array_from_post(array('ticket_code', 'subject', 'reporter', 'priority', 'departments_id', 'body', 'tags'));
		$data['tags'] = normalize_and_sync_tags($data['tags']);
		$data['project_id'] = $this->input->post('project_id', true);
		if ($data['project_id'] == 'None') {
			$data['project_id'] = 0;
		}
		if (empty($id)) {
			$status = $this->input->post('status', true);
			if (!empty($status)) {
				$data['status'] = $status;
				if ($status == 'index') {
					$data['status'] = 'open';
				}
			} else {
				$data['status'] = 'open';
			}
		}

		$created = can_action(6, 'created');
		$edited = can_action(6, 'edited');

		if (!empty($created) || !empty($edited) && !empty($id)) {

			$upload_file = array();

			$files = $this->input->post("files", true);
			$target_path = getcwd() . "/uploads/";
			//process the fiiles which has been uploaded by dropzone
			if (!empty($files) && is_array($files)) {
				foreach ($files as $key => $file) {
					if (!empty($file)) {
						$file_name = $this->input->post('file_name_' . $file, true);
						$new_file_name = move_temp_file($file_name, $target_path);
						$file_ext = explode(".", $new_file_name);
						$is_image = check_image_extension($new_file_name);
						$size = $this->input->post('file_size_' . $file, true) / 1000;
						if ($new_file_name) {
							$up_data = array(
								"fileName" => $new_file_name,
								"path" => "uploads/" . $new_file_name,
								"fullPath" => getcwd() . "/uploads/" . $new_file_name,
								"ext" => '.' . end($file_ext),
								"size" => round($size, 2),
								"is_image" => $is_image,
							);
							array_push($upload_file, $up_data);
						}
					}
				}
			}

			$fileName = $this->input->post('fileName', true);
			$path = $this->input->post('path', true);
			$fullPath = $this->input->post('fullPath', true);
			$size = $this->input->post('size', true);
			$is_image = $this->input->post('is_image', true);

			if (!empty($fileName)) {
				foreach ($fileName as $key => $name) {
					$old['fileName'] = $name;
					$old['path'] = $path[$key];
					$old['fullPath'] = $fullPath[$key];
					$old['size'] = $size[$key];
					$old['is_image'] = $is_image[$key];

					array_push($upload_file, $old);
				}
			}
			if (!empty($upload_file)) {
				$data['upload_file'] = json_encode($upload_file);
			} else {
				$data['upload_file'] = null;
			}

			$permission = $this->input->post('permission', true);
			if (!empty($permission)) {
				if ($permission == 'everyone') {
					$assigned = 'all';
				} else {
					$assigned_to = $this->tickets_model->array_from_post(array('assigned_to'));
					if (!empty($assigned_to['assigned_to'])) {
						foreach ($assigned_to['assigned_to'] as $assign_user) {
							$assigned[$assign_user] = $this->input->post('action_' . $assign_user, true);
						}
					}
				}
				if (!empty($assigned)) {
					if ($assigned != 'all') {
						$assigned = json_encode($assigned);
					}
				} else {
					$assigned = 'all';
				}
				$data['permission'] = $assigned;
			} else {
				set_message('error', lang('assigned_to') . ' Field is required');
				if (empty($_SERVER['HTTP_REFERER'])) {
					redirect('admin/tickets');
				} else {
					redirect($_SERVER['HTTP_REFERER']);
				}
			}

			$this->tickets_model->_table_name = 'tbl_tickets';
			$this->tickets_model->_primary_key = 'tickets_id';
			$is_update = !empty($id);
			$defer_email = $is_update;
			if ($is_update) {
				$this->tickets_model->save($data, $id);
				$activity_name = 'activity_update_tickets';
				$message = lang('ticket_updated');
			} else {
				$id = $this->tickets_model->save($data, $id);
				$activity_name = 'activity_create_tickets';
				$message = lang('ticket_created');
			}
			save_custom_field(7, $id);
			// send email to reporter
			$this->send_tickets_info_by_email($data, FALSE, $defer_email, $is_update);
			// Send email to Client
			$this->send_tickets_info_by_email($data, TRUE, $defer_email, $is_update);

			// save into activities
			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'tickets',
				'module_field_id' => $id,
				'activity' => $activity_name,
				'icon' => 'fa-ticket',
				'link' => 'admin/tickets/tickets_details/' . $id,
				'value1' => $data['ticket_code'],
			);
			// Update into tbl_project
			$this->tickets_model->_table_name = "tbl_activities"; //table name
			$this->tickets_model->_primary_key = "activities_id";
			$this->tickets_model->save($activities);

			// messages for user
			$type = "success";
			set_message($type, $message);
			if (!empty($data['project_id']) && is_numeric($data['project_id'])) {
				redirect('admin/projects/project_details/' . $data['project_id']);
			} else {
				redirect('admin/tickets/tickets_details/' . $id);
			}
		} else {
			if (empty($_SERVER['HTTP_REFERER'])) {
				redirect('admin/tickets');
			} else {
				redirect($_SERVER['HTTP_REFERER']);
			}
		}
	}

	public function new_ticket_form()
	{
		if (!$this->input->is_ajax_request()) {
			redirect('admin/dashboard');
		}
		$data = array();
		$pathonor_jonno['new'] = $this->load->view("admin/tickets/new_ticket", $data, true);
		echo json_encode($pathonor_jonno);
		exit;
	}


	public function save_tickets_reply($id)
	{
		$date = date('Y-m-d H:i:s');
		$status = $this->uri->segment(6);
		if (!empty($status)) {
			if ($status != 'closed' && config_item('notify_ticket_reopened') == 'TRUE') {
				$this->notify_ticket_reopened($id);
			}
			$this->tickets_model->set_action(array('tickets_id' => $id), array('status' => $status), 'tbl_tickets');
		}
		$this->tickets_model->set_action(array('tickets_id' => $id), array('last_reply' => $date), 'tbl_tickets');

		$rdata['body'] = $this->input->post('body', TRUE);
		$upload_file = array();
		$files = $this->input->post("files", true);
		$target_path = getcwd() . "/uploads/";
		//process the fiiles which has been uploaded by dropzone
		if (!empty($files) && is_array($files)) {
			foreach ($files as $key => $file) {
				if (!empty($file)) {
					$file_name = $this->input->post('file_name_' . $file, true);
					$new_file_name = move_temp_file($file_name, $target_path);
					$file_ext = explode(".", $new_file_name);
					$is_image = check_image_extension($new_file_name);
					$size = $this->input->post('file_size_' . $file, true) / 1000;
					if ($new_file_name) {
						$up_data = array(
							"fileName" => $new_file_name,
							"path" => "uploads/" . $new_file_name,
							"fullPath" => getcwd() . "/uploads/" . $new_file_name,
							"ext" => '.' . end($file_ext),
							"size" => round($size, 2),
							"is_image" => $is_image,
						);
						array_push($upload_file, $up_data);
					}
				}
			}
		}
		if (!empty($upload_file)) {
			$rdata['attachment'] = json_encode($upload_file);
		}
		$rdata['tickets_id'] = $id;
		$rdata['replierid'] = $this->session->userdata('user_id');


		$this->tickets_model->_table_name = 'tbl_tickets_replies';
		$this->tickets_model->_primary_key = 'tickets_replies_id';
		$tickets_replies_id = $this->tickets_model->save($rdata);
		if (!empty($tickets_replies_id)) {
			//check this tickets already answer or not
			$ticket_info = $this->db->where(array('tickets_id' => $id, 'status' => 'answered'))->get('tbl_tickets')->row();
			if (empty($ticket_info)) {
				$this->tickets_model->set_action(array('tickets_id' => $id), array('status' => 'answered'), 'tbl_tickets');
			}

			$user_info = $this->db->where(array('user_id' => $rdata['replierid']))->get('tbl_users')->row();

			if ($user_info->role_id == '2') {
				$this->get_notify_ticket_reply('admin', $rdata); // Send email to admins
			} else {
				$this->get_notify_ticket_reply('client', $rdata); // Send email to client
			}
			// save into activities
			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'tickets',
				'module_field_id' => $id,
				'activity' => 'activity_reply_tickets',
				'icon' => 'fa-ticket',
				'link' => 'admin/tickets/tickets_details/' . $id,
				'value1' => $rdata['body'],
			);
			// Update into tbl_project
			$this->tickets_model->_table_name = "tbl_activities"; //table name
			$this->tickets_model->_primary_key = "activities_id";
			$this->tickets_model->save($activities);
			$response_data = "";
			$view_data['ticket_replies'] = $this->db->where(array('tickets_replies_id' => $tickets_replies_id))->order_by('time', 'DESC')->get('tbl_tickets_replies')->result();
			$response_data = $this->load->view("admin/tickets/tickets_reply", $view_data, false);
			if ($this->input->is_ajax_request()) {
				echo json_encode(array("status" => 'success', "data" => $response_data, 'message' => lang('tickets_reply_saved')));
				exit();
			}
			redirect('admin/tickets/tickets_details/' . $id);
		} else {
			echo json_encode(array("status" => 'error', 'message' => lang('error_occurred')));
			exit();
		}
	}

	function notify_ticket_reopened($id)
	{
		$ticket_info = $this->db->where(array('tickets_id' => $id))->get('tbl_tickets')->row();
		$email_template = email_templates(array('email_group' => 'ticket_reopened_email'), $ticket_info->reporter, true);

		$designation_info = $this->db->where('departments_id', $ticket_info->departments_id)->get('tbl_designations')->result();
		if (!empty($designation_info)) {
			foreach ($designation_info as $v_designation) {
				$user_info[] = $this->db->where('designations_id', $v_designation->designations_id)->get('tbl_account_details')->row();
			}
		}

		$message = $email_template->template_body;
		$subject = $email_template->subject;

		$RECIPIENT = str_replace("{RECIPIENT}", fullname($ticket_info->reporter), $message);
		$SUBJECT = str_replace("{SUBJECT}", $ticket_info->ticket_code, $RECIPIENT);
		$USER = str_replace("{USER}", fullname(my_id()), $SUBJECT);
		$TicketLink = str_replace("{TICKET_LINK}", base_url() . 'admin/tickets/tickets_details/' . $ticket_info->tickets_id, $USER);
		$message = str_replace("{SITE_NAME}", config_item('company_name'), $TicketLink);
		$data['message'] = $message;
		$message = $this->load->view('email_template', $data, TRUE);

		$subject = str_replace("[TICKET_CODE]", '[' . $ticket_info->ticket_code . ']', $subject);

		$params['subject'] = $subject;
		$params['message'] = $message;
		$params['resourceed_file'] = '';
		$notifyUser = array();
		if (!empty($user_info)) {
			foreach ($user_info as $v_user) {
				if (!empty($v_user)) {
					$login_info = $this->tickets_model->check_by(array('user_id' => $v_user->user_id), 'tbl_users');
					$params['recipient'] = $login_info->email;
					$this->tickets_model->send_email($params);
					$notifyUser[] = $v_user->user_id;
					if ($v_user->user_id != $this->session->userdata('user_id')) {
						add_notification(array(
							'to_user_id' => $v_user->user_id,
							'icon' => 'ticket',
							'description' => 'not_ticket_assign_to_you',
							'link' => 'admin/tickets/tickets_details/' . $ticket_info->tickets_id,
							'value' => $ticket_info->ticket_code,
						));
					}
				}
			}
		}
		if (!empty($notifyUser)) {
			show_notification($notifyUser);
		}
		return true;
	}

	public function save_comments_reply($tickets_replies_id)
	{
		$rdata['tickets_id'] = $this->input->post('tickets_id', TRUE);
		$rdata['body'] = $this->input->post('reply_comments', TRUE);
		$rdata['ticket_reply_id'] = $tickets_replies_id;

		$rdata['replierid'] = $this->session->userdata('user_id');

		$this->tickets_model->_table_name = 'tbl_tickets_replies';
		$this->tickets_model->_primary_key = 'tickets_replies_id';
		$tickets_replies_id = $this->tickets_model->save($rdata);
		if (!empty($tickets_replies_id)) {

			$user_info = $this->db->where(array('user_id' => $rdata['replierid']))->get('tbl_users')->row();

			if ($user_info->role_id == '2') {
				$this->get_notify_ticket_reply('admin', $rdata); // Send email to admins
			} else {
				$this->get_notify_ticket_reply('client', $rdata); // Send email to client
			}
			// save into activities
			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'tickets',
				'module_field_id' => $rdata['tickets_id'],
				'activity' => 'activity_reply_tickets',
				'icon' => 'fa-ticket',
				'link' => 'admin/tickets/tickets_details/' . $rdata['tickets_id'],
				'value1' => $rdata['body'],
			);
			// Update into tbl_project
			$this->tickets_model->_table_name = "tbl_activities"; //table name
			$this->tickets_model->_primary_key = "activities_id";
			$this->tickets_model->save($activities);

			$response_data = "";
			$view_data['comment_reply_details'] = $this->db->where(array('tickets_replies_id' => $tickets_replies_id))->order_by('time', 'ASC')->get('tbl_tickets_replies')->result();
			$response_data = $this->load->view("admin/tickets/comments_reply", $view_data, false);
			if ($this->input->is_ajax_request()) {
				echo json_encode(array("status" => 'success', "data" => $response_data, 'message' => lang('tickets_reply_saved')));
				exit();
			}
			redirect('admin/tickets/tickets_details/' . $rdata['tickets_id']);
		} else {
			echo json_encode(array("status" => 'error', 'message' => lang('error_occurred')));
			exit();
		}
	}

	function send_tickets_info_by_email($postdata, $client = FALSE, $defer = FALSE, $is_update = FALSE)
	{
		if (!empty($postdata['reporter'])) {
			$postdata['reporter'] = $postdata['reporter'];
		} else {
			$postdata['reporter'] = $this->session->userdata('user_id');
		}

		$user_login_info = $this->tickets_model->check_by(array('user_id' => $postdata['reporter']), 'tbl_users');
		$ticket_info = $this->tickets_model->check_by(array('ticket_code' => $postdata['ticket_code']), 'tbl_tickets');

		if (!empty($client)) {
			$client_recipient_email = !empty($ticket_info->email) ? $ticket_info->email : (!empty($user_login_info->email) ? $user_login_info->email : '');
			if (!empty($client_recipient_email)) {

				$email_template = email_templates(array('email_group' => 'ticket_client_email'), $postdata['reporter'], true);
				$message = $email_template->template_body;
				$subject = $email_template->subject;
				if ($is_update) {
					$message = preg_replace('/Ticket Opened/i', 'Ticket Updated', $message);
					$message = preg_replace('/Your ticket has been opened with us\./i', 'Your ticket has been updated with us.', $message);
					$message = preg_replace('/Status\s*:\s*Open/i', 'Status : Updated', $message);
				}

				$client_email = str_replace("{CLIENT_EMAIL}", $client_recipient_email, $message);
				$ticket_code = str_replace("{TICKET_CODE}", $postdata['ticket_code'], $client_email);
				$TicketLink = str_replace("{TICKET_LINK}", base_url() . 'client/tickets/create/tickets_details/' . $ticket_info->tickets_id, $ticket_code);
				$message = str_replace("{SITE_NAME}", config_item('company_name'), $TicketLink);
				$data['message'] = $message;

				$message = $this->load->view('email_template', $data, TRUE);

				$subject = str_replace("[TICKET_CODE]", '[' . $postdata['ticket_code'] . ']', $subject);
				if ($is_update) {
					$subject = preg_replace('/\bnew ticket\b/i', 'Updated Ticket', $subject);
				}

				$params['recipient'] = $client_recipient_email;
				$params['subject'] = $subject;
				$params['message'] = $message;
				$params['resourceed_file'] = '';
				if ($defer) {
					send_later($params);
				} else {
					$this->tickets_model->send_email($params);
				}

				// send notification to client
				$notifyUser = array();
				if (!empty($user_login_info->user_id) && !empty($user_login_info->email) && strcasecmp($user_login_info->email, $client_recipient_email) === 0) {
					$notifyUser[] = $user_login_info->user_id;
				}
				if (!empty($notifyUser)) {
					foreach ($notifyUser as $v_user) {
						if ($v_user != $this->session->userdata('user_id')) {
							add_notification(array(
								'to_user_id' => $v_user,
								'icon' => 'ticket',
								'description' => 'not_ticket_email_to_client',
								'link' => 'client/tickets/create/tickets_details/' . $ticket_info->tickets_id,
								'value' => $postdata['ticket_code'],
							));
						}
					}
					show_notification($notifyUser);
				}
			}
		} else {
			$email_template = email_templates(array('email_group' => 'ticket_staff_email'), $user_login_info->user_id, true);

			$designation_info = $this->db->where('departments_id', $postdata['departments_id'])->get('tbl_designations')->result();
			if (!empty($designation_info)) {
				foreach ($designation_info as $v_designation) {
					$user_info[] = $this->db->where('designations_id', $v_designation->designations_id)->get('tbl_account_details')->row();
				}
			}

			$message = $email_template->template_body;
			$subject = $email_template->subject;
			if ($is_update) {
				$message = preg_replace('/New Ticket/i', 'Updated Ticket', $message);
				$message = preg_replace('/has been created by the client\./i', 'has been updated by the client.', $message);
			}

			$TicketCode = str_replace("{TICKET_CODE}", $postdata['ticket_code'], $message);
			$ReporterEmail = str_replace("{REPORTER_EMAIL}", !empty($user_login_info->email) ? $user_login_info->email : $this->session->userdata('email'), $TicketCode);
			$TicketLink = str_replace("{TICKET_LINK}", base_url() . 'admin/tickets/tickets_details/' . $ticket_info->tickets_id, $ReporterEmail);
			$message = str_replace("{SITE_NAME}", config_item('company_name'), $TicketLink);
			$data['message'] = $message;
			$message = $this->load->view('email_template', $data, TRUE);

			$subject = str_replace("[TICKET_CODE]", '[' . $postdata['ticket_code'] . ']', $subject);
			if ($is_update) {
				$subject = preg_replace('/\bnew ticket\b/i', 'Updated Ticket', $subject);
			}

			$params['subject'] = $subject;
			$params['message'] = $message;
			$params['resourceed_file'] = '';
			$notifyUser = array();
			$seenRecipients = array();
			$seenUsers = array();
			if (!empty($user_info)) {
				foreach ($user_info as $v_user) {
					if (!empty($v_user)) {
						$login_info = $this->tickets_model->check_by(array('user_id' => $v_user->user_id), 'tbl_users');
						if (empty($login_info->email) || isset($seenRecipients[$login_info->email])) {
							continue;
						}
						$seenRecipients[$login_info->email] = true;
						$params['recipient'] = $login_info->email;
						if ($defer) {
							send_later($params);
						} else {
							$this->tickets_model->send_email($params);
						}
						if (!empty($v_user->user_id)) {
							if (isset($seenUsers[$v_user->user_id])) {
								continue;
							}
							$seenUsers[$v_user->user_id] = true;
							array_push($notifyUser, $v_user->user_id);
							if ($v_user->user_id != $this->session->userdata('user_id')) {

								add_notification(array(
									'to_user_id' => $v_user->user_id,
									'icon' => 'ticket',
									'description' => 'not_ticket_assign_to_you',
									'link' => 'admin/tickets/tickets_details/' . $ticket_info->tickets_id,
									'value' => $postdata['ticket_code'],
								));
							}
						}
					}
				}
			}
			if (!empty($notifyUser)) {
				show_notification($notifyUser);
			}
		}
	}

	function get_notify_ticket_reply($users, $postdata)
	{
		$email_template = email_templates(array('email_group' => 'ticket_reply_email'));
		$tickets_info = $this->tickets_model->check_by(array('tickets_id' => $postdata['tickets_id']), 'tbl_tickets');

		$message = $email_template->template_body;

		$subject = $email_template->subject;

		$status = $tickets_info->status;

		$TicketCode = str_replace("{TICKET_CODE}", $tickets_info->ticket_code, $message);
		$TicketStatus = str_replace("{TICKET_STATUS}", ucfirst($status), $TicketCode);
		$TicketLink = str_replace("{TICKET_LINK}", base_url() . 'client/tickets/create/tickets_details/' . $tickets_info->tickets_id, $TicketStatus);
		$message = str_replace("{SITE_NAME}", config_item('company_name'), $TicketLink);

		$subject = str_replace("[TICKET_CODE]", '[' . $tickets_info->ticket_code . ']', $subject);

		$data['message'] = $message;
		$message = $this->load->view('email_template', $data, TRUE);

		$params['subject'] = $subject;
		$params['message'] = $message;
		$params['resourceed_file'] = '';

		switch ($users) {
			case 'admin':
				$designation_info = $this->db->where('departments_id', $tickets_info->departments_id)->get('tbl_designations')->result();
				if (!empty($designation_info)) {
					foreach ($designation_info as $v_designation) {
						$user_info[] = $this->db->where('designations_id', $v_designation->designations_id)->get('tbl_account_details')->row();
					}
				}
				$notifyUser = array();
				if (!empty($user_info)) {
					foreach ($user_info as $v_user) {
						$login_info = $this->tickets_model->check_by(array('user_id' => $v_user->user_id), 'tbl_users');
						$params['recipient'] = $login_info->email;
						$this->tickets_model->send_email($params);

						$notifyUser[] = $v_user->user_id;
						if ($v_user->user_id != $this->session->userdata('user_id')) {
							add_notification(array(
								'to_user_id' => $v_user->user_id,
								'icon' => 'ticket',
								'description' => 'not_ticket_reply',
								'link' => 'admin/tickets/tickets_details/' . $tickets_info->tickets_id,
								'value' => $tickets_info->ticket_code,
							));
						}
					}
				}

				if (!empty($notifyUser)) {
					show_notification($notifyUser);
				}
			default:
				$login_info = $this->tickets_model->check_by(array('user_id' => $tickets_info->reporter), 'tbl_users');
				if (!empty($login_info)) {
					$params['recipient'] = $login_info->email;
					if ($login_info->role_id == 2) {
						$url = 'client';
					} else {
						$url = 'admin';
					}
					$this->tickets_model->send_email($params);
					if ($login_info->user_id != $this->session->userdata('user_id')) {
						add_notification(array(
							'to_user_id' => $login_info->user_id,
							'icon' => 'ticket',
							'description' => 'not_ticket_reply',
							'link' => $url . '/tickets/create/tickets_details/' . $tickets_info->tickets_id,
							'value' => $tickets_info->ticket_code,
						));
					}
					$notifyUser = array($login_info->user_id);
					show_notification($notifyUser);
				}
		}
	}

	public
	function change_status($id, $status)
	{

		$can_edit = $this->tickets_model->can_action('tbl_tickets', 'edit', array('tickets_id' => $id));

		$edited = can_action(6, 'edited');
		if (!empty($can_edit) && !empty($edited)) {
			$data['id'] = $id;
			$data['status'] = $status;
			$data['subview'] = $this->load->view('admin/tickets/_modal_change_status', $data, TRUE);
			if ($this->input->is_ajax_request()) {
				echo $data['subview'];
				exit();
			}
			$this->load->view('admin/_layout_modal', $data);
		} else {
			set_message('error', lang('there_in_no_value'));
			if (empty($_SERVER['HTTP_REFERER'])) {
				redirect('admin/tickets');
			} else {
				redirect($_SERVER['HTTP_REFERER']);
			}
		}
	}

	public function bulk_delete()
	{
		$selected_id = $this->input->post('ids', true);
		if (!empty($selected_id)) {
			foreach ($selected_id as $id) {
				$result[] = $this->delete('delete_tickets', $id, true);
			}
			echo json_encode($result);
			exit();
		} else {
			$type = "error";
			$message = lang('you_need_select_to_delete');
			echo json_encode(array("status" => $type, 'message' => $message));
			exit();
		}
	}

	public
	function delete($action, $id, $replay_id = NULL)
	{
		if ($action == 'delete_ticket_replay') {
			$comments_info = $this->tickets_model->check_by(array('tickets_replies_id' => $replay_id), 'tbl_tickets_replies');
			if (!empty($comments_info) && !empty($comments_info->attachment)) {
				$attachment = json_decode($comments_info->attachment);
				if (is_array($attachment) || is_object($attachment)) {
					foreach ($attachment as $v_file) {
						if (!empty($v_file->fileName)) {
							remove_files($v_file->fileName);
						}
					}
				}
			}
			// save into activities
			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'tickets',
				'module_field_id' => $id,
				'activity' => 'activity_comment_deleted',
				'icon' => 'fa-ticket',
				'link' => 'admin/tickets/tickets_details/' . $id,
				'value1' => $comments_info->body,
			);
			// Update into tbl_project
			$this->tickets_model->_table_name = "tbl_activities"; //table name
			$this->tickets_model->_primary_key = "activities_id";
			$this->tickets_model->save($activities);

			$this->tickets_model->_table_name = 'tbl_tickets_replies';
			$this->tickets_model->delete_multiple(array('ticket_reply_id' => $replay_id));

			$this->tickets_model->_table_name = 'tbl_tickets_replies';
			$this->tickets_model->_primary_key = 'tickets_replies_id';
			$this->tickets_model->delete($replay_id);

			echo json_encode(array("status" => 'success', 'message' => lang('ticket_reply_deleted')));
			exit();
		}
		if ($action == 'delete_tickets') {

			$tik_info = $this->tickets_model->check_by(array('tickets_id' => $id), 'tbl_tickets');
			$deleted = can_action(6, 'deleted');
			if (!empty($deleted)) {
				if (empty($tik_info)) {
					$type = 'error';
					$message = lang('no_record_found');
					if (!empty($replay_id)) {
						return (array("status" => $type, 'message' => $message));
					}
					echo json_encode(array("status" => $type, 'message' => $message));
					exit();
				}

				$all_replies_info = $this->db->where(array('tickets_id' => $id))->get('tbl_tickets_replies')->result();

				if (!empty($all_replies_info)) {
					foreach ($all_replies_info as $v_replies) {
						if (!empty($v_replies->attachment)) {
							$attachment = json_decode($v_replies->attachment);
							if (is_array($attachment) || is_object($attachment)) {
								foreach ($attachment as $v_file) {
									if (!empty($v_file->fileName)) {
										remove_files($v_file->fileName);
									}
								}
							}
						}
					}
				}

				$comments_info = $this->tickets_model->check_by(array('tickets_id' => $id), 'tbl_tickets');
				if (!empty($comments_info->upload_file)) {
					$attachment = json_decode($comments_info->upload_file);
					if (is_array($attachment) || is_object($attachment)) {
						foreach ($attachment as $v_file) {
							if (!empty($v_file->fileName)) {
								remove_files($v_file->fileName);
							}
						}
					}
				}
				// save into activities
				$activities = array(
					'user' => $this->session->userdata('user_id'),
					'module' => 'tickets',
					'module_field_id' => $id,
					'activity' => 'activity_tickets_deleted',
					'icon' => 'fa-ticket',
					//                    'link' => 'admin/tickets/tickets_details/' . $comments_info->tickets_id,
					'value1' => (!empty($tik_info->ticket_code) ? $tik_info->ticket_code : ''),
				);
				// Update into tbl_project
				$this->tickets_model->_table_name = "tbl_activities"; //table name
				$this->tickets_model->_primary_key = "activities_id";
				$this->tickets_model->save($activities);

				$this->tickets_model->_table_name = 'tbl_tickets_replies';
				$this->tickets_model->delete_multiple(array('tickets_id' => $id));

				$this->tickets_model->_table_name = 'tbl_pinaction';
				$this->tickets_model->delete_multiple(array('module_name' => 'tickets', 'module_id' => $id));


				$this->tickets_model->_table_name = 'tbl_tickets';
				$this->tickets_model->_primary_key = 'tickets_id';
				$this->tickets_model->delete($id);
				$type = 'success';
				$message = lang('ticket_deleted');
			} else {
				$type = 'error';
				$message = lang('access_denied');
			}
			if (!empty($replay_id)) {
				return (array("status" => $type, 'message' => $message));
			}
			echo json_encode(array("status" => $type, 'message' => $message));
			exit();
		}
	}


	public
	function download_file($tickets_id, $key, $reply_id = null)
	{
		$this->load->helper('download');
		if (!empty($reply_id)) {
			$file_info = $this->tickets_model->check_by(array('tickets_replies_id' => $reply_id), 'tbl_tickets_replies');
			$attachment = json_decode($file_info->attachment);
		} else {
			$file_info = $this->tickets_model->check_by(array('tickets_id' => $tickets_id), 'tbl_tickets');
			$attachment = json_decode($file_info->upload_file);
		}
		// get array key from $attachment array
		$keys = array_keys((array)$attachment);

		// get array value from $attachment array
		$values = array_values((array)$attachment);

		// get file name from array value
		$file_name = $values[$key];
		$path = $file_name->path;
		// check file is exist or not
		if (file_exists('./' . $path)) {
			$data = file_get_contents('./' . $path); // Read the file's contents
			force_download($file_name->fileName, $data);
		} else {
			$type = 'error';
			$message = lang('operation_failed');
			set_message($type, $message);
			redirect('admin/tickets/tickets_details/' . $tickets_id);
		}
	}
}
