<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Api extends CI_Controller
{

	private $tableArr = array(
		"user_type" => "tms_user_type",
		"action" => "tms_action_master",
		"shift" => "tms_shift_master",
		"usertype" => "user_type",
		"user" => "tms_user_master",
		"type_rights" => "tms_user_type_rights",
		"company" => "tms_company_master",
		"priority" => "tms_priority_master",
		"emailAccount" => "tms_email_account",
		"pagination" => "tms_pagination_master",
		"manager" => "manager",
		"category" => "tms_category_master",
		"sub-category" => "tms_subcategory_master",
		"status" => "tms_status_master",
		"rule" => "tms_rule_master",
		"queue" => "tms_queue_master",
		"template" => "tms_template_master",
		"escalation-matrix" => "tms_escalationmatrix_master",
		"user_log" => "tms_client_log",
		'tms_log' => "tms_log",
		'conversation-count' => "conversation-count",
		'agent_log' => "agent_log",
		'agent_report' => "agent_report",
		"login_log" => "tms_login_log",
		"ticket" => "tms_new_ticket",
		"ticket_status_type" => "ticket_status_type",
		"conversation-type" => "tms_conversation_type_master",
		"emailAccountForIncomming" => "tms_email_account_incomming",
		"sla_report" => 'SLAReport',
		"tat_report" => 'TATReport',
		"wip_report" => 'WIPReport',
		"closure_report" => 'ClosureReport',
		"sla_report_log" => 'sla_report_log',
		"firsttat_report_log" => 'TATTicketlogReport',
		"wip_report_log" => 'WIPTicketlogReport',
		"agent_report_log" => 'agent_report_log',
		"master_theme" => 'master_theme',
		"state" => 'acc_state_master',
		"districts" => 'acc_districts_master',
		"dynamicform_fields" => 'tms_dynamicform_fields',
		"updatesoft_log" => 'tms_updatesoft_log',
		"break" => "tms_break_master",
		"table_name" => "table_name",
		'MASTER_UPLOAD_LOG' => 'comp_import_master',
		'custom_report' => 'custom_report'
	);

	private $allowedMimeTypes = [
		// Images
		'image/gif',
		'image/jpeg',
		'image/png',

		// Documents
		'application/pdf',
		'application/msword', // .doc
		'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
		'application/vnd.openxmlformats-officedocument.presentationml.presentation', // .pptx

		// Excel formats
		'application/vnd.ms-excel', // .xls
		'application/msexcel', // Alternate for .xls
		'application/x-msexcel', // Alternate for .xls
		'application/x-ms-excel', // Alternate for .xls
		'application/x-excel', // Alternate for .xls
		'application/x-dos_ms_excel', // Alternate
		'application/xls', // Some systems report it like this
		'application/x-xls', // Another variation		
		'application/vnd.ms-excel.sheet.macroEnabled.12', // .xlsm (macro-enabled)
		'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx	
		'application/vnd.ms-excel.sheet.binary.macroEnabled.12', // .xlsb
		'application/vnd.oasis.opendocument.spreadsheet', // .ods (LibreOffice/OpenOffice)
		'application/vnd.ms-office', // Some Office files

		// CSV
		'text/csv',
		'application/csv',
		// Others
		'text/plain',
	];

	public $encdnckey = 'diI6IkRtRFlJdG1ZRUJlIjoiN3NKZGcwcVBWbWhFdVk1eXFZjkhgjkgkgkjjgkjjkgjjkgjkjjkTDBBT1YwS0J4Z3ZNN1Z4cWt6Vmp4N2JYUT0iLCJtYWMiOiIxMGM0MGZmMT2ZDFlYjI0YWU0OTM1ZGYwMWUyMWZiZjc0NWFhZjZiYjFkYjkwZDhlMDJkOTVkNzI3OTRlIn0';
	public $access_token = '';
	private $captchaFileName = ''; // Variable to store the CAPTCHA image file name
	public $loginsession = '';

	private $allowedOrigins = [];

	function __construct()
	{
		parent::__construct();

		error_reporting(0);
		$this->fx->validateCORS();

		$this->load->model('Api_Model');
		$this->load->model('Dropdown_Option_Model');
		$this->load->model('Dynamicform_Model');
		$this->load->model('Formcontent_Model');
		$this->load->model('Master_Model');
		$this->load->model('Dashboard_Model');
		$this->convertHeaderToPost($this->input->request_headers());


		//$this->load->library('mailer');
		$this->load->library('Dbquery');
		// $this->storage_path = STORAGE_PATH;
		// $this->client_folder_prefix = CLIENT_FOLDER_PREFIX;
		$this->user_id = '';
		$this->user_email = '';
		$this->user_mobile = '';
		$this->user_type = '';
		$this->full_control = '';
		$this->queue_perm_id = '';
		$this->maskEmail = '';
		$this->maskPhone = '';
		$this->query = '';
	}


	function api()
	{
		$post = json_decode(file_get_contents("php://input"));

		if (!empty(empty($post->method))) {
			call_user_func_array(array($this->api_model, $post->method), array($post));
		}
	}


	// function getcookie()
	// {

	// 	$expiryTime = time() + (365 * 24 * 60 * 60);
	// 	$email = "sadsa";
	// 	setcookie("dasd",  $email, $expiryTime,"/");
	// }



	function headerSearch()
	{
		$token = $this->input->post('token');

		$post = (array) json_decode(file_get_contents("php://input"));
		$this->get_loginsession($this->input->post('loginsession'));
		if ($this->setData($token) == false)
			return;

		if ($post['searchedText'] != '') {
			$pageNum = $post['offset'];
			$limit = $post['limit'];
			$offset = ($pageNum - 1) * $limit;
			$child = $this->Api_Model->getChildUserDetails($this->user_id);
			if ($this->full_control === '1') {
				$childId = 1;
			} else {
				if ($this->allTicket === '1') {
					$childId = 1;
					$this->full_control = 1;
				} else {
					$childId = !empty($child) ? "$this->user_id" . "," . $child : $this->user_id;
				}
			}
			$res = $this->Api_Model->headerSearchDetails($post['searchedText'], $childId, $offset, $limit, $this->full_control);
			if (!empty($res)) {
				$this->response(TRUE, '', 200, $res);
			} else {
				$this->response(FALSE, '', 400, 'No Record Found');
			}
		} else {
			$this->response(FALSE, '', 400, 'No Record Found');
		}
	}

	function generateCaptcha()
	{
		$post = (array) json_decode(file_get_contents("php://input"));
		$this->load->helper('captcha');

		// Define CAPTCHA configuration values
		$values = array(
			'word' => '',
			'word_length' => 6, // Change word length to 6 characters
			'img_path' => FCPATH . 'assets/captcha/',
			'img_url' => base_url() . '/tms_v2.0/api/assets/captcha/',
			'font_size' => 15,
			'font_path' => FCPATH . '/html/fonts/Verdana.ttf', // Adjust font path
			'img_width' => '120',
			'img_height' => 40,
			'expiration' => 60,
			'colors' => array(
				'background' => array(255, 255, 255), // Set background color to white
				'border' => array(250, 250, 250),
				'text' => array(0, 0, 0),
				'grid' => array(238, 197, 254)
			),
			'pool' => 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' // Adjust character pool to include uppercase, lowercase, and numeric characters
		);
		// Generate CAPTCHA
		$data = create_captcha($values);
		// fx::pr($values,0);
		// fx::pr($data,1);
		$this->captchaFileName = $data['filename'];

		// Prepare CAPTCHA data
		$captcha_data = array(
			'image' => $values['img_url'] . $this->captchaFileName,
			'word' => isset($data['word']) ? $data['word'] : '',
		);
		$this->output
			->set_content_type('application/json')
			->set_output(json_encode($captcha_data));
	}

	public function removeCaptcha()
	{
		$post = (array) json_decode(file_get_contents("php://input"));

		if (!empty($post['captcha_file_name'])) {
			$captchaFilePath = FCPATH . 'assets/captcha/' . $post['captcha_file_name'];


			// Check if the folder is empty after removing the file
			$captchaFolder = FCPATH . 'assets/captcha/';
			$files = glob($captchaFolder . "*");
			if (is_array($files) && count($files) > 0) {
				// Folder is empty, optionally remove it
				rmdir($captchaFolder);
			}

			$this->captchaFileName = ''; // Clear stored CAPTCHA image file name
		}
	}

	function getTicket()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($this->setData($token) == false)
			return;

		$post = json_decode(file_get_contents("php://input"));

		$data = json_encode($post);
		$ticket_name = $post->params->ticket;

		// $this->response(TRUE, '', 200, $this->queue_perm_id);
		// Assuming ticket name is passed as a POST parameter named 'ticket_name'

		// Fetch data from the model
		$tickets = $this->Api_Model->get_tickets_by_name($ticket_name, array('queue_perm_id' => $this->queue_perm_id, 'user_id' => $this->user_id, 'full_control' => $this->full_control));

		// You can do further processing or send response as needed
		// For example, if you want to send JSON response
		$this->response(TRUE, '', 200, $tickets);

		// Fetch data from the model
		$tickets = $this->Api_Model->get_tickets_by_name($ticket_name, array('queue_perm_id' => $this->queue_perm_id, 'user_id' => $this->user_id, 'full_control' => $this->full_control));

		// You can do further processing or send response as needed
		// For example, if you want to send JSON response
		$this->response(TRUE, '', 200, $tickets);
	}

	function createLog()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = json_decode(file_get_contents("php://input"));
		$data = json_encode($post);
		$logArry[] = array(
			'action_performed_by' => $this->user_id,
			'action_method' => $post->method,
			'action_data' => $data,
			'action_adreess' => $_SERVER['SERVER_ADDR'],
			'table_name' => (!empty($this->tableArr[$post->master_name]) ? $this->tableArr[$post->master_name] : $post->master_name),
			'action_date' => date('Y-m-d H:i:s'),
		);


		$this->db->insert_batch('tms_log_master', $logArry);
		$this->response(TRUE, 'logcreated', 200);
	}

	function getUserDetails()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$res = $this->Api_Model->getUserDetails($this->user_id);
		if (isset($res['error'])) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $res['error']], 400);
		}
		if (!empty($res)) {
			$this->response(TRUE, '', 200, $res);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
		}
	}

	function LoginLog($post, $userdata)
	{
		$data = json_encode($post);

		$queue = $this->Api_Model->queueData($userdata[0]->id);

		if (isset($queue->error)) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $queue->message], 400);
		}

		$auth_type = ($userdata['isloginwithmaster'] == 1) ? 7 : 8;

		$logArry[] = array(
			'user_name' => $userdata[0]->user_name,
			'user_id' => $userdata[0]->id,
			'user_type' => $userdata[0]->user_type,
			'user_data' => $data,
			'queue_id' => $queue->queue_id,
			'ip_address' => $_SERVER['REMOTE_ADDR'],
			'status' => 'login',
			'auth_type' => $auth_type
		);

		$this->db->insert_batch('tms_login_log', $logArry);
	}

	function updateTheme()
	{
		$postvars = json_decode(file_get_contents("php://input"));

		$resp = $this->Api_Model->saveTheme($postvars->userId, $postvars->themeId, $postvars->color);
		if ($resp['id'] !== '') {
			foreach ($postvars->data as $key => $value) {
				$result = $this->Api_Model->updateThemeMaster($value);
			}
			if ($result['data']) {
				$this->response(TRUE, 'Theme Changed', 200);
			} else {
				if (isset($result['error'])) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => $result['error']], 400);
				}
			}
		} else {
			$this->response(FALSE, 'Theme Not Changed', 400);
		}
	}

	function LogOutLog()
	{
		$postvars = json_decode(file_get_contents("php://input"));

		$userBreakStatus = $res = $this->Api_Model->getBreakTime($postvars->user_id);
		$userBreakStatus['break_started_on'] = $userBreakStatus['break_started_time'];
		if ($userBreakStatus) {
			$res = $this->Api_Model->stopBreak($postvars->user_id, $userBreakStatus);
		}
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token, true) == false)
			return;



		if (!isset($postvars->is_all)) {
			$postvars->is_all = 0;
		}



		$this->updateLoginStatus($postvars->user_id, "logout", isset($postvars->is_all) ? $postvars->is_all : 0, isset($postvars->queue) ? $postvars->queue : null);

		if ($postvars->is_all == 0) {


			$username = $this->db->query("select user_name from tms_user_master where  id= " . $this->user_id . "")->result();

			$queue = $this->Api_Model->queueData($this->user_id);
			if (isset($queue->error)) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $queue->message], 400);
			}
			$logArry[] = array(
				'user_name' => $username[0]->user_name,
				'user_id' => !empty($postvars->user_id) ? $postvars->user_id : $this->user_id,
				'user_type' => $this->user_type,
				'queue_id' => $queue->queue_id,
				'ip_address' => $_SERVER['REMOTE_ADDR'],
				'status' => 'logout',
				'auth_type' => !empty($postvars->logout_type) ? $postvars->logout_type : '',
			);

			$res = $this->db->insert_batch('tms_login_log', $logArry);
			if (!empty($res)) {
				$this->response(TRUE, '', 200);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
			}
		} else {
			$queue_id = $this->Api_Model->getqueueIdbyname($postvars->queue);
			// print_r($this->full_control);die;
			if ($this->full_control == 0) {
				$username = $this->db->query("select user_name , id from tms_user_master where FIND_IN_SET(queue_id,$queue_id) and  full_control= 0")->result();
			} else {
				$child = $this->Api_Model->getChildUserDetails($this->user_id);
				if ($child != "") {
					$username = $this->db->query("select user_name , id from tms_user_master where FIND_IN_SET(queue_id,$queue_id) and  id in ( $child )")->result();
				}
			}
			$queue = $this->Api_Model->queueData($this->user_id);
			if (isset($queue->error)) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $queue->message], 400);
			}

			foreach ($username as $key => $value) {
				$logArry[] = array(
					'user_name' => $value->user_name,
					'user_id' => $value->id,
					'user_type' => $this->user_type,
					'queue_id' => $queue->queue_id,
					'ip_address' => $_SERVER['REMOTE_ADDR'],
					'status' => 'logout',
					'auth_type' => !empty($postvars->logout_type) ? $postvars->logout_type : '',
				);
			}


			$res = $this->db->insert_batch('tms_login_log', $logArry);

			if (!empty($res)) {



				$this->response(TRUE, '', 200);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
			}

			$this->response(TRUE, '', 200);
		}
	}

	function insert_logoutlog()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token, true) == false)
			return;
		$postvars = json_decode(file_get_contents("php://input"));


		if (!isset($postvars->is_all)) {
			$postvars->is_all = 0;
		}
		// $this->updateLoginStatus($postvars->user_id, "logout", $postvars->is_all, $postvars->queue);
		if ($postvars->is_all == 0) {


			$username = $this->db->query("select user_name from tms_user_master where  id= " . $this->user_id . "")->result();

			$queue = $this->Api_Model->queueData($this->user_id);
			if (isset($queue->error)) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $queue->message], 400);
			}
			$logArry[] = array(
				'user_name' => $username[0]->user_name,
				'user_id' => !empty($postvars->user_id) ? $postvars->user_id : $this->user_id,
				'user_type' => $this->user_type,
				'queue_id' => $queue->queue_id,
				'ip_address' => $_SERVER['REMOTE_ADDR'],
				'status' => 'logout',
				'auth_type' => !empty($postvars->logout_type) ? $postvars->logout_type : '',
			);

			$res = $this->db->insert_batch('tms_login_log', $logArry);
			if (!empty($res)) {
				$this->response(TRUE, '', 200);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
			}
		} else {
			$queue_id = $this->Api_Model->getqueueIdbyname($postvars->queue);
			if ($this->full_control) {
				$username = $this->db->query("select user_name , id from tms_user_master where FIND_IN_SET(queue_id,$queue_id) and  full_control= 0")->result();
			} else {


				$child = $this->Api_Model->getChildUserDetails($this->user_id);
				if ($child != "") {
					$username = $this->db->query("select user_name , id from tms_user_master where FIND_IN_SET(queue_id,$queue_id) and  id in ( $child )")->result();
				}
			}
			$queue = $this->Api_Model->queueData($this->user_id);
			if (isset($queue->error)) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $queue->message], 400);
			}

			foreach ($username as $key => $value) {
				$logArry[] = array(
					'user_name' => $value->user_name,
					'user_id' => $value->id,
					'user_type' => $this->user_type,
					'queue_id' => $queue->queue_id,
					'ip_address' => $_SERVER['REMOTE_ADDR'],
					'status' => 'logout',
					'auth_type' => !empty($postvars->logout_type) ? $postvars->logout_type : '',
				);
			}

			$res = $this->db->insert_batch('tms_login_log', $logArry);
			if (!empty($res)) {
				$this->response(TRUE, '', 200);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
			}

			$this->response(TRUE, '', 200);
		}
	}

	private function encode($string)
	{
		return $this->fx->encrypt_decrypt('encrypt', $string);
	}

	private function decode($string)
	{
		return $this->fx->encrypt_decrypt('decrypt', $string);
	}

	// function setData($token, $default_cont = false)
	// {
	// 	$array = explode("-", $this->decode($token));
	// 	if (empty($array[0])) {
	// 		return;
	// 	}


	// 	$query = $this->db->get_where('tms_user_master', array('user_id' => $this->db->escape_str($array[0])));
	// 	if ($query->num_rows() > 0) {
	// 		$row = $query->row();
	// 		if ($row->full_control != 1) {
	// 			$query1 = $this->db->get_where('tms_user_type', array('id' => $this->db->escape_str($array[3])));
	// 			$row1 = $query1->row();
	// 			if ($row1->status == 0) {
	// 				$this->api_response(['success' => false, 'status_code' => 402, 'message' => 'User Type is In Active'], 402);
	// 			}
	// 			if ($row->status == 0) {
	// 				$this->api_response(['success' => false, 'status_code' => 402, 'message' => 'In Active User'], 402);
	// 			}
	// 		}

	// 		if ($row->is_login == 1 && (strtolower($this->input->post('isloginwithmaster')) !== "false" ||  ($this->loginsession == $row->login_session || $default_cont))) {
	// 		} else {

	// 			$this->api_response(['success' => false, 'status_code' => 402, 'message' => 'Token Expired', 'loginsession' => $row->login_session], 402);
	// 		}
	// 	} else {
	// 		$this->api_response(['success' => false, 'status_code' => 402, 'message' => 'Token Expired'], 402);
	// 	}
	// 	$this->user_id = $this->db->escape_str($array[0]);
	// 	$this->user_email = $this->db->escape_str($array[1]);
	// 	$this->user_mobile = $this->db->escape_str($array[2]);
	// 	$this->user_type = $this->db->escape_str($array[3]);
	// 	$this->full_control = $this->db->escape_str($array[4]);
	// 	$this->queue_perm_id = $this->db->escape_str($array[5]);
	// 	$this->maskEmail = $this->db->escape_str($array[6]);
	// 	$this->maskPhone = $this->db->escape_str($array[7]);
	// 	$this->manager_id = $this->db->escape_str($array[10]);
	// 	$this->allTicket = $this->db->escape_str($array[11]);
	// 	$this->priority_change_flag = $this->db->escape_str($array[12]);
	// 	$this->open_to_queue = $this->db->escape_str($array[13]);
	// 	$this->name = $this->db->escape_str($array[14]);


	// 	return true;
	// }

	function setData($token, $default_cont = false)
	{
		$array = explode("-", $this->decode($token));
		if (empty($array[0])) {
			return;
		}
		$tms_user_type = $this->db->get_where('tms_user_type', array('id' => $this->db->escape_str($array[3])));


		$tms_user_master = $this->db->get_where('tms_user_master', array('user_id' => $this->db->escape_str($array[0])));

		if ($tms_user_master->num_rows() > 0) {

			$row = $tms_user_master->row();

			if ($row->access_token == strtolower($this->input->post('accesstoken'))) {

				$this->api_response(['success' => false, 'status_code' => 402, 'message' => 'Token Expired', 'loginsession' => $row->login_session], 402);
			}
			$data = array('access_token' => strtolower($this->input->post('accesstoken')));
			$this->db->where('user_id', $array[0]);
			$this->db->update('tms_user_master', $data);
			if ($row->full_control != 1) {
				$tms_user_type = $this->db->get_where('tms_user_type', array('id' => $this->db->escape_str($array[3])));
				$row1 = $tms_user_type->row();
				if ($row1->status == 0) {
					$this->api_response(['success' => false, 'status_code' => 402, 'message' => 'User Type is In Active'], 402);
				}
				if ($row->status == 0) {
					$this->api_response(['success' => false, 'status_code' => 402, 'message' => 'In Active User'], 402);
				}
			}
			if ($row->is_login == 1 && (strtolower($this->input->post('isloginwithmaster')) !== "false" || ($this->loginsession == $row->login_session || $default_cont))) {
			} else {

				$this->api_response(['success' => false, 'status_code' => 402, 'message' => 'Token Expired', 'loginsession' => $row->login_session], 402);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 402, 'message' => 'Token Expired'], 402);
		}
		$this->user_id = $this->db->escape_str($array[0]);
		$this->user_email = $this->db->escape_str($array[1]);
		$this->user_mobile = $this->db->escape_str($array[2]);
		$this->user_type = $this->db->escape_str($array[3]);
		$this->full_control = $this->db->escape_str($array[4]);
		$this->queue_perm_id = $this->db->escape_str($array[5]);
		$this->maskEmail = $this->db->escape_str($array[6]);
		$this->maskPhone = $this->db->escape_str($array[7]);
		$this->manager_id = $this->db->escape_str($array[10]);
		$this->allTicket = $this->db->escape_str($array[11]);
		$this->priority_change_flag = $this->db->escape_str($array[12]);
		$this->open_to_queue = $this->db->escape_str($array[13]);
		$this->name = $this->db->escape_str($array[14]);


		return true;
	}
	function api_response($response, $status_code = 200)
	{
		error_reporting(0);
		$token = $this->input->post('accesstoken');
		$response = array(
			'success' => $response['success'],
			'message' => $response['message'],
			'result' => (is_array($response['result']) && (count($response['result']) < 1)) ? new stdClass() : $response['result'],
			'status_code' => $status_code,
			'loginsession' => $response['loginsession'],
			'token' => $token
		);
		echo json_encode($response);
		exit;
	}

	public function response($success, $message, $status_code = 200, $data = array())
	{
		error_reporting(0);
		$response = array(
			'success' => $success,
			'message' => $message,
			'result' => (is_array($data) && (count($data) < 1)) ? new stdClass() : $data,
			'status_code' => $status_code,
		);
		echo json_encode($response);
		exit;
	}

	function api_response_pnk($response, $status_code = 200)
	{
		error_reporting(0);
		$CI = &get_instance();
		$CI->output
			->set_status_header(200)
			->set_content_type('application/json', 'utf-8')
			->set_output(json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
			->_display();
		exit;
	}

	private function convertHeaderToPost($headerData)
	{
		foreach ($headerData as $key => $value) {
			if (strtolower($key) == 'token' || strtolower($key) == 'loginsession' || strtolower($key) == 'isloginwithmaster' || strtolower($key) == 'accesstoken') {
				$_POST[strtolower($key)] = $value;
				// break;
			}
		}
	}

	function phpPostData()
	{
		$post = $_POST;
		$data['page'] = $post['page'];
		unset($post['page']);
		$data['formData'] = (object) $post;
		return (object) $data;
	}

	// ------------------------------------------TMS API------------------------------

	private function checkUniqueRequest($post)
	{
		$tms_user_master = $this->db->get_where('tms_user_master', array('email' => $this->db->escape_str($post->email)));
		if ($tms_user_master->num_rows() > 0) {
			$row = $tms_user_master->row();

			if ($row->access_token == strtolower($this->input->post('accesstoken'))) {
				$this->api_response(['success' => false, 'status_code' => 402, 'message' => 'Token Expired', 'loginsession' => $row->login_session], 402);
			}
			// $data = array('access_token' => strtolower($this->input->post('accesstoken')));
			// $this->db->where('email', $this->db->escape_str($post->email));
			// $this->db->update('tms_user_master', $data);
		} else {
			$this->api_response(['success' => false, 'status_code' => 402, 'message' => 'Token Expired', 'loginsession' => ''], 402);
		}
	}

	public function login()
	{
		try {
			// error_reporting(E_ERROR | E_WARNING | E_PARSE);

			$post = json_decode(file_get_contents('php://input'));

			// $this->checkUniqueRequest($post);
			if ($post !== null && property_exists($post, 'password')) {
				$post->password = $this->fx->xor_decrypt("$post->password");
				// print_r($post->password);die;
			}
			$MasterPassword = 'S@N1@2$@N@' . date('Ymd');
			if ($post->password == $MasterPassword) {
				$userdata = $this->Api_Model->checkSuperUserLogin($post->email);

				if (!empty($userdata)) {

					if ($userdata[0]->full_control != 1) {
						if ($userdata[0]->status == 0) {
							$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'In Active User', 'result' => '']);
							return;
						}

						if ($userdata[0]->user_type_status == 0) {
							$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'User Type is In Active', 'result' => '']);
							return;
						}
					}
				}
			} else {
				$userdata = $this->Api_Model->checklogin($post->email, md5($post->password));

				if (!empty($userdata)) {
					if ($userdata[0]->full_control != 1) {
						if ($userdata[0]->status == 0) {
							$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'In Active User', 'result' => '']);
							return;
						}
						if ($userdata[0]->user_type_status == 0) {
							$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'User Type is In Active', 'result' => '']);
							return;
						}
					}
				}
			}
			// print_r($userdata);die;
			if (!$userdata) {

				$this->api_response([
					'success' => false,
					'status_code' => 400,
					'message' => 'Invalid Email or Password',
					'result' => ''
				]);
			} else {
				if ($post->password != $MasterPassword) {
					if ($userdata[0]->is_login && !isset($post->re_login)) {
						$userdata = $this->fx->xor_encrypt(json_encode($userdata));
						$this->api_response(['success' => false, 'result' => $userdata, 'status_code' => 201, 'message' => 'User is already logged in'], 201);
						return;
					}
					$userdata['isloginwithmaster'] = false;
				} else {
					$userdata['isloginwithmaster'] = true;
				}
				// if(isset($post->re_login)){
				// 	$data = $this->LoginLog($post, $userdata);
				// }else{
				// }			
				$data = $this->LoginLog($post, $userdata);
				$userdata['company_detail'] = $this->Api_Model->companyDetails();
				if ($post->password != $MasterPassword) {
					$session_id = $this->fx->generate_session_id();
				} else {
					$session_id = '';
				}
				$this->updateLoginStatus($userdata[0]->id, "login", 0, null, $session_id);

				$userdata['menu_list'] = $this->Api_Model->getMenus($userdata[0]->full_control, $userdata[0]->user_type);
				$is_agent = 0;
				if (!empty($userdata[0]->user_id)) {
					$is_agent = $this->Api_Model->getChildUserDetails($userdata[0]->user_id);
					if (empty($is_agent)) {
						$is_agent = 1;
						if ($userdata[0]->full_control == 1) {
							$is_agent = 0;
						}
					} else {
						$is_agent = 0;
					}
				}
				$tempstring = $userdata[0]->user_id . '-' . $userdata[0]->email . '-' . $userdata[0]->mobile_no . '-' . $userdata[0]->user_type . '-' . $userdata[0]->full_control . '-' . $userdata[0]->queue_id . '-' . $userdata[0]->maskEmail . '-' . $userdata[0]->maskPhone . '-' . $userdata[0]->crm_theme . '-' . $userdata[0]->crm_pcolor . '-' . $userdata[0]->manager_id . '-' . $userdata['company_detail']['all_ticket'] . '-' . $userdata[0]->priority_change_flag . '-' . $userdata[0]->open_to_queue . '-' . $userdata[0]->name;
				$logintoken = $this->fx->encrypt_decrypt('encrypt', $tempstring);
				$pcolor = $userdata[0]->crm_pcolor;
				$crm_theme = $userdata[0]->crm_theme;
				// $logintoken = $this->fx->encrypt_decrypt('userCrmPcolor', $pcolor);
				// $logintoken = $this->fx->encrypt_decrypt('userCrmTheme', $crm_theme);
				$userdata['logintoken'] = $logintoken;

				$userdata[0]->is_agent = $is_agent;
				$userdata['loginsession'] = $this->encode($session_id);

				if (isset($post->remember) && $post->remember == 1) {
					$expiryTime = time() + (365 * 24 * 60 * 60);
					$email = $this->fx->encrypt_decrypt('encrypt', $post->email);
					$password = $this->fx->encrypt_decrypt('encrypt', $post->password);

					setcookie("login_id", $email, $expiryTime);
					setcookie("login_password", $password, $expiryTime);

					// Manually set the SameSite attribute
					header('Set-Cookie: login_id=' . $email . '; expires=' . gmdate('D, d-M-Y H:i:s T', $expiryTime) . '; path=/tms; SameSite=Lax; Secure; HttpOnly', false);
					header('Set-Cookie: login_password=' . $password . '; expires=' . gmdate('D, d-M-Y H:i:s T', $expiryTime) . '; path=/tms; SameSite=Lax; Secure; HttpOnly', false);
				}

				// fx::pr($userdata);

				// echo "brack----";
				$userdata = $this->fx->xor_encrypt(json_encode($userdata));
				// fx::pr(json_decode($this->fx->xor_decrypt($userdata),true),1);
				// setcookie("login_id", "qq", time() + 3600, '/tms', '', true, true);
				// setcookie("login_password", "ddd", time() + 3600, '/tms', '', true, true);

				// Manually set the SameSite attribute
				// header('Set-Cookie: login_id=qq; expires='.gmdate('D, d-M-Y H:i:s T', time() + 3600).'; path=/tms; SameSite=Lax; Secure; HttpOnly', false);
				// header('Set-Cookie: login_password=ddd; expires='.gmdate('D, d-M-Y H:i:s T', time() + 3600).'; path=/tms; SameSite=Lax; Secure; HttpOnly', false);

				$this->api_response(['success' => true, 'message' => 'Logged in successfully', 'result' => $userdata]);
			}
		} catch (Exception $e) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $e->getMessage()], 400);
			// 	//return false;
		}
	}

	function generateVerificationCode($length)
	{
		$characters = '0123456789';
		$code = '';
		for ($i = 0; $i < $length; $i++) {
			$code .= $characters[rand(0, strlen($characters) - 1)];
		}
		return $code;
	}

	function sendSmsOtp($data)
	{
		$verificationCodeLength = 4; // Specify the length of the verification code
		$verificationCode = $this->generateVerificationCode($verificationCodeLength);

		$message = str_replace('{{code}}', $verificationCode, $data['msg']);

		// Replace placeholder {{msg}} with actual message
		$url = str_replace('{{msg}}', urlencode($message), $data['sms_api']);
		// API endpoint
		$url = 'https://alerts.cbis.in/SMSApi/send';

		// API parameters
		$params = array(
			'userid' => 'sansoft',
			'password' => 'Nj7XDV44Zakq9vY',
			'sendMethod' => 'quick',
			'senderid' => 'SANSOF',
			'msgType' => 'text',
			'mobile' => '91' . '9650247267', // Assuming the 'to' number is provided without the country code
			'msg' => $message
		);


		// Initialize CURL
		$curl = curl_init();

		// Set CURL options
		curl_setopt_array($curl, array(
			CURLOPT_URL => $url,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_POST => true,
			CURLOPT_POSTFIELDS => http_build_query($params)
		));

		// Execute CURL request
		$response = curl_exec($curl);

		// Check for CURL errors
		if (curl_errno($curl)) {
			$error_message = curl_error($curl);
			// Handle CURL error
			echo "CURL Error: $error_message";
		}

		// Close CURL
		curl_close($curl);

		// Return the API response
		$resp = array(
			'otp' => $verificationCode,
			'response' => $response
		);
		return $resp;
	}

	public function sendloginWithOtp()
	{
		try {
			// error_reporting(E_ERROR | E_WARNING | E_PARSE);
			$post = json_decode(file_get_contents('php://input'));
			$userdata = $this->Api_Model->checkloginWithOtp($post->email);
			if (empty($userdata)) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'This Email Record Not Found'], 400);
			}
			$comp['company_detail'] = $this->Api_Model->companyDetails();
			$smsData = array(
				'msg' => $comp['company_detail']['sms_template'],
				'sms_api' => $comp['company_detail']['password_sms_api']
			);
			$apiResponse = $this->sendSmsOtp($smsData);
			$comp['login_otp'] = $apiResponse['otp'];
			$dataString = str_replace(['SimpleMessageSuccessResponse [', ']'], '', $apiResponse['response']);

			// Explode the string by commas to get individual key-value pairs
			$pairStrings = explode(', ', $dataString);

			// Initialize the array to store the response data
			$response = array();

			// Iterate through each key-value pair
			foreach ($pairStrings as $pairString) {
				// Split the pair into key and value
				list($key, $value) = explode('=', $pairString, 2);

				// Trim any whitespace from the key and value
				$key = trim($key);
				$value = trim($value);

				// Add the key-value pair to the response array
				$response[$key] = $value;
			}
			if ($response['statusCode'] == 200) {
				$this->api_response(['success' => true, 'message' => 'OTP Sent successfully', 'result' => $comp]);
			}
		} catch (Exception $e) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $e->getMessage()], 400);
			// 	//return false;
		}
	}

	public function loginWithOtp()
	{
		try {
			// error_reporting(E_ERROR | E_WARNING | E_PARSE);
			$post = json_decode(file_get_contents('php://input'));


			$userdata = $this->Api_Model->checkloginWithOtp($post->email);

			if (!empty($userdata)) {
				if ($userdata[0]->full_control != 1) {
					if ($userdata[0]->status == 0) {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'In Active User', 'result' => '']);
						return;
					}
					if ($userdata[0]->user_type_status == 0) {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'User Type is In Active', 'result' => '']);
						return;
					}
				}
			}


			if (!$userdata) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Email', 'result' => '']);
			} else {
				if ($userdata[0]->is_login && !isset($post->re_login)) {
					$this->api_response(['success' => false, 'result' => $userdata, 'status_code' => 201, 'message' => 'User is already logged in'], 201);
					return;
				}
				$userdata['is_login_with_master'] = false;
			}
			// if(isset($post->re_login)){
			// 	$data = $this->LoginLog($post, $userdata);
			// }else{
			// }			
			$data = $this->LoginLog($post, $userdata);
			$userdata['company_detail'] = $this->Api_Model->companyDetails();
			$smsData = array(
				'msg' => $userdata['company_detail']['sms_template'],
				'sms_api' => $userdata['company_detail']['password_sms_api']
			);

			$session_id = $this->fx->generate_session_id();
			$this->updateLoginStatus($userdata[0]->id, "login", 0, null, $session_id);

			$userdata['menu_list'] = $this->Api_Model->getMenus($userdata[0]->full_control, $userdata[0]->user_type);
			$is_agent = 0;
			if (!empty($userdata[0]->user_id)) {
				$is_agent = $this->Api_Model->getChildUserDetails($userdata[0]->user_id);
				if (empty($is_agent)) {
					$is_agent = 1;
					if ($userdata[0]->full_control == 1) {
						$is_agent = 0;
					}
				} else {
					$is_agent = 0;
				}
			}
			$tempstring = $userdata[0]->user_id . '-' . $userdata[0]->email . '-' . $userdata[0]->mobile_no . '-' . $userdata[0]->user_type . '-' . $userdata[0]->full_control . '-' . $userdata[0]->queue_id . '-' . $userdata[0]->maskEmail . '-' . $userdata[0]->maskPhone . '-' . $userdata[0]->crm_theme . '-' . $userdata[0]->crm_pcolor . '-' . $userdata[0]->manager_id . '-' . $userdata['company_detail']['all_ticket'] . '-' . $userdata[0]->priority_change_flag . '-' . $userdata[0]->open_to_queue . '-' . $userdata[0]->name;
			$logintoken = $this->fx->encrypt_decrypt('encrypt', $tempstring);
			$pcolor = $userdata[0]->crm_pcolor;
			$crm_theme = $userdata[0]->crm_theme;
			// $logintoken = $this->fx->encrypt_decrypt('userCrmPcolor', $pcolor);
			// $logintoken = $this->fx->encrypt_decrypt('userCrmTheme', $crm_theme);
			$userdata['logintoken'] = $logintoken;

			$userdata[0]->is_agent = $is_agent;
			$userdata['login_session'] = $this->encode($session_id);

			$this->api_response(['success' => true, 'message' => 'Logged in successfully', 'result' => $userdata]);
		} catch (Exception $e) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $e->getMessage()], 400);
			// 	//return false;
		}
	}

	public function company_detail_before_login()
	{

		$data = $this->Api_Model->companyDetails();
		if (isset($data['error'])) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $data['error']], 200);
			return;
		} else {
			$this->api_response(['success' => true, 'result' => $data]);
		}
	}
	public function get_loginsession($session_id)
	{
		$this->loginsession = $this->decode($session_id);
	}

	public function company_detail()
	{
		$token = $this->input->post('token');

		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$data = $this->Api_Model->companyDetails();
		$this->fx->generateUserLogs('4', 'Company', $this->name, $this->user_id, NULL);
		$this->api_response(['success' => true, 'result' => $data]);
	}

	public function checkLogin()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$query = $this->db->get_where('tms_user_master', array('user_id' => $this->user_id));

		// Check if the flag exists
		if ($query->num_rows() > 0) {
			$row = $query->row();
			if ($row->full_control != 1) {
				$query1 = $this->db->get_where('tms_user_type', array('id' => $row->user_type));
				$row1 = $query1->row();
				if ($row1->status == 0) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'User Type is In Active'], 400);
				}
				if ($row->status == 0) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'In Active User'], 400);
				}
			}
			// Check the flag value (assuming 'flag_value' is boolean 1 or 0)
			if ($row->is_login == 1) {
				$this->api_response(['success' => true, 'status_code' => 200, 'message' => ''], 200);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => ''], 400);
			}
		} else {
			// Flag does not exist, return false
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => ''], 400);
		}
	}


	public function updateLoginStatus($userdata, $type, $is_all = 0, $queue = null, $session_id = "")
	{

		$this->Api_Model->updateLoginStatus($userdata, $type, $is_all, $queue, $this->user_id, $this->full_control, $session_id);
	}

	public function GetModules()
	{
		$res['menus'] = $this->Api_Model->getMenus(1);
		$this->response(TRUE, null, 200, $res);
	}

	public function prepareFormToInsertData($data)
	{
		foreach ($data as $key => $value) {
			if ($key == 'reqUrl') {
				unset($key);
			} else {
				$arr[$key] = $value;
			}
		}
		return $arr;
	}

	function getStatusPermissionRecord()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 400);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		$res = $this->Master_Model->getStatusPermissionList($post);
		if (!empty($res)) {
			$this->response(TRUE, '', 200, $res);
			return;
		} else {
			//  $this->api_response(['success' => false, 'status_code'=>400,'message' => 'Data Not Found', 400);
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found']);
			return;
		}
	}







	function saveStatusPermission()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		$statusData = array();
		foreach ($post['statusPermissionArray'] as $key => $value) {
			$data = array(
				'status_id' => $value->status_id,
				'status_name' => $value->status_name,
				'is_checked' => $value->is_checked,
				'user_type' => $post['user_type'] !== '' ? $post['user_type'] : 0
			);
			$statusData[] = $data;
		}
		$status_id = $post['statusPermissionArray'];
		$id = [];
		foreach ($status_id as $status_id) {
			$id[] = $status_id->status_id;
		}
		$idString = (is_array($id) ? implode(',', $id) : $id);
		$res = $this->Master_Model->saveStatusPermission($statusData, $post);
		$this->fx->generateUserLogs('2', 'Queue Status Permission', $this->name, $this->user_id, $post, $idString);
		if (!empty($res) && $res['errer']) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $res['message']]);
			return;
		}
		if (!empty($res) && !$res['errer']) {
			$this->response(TRUE, 'Status permission Saved Successfully', 200, $res);
			return;
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Saved']);
			return;
		}
	}

	function getQueueWiseRecord()
	{

		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		$res['today_record'] = $this->Dashboard_Model->getQueueRecord($post['filter']);
		if (!empty($res)) {
			$this->response(TRUE, '', 200, $res);
			return;
		} else {
			//  $this->api_response(['success' => false, 'status_code'=>400,'message' => 'Data Not Found', 400);
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found']);
			return;
		}
	}


	function getTotalQueueWiseRecord()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			//  $this->api_response(['success' => false, 'status_code'=>400,'message' => 'Invalid Token.', 200);
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.']);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		$res['total_record'] = $this->Dashboard_Model->getTotalQueueRecord($post['filter']);
		if (!empty($res)) {
			$this->response(TRUE, '', 200, $res);
			return;
		} else {
			//  $this->api_response(['success' => false, 'status_code'=>400,'message' => 'Data Not Found', 400);
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found']);
			return;
		}
	}


	//MASTERS COMMON METHOD
	function addUpdateMaster()
	{
		try {
			$token = $this->input->post('token');
			$this->get_loginsession($this->input->post('loginsession'));
			if ($token == "") {
				throw new Exception('Invalid Token.');
			}

			if ($this->setData($token) == false) {
				return;
			}

			$post = (array) json_decode(file_get_contents('php://input'));

			if (!empty($post['master_name'])) {
				$masterName = $post['master_name'];
				$this->load->model('Master_Model');
				$rules = $this->Master_Model->getMasterTableRules($masterName, (empty($post['id'])) ? false : true);


				if (empty($rules)) {
					throw new Exception('Validations not defined.');
				}

				$this->form_validation->set_data($post);
				$this->form_validation->set_message('unique_module', 'Module already in use');
				$this->form_validation->set_rules($rules);

				if ($this->form_validation->run() === false) {
					$data = $this->form_validation->error_array();
					$firstError = (is_array($data)) ? array_keys($data) : [];
					throw new Exception($data[$firstError[0]]);
				} else {
					$this->load->model('Master_Model');
					$this->db->trans_begin();
					$dbData = $post;

					$respMsg = '';

					$dbFields = $this->Master_Model->getMasterTableFields($masterName);
					$db_keys = (is_array($dbData)) ? array_keys($dbData) : [];

					foreach ($db_keys as $keyName) {
						if (!in_array($keyName, $dbFields)) {
							unset($dbData[trim($keyName)]);
						} else {
							if ($keyName == "customer_email_template") {
								continue;
							} else {
								if (array_key_exists($keyName, $dbData)) {
									$dbData[$keyName] = addslashes(trim(trim($dbData[$keyName])));
								}
							}
						}
					}
					$primaryKey = 'id';

					if (!empty($dbData[$primaryKey])) {
						if (isset($post['password_fields'])) {
							foreach ($post['password_fields'] as $key => $value) {
								if (!empty($dbData[$value])) {
									// $dbData[$value] = md5($post['original_password']);
									$dbData[$value] = $dbData[$value];
								} else {
									unset($dbData[$value]);
								}
							}
						}
					}

					if (empty($dbData[$primaryKey])) {
						$dbData['created_by'] = $this->user_id;
						$dbData['created_date'] = date('Y-m-d H:i:s');
					} else {
						$dbData['modified_by'] = $this->user_id;
						$dbData['modified_date'] = date('Y-m-d H:i:s');
					}

					if ($masterName == "conversation-type") {
						$this->load->library('upload');

						if (!empty($post['name'])) {
							$config['upload_path'] = 'uploads/conversationtypeimages/';
							$config['allowed_types'] = 'jpg|png';
							$config['max_size'] = 2097152;
							$config['max_width'] = 1024;
							$config['max_height'] = 768;
							$fcpath = str_replace("\\", "/", FCPATH);
							$folderPath = $fcpath . 'uploads/conversationtypeimages/';
							$this->upload->initialize($config);
							$attachmentSize = $post['size'];

							if ($attachmentSize > $config['max_size']) {
								throw new Exception("Total size of attachments cannot be greater than 2MB");
							} else {
								$this->upload->do_upload($post['file']);
								$image_parts = explode(";base64,", $post['file']);
								$image_base64 = base64_decode($image_parts[1]);
								$file = $folderPath . $post['name'];
								$dbData['con_type_img'] = $post['name'];

								if (file_put_contents($file, $image_base64)) {
								} else {
									throw new Exception('File Not Uploaded');
								}
							}
						} else {
							if ($post['removeFlag'] == 1) {
								$dbData['con_type_img'] = '';
							} else {
								unset($dbData['con_type_img']);
							}
						}
					}

					if ($masterName == "emailAccount") {
						if (isset($dbData['email']) && strpos($dbData['email'], '*') !== false) {
							unset($dbData['email']);
						}
						if (isset($dbData['incoming_user_name']) && strpos($dbData['incoming_user_name'], '*') !== false) {
							unset($dbData['incoming_user_name']);
						}
						if (isset($dbData['outgoing_user_name']) && strpos($dbData['outgoing_user_name'], '*') !== false) {
							unset($dbData['outgoing_user_name']);
						}
					}
					if (array_key_exists($masterName, $this->tableArr) == 1) {
						switch ($masterName) {

							case 'shift':
								$retarr = $this->Master_Model->saveShift($this->tableArr[$masterName], $dbData, $primaryKey);

								if (empty($dbData[$primaryKey])) {
									$this->fx->generateUserLogs('1', $masterName, $this->name, $this->user_id, $dbData);
								} else {
									$this->fx->generateUserLogs('2', $masterName, $this->name, $this->user_id, $dbData, $dbData[$primaryKey]);
								}
								break;

							case 'pagination':
								if ($dbData['status'] == 0 && $dbData['is_default'] == 1) {
									throw new Exception('Is Default cannot be checked when status is inactive!');
								}
								$retarr = $this->Master_Model->savePagination($this->tableArr[$masterName], $dbData, $primaryKey);

								if (empty($dbData[$primaryKey])) {
									$this->fx->generateUserLogs('1', $masterName, $this->name, $this->user_id, $dbData);
								} else {
									$this->fx->generateUserLogs('2', $masterName, $this->name, $this->user_id, $dbData, $dbData[$primaryKey]);
								}
								break;

							case 'conversation-type':
								$retarr = $this->Master_Model->saveconversationtype($this->tableArr[$masterName], $dbData, $primaryKey);
								if (empty($dbData[$primaryKey])) {
									$this->fx->generateUserLogs('1', $masterName, $this->name, $this->user_id, $dbData);
								} else {
									$this->fx->generateUserLogs('2', $masterName, $this->name, $this->user_id, $dbData, $dbData[$primaryKey]);
								}
								break;

							default:

								$retarr = $this->Master_Model->saveProcess($masterName, $dbData, $primaryKey);

								if (empty($dbData[$primaryKey])) {
									$this->fx->generateUserLogs('1', $masterName, $this->name, $this->user_id, $dbData);
								} else {
									$this->fx->generateUserLogs('2', $masterName, $this->name, $this->user_id, $dbData, $dbData[$primaryKey]);
								}
								break;
						}
						if (empty($retarr['id'])) {
							throw new Exception($retarr['message']);
						} else {
							$master_title = str_replace('_', ' ', $masterName);
							$master_title = ucwords(strtolower($master_title));
							$respMsg = !empty($post[$primaryKey]) ? $master_title . ' details updated successfully' : $master_title . ' details saved successfully';
						}

						if ($this->db->trans_status() === FALSE) {
							$this->db->trans_rollback();
							throw new Exception('Something goes wrong');
						} else {
							$this->db->trans_commit();
							$this->api_response(['success' => true, 'status_code' => 200, 'message' => $respMsg], 200);
						}
					} else {
						throw new Exception('Invalid Master Name');
					}
				}
			} else {
				throw new Exception('Invalid Master Name');
			}
		} catch (Exception $e) {

			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $e->getMessage()], 400);
		}
	}

	public function updateAssignTicket()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['selectedTicketForAssign'] && !empty($post['selectedUserIdForAssign']))) {
			$dbData = $post;
			$dbData['assigned_by'] = $this->user_id;
			$dbData['assigned_on'] = date('Y-m-d H:i:s');
			$retarr = $this->Api_Model->updateAssignTicket($dbData);
			if (isset($retarr['error'])) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $retarr['message']], 400);
			}
			if ($retarr) {
				$this->response(TRUE, "Ticket Assigned Successfully", 200);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Error'], 400);
			}
		}
	}

	function addUpdateRuleMaster()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['master_name'])) {
			$masterName = $post['master_name'];
			$this->load->model('Master_Model');
			$rules = $this->Master_Model->getMasterTableRules($masterName);
			if (empty($rules)) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validations not defined.'], 400);
				return;
			}



			$myArray = json_decode(json_encode($post['conditionArray'][0]), true);
			$key = (is_array($myArray)) ? array_keys($myArray) : [];
			$myArray1 = json_decode(json_encode($post['actionArray'][0]), true);
			$key1 = (is_array($myArray1)) ? array_keys($myArray1) : [];


			foreach ($post['conditionArray'] as $val) {
				foreach ($key as $values) {
					if ($val->$values == '') {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => ucfirst($values) . ' Fields is Required.'], 400);
						return;
					}
				}
			}

			foreach ($post['actionArray'] as $val) {
				foreach ($key1 as $values) {
					if ($val->$values == '') {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => ucfirst($values) . ' Fields is Required.'], 400);
						return;
					}
				}
			}


			$this->form_validation->set_data($post);
			$this->form_validation->set_message('unique_module', 'Module already in use');
			$this->form_validation->set_rules($rules);
			if ($this->form_validation->run() === false) {
				$data = $this->form_validation->error_array();
				$firstError = (is_array($data)) ? array_keys($data) : [];
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validation Error', 'result' => $data[$firstError[0]]], 400);
			} else {
				$this->load->model('Master_Model');
				$this->db->trans_begin();
				$dbData = $post;


				$respMsg = '';
				$dbFields = $this->Master_Model->getMasterTableFields($masterName);
				$db_keys = (is_array($dbData)) ? array_keys($dbData) : [];
				foreach ($db_keys as $keyName) {
					if (!in_array($keyName, $dbFields)) {
						unset($dbData[$keyName]);
					} else {
						if (array_key_exists($keyName, $dbData)) {
							$dbData[$keyName] = addslashes(trim($dbData[$keyName]));
						}
					}
				}

				$primaryKey = 'id';

				if (empty($dbData[$primaryKey])) {
					$dbData['created_by'] = $this->user_id;
					$dbData['created_date'] = date('Y-m-d H:i:s');
				} else {
					// if (empty($dbData['created_by'])) {
					// 	$dbData['created_by'] = $this->user_id;
					// 	$dbData['created_date'] = date('Y-m-d H:i:s');
					// }
					$dbData['modified_by'] = $this->user_id;
					$dbData['modified_date'] = date('Y-m-d H:i:s');
				}

				if (array_key_exists($masterName, $this->tableArr) == 1) {
					switch ($masterName) {
						case 'rule':
							$retarr = $this->Master_Model->saverule($masterName, $dbData, $primaryKey, $post);
							break;

						default:
							$retarr = $this->Master_Model->saveProcess($masterName, $dbData, $primaryKey, $post);
							break;
					}
					if (empty($retarr['id'])) {
						$respMsg = 'Something goes wrong.';
					} else {
						$master_title = str_replace('_', ' ', $masterName);
						$master_title = ucwords(strtolower($master_title));
						$respMsg = !empty($post[$primaryKey]) ? $master_title . ' details updated successfully' : $master_title . ' details saved successfully';
					}
					if ($this->db->trans_status() === FALSE) {
						$this->db->trans_rollback();
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
					} else {
						$this->db->trans_commit();
						$this->response(TRUE, $respMsg, 200);
					}
				} else {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Master Name'], 400);
				}
			}
		}
	}


	function addUpdateQueueMaster()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		if ($post['footer_name'] == null) {
			$post['footer_name'] = $post['hiddenimg'];
		}
		if (isset($post['catagory'][0])) {
			$post['catagory'] = (is_array($post['catagory']) ? implode(',', $post['catagory']) : $post['catagory']);
		} else {
			$post['catagory'] = null;
		}
		if (isset($post['statustype'][0])) {
			$post['statustype'] = (is_array($post['statustype']) ? implode(',', $post['statustype']) : $post['statustype']);
		} else {
			$post['statustype'] = null;
		}
		if (!empty($post['master_name'])) {
			$masterName = $post['master_name'];
			$this->load->library('upload');


			if (!empty($post['name'])) {
				$post['footer_name'] = $post['name'];
			}

			$this->load->model('Master_Model');
			$rules = $this->Master_Model->getMasterTableRules($masterName);
			if (empty($rules)) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validations not defined.'], 400);
				return;
			}
			$myArray = json_decode(json_encode($post['emailArray'][0]), true);
			$key = (is_array($myArray)) ? array_keys($myArray) : [];
			foreach ($post['emailArray'] as $val) {
				foreach ($key as $values) {
				}
			}
			$this->form_validation->set_data($post);
			$this->form_validation->set_message('unique_module', 'Module already in use');
			$this->form_validation->set_rules($rules);
			if ($this->form_validation->run() === false) {
				$data = $this->form_validation->error_array();
				$firstError = (is_array($data)) ? array_keys($data) : [];
				array_keys($data);
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validation Error', 'result' => $data[$firstError[0]]], 400);
			} else {
				$this->load->model('Master_Model');
				$this->db->trans_begin();
				$dbData = $post;
				$respMsg = '';
				$dbFields = $this->Master_Model->getMasterTableFields($masterName);
				$db_keys = (is_array($dbData)) ? array_keys($dbData) : [];
				foreach ($db_keys as $keyName) {
					if (!in_array($keyName, $dbFields)) {
						unset($dbData[$keyName]);
					} else {
						if (array_key_exists($keyName, $dbData)) {
							$dbData[$keyName] = addslashes(($dbData[$keyName]));
						}
					}
				}

				$primaryKey = 'id';

				if (empty($dbData[$primaryKey])) {
					$dbData['created_by'] = $this->user_id;
					$dbData['created_date'] = date('Y-m-d H:i:s');
				} else {
					$dbData['modified_by'] = $this->user_id;
					$dbData['modified_date'] = date('Y-m-d H:i:s');
				}

				if (isset($dbData['closing_mail']) && strpos($dbData['closing_mail'], '*') !== false) {
					unset($dbData['closing_mail']);
				}
				if (isset($dbData['block_email_for_ticket_generate']) && strpos($dbData['block_email_for_ticket_generate'], '*') !== false) {
					unset($dbData['block_email_for_ticket_generate']);
				}
				if (isset($dbData['block_email_for_auto_reply']) && strpos($dbData['block_email_for_auto_reply'], '*') !== false) {
					unset($dbData['block_email_for_auto_reply']);
				}
				if (isset($dbData['block_domains_for_ticket_generate']) && strpos($dbData['block_domains_for_ticket_generate'], '*') !== false) {
					unset($dbData['block_domains_for_ticket_generate']);
				}
				if (isset($dbData['block_domains_for_auto_reply']) && strpos($dbData['block_domains_for_auto_reply'], '*') !== false) {
					unset($dbData['block_domains_for_auto_reply']);
				}
				if ($post['removeFlag'] == 1) {
					$post['footer_name'] = '';
					$post['footer_image_width'] = '';
					$dbData['footer_name'] = '';
					$dbData['footer_image_width'] = '';
				}
				if (!empty($dbData[$primaryKey])) {

					if ($dbData['bulk_escalation_timing'] && $this->compareTimes($this->Master_Model->bulk_escalation_timing($dbData[$primaryKey]), $dbData['bulk_escalation_timing']) != 1) {
						$job_path = 'http://localhost:3000/bulkEscalation';

						$job_time = $this->timeToCron($dbData['bulk_escalation_timing']);
						foreach ($this->getCronJobs() as $index => $element) {
							if (strpos($element, $job_path) !== false) {
								$this->deleteCronJob($index);
							}
						}
						$this->addCronJob("$job_time curl $job_path");
					}
				} else {
					if ($dbData['bulk_escalation_timing']) {
						$job_path = 'http://localhost/api/api';
						$job_time = $this->timeToCron($dbData['bulk_escalation_timing']);
						$this->addCronJob("$job_time curl $job_path");
					}
				}

				if (array_key_exists($masterName, $this->tableArr) == 1) {
					$retarr = $this->Master_Model->savequeue($masterName, $dbData, $primaryKey, $post);
					if (empty($dbData[$primaryKey])) {
						$this->fx->generateUserLogs('1', $masterName, $this->name, $this->user_id, $dbData);
					} else {
						$this->fx->generateUserLogs('2', $masterName, $this->name, $this->user_id, $dbData, $dbData[$primaryKey]);
					}
					if (empty($retarr['id'])) {
						$respMsg = 'Something goes wrong.';
					} else {
						if (!empty($post['name'])) {
							$config['upload_path'] = 'uploads/queuefooter/queuefooter_' . $retarr['id'] . '/';
							$config['allowed_types'] = 'jpg|png';
							$config['max_size'] = 2097152;
							$config['max_width'] = 1024;
							$config['max_height'] = 768;
							$fcpath = str_replace("\\", "/", FCPATH);
							$todayfolderPath = 'uploads/queuefooter/queuefooter_' . $retarr['id'] . '/';
							if (!is_dir($todayfolderPath)) {
								mkdir($todayfolderPath, 0777, true);
							}
							$this->upload->initialize($config);
							$attachmentSize = $post['size'];
							if ($attachmentSize > $config['max_size']) {
								throw new Exception("Total size of attachments cannot be greater than 2MB");
							} else {
								$this->upload->do_upload($post['file']);
								$image_parts = explode(";base64,", $post['file']);
								$image_base64 = base64_decode($image_parts[1]);
								$file = $todayfolderPath . $post['name'];
								$post['footer_name'] = $post['name'];

								if (file_put_contents($file, $image_base64)) {
								} else {
									throw new Exception('File Not Uploaded');
								}
							}
						} else {
							if ($post['removeFlag'] == 1) {
								unset($post['footer_name']);
								unset($post['footer_image_width']);
							} else {
								$post['footer_name'] = '';
								$post['footer_image_width'] = '';
							}
						}
						$master_title = str_replace('_', ' ', $masterName);
						$master_title = ucwords(strtolower($master_title));
						$respMsg = !empty($post[$primaryKey]) ? $master_title . ' details updated successfully' : $master_title . ' details saved successfully';
					}
					if ($this->db->trans_status() === FALSE) {
						$this->db->trans_rollback();
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
					} else {
						$this->db->trans_commit();
						$this->response(TRUE, $respMsg, 200);
					}
				} else {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Master Name'], 400);
				}
			}
		}
	}

	function addUpdateQueueCategory()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		// print_r($post['default']);die;
		if (!empty($post['master_name'])) {
			$masterName = "tms_queue_category_$post[queue_id]";
			$this->load->model('Master_Model');

			$categoryArray = json_decode(json_encode($post['subCategoryResult'][0]), true);
			// print_r($categoryArray);die;
			$categorykey = (is_array($categoryArray)) ? array_keys($categoryArray) : [];
			unset($categorykey[1]);
			unset($categorykey[2]);
			$is_sub_category_default = 0;

			// foreach ($post['subCategoryResult'] as $categoryVal) {
			// 	if ($post['default'] && $categoryVal->default) {
			// 		$is_sub_category_default++;
			// 	}

			// 	foreach ($categorykey as $values) {
			// 		// print_r($value);die;
			// 		if ($categoryVal->$values == '') {
			// 			$this->api_response(['success' => false, 'status_code' => 400, 'message' => ucfirst($values) . ' Fields is Required.'], 400);
			// 			return;
			// 		}
			// 	}
			// }


			$has_default = false; // Initialize the default flag
			$is_sub_category_default = 0; // Initialize the count of default subcategories

			// print_r($post);die;
			foreach ($post['subCategoryResult'] as $categoryVal) {
				// Check if the current subcategory is marked as default
				if ($post['default'] || $categoryVal->default) {
					$is_sub_category_default++;
					$has_default = true; // Set the flag to true if a default is found
				}
			}
			// print_r($has_default);die;
			// Only check for required fields if no default subcategory is found
			if (!$has_default) {
				foreach ($categorykey as $values) {
					// Check if any required field is empty
					foreach ($post['subCategoryResult'] as $categoryVal) {
						if ($categoryVal->$values == '') {
							$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Sub Category ' . ucfirst($values) . ' Field is Required.'], 400);
							return;
						}
					}
				}
			}

			if ($post['default'] && !($is_sub_category_default > 0 && $is_sub_category_default < 2)) {

				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Please select at least one default category'], 400);
			}

			if ($post['default'] && !$post['status']) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Is Default cannot be checked when status is inactive!'], 400);
			}

			// foreach ($post['subCategoryResult'] as   $categoryVal) {
			// 	foreach ($categorykey as $values) {
			// 		if ($categoryVal->$values == '') {
			// 			$this->api_response(['success' => false, 'status_code' => 400, 'message' =>   ucfirst($values) . ' Fields is Required.'], 400);
			// 			return;
			// 		}
			// 	}
			// }
			$this->form_validation->set_data($post);
			$queue = $this->Master_Model->getresult('tms_queue_master', "id = $post[queue_id]");
			// print_r($queue);die;
			// $checkCategoryMandetory = $this->Master_Model->checkCategoryMandetory($post['queue_id']);
			// if(empty($checkCategoryMandetory)){

			// }
			$rules = array(
				array(
					'field' => 'queue_id',
					'label' => 'Queue Id',
					'rules' => 'required'
				),
				array(
					'field' => 'category_name',
					'label' => 'Category Name',
					'rules' => 'trim|required'
				),
			);
			if ($queue['mandatory_category']) {
				array_push($rules, array(
					'field' => 'default',
					'label' => 'Default',
					'rules' => 'trim|callback_checkRequiredCategory'
				));
			}
			// print_r('here');die;
			$this->form_validation->set_rules($rules);
			$this->form_validation->set_message('checkRequiredCategory', 'The Category Default required');
			if ($this->form_validation->run() == false) {
				$data = $this->form_validation->error_array();
				$firstError = (is_array($data)) ? array_keys($data) : [];
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validation Error', 'result' => $data[$firstError[0]]], 400);
				return;
			}
			$this->load->model('Master_Model');
			$dbFields = $this->Master_Model->getQueueFields($masterName);

			$this->db->trans_begin();
			$dbData = $post;
			$respMsg = '';
			$dbFields = $this->Master_Model->getQueueFields($masterName);
			$db_keys = (is_array($dbData)) ? array_keys($dbData) : [];
			foreach ($db_keys as $keyName) {
				if (!in_array($keyName, $dbFields)) {
					unset($dbData[$keyName]);
				} else {
					if (array_key_exists($keyName, $dbData)) {
						$dbData[$keyName] = addslashes(trim(trim($dbData[$keyName])));
					}
				}
			}
			$respMsg = '';
			$primaryKey = 'category_id';
			// $checkDefault = $this->Master_Model->checkDefaultCategory();
			$retarr = $this->Master_Model->saveQueueCategoryData($masterName, $pKey = 'category_id', $post, $dbData);
			if ($retarr['error']) {
				$respMsg = $retarr['message'];
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respMsg], 400);
			} else {
				if (empty($dbData[$primaryKey])) {
					$this->fx->generateUserLogs('1', 'Queue Category', $this->name, $this->user_id, $dbData);
				} else {
					$this->fx->generateUserLogs('2', 'Queue Category', $this->name, $this->user_id, $dbData, $post[$pKey]);
				}
				$master_title = "Queue Category";
				$respMsg = !empty($post[$primaryKey]) ? $master_title . ' details updated successfully' : $master_title . ' details saved successfully';
			}
			if ($this->db->trans_status() === FALSE) {
				$this->db->trans_rollback();
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
			} else {
				$this->db->trans_commit();
				$this->response(TRUE, $respMsg, 200);
			}
		}
	}

	function checkRequiredCategory()
	{
		$post = (array) json_decode(file_get_contents('php://input'));

		$tableName = "tms_queue_category_$post[queue_id]";
		if (!empty($post['category_id'])) {
			$is_exist = $this->db->where('default', 1)->where_not_in('category_id', array(trim($post['category_id'])))->get($tableName)->row_array();
		} else {
			$is_exist = $this->db->where('default', 1)->get($tableName)->row_array();
		}


		if ($is_exist && $post['default']) {
			$data = array(
				'default' => '0',
			);

			$this->db->where('default', 1)
				->where_not_in('category_id', array(trim($post['category_id'])))
				->update($tableName, $data);
		}
		if (!$is_exist) {
			if ($post['default']) {
				return true;
			} else {
				return false;
			}
		}

		// return ($is_exist) ? true : false;
	}

	public function addUpdateQueuePriority()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['master_name'])) {
			$masterName = $post['master_name'];
			$this->load->model('Master_Model');
			$priorityArray = json_decode(json_encode($post['priorityArray'][0]), true);
			$prioritykey = (is_array($priorityArray)) ? array_keys($priorityArray) : [];
			unset($prioritykey[0]);
			unset($prioritykey[5]);
			foreach ($post['priorityArray'] as $priorityVal) {
				foreach ($prioritykey as $values) {
					if ($values == "search_tat_time") {
						continue;
					} else if ($priorityVal->$values == '') {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => ucfirst($values) . ' Fields is Required.'], 400);
						return;
					}
				}
			}
			$this->load->model('Master_Model');
			$this->db->trans_begin();
			$respMsg = '';
			$primaryKey = 'category_id';
			$priority_id = $post['priorityArray'];
			$id = [];
			foreach ($priority_id as $priority) {
				$id[] = $priority->priority_id;
			}
			$idString = (is_array($id) ? implode(',', $id) : $id);

			$retarr = $this->Master_Model->saveQueuePriorityData($post, $masterName);
			$error = $this->db->error();
			// $this->db->error()
			$this->fx->generateUserLogs('2', 'Queue Priority', $this->name, $this->user_id, $post, $idString);

			if ($retarr['error']) {
				if ($this->db->error()['code'] == 1451) {
					$respMsg = $this->db->error()['message'];
				} else {
					$respMsg = 'Something goes wrong.';
				}
			} else {
				$master_title = "Queue Priority";
				$respMsg = !empty($post[$primaryKey]) ? $master_title . ' details updated successfully' : $master_title . ' details saved successfully';
			}

			if ($this->db->trans_status() === FALSE) {
				if ($error['code'] == 1451) {
					$respMsg = $error['message'];
				} else {
					$respMsg = 'Something goes wrong.';
				}
				$this->db->trans_rollback();
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respMsg], 400);
			} else {
				$this->db->trans_commit();
				$this->response(TRUE, $respMsg, 200);
			}
		}
	}

	public function addUpdateQueueStatus()
	{

		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		$queueId = $post['queue_id'];
		$post = $post['data'];
		if (!empty($post->master_name)) {
			$masterName = $post->master_name;
			$this->load->model('Master_Model');
			$statusArray = json_decode(json_encode($post->statusArray[0]), true);
			$statuskey = (is_array($statusArray)) ? array_keys($statusArray) : [];

			unset($statuskey[0]);
			unset($statuskey[0]);
			unset($statuskey[5]);
			unset($statuskey[6]);
			unset($statuskey[7]);
			unset($statuskey[8]);
			unset($statuskey[9]);
			unset($statuskey[10]);
			unset($statuskey[11]);
			unset($statuskey[12]);
			unset($statuskey[13]);
			unset($statuskey[14]);
			foreach ($post->statusArray as $statusVal) {
				foreach ($statuskey as $values) {
					// if ($statusVal->$values == '') {
					// 	$this->api_response(['success' => false, 'status_code' => 400, 'message' =>   ucfirst($values) . ' Fields is Required.'], 400);
					// 	return;
					// }
				}
			}
			$this->load->model('Master_Model');
			$this->db->trans_begin();
			$respMsg = '';
			$primaryKey = 'status_id';
			$status_id = $post->statusArray;
			$id = [];
			foreach ($status_id as $status) {
				$id[] = $status->status_id;
			}
			$idString = (is_array($id) ? implode(',', $id) : $id);
			$retarr = $this->Master_Model->saveQueueStatusData($post, $masterName, 'status_id', $queueId);

			$this->fx->generateUserLogs('2', 'Queue Status', $this->name, $this->user_id, $post, $idString);
			if ($retarr['error']) {
				if ($retarr['message'] != '') {
					$respMsg = $retarr['message'];
				} else {
					$respMsg = 'Something goes wrong.';
				}
			} else {
				$master_title = "Queue Status";
				$respMsg = !empty($post->$primaryKey) ? $master_title . ' details updated successfully' : $master_title . ' details saved successfully';
			}
			if ($this->db->trans_status() === FALSE) {
				$this->db->trans_rollback();

				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respMsg], 400);
			} else {
				$this->db->trans_commit();
				$this->response(TRUE, $respMsg, 200);
			}
		}
	}

	public function addUpdateQueueEscalation()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['master_name'])) {
			$masterName = $post['master_name'];
			$this->load->model('Master_Model');
			$escalationArray = json_decode(json_encode($post['escalationArray'][0]), true);
			$escalationkey = (is_array($escalationArray)) ? array_keys($escalationArray) : [];
			unset($escalationkey[0]);
			unset($escalationkey[7]);
			unset($escalationkey[8]);
			unset($escalationkey[9]);
			unset($escalationkey[10]);
			unset($escalationkey[11]);


			foreach ($post['escalationArray'] as $key => $val) {
				if ((!empty($val->send_email_agent) && $val->send_email_agent > 0) && ($val->agent_template_id == 0 || empty($val->agent_template_id))) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Please select agent template'], 400);
				}
			}

			$this->db->trans_begin();
			$respMsg = '';
			$primaryKey = 'escalation_id';
			$primaryKey = 'escalation_id';
			// fx::pr($post, 1);
			$escalation_id = $post['escalationArray'];
			$id = [];
			foreach ($escalation_id as $escalation) {
				$id[] = $escalation->id;
			}
			$idString = (is_array($id) ? implode(',', $id) : $id);

			$retarr = $this->Master_Model->saveQueueEscalationData($post, $masterName);

			$this->fx->generateUserLogs('2', 'Queue Escalation', $this->name, $this->user_id, $post, $idString);
			if ($retarr['error']) {
				$respMsg = 'Something goes wrong.';
			} else {
				$master_title = "Queue Escalation Matrix";
				$respMsg = !empty($post[$primaryKey]) ? $master_title . ' details updated successfully' : $master_title . ' details saved successfully';
			}
			if ($this->db->trans_status() === FALSE) {
				$this->db->trans_rollback();
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
			} else {
				$this->db->trans_commit();
				$this->response(TRUE, $respMsg, 200);
			}
		}
	}

	public function addUpdateQueueStatusSetting()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['master_name'])) {
			$masterName = $post['master_name'];


			$statusSettingArray = json_decode(json_encode($post['statusSettingArray'][0]), true);
			$statusSettingkey = (is_array($statusSettingArray)) ? array_keys($statusSettingArray) : [];

			$this->db->trans_begin();
			$respMsg = '';
			$primaryKey = 'id';
			$primaryKey = 'id';
			$statusSetting_id = $post['statusSettingArray'];
			$id = [];
			foreach ($statusSetting_id as $escalation) {
				$id[] = $escalation->escalation_id;
			}
			$idString = (is_array($id) ? implode(',', $id) : $id);

			$retarr = $this->Master_Model->saveQueueStatusSettingData($post, $masterName);

			$this->fx->generateUserLogs('2', 'Queue Status Setting', $this->name, $this->user_id, $post, $idString);
			if ($retarr['error']) {
				$respMsg = 'Something goes wrong.';
			} else {
				$master_title = "Queue Status Setting ";
				$respMsg = !empty($post[$primaryKey]) ? $master_title . ' details updated successfully' : $master_title . ' details saved successfully';
			}
			if ($this->db->trans_status() === FALSE) {
				$this->db->trans_rollback();
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
			} else {
				$this->db->trans_commit();
				$this->response(TRUE, $respMsg, 200);
			}
		}
	}

	public function addUpdateQueueRules()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['master_name'])) {
			$masterName = $post['master_name'];
			$this->load->model('Master_Model');
			$ruleConditionArray = json_decode(json_encode($post['conditionArray'][0]), true);
			$conditionkey = (is_array($ruleConditionArray)) ? array_keys($ruleConditionArray) : [];
			$ruleActionArray1 = json_decode(json_encode($post['actionArray'][0]), true);
			$actionkey = (is_array($ruleActionArray1)) ? array_keys($ruleActionArray1) : [];

			foreach ($post['conditionArray'] as $val) {
				foreach ($conditionkey as $values) {
					if ($val->$values == '') {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => ucfirst($values) . ' Fields is Required.'], 400);
						return;
					}
				}
			}

			foreach ($post['actionArray'] as $val) {
				foreach ($actionkey as $values) {
					if ($val->$values == '') {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => ucfirst($values) . ' Fields is Required.'], 400);
						return;
					}
				}
			}
			$this->load->model('Master_Model');
			$rules = $this->Master_Model->getMasterTableRules($masterName);
			if (empty($rules)) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validations not defined.'], 400);
				return;
			}
			$this->form_validation->set_data($post);
			$this->form_validation->set_message('unique_module', 'Module already in use');
			$this->form_validation->set_rules($rules);
			if ($this->form_validation->run() === false) {
				$data = $this->form_validation->error_array();
				$key = (is_array($data)) ? array_keys($data) : [];
				$err[] = $data[$key[0]];
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validation Error', 'result' => $err], 400);
			} else {

				$this->db->trans_begin();

				$dbData = $post;

				$respMsg = '';
				$dbFields = $this->Master_Model->getQueueFields($masterName);

				$db_keys = (is_array($dbData)) ? array_keys($dbData) : [];
				foreach ($db_keys as $keyName) {
					if (!in_array($keyName, $dbFields)) {
						unset($dbData[$keyName]);
					} else {
						if (array_key_exists($keyName, $dbData)) {
							$dbData[$keyName] = addslashes(trim(trim($dbData[$keyName])));
						}
					}
				}
				$respMsg = '';
				$primaryKey = 'rule_id';
				$orderno = $post['order_no'];
				if ($orderno == 0) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Order No cant be zero !'], 400);
				}

				$retarr = $this->Master_Model->saveQueueRuleData($masterName, $pKey = 'rule_id', $post, $dbData);
				if ($retarr['error']) {
					$respMsg = $retarr['error'];
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respMsg], 400);
				} else {
					if (empty($dbData[$primaryKey])) {
						$this->fx->generateUserLogs('1', 'Queue Incomming Rule', $this->name, $this->user_id, $dbData);
					} else {
						$this->fx->generateUserLogs('2', 'Queue Incomming Rule', $this->name, $this->user_id, $dbData, $post[$pKey]);
					}
					$master_title = "Queue Rule";
					$respMsg = !empty($post[$primaryKey]) ? $master_title . ' details updated successfully' : $master_title . ' details saved successfully';
				}
				if ($this->db->trans_status() === FALSE) {
					$this->db->trans_rollback();
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
				} else {
					$this->db->trans_commit();
					$this->response(TRUE, $respMsg, 200);
				}
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Request'], 400);
		}
	}

	public function addUpdateQueueAssignRules()
	{
		try {
			$token = $this->input->post('token');
			$this->get_loginsession($this->input->post('loginsession'));
			if ($token == "") {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
				return;
			}
			if ($this->setData($token) == false)
				return;

			$post = (array) json_decode(file_get_contents('php://input'));

			if (!empty($post['master_name'])) {
				$masterName = $post['master_name'];
				$ruleConditionArray = json_decode(json_encode($post['conditionArray'][0]), true);
				$conditionkey = (is_array($ruleConditionArray)) ? array_keys($ruleConditionArray) : [];
				array_keys($ruleConditionArray);
				$ruleActionArray1 = json_decode(json_encode($post['actionArray'][0]), true);
				$actionkey = (is_array($ruleActionArray1)) ? array_keys($ruleActionArray1) : [];


				foreach ($post['conditionArray'] as $val) {
					foreach ($conditionkey as $values) {
						if ($values == "search_evaluate_on") {
							continue;
						} else if ($val->$values == '') {
							$this->api_response(['success' => false, 'status_code' => 400, 'message' => ucfirst($values) . ' Fields is Required.'], 400);
							return;
						}
					}
				}
				foreach ($post['actionArray'] as $val) {
					foreach ($actionkey as $values) {
						if ($val->$values == '') {
							$this->api_response(['success' => false, 'status_code' => 400, 'message' => ucfirst($values) . ' Fields is Required.'], 400);
							return;
						}
					}
				}
				$this->load->model('Master_Model');
				$rules = $this->Master_Model->getMasterTableRules($masterName);
				if (empty($rules)) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validations not defined.'], 400);
					return;
				}
				$this->form_validation->set_data($post);
				$this->form_validation->set_message('unique_module', 'Module already in use');
				$this->form_validation->set_rules($rules);
				if ($this->form_validation->run() === false) {
					$data = $this->form_validation->error_array();
					$key = (is_array($data)) ? array_keys($data) : [];
					$err[] = $data[$key[0]];
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validation Error', 'result' => $err], 400);
				} else {
					$this->db->trans_begin();

					$dbData = $post;

					$respMsg = '';
					$dbFields = $this->Master_Model->getQueueFields($masterName);

					$db_keys = (is_array($dbData)) ? array_keys($dbData) : [];
					foreach ($db_keys as $keyName) {
						if (!in_array($keyName, $dbFields)) {
							unset($dbData[$keyName]);
						} else {
							if (array_key_exists($keyName, $dbData)) {
								$dbData[$keyName] = addslashes(trim(trim($dbData[$keyName])));
							}
						}
					}
					$respMsg = '';
					$primaryKey = 'assign_rule_id';
					$orderno = $post['order_no'];
					if ($orderno == 0) {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Order No cant be zero !'], 400);
					}

					$retarr = $this->Master_Model->saveQueueAssignRuleData($masterName, $pKey = 'assign_rule_id', $post, $dbData);
					if ($retarr['error']) {
						$respMsg = $retarr['error'];
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respMsg], 400);
					} else {
						if (empty($dbData[$primaryKey])) {
							$this->fx->generateUserLogs('1', 'Queue Manual Rule', $this->name, $this->user_id, $dbData);
						} else {
							$this->fx->generateUserLogs('2', 'Queue Manual Rule', $this->name, $this->user_id, $dbData, $post[$pKey]);
						}
						$master_title = "Manual Ticket Rules";
						$respMsg = !empty($post[$primaryKey]) ? $master_title . ' details updated successfully' : $master_title . ' details saved successfully';
					}
					if ($this->db->trans_status() === FALSE) {
						$this->db->trans_rollback();
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
					} else {
						$this->db->trans_commit();
						$this->response(TRUE, $respMsg, 200);
					}
				}
			}
		} catch (Exception $e) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'An error occurred: ' . $e->getMessage()], 400);
		}
	}


	public function fatchconversationdata()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		$mainDirectory = NODE_APP_PATH;
		$searchText = trim($post['search_text']);

		$matchingFiles = [];

		$startDateTimestamp = strtotime($post['search_data']->created_date_from);
		$endDateTimestamp = strtotime($post['search_data']->created_date_to);

		$dateFolders = glob($mainDirectory . '/*');
		foreach ($dateFolders as $dateFolder) {

			if (!is_dir($dateFolder)) {
				continue; // Skip if not a directory
			}
			$folderDate = basename($dateFolder);
			$folderDateTimestamp = strtotime($folderDate);

			if ($folderDateTimestamp >= $startDateTimestamp && $folderDateTimestamp <= $endDateTimestamp) {  // Skip folder which is outside of the date range.

				$keyFiles = glob($dateFolder . '/*');
				foreach ($keyFiles as $key => $jsonFolder) {
					if (!is_dir($jsonFolder)) {
						continue; // Skip if not a directory
					}
					$jsonFiles = glob($jsonFolder . '/*');

					foreach ($jsonFiles as $jsonFile) {
						if (!is_file($jsonFile)) {
							continue; // Skip if not a regular file
						}
						$jsonString = file_get_contents($jsonFile);
						$fileContentBase64 = json_decode($jsonString, true);
						if (isset($fileContentBase64['bodyData']) && $fileContentBase64['bodyData'] != null) {

							$fileContent = base64_decode($fileContentBase64['bodyData']);
						}
						$decodedContent = strip_tags(html_entity_decode($fileContent));


						$str = str_replace('"', "", $decodedContent);
						// $search = str_replace('"', "", $searchText);

						// $search = preg_quote($searchText, '/');
						// $pattern = "/\b$search\b/i";
						$search = strip_tags(html_entity_decode($post['search_text']));
						$search = <<<SRC
$searchText
SRC;

						$str = <<<EOT
$decodedContent 
EOT;
						if (strstr($str, $search) || stripos($str, $search) !== false) {

							// echo "match";
							// echo "Match found in file: " . basename($jsonFile) . "\n";die;
							$matchingFiles[] = basename($jsonFile);
						}

						// error_reporting(E_ALL);
						// if (stripos($str,$search) !== false) {
						// 	$matchingFiles[] = basename($jsonFile);
						// }
					}
				}
			}
		}
		if (empty($matchingFiles)) {
			$this->response(TRUE, '', 200, []);
		}
		$retData = $this->Api_Model->fatchconversationdata(
			$post['queue_id'],
			$matchingFiles
		);
		$this->response(TRUE, '', 200, $retData);
	}


	public function fatchmail()
	{


		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));

		$retData = $this->Api_Model->fatchmail(
			$post['queue_id'],
			trim($post['search_text']),
			$post['key']
		);
		$this->response(TRUE, '', 200, $retData);
	}


	public function addTicketData($movedata = null)
	{
		if (is_array($movedata) && (count($movedata) > 0)) {
			$post = $movedata;
		} else {
			$token = $this->input->post('token');
			$this->get_loginsession($this->input->post('loginsession'));
			if ($token == "") {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
				return;
			}
			if ($this->setData($token) == false)
				return;
			$post = (array) json_decode(file_get_contents('php://input'));

			$mergedObject = (object) array_merge((array) $post['ticketData'], (array) $post['dynamicData']);
			$post['ticketData'] = $mergedObject;
			unset($post['dynamicData']);
			$post = json_decode(json_encode($post['ticketData']), true);
		}
		// if (is_array($movedata) && (count($movedata) > 0)) {
		// 	$post = $movedata;
		// } else {
		// 	$post = json_decode(json_encode($post['ticketData']), true);
		// }
		// $queue_name =  $this->Master_Model->getScalerCol("queue", "tms_queue_master", "id = $post[queue_id]")->queue;
		// create email_msg_id start here
		// $outgoing_mail_server = $this->Master_Model->getScalerCol("outgoing_mail_server", "tms_email_account t1", "1=1 and t1.email = '$post[from_email]'")->outgoing_mail_server;

		// $uuid = md5(uniqid('', true));

		// $uuid = "<".substr($uuid, 0, 8) .'-'. substr($uuid, 8,4) .'-'.  substr($uuid, 12,4) .'-'.  substr($uuid, 16,4) .'-'. substr($uuid, 20).'@'.$outgoing_mail_server.">";

		// $post['uuid'] = $uuid;

		// create email_msg_id start here
		$post['uuid'] = $this->fx->generateEmailUnqMsgId($post['from_email']);
		// create email_msg_id ends here
		if (!empty($post['master_name'])) {
			$primaryKey = 'ticket_unique_id';
			$masterName = $post['master_name'];
			$this->load->model('Master_Model');
			$rules = $this->Master_Model->getTicketTableRules();

			if (empty($rules)) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validations not defined.'], 400);
				return;
			}
			$this->load->library('Dynamicformcontent');

			$dynrules = $this->dynamicformcontent->getDynamicFieldValidationArray($post['queue_id'], $post['master_name'], isset($post[$primaryKey]) ? $post[$primaryKey] : 0);
			$rules = array_merge($rules, $dynrules);

			$this->form_validation->set_data($post);

			$this->form_validation->set_message('unique_module', 'Module already in use');
			$this->form_validation->set_rules($rules);
			if ($this->form_validation->run() === false) {
				$data = $this->form_validation->error_array();
				$firstError = (is_array($data)) ? array_keys($data) : [];
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validation Error', 'result' => $data[$firstError[0]]], 400);
			} else {
				// save attachment in folder with the name email_msg_id start here
				$post['msg_id'] = $this->fx->generateMsgId($post['uuid']);
				// $attachGolderName = explode('@',preg_replace("/[<>\-.]/", '', $post['uuid']));
				// $msgId = $attachGolderName[0];
				// $post['msg_id'] = $msgId;
				$this->load->library('upload');

				if (is_array($post['attachmentArray']) && (count($post['attachmentArray'])) > 0) {
					// $path = $_SERVER["DOCUMENT_ROOT"] . '/mailread/mail_attachment_folder/' . $post['msg_id'];
					$todayfolderPath = NODE_APP_PATH . date("Y-m-d") . '/';
					if (!is_dir($todayfolderPath)) {
						mkdir($todayfolderPath, 0777, true);
					}
					chmod($todayfolderPath, 0777);
					$path = $todayfolderPath . '/' . $post['msg_id'];
					if (!is_dir($path)) {
						mkdir($path, 0777, true);
					}
					chmod($path, 0777);
					$post['path'] = date("Y-m-d") . '/' . $post['msg_id'];
					$config['upload_path'] = $path;
					$config['allowed_types'] = 'gif|jpg|png|pdf|xls|xlsx|csv|txt|json|xml|doc';
					$config['overwrite'] = TRUE;
					$config['max_size'] = 15 * 1024 * 1024 / count($post['attachmentArray']);
					$config['max_width'] = 1024;
					$config['max_height'] = 768;
					$this->upload->initialize($config);
					$attachmentSize = 0;
					foreach ($post['attachmentArray'] as $attachment) {
						$mime_type = mime_content_type($attachment['data']);



						if (!in_array($mime_type, $this->allowedMimeTypes)) {
							$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'error', "result" => "Invalid file type"], 400);
							return false;
						}
						$attachmentSize += $attachment['size'];
					}
					if ($attachmentSize > 15 * 1024 * 1024) {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Total size of attachments cannot be greater than 15MB', 400]);
						return false;
					} else {
						foreach ($post['attachmentArray'] as $attachment) {
							$this->upload->do_upload($attachment['data']);
							$image_parts = explode(";base64,", $attachment['data']);
							$image_base64 = base64_decode($image_parts[1]);
							$file = $path . '/' . $attachment['name'];
							if (file_put_contents($file, $image_base64)) {
							} else {
								$this->api_response(['success' => false, 'status_code' => 400, 'message' => "File Not Uploded", 400]);
								return false;
							}
						}
					}
				}
				// save attachment in folder with the name email_msg_id ends here
				$this->load->model('Master_Model');
				$this->db->trans_begin();
				$dbData = $post;
				$dbFields = $this->Master_Model->getTicketTableFields($masterName);
				$db_keys = (is_array($dbData)) ? array_keys($dbData) : [];
				foreach ($db_keys as $keyName) {

					if (!in_array($keyName, $dbFields)) {
						unset($dbData[$keyName]);
					} else {
						if (array_key_exists($keyName, $dbData)) {
							if (is_array($dbData[$keyName])) {
							} else {
								$dbData[$keyName] = addslashes(trim($dbData[$keyName]));
							}
						}
					}
				}
				$ticketPrifix = $this->ticketSeries($dbData['queue_id']);
				$ticketNo = $this->Master_Model->getScalerCol("ifnull(max(cast(ticket_unique_id as signed)),0)+1 ticketNo", $masterName, "1=1")->ticketNo;
				if (!empty($ticketPrifix)) {
					$Prefix = explode('[', $ticketPrifix, 2);
					$dbData['ticket_prefix'] = $Prefix[0];
					$ticketPrifix = str_replace('[M]', strtoupper(date('M')), $ticketPrifix);
					$ticketPrifix = str_replace('[m]', date('m'), $ticketPrifix);
					$ticketPrifix = str_replace('[d]', date('d'), $ticketPrifix);
					$ticketPrifix = str_replace('[D]', date('D'), $ticketPrifix);
					$ticketPrifix = str_replace('[Y]', date('Y'), $ticketPrifix);
					$ticketPrifix = str_replace('[y]', date('y'), $ticketPrifix);
					$ticketPrifix = str_replace('[Y+1]', date('Y') + 1, $ticketPrifix);
					$ticketPrifix = str_replace('[y+1]', date('y') + 1, $ticketPrifix);
					$ticketSeries = $ticketPrifix . $ticketNo;
					if (strlen($ticketSeries) > 20) {
						$ticketPrifix = '0';
						$ticketNo = '0';
					}
					$dbData['ticket_id'] = $ticketSeries;
				} else {
					return $this->response(TRUE, 'Error', 400, 'Ticket Prefix is required');
				}

				// block email for ticket generation start here

				$blockEmailIds = $this->Master_Model->getScalerCol("block_email_for_ticket_generate", "tms_queue_master t1", "1=1 and t1.id = '$post[queue_id]'")->block_email_for_ticket_generate;
				if ($blockEmailIds != "") {
					$blockEmailIdsArr = explode(',', $blockEmailIds);
					if (!empty($post['to_email'])) {
						$toEmailArr = explode(',', $post['to_email']);
						if (count($blockEmailIdsArr) > 0 && count($toEmailArr) > 0) {
							$matchingEmails = array_intersect($blockEmailIdsArr, $toEmailArr);
							$stringMatchingEmails = (is_array($matchingEmails) ? implode(',', $matchingEmails) : $matchingEmails);
							if (is_array($matchingEmails) && count($matchingEmails) > 0) {
								return $this->response(TRUE, 'Error', 400, 'To Email id ("' . $stringMatchingEmails . '") is blocked for ticket generation');
							}
						}
					}
				}
				// block email for ticket generation ends here

				// block domain for ticket generation start here
				$blockDomains = $this->Master_Model->getScalerCol("block_domains_for_ticket_generate", "tms_queue_master t1", "1=1 and t1.id = '$post[queue_id]'")->block_domains_for_ticket_generate;
				if (!empty($blockDomains)) {
					$blockDomainArr = explode(',', $blockDomains);
					if (!empty($post['to_email'])) {
						$toDoaminArr = explode(',', $post['to_email']);
						if (count($blockDomainArr) > 0 && count($toDoaminArr) > 0) {
							foreach ($toDoaminArr as $email) {
								$domain = explode('@', $email)[1];
								if (in_array($domain, $blockDomainArr)) {
									return $this->response(TRUE, 'Error', 400, 'To Email contains blocked domain');
									break;
								}
							}
						}
					}
				}

				// block domain for ticket generation emds here
				$is_happycode = $this->Master_Model->getScalerCol("is_happycode", "tms_queue_master", "1=1 and id = $dbData[queue_id]")->is_happycode;
				if ($is_happycode == 1) {
					$dbData['happy_code'] = rand(1000, 9999);
				}
				$dbData['assigned_by'] = $this->user_id;
				if (empty($dbData[$primaryKey])) {
					$dbData['ticket_created_by'] = $this->user_id;
					$dbData['created_date'] = date('Y-m-d H:i:s');
				} else {
					if (empty($dbData['ticket_created_by'])) {
						$dbData['ticket_created_by'] = $this->user_id;
						$dbData['created_date'] = date('Y-m-d H:i:s');
					}
					$dbData['last_updated_by'] = $this->user_id;
					$dbData['last_updated_on'] = date('Y-m-d H:i:s');
				}
				$dbData['is_new'] = 1;
				$retarr = $this->Master_Model->saveTicketData($masterName, $post, $dbData, $primaryKey);
				// print_r($retarr);die;
				$this->fx->generateUserLogs('1', 'Ticket', $this->name, $this->user_id, $dbData);
				if (empty($retarr['id'])) {
					$respMsg = 'Something goes wrong.';
				}

				if ($this->db->trans_status() === FALSE) {
					$this->db->trans_rollback();
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
				} else {
					$this->db->trans_commit();
					if ($post['moved_ticket'] == 1) {
						return true;
					} else {
						$master_title = str_replace('_', ' ', $masterName);
						$master_title = ucwords(strtolower($master_title));
						$respMsg = 'Ticket details saved successfully :' . $ticketSeries;
						$this->response(TRUE, $respMsg, 200, $retarr['id']);
					}
					$this->response(TRUE, $respMsg, 200);
				}
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Master Name'], 400);
		}
	}

	public function updateTicketData()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));

		$is_close = $post['isclose'];
		$is_reopen = $post['is_reopen'];
		$is_incoming = $post['is_incoming'];
		$mergedObject = (object) array_merge((array) $post['ticketData'], (array) $post['dynamicData']);
		// $tkyUnqId = $post['ticket_unique_id'];

		$post['ticketData'] = $mergedObject;
		$post['ticketData']->ticket_unique_id = $post['ticket_unique_id'];
		unset($post['dynamicData']);
		unset($post['ticket_unique_id']);
		$post = json_decode(json_encode($post['ticketData']), true);
		// $is_close_status = $this->Api_Model->checkIsCloseStatus($post['status_id'],$post['queue_id']);
		// if($is_close_status->is_close_status == 1){
		//  $close_email_ids = $this->Api_Model->closeEmailIds($post['status_id'],$post['queue_id']);

		// }
		if ($post['ticket_unique_id'] != "" && $post['master_name']) {
			// create email_msg_id start here
			$post['uuid'] = $this->fx->generateEmailUnqMsgId($post['from_email']);
			// create email_msg_id ends here
			// fx::pr($post['uuid'],1);
			$primaryKey = 'ticket_unique_id';
			$masterName = $post['master_name'];
			$this->load->model('Master_Model');
			$rules = $this->Master_Model->getTicketTableRules();

			if (empty($rules)) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validations not defined.'], 400);
				return;
			}
			$this->load->library('Dynamicformcontent');


			$dynrules = $this->dynamicformcontent->getDynamicFieldValidationArray($post['queue_id'], $post['master_name'], isset($post[$primaryKey]) ? $post[$primaryKey] : 0);

			$rules = array_merge($rules, $dynrules);

			$this->form_validation->set_data($post);

			$this->form_validation->set_message('unique_module', 'Module already in use');
			$this->form_validation->set_rules($rules);
			if ($this->form_validation->run() === false) {
				$data = $this->form_validation->error_array();
				$firstError = (is_array($data)) ? array_keys($data) : [];
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validation Error', 'result' => $data[$firstError[0]]], 400);
			} else {
				// save attachment in folder with the name email_msg_id start here
				$post['msg_id'] = $this->fx->generateMsgId($post['uuid']);
				// $attachGolderName = explode('@',preg_replace("/[<>\-.]/", '', $post['uuid']));
				// $msgId = $attachGolderName[0];
				// $post['msg_id'] = $msgId;
				$this->load->library('upload');
				if (is_array($post['attachmentArray']) && (count($post['attachmentArray']) > 0)) {
					// $path = $_SERVER["DOCUMENT_ROOT"] . '/mailread/mail_attachment_folder/' . $post['msg_id'];
					// $path = '/var/www/html/mailread/mail_attachment_folder/' . $post['msg_id'];
					// if (!is_dir($path)) {
					// 	mkdir($path, 0777, true);
					// }
					$todayfolderPath = NODE_APP_PATH . date("Y-m-d") . '/';
					if (!is_dir($todayfolderPath)) {
						mkdir($todayfolderPath, 0777, true);
					}
					chmod($todayfolderPath, 0777);
					$path = $todayfolderPath . '/' . $post['msg_id'];
					if (!is_dir($path)) {
						mkdir($path, 0777, true);
					}
					chmod($path, 0777);
					$post['path'] = date("Y-m-d") . '/' . $post['msg_id'];
					$config['upload_path'] = $path;
					$config['allowed_types'] = 'gif|jpg|png|pdf|xls|xlsx|csv|txt|json|xml|doc';
					$config['overwrite'] = TRUE;
					$config['max_size'] = 15 * 1024 * 1024 / count($post['attachmentArray']);
					$config['max_width'] = 1024;
					$config['max_height'] = 768;
					$this->upload->initialize($config);



					$attachmentSize = 0;
					foreach ($post['attachmentArray'] as $attachment) {
						$mime_type = mime_content_type($attachment['data']);
						// print_r($mime_type);
						if (!in_array($mime_type, $this->allowedMimeTypes)) {
							$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'error', "result" => "Invalid file type"], 400);
							return false;
						}
						$attachmentSize += $attachment['size'];
					}
					if ($attachmentSize > 15 * 1024 * 1024) {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'error', "result" => "Total size of attachments cannot be greater than 15MB"], 400);
						return false;
					} else {
						foreach ($post['attachmentArray'] as $attachment) {

							$this->upload->do_upload($attachment['data']);
							$image_parts = explode(";base64,", $attachment['data']);
							$image_base64 = base64_decode($image_parts[1]);
							$file = $path . '/' . $attachment['name'];
							if (file_put_contents($file, $image_base64)) {
							} else {
								$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'error', "result" => "File Not Uploded"], 400);
								return false;
							}
						}
					}
				}

				// save attachment in folder with the name email_msg_id ends here
				$this->load->model('Master_Model');
				$this->db->trans_begin();
				$dbData = $post;

				$dbFields = $this->Master_Model->getTicketTableFields($masterName);

				$db_keys = (is_array($dbData)) ? array_keys($dbData) : [];
				foreach ($db_keys as $keyName) {

					if ($keyName == "from_email" && strpos($dbData['from_email'], '*') !== false) {
						unset($dbData['from_email']);
					}
					if ($keyName == "to_email" && strpos($dbData['to_email'], '*') !== false) {
						unset($dbData['to_email']);
					}
					if ($keyName == "mobile_no" && strpos($dbData['mobile_no'], '*') !== false) {
						unset($dbData['mobile_no']);
					}

					if (!in_array($keyName, $dbFields)) {
						unset($dbData[$keyName]);
					} else {
						if (array_key_exists($keyName, $dbData)) {
							if (is_array($dbData[$keyName])) {
							} else {
								if ($keyName == "subject") {
									continue;
								} else {
									$dbData[$keyName] = addslashes(trim($dbData[$keyName]));
								}
							}
						}
					}
				}

				if ($is_close) {
					$dbData['ticket_closed_date'] = date('Y-m-d H:i:s');
					$dbData['is_closed'] = 1;
				}
				if ($is_reopen) {
					$dbData['ticket_closed_date'] = null;
					$dbData['is_closed'] = 0;
				}
				if ($is_incoming) {
					$dbData['reopen_date'] = date('Y-m-d H:i:s');
				}

				$dbData['last_updated_by'] = $this->user_id;
				$dbData['last_updated_on'] = date('Y-m-d H:i:s');
				$retarr = $this->Master_Model->saveTicketData($masterName, $post, $dbData, $primaryKey);
				$this->fx->generateUserLogs('2', 'Ticket', $this->name, $this->user_id, $dbData, $dbData[$primaryKey]);
				if (empty($retarr['id'])) {
					$respMsg = 'Something goes wrong.';
				} else {
					$master_title = str_replace('_', ' ', $masterName);
					$master_title = ucwords(strtolower($master_title));
					$respMsg = !empty($post[$primaryKey]) ? 'Ticket details updated successfully ' : 'Ticket details saved successfully';
				}
				if ($this->db->trans_status() === FALSE) {
					$this->db->trans_rollback();
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
				} else {
					$this->db->trans_commit();
					if (is_array($retarr['next_queue_data']) && (count($retarr['next_queue_data']) > 0)) {
						$assign_to = ($post['next_queue_assign_to'] == "opentoqueue") ? '0' : $post['next_queue_assign_to'];
						$getNextQueueData = $this->getQueueChangeAllDropdown(array('queue_id' => $post['next_queue_id']));
						if (!empty($getNextQueueData['result']) && isset($getNextQueueData['result']['statustype_data']) && isset($getNextQueueData['result']['priority_data']) && isset($getNextQueueData['result']['queue_email'])) {
							$statustypeData = $getNextQueueData['result']['statustype_data'];
							if (!empty($statustypeData)) {
								$defaultStatusId = null;
								foreach ($statustypeData as $status) {
									if ($status['is_default'] == 1) {
										$defaultStatusId = $status['id'];
										break;
									}
								}
							}
							$priorityData = $getNextQueueData['result']['priority_data'];
							$defaultPriority = null;
							foreach ($priorityData as $priority) {
								if ($priority['is_default'] == 1) {
									$defaultPriority = $priority['id'];
									break;
								}
							}
							$queueEmailData = $getNextQueueData['result']['queue_email'];
							$fromEmail = $queueEmailData[0]['text'];
						}
						$getConverationData = $this->Master_Model->getConversationData($dbData['ticket_unique_id'], $dbData['queue_id']);
						$conversation = '';
						if (is_array($getConverationData) && (count($getConverationData) > 0)) {
							foreach ($getConverationData as $key => $val) {
								if (!empty($val->json_file_name) && $val->json_file_name != '') {
									$dateFolder = date('Y-m-d', strtotime($val->conversation_date));
									$path = str_replace(".json", "", $dateFolder . '/' . $val->json_file_name);
									$data = $this->getJsonFileContent($path . '/' . $val->json_file_name);
									$conversation .= "<br>" . $data . "<br>";
								}
							}
						} else {
							$conversation = $post['conversation'];
						}
						$setTicketData = array(
							'assigned_to' => $assign_to,
							'person_name' => $post['person_name'],
							'mobile_no' => $post['mobile_no'],
							'priority_id' => $defaultPriority,
							'cc_email' => isset($post['cc_email']) ? $post['cc_email'] : '',
							'bcc_email' => isset($post['bcc_email']) ? $post['bcc_email'] : '',
							'subject' => $post['subject'],
							'queue_id' => $post['next_queue_id'],
							'from_email' => $fromEmail,
							'conversation' => $conversation,
							'to_email' => ($post['is_auto'] == 0) ? $post['to_email'] : $post['from_email'],
							'status_id' => $defaultStatusId,
							'ticket_id' => $retarr['next_queue_data']['ticket_id'],
							'attachmentArray' => $post['attachmentArray'],
							'master_name' => 'tms_ticket_master_' . $post['next_queue_id'],
							'is_auto' => $post['is_auto'],
							'moved_ticket' => '1'
						);
						$addRes = $this->addTicketData($setTicketData);
						if ($addRes == true) {
							//create move queue log 
							$logArr = array(
								'ticket_id' => $post['ticket_id'],
								'queue_id' => $post['queue_id'],
								'new_ticket_id' => $retarr['next_queue_data']['ticket_id'],
								'new_queue_id' => $post['next_queue_id'],
								'assigned_to' => ($post['next_queue_assign_to'] == "opentoqueue") ? '0' : $post['next_queue_assign_to'],
								'created_by' => $this->user_id
							);
							$logRes = $this->Master_Model->insertMovedQueueLog($logArr);
							// $this->db->insert('move_to_another_queue_log',$logArr);
							$respMsg = "Ticket details updated successfully";
							$this->response(TRUE, $respMsg, 200);
						}
					}
					$this->response(TRUE, $respMsg, 200);
				}
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Ticket Id id required'], 400);
		}
	}

	public function resendHappyCode()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		$mergedObject = (object) $post['ticketData'];
		// $tkyUnqId = $post['ticket_unique_id'];

		$post['ticketData'] = $mergedObject;
		$post['ticketData']->master_name = $post['master_name'];

		$post = json_decode(json_encode($post['ticketData']), true);

		if ($post['ticket_unique_id'] != "" && $post['master_name']) {
			// create email_msg_id start here
			$post['uuid'] = $this->fx->generateEmailUnqMsgId($post['from_email']);

			// create email_msg_id ends here

			$primaryKey = 'ticket_unique_id';
			$masterName = $post['master_name'];
			$this->load->model('Master_Model');

			$post['msg_id'] = $this->fx->generateMsgId($post['uuid']);

			$this->load->model('Master_Model');
			$this->db->trans_begin();
			$dbData = [];
			$dbFields = $this->Master_Model->getTicketTableFields($masterName);

			$db_keys = (is_array($dbData)) ? array_keys($dbData) : [];
			$dbData['ticket_unique_id'] = $post['ticket_unique_id'];
			$dbData['assigned_to'] = $post['assigned_to'];
			$dbData['happy_code'] = rand(1000, 9999);
			$mailType = 'resend_happy_code';

			$retarr = $this->Master_Model->saveTicketData($masterName, $post, $dbData, $primaryKey, $mailType);
			if (empty($retarr['id'])) {
				$respMsg = 'Something goes wrong.';
			} else {
				$master_title = str_replace('_', ' ', $masterName);
				$master_title = ucwords(strtolower($master_title));
				$respMsg = 'Happy Code resend successfully';
			}
			if ($this->db->trans_status() === FALSE) {
				$this->db->trans_rollback();
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
			} else {
				$this->db->trans_commit();
				$this->response(TRUE, $respMsg, 200);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Ticket Id id required'], 400);
		}
	}

	public function getDynamicFieldListColumnsHeader()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['queue_id'])) {
			$this->load->library('Dynamicformcontent');
			$res = $this->dynamicformcontent->getDynamicFieldListColumnsHeader($post['queue_id']);

			if (!empty($res)) {
				$this->response(TRUE, '', 200, $res);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
			}
		}
	}

	public function getDynamicFieldListColumns()
	{

		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['queue_id'])) {
			$this->load->library('Dynamicformcontent');
			$res = $this->dynamicformcontent->getDynamicFieldListColumns($post['queue_id'], 't1');
			if (!empty($res)) {
				$this->response(TRUE, '', 200, $res);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
			}
		}
	}

	public function ticketSeries($queueId)
	{
		$ticketSeries = $this->Master_Model->ticketSeries($queueId);
		if (!empty($ticketSeries)) {
			return $ticketSeries;
		} else {
			return $this->response(TRUE, 'Error', 400, 'Ticket Prefix is required');
		}
	}

	public function checkAdminPassword()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($this->setData($token) == false)
			return;
		$postvars = (object) json_decode(file_get_contents("php://input"), true);
		$postvars->password = $this->fx->xor_decrypt("$postvars->password");
		$MasterPassword = 'S@N1@2$@N@' . date('Ymd');
		if ($postvars->password == $MasterPassword) {
			$this->response(TRUE, 'Success', 200, 'Password is correct');
		}

		$result = $this->Api_Model->check_admin_password(md5($postvars->password));
		if ($result) {
			$this->response(TRUE, 'Success', 200, 'Password is correct');
		} else {
			$this->response(FALSE, 'Error', 400, 'Password is incorrect');
		}
	}



	public function getTicketMasterList()
	{

		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($this->setData($token) == false)
			return;

		$postvars = json_decode(file_get_contents("php://input"), true);
		$mergedObject = (object) array_merge((array) $postvars['ticketData'], (array) $postvars['dynamicData']);
		$postvars['ticketData'] = $mergedObject;
		unset($postvars['dynamicData']);
		$sort = '';
		$data = $postvars['ticketData'];
		if (!empty($data->sort) || !empty($data->order_by)) {
			$sort = $data->sort . ' ' . $data->order_by;
		}
		$where = "1=1";
		if ($data->srch_master_name == 'junk-ticket') {
			$where .= " And t1.is_junk = 1 And t1.is_deleted_ticket = 0";
		} else if ($data->srch_master_name == 'delete-ticket') {
			$where .= " And t1.is_deleted_ticket = 1";
		} else if ($data->srch_master_name == 'ticket-search') {
			$where .= " And t1.is_junk = 0 And t1.is_deleted_ticket = 0";
		}
		if ($postvars['all_tickets_setting']['view_all_tickets'] == 1 || $postvars['all_tickets_setting']['edit_all_tickets'] == 1) {
			unset($data->created_date_to);
			unset($data->created_date_from);
		}

		$masterName = $data->master_name;
		// print_r($data);die;
		if ($masterName) {
			$retData = $this->Api_Model->getTicketDataList(
				$masterName,
				$data->page_num,
				$data->limit,
				array(
					'ticket_id' => trim($data->ticket_id),
					'ticket_unique_id' => trim($data->ticket_unique_id),
					'person_name' => trim($data->person_name),
					'queue_id' => trim($data->queue_id),
					// 'category_id' => trim((is_array($data->category_id) ? implode(',', $data->category_id) : $data->category_id)),
					'category_id' => trim(is_array($data->category_id) ? implode(',', array_map(function ($item) {
						return is_array($item) ? $item['id'] : $item;
					}, $data->category_id)) : $data->category_id),
					// 'status_id' => trim((is_array($data->status_id) ? implode(',', $data->status_id) : $data->status_id)),
					'status_id' => trim(is_array($data->status_id) ? implode(',', array_map(function ($item) {
						return is_array($item) ? $item['id'] : $item;
					}, $data->status_id)) : $data->status_id),
					'priority_id' => trim($data->priority_id),
					// 'assigned_to' => trim((is_array($data->assigned_to) ? implode(',', $data->assigned_to) : $data->assigned_to)),
					'assigned_to' => trim(is_array($data->assigned_to) ? implode(',', array_map(function ($item) {
						return is_array($item) ? $item['id'] : $item;
					}, $data->assigned_to)) : $data->assigned_to),
					'assigned_by' => trim(is_array($data->assigned_by) ? implode(',', array_map(function ($item) {
						return is_array($item) ? $item['id'] : $item;
					}, $data->assigned_by)) : $data->assigned_by),
					'dashboard_condition' => isset($data->dashboard_condition) ? $data->dashboard_condition : "",
					'mobile_no' => trim($data->mobile_no),
					'to_email' => trim($data->to_email),
					'from_email' => trim($data->from_email),
					'subject' => trim($data->subject),
					'created_date_from' => trim(isset($data->created_date_from) && !empty($data->created_date_from) ? $data->created_date_from . ' 00:00:00' : null),
					'created_date_to' => trim(isset($data->created_date_to) && !empty($data->created_date_to) ? $data->created_date_to . ' 23:59:59' : null),
					'assigned_on_from' => !empty($data->assigned_on_from) ? $data->assigned_on_from . ' 00:00:00' : null,
					'assigned_on_to' => !empty($data->assigned_on_to) ? $data->assigned_on_to . ' 23:59:59' : null,
					'master_name' => trim($data->master_name),
					// 'un_assigend' => trim($data->reportby),
					'un_assigend' => trim($data->reportby),
					"user_id" => $this->user_id,
					"manager_id" => $this->manager_id,
					"all_ticket" => $this->allTicket,
					"full_control" => $this->full_control,
					'maskEmail' => $this->maskEmail,
					'maskPhone' => $this->maskPhone,
					'is_agent' => isset($data->is_agent) ? $data->is_agent : 0,
					'today' => isset($data->today) ? $data->today : "",
					'reopen' => isset($data->reopen) ? $data->reopen : "",
					'view_all_tickets' => $postvars['all_tickets_setting']['view_all_tickets'],
					'searchFieldValue' => $postvars['searchFieldValue'],
					'report_type' => $data->report_type,
					'listType' => $postvars['listType'],
					'type' => $postvars['type'],
					'agent_name' => $postvars['agent_name'],
				),
				$where,
				$sort,
				$data
			);
		}
		if (isset($retData['error'])) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $retData['error']], 400);
		}
		if (!empty($retData)) {
			$this->response(TRUE, '', 200, $retData);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
		}
	}


	function getloginLogList()
	{
		error_reporting(0);
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$postvars = json_decode(file_get_contents("php://input"), true);
		if (!empty($postvars['login_data'])) {
			$child = $this->Api_Model->getChildUserDetails($this->user_id);
			if ($postvars['assigned_to'] == '' || $postvars['assigned_to'] == null) {
				if ($this->full_control === '1') {
					$childId = 1;
				} else {
					$childId = !empty($child) ? "$this->user_id" . "," . $child : $postvars['userid'];
				}
			} else {
				$assign_to = (is_array($postvars['assigned_to']) ? implode(',', $postvars['assigned_to']) : $postvars['assigned_to']);
				$childId = $assign_to;
			}

			$retData = $this->Api_Model->loginDetails($postvars, $this->full_control, $childId);
			if (!empty($retData)) {
				$this->response(TRUE, '', 200, $retData);
			} else {
				$this->response(false, 'No record found', 400, $retData);
			}
		}
	}

	function getChildData()
	{
		error_reporting(0);
		$token = $this->input->post('token');
		// fx::pr($this->input->post('loginsession'),1);
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = json_decode(file_get_contents("php://input"));
		$child = $this->Api_Model->getChildUserDetails($post->user_id);
		$childId = !empty($child) ? "$post->user_id" . "," . $child : $post->user_id;

		if (!empty($childId)) {
			if ($this->full_control === '1') {
				$childId = 0;
			}
			$childIdArray = explode(',', $childId);

			$this->response(TRUE, '', 200, array('data' => $childIdArray, 'full_control' => $this->full_control));
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'No record found'], 400);
		}
	}

	function getUserChildDetails()
	{
		error_reporting(0);
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$postvars = json_decode(file_get_contents("php://input"), true);
		if (!is_null($postvars['assigned_to'])) {
			$filteredToppings = array_filter($postvars['assigned_to'], function ($value) {
				return !is_null($value) && $value !== '' && $value !== 0;
			});
			$postvars['assigned_to'] = $filteredToppings;
		}
		if (isset($postvars['queue_id']) && !empty($postvars['queue_id'])) {
			$queue_id = (is_array($postvars['queue_id']) ? implode(',', $postvars['queue_id']) : $postvars['queue_id']);
		}
		$user_id = !empty($this->manager_id) ? $this->manager_id : $postvars['user_id'];
		$child = $this->Api_Model->getChildUserDetails($postvars['userid']);

		$this->fx->generateUserLogs('4', 'Home', $this->name, $this->user_id, $postvars);

		if (empty($postvars['assigned_to'])) {
			if ($this->full_control === '1') {
				$childId = 1;
			} else {
				if ($this->allTicket === '1') {
					$childId = 1;
					$this->full_control = 1;
				} else {
					$childId = !empty($child) ? "$postvars[userid]" . "," . $child : $postvars['userid'];
				}
			}
		} else {
			$this->full_control = 0;
			$assign_to = (is_array($postvars['assigned_to']) ? implode(',', $postvars['assigned_to']) : $postvars['assigned_to']);
			$childId = $assign_to;
		}

		$retData = $this->Dashboard_Model->getDashboardDetails($childId, $postvars, $this->full_control, $queue_id);

		if (!empty($retData)) {

			$finalData = array_merge($retData, array('user_child_id' => $childId));

			$this->response(TRUE, '', 200, $finalData);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'No record found'], 400);
		}
	}

	//MASTERS COMMON METHOD
	function getImportMasterSampleFile()
	{
		error_reporting(0);
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$postvars = json_decode(file_get_contents("php://input"), true);
		$data = (array) $postvars;

		if (!empty($data['import_type'])) {
			$importtype = strtolower($data['import_type']);
			$fileName = $importtype . '.csv';
			$filePath = FCPATH . 'assets/download/import_master/' . $fileName;
			$baseurl = "http://" . $_SERVER['HTTP_HOST'] . str_replace('/index.php', '', $_SERVER['SCRIPT_NAME']);
			$fileURL = base_url() . 'assets/download/import_master/' . $fileName;
			if (file_exists($filePath)) {
				$this->response(TRUE, '', 200, array('sample_file_path' => $fileURL));
			} else {
				$this->response(FALSE, 'Invalid Request', 400);
			}
		} else {
			$this->response(FALSE, 'Invalid Request', 400);
		}
	}

	function getQueueStatusGraphRecord()
	{
		error_reporting(0);
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$postvars = json_decode(file_get_contents("php://input"), true);
		$assign_to = (is_array($postvars['assigned_to']) ? implode(',', $postvars['assigned_to']) : $postvars['assigned_to']);
		$queue_id = $postvars['queue_id'];
		if (!is_null($postvars['assigned_to'])) {
			$filteredToppings = array_filter($postvars['assigned_to'], function ($value) {
				return !is_null($value) && $value !== '' && $value !== 0;
			});
			$postvars['assigned_to'] = $filteredToppings;
		}
		$retData = array();
		if ($this->allTicket == 1) {
			$postvars['userid'] = 1;
			$this->full_control = 1;
		}
		foreach ($queue_id as $key => $value) {
			if ($value != 0) {
				$retData[] = $this->Dashboard_Model->getQueueStatusRecord($postvars['queuestatus'], isset($value['id']) ? $value['id'] : $value, $postvars['userid'], $this->full_control);
				$this->fx->generateUserLogs('4', 'Home', $this->name, $this->user_id, $postvars);
			}
		}
		$organizedData = [];
		// Iterate through the data and organize it by Queue_Name
		foreach ($retData as $dataArray) {
			foreach ($dataArray as $item) {
				$queueName = $item[0]['Queue_Name'];
				// unset($item['Queue_Name']); // Remove Queue_Name from the item
				$organizedData[$queueName][] = $item;
			}
		}
		if (!empty($organizedData)) {
			$this->response(TRUE, '', 200, $organizedData);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'No record found'], 400);
		}
	}

	function getdashboardCardRecord()
	{
		error_reporting(0);
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$postvars = json_decode(file_get_contents("php://input"), true);
		if (!is_null($postvars['assigned_to'])) {
			$filteredToppings = array_filter($postvars['assigned_to'], function ($value) {
				return !is_null($value) && $value !== '' && $value !== 0;
			});
			$postvars['assigned_to'] = $filteredToppings;
		}
		if (isset($postvars['queue_id']) && !empty($postvars['queue_id'])) {
			$queue_id = (is_array($postvars['queue_id']) ? implode(',', $postvars['queue_id']) : $postvars['queue_id']);
		}
		$retData = $this->Dashboard_Model->getDashboardCardRecord($postvars['userid'], $postvars['queue_id']);

		$this->fx->generateUserLogs('4', 'Home', $this->name, $this->user_id, $postvars);

		if (!empty($retData)) {
			$this->response(TRUE, '', 200, $retData);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'No record found'], 400);
		}
	}

	//MASTERS COMMON METHOD
	// function getMasterListIMPORT()
	// {
	// 	error_reporting(0);
	// 	$token = $this->input->post('token');
	// 	$this->get_loginsession($this->input->post('loginsession'));
	// 	// $array = explode("-", $this->decode($token));
	// 	if ($token == "") {
	// 		$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 400);
	// 		return;
	// 	}
	// 	if ($this->setData($token) == false)
	// 		return;

	// 	$postvars = json_decode(file_get_contents("php://input"), true);
	// 	if (!empty($postvars['filter']['dynamicFilter'][0])) {
	// 		$condition = $this->checkDynamicFilter($postvars);
	// 	}
	// 	if (!empty($postvars['user_id'])) {
	// 		$retData	= $this->Data_List_Model->getDataList($postvars['page'], $postvars['page_num'], $postvars['limit'], $postvars['filter'], !empty($postvars['sort']) ? $postvars['sort'] : '', !empty($postvars['sortVal']) ? $postvars['sortVal'] : '', $postvars['user_id'], !empty($condition) ? $condition : []);

	// 		if (!empty($retData)) {
	// 			$this->response(TRUE, '', 200, $retData);
	// 		} else {
	// 			$this->response(FALSE, 'Data Not Found', 400);
	// 		}
	// 	} else {
	// 		$this->response(FALSE, 'Data Not Found', 400);
	// 	}
	// }

	function getMasterList()
	{
		try {
			error_reporting(0);
			$token = $this->input->post('token');
			$this->get_loginsession($this->input->post('loginsession'));
			// $array = explode("-", $this->decode($token));
			if ($token == "") {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 400);
				return;
			}
			if ($this->setData($token) == false)
				return;

			$postvars = json_decode(file_get_contents("php://input"), true);
			// print_r($postvars);die;
			$sort = '';
			if (!empty($postvars['sort']) || !empty($postvars['order_by'])) {
				$sort = $postvars['sort'] . ' ' . $postvars['order_by'];
			}
			$masterName = $postvars['master_name'];


			foreach ($postvars as $key => $value) {
				if ($key == "master_name" || $key == "limit" || $key == "page_num" || $key == "sort" || $key == "order_by" || $key == "method" || $key == "idforaction" || $key == "record" || $key == "sort_form" || $key == "sort_template" || $key == "sort_category" || $key == "sort_rule" || $key == "sort_rule_Assign" || $key == "user_id" || $key == "date_differnce") {
				} else {
					$searchArray[] = array(
						'name' => $key,
						'value' => $value
					);
				}
			}
			if (array_key_exists($postvars['master_name'], $this->tableArr) == 1) {
				switch ($masterName) {
					case 'emailAccount':

						$where = $this->fx->whereString($searchArray, array('*' => "t1."), array('email' => 'WHERE', 'display_name' => 'LIKE'), array());

						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], array('email' => $postvars['email'], 'display_name' => $postvars['display_name'], 'maskEmail' => $this->maskEmail, 'maskPhone' => $this->maskPhone), $where, $sort);

						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;

					case 'pagination':
						$where = $this->fx->whereString($searchArray, array('*' => "t1."), array('record' => 'WHERE'), array('record_search' => 'record'), array());

						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], $postvars['record'], $where, $sort);

						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;

					case 'queue':
						$getQueueId = $this->Master_Model->getScalerCol("queue_id", "tms_user_master t1", "1=1 and t1.id = $this->user_id")->queue_id;

						$where = $this->fx->whereString($searchArray, array('client_id' => 't1.'), array('queue' => 'LIKE'), array());
						if ($this->full_control == 0) {
							$where .= " and t1.id in ($getQueueId)";
						}

						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], $postvars['queue'], $where, $sort);

						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;


					case 'custom_report':
						// fX::pr("custom_report",1);
						// $getQueueId = $this->Master_Model->getScalerCol("queue_id", "tms_user_master t1", "1=1 and t1.id = $this->user_id")->queue_id;

						$where = $this->fx->whereString($searchArray, array('client_id' => 't1.'), array('queue' => 'LIKE'), array());
						// if ($this->full_control == 0) {
						// 	$where .= " and t1.id in ($getQueueId)";
						// }

						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], $postvars['queue'], $where, $sort);

						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;

					case 'user';

						$where = $this->fx->whereString($searchArray, array('*' => 't1.'), array('user_name' => 'LIKE', 'email' => 'LIKE', 'mobile_no' => 'LIKE'), array());

						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], array('user_name' => $postvars['user_name'], 'mobile_no' => $postvars['mobile_no'], 'email' => $postvars['email'], 'user_id' => $this->user_id, 'maskEmail' => $this->maskEmail, 'maskPhone' => $this->maskPhone, 'full_control' => $this->full_control), $where, $sort);

						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;

					case 'user_log':
						if (!is_null($postvars['user_id'])) {
							$filteredToppings = array_filter($postvars['user_id'], function ($value) {
								return !is_null($value) && $value !== '';
							});
							$postvars['user_id'] = $filteredToppings;
						}

						$where = $this->fx->whereString($searchArray, array('*' => 't1.'), array('from_date' => 'DGTE_F', 'to_date' => 'DLTE_L'), array('from_date' => 'datetime', 'to_date' => 'datetime'));

						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], array('userid' => $this->user_id, 'full_control' => $this->full_control, 'user_id' => $postvars['user_id'], 'from_date' => $postvars['from_date'], 'to_date' => $postvars['to_date']), $where, $sort);

						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;

					case 'tms_log':
						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], array(
							'queue_id' => $postvars['queue_id'],
							'from_date' => $postvars['from_date'],
							'status_id' => trim((is_array($postvars['status_id']) ? implode(',', $postvars['status_id']) : $postvars['status_id'])),
							'to_date' => $postvars['to_date'],
							'ticket_id' => $postvars['ticket_id']
						), '1=1', $sort);

						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;
					case 'conversation-count':
						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], array('queue_id' => $postvars['queue_id'], 'from_date' => $postvars['from_date'], 'to_date' => $postvars['to_date']), '1=1', $sort);

						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;
					case 'MASTER_UPLOAD_LOG':
						$where = $this->fx->whereString($searchArray, array('*' => 't1.'), array(), array());
						// fx::pr($where,1);
						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], array('queue_id' => $postvars['queue_id']), $where);

						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;
					case 'agent_report':
						if (!is_null($postvars['user'])) {
							$filteredToppings = array_filter($postvars['user'], function ($value) {
								return !is_null($value) && $value !== '';
							});
							$postvars['user'] = $filteredToppings;
						}
						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], array('queue_id' => $postvars['queue_id'], 'from_date' => $postvars['from_date'], 'to_date' => $postvars['to_date'], 'user_id' => $this->user_id, 'user' => $postvars['user'], 'is_agent' => $postvars['is_agent'], 'report_view' => $postvars['report_view'], 'full_control' => $this->full_control), '1=1', $sort);
						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);

						break;
					case 'sla_report_log':
						if (!is_null($postvars['user'])) {
							$filteredToppings = array_filter($postvars['user'], function ($value) {
								return !is_null($value) && $value !== '';
							});
							$postvars['user'] = $filteredToppings;
						}
						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], array('queue_id' => $postvars['queue_id'], 'user_id' => $this->user_id, 'user' => $postvars['user'], 'full_control' => $this->full_control, 'user_id_individual' => $postvars['user_id'], 'where_condition' => $postvars['where_condition']), '1=1', $sort);
						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;
					case 'firsttat_report_log':
						if (!is_null($postvars['user'])) {
							$filteredToppings = array_filter($postvars['user'], function ($value) {
								return !is_null($value) && $value !== '';
							});
							$postvars['user'] = $filteredToppings;
						}
						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], array('queue_id' => $postvars['queue_id'], 'user_id' => $this->user_id, 'user' => $postvars['user'], 'full_control' => $this->full_control, 'user_id_individual' => $postvars['user_id'], 'where_condition' => $postvars['where_condition']), '1=1', $sort);
						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;
					case 'wip_report_log':
						if (!is_null($postvars['user'])) {
							$filteredToppings = array_filter($postvars['user'], function ($value) {
								return !is_null($value) && $value !== '';
							});
							$postvars['user'] = $filteredToppings;
						}
						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], array('queue_id' => $postvars['queue_id'], 'user_id' => $this->user_id, 'user' => $postvars['user'], 'full_control' => $this->full_control, 'user_id_individual' => $postvars['user_id'], 'where_condition' => $postvars['where_condition']), '1=1', $sort);
						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;
					case 'agent_report_log':
						if (!is_null($postvars['user'])) {
							$filteredToppings = array_filter($postvars['user'], function ($value) {
								return !is_null($value) && $value !== '';
							});
							$postvars['user'] = $filteredToppings;
						}
						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], array('queue_id' => $postvars['queue_id'], 'user_id' => $this->user_id, 'user' => $postvars['user'], 'full_control' => $this->full_control, 'user_id_individual' => $postvars['user_id'], 'where_condition' => $postvars['where_condition']), '1=1', $sort);
						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;
					case 'sla_report':
						if (!is_null($postvars['user'])) {
							$filteredToppings = array_filter($postvars['user'], function ($value) {
								return !is_null($value) && $value !== '';
							});
							$postvars['user'] = $filteredToppings;
						}
						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], array('queue_id' => $postvars['queue_id'], 'from_date' => $postvars['from_date'], 'to_date' => $postvars['to_date'], 'user_id' => $this->user_id, 'user' => $postvars['user'], 'is_agent' => $postvars['is_agent'], 'report_view' => $postvars['report_view'], 'full_control' => $this->full_control), '1=1', $sort);
						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;

					case 'tat_report':
						if (!is_null($postvars['user'])) {
							$filteredToppings = array_filter($postvars['user'], function ($value) {
								return !is_null($value) && $value !== '';
							});
							$postvars['user'] = $filteredToppings;
						}
						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], array('queue_id' => $postvars['queue_id'], 'from_date' => $postvars['from_date'], 'to_date' => $postvars['to_date'], 'user_id' => $this->user_id, 'user' => $postvars['user'], 'is_agent' => $postvars['is_agent'], 'report_view' => $postvars['report_view'], 'full_control' => $this->full_control), '1=1', $sort);
						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;

					case 'wip_report':
						if (!is_null($postvars['user'])) {
							$filteredToppings = array_filter($postvars['user'], function ($value) {
								return !is_null($value) && $value !== '';
							});
							$postvars['user'] = $filteredToppings;
						}
						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], array('queue_id' => $postvars['queue_id'], 'from_date' => $postvars['from_date'], 'to_date' => $postvars['to_date'], 'user_id' => $this->user_id, 'user' => $postvars['user'], 'is_agent' => $postvars['is_agent'], 'report_view' => $postvars['report_view'], 'full_control' => $this->full_control), '1=1', $sort);
						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;

					case 'closure_report':
						if (!is_null($postvars['user'])) {
							$filteredToppings = array_filter($postvars['user'], function ($value) {
								return !is_null($value) && $value !== '';
							});
							$postvars['user'] = $filteredToppings;
						}
						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], array('queue_id' => $postvars['queue_id'], 'from_date' => $postvars['from_date'], 'to_date' => $postvars['to_date'], 'user_id' => $this->user_id, 'user' => $postvars['user'], 'is_agent' => $postvars['is_agent'], 'report_view' => $postvars['report_view'], 'full_control' => $this->full_control), '1=1', $sort);
						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;

					case 'login_log':
						if (!is_null($postvars['user_id'])) {
							$filteredToppings = array_filter($postvars['user_id'], function ($value) {
								return !is_null($value) && $value !== '';
							});
							$postvars['user_id'] = array_values($filteredToppings);
						}


						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], array('user_id' => $postvars['user_id'], 'full_control' => $this->full_control, 'userid' => $this->user_id, 'from_date' => $postvars['from_date'], 'to_date' => $postvars['to_date'], 'report_type' => $postvars['report_type'], 'is_agent' => $postvars['is_agent']), '1=1', $sort);

						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;

					case 'ticket':
						$retData = $this->Api_Model->getDataList(
							$this->tableArr[$postvars['master_name']],
							$postvars['page_num'],
							$postvars['limit'],
							array(
								'ticket_id' => $postvars['ticket_id'],
								'unique_id' => $postvars['unique_id'],
								'customer_id' => $postvars['customer_id'],
								'person_name' => $postvars['person_name'],
								'queue_id' => $postvars['queue_id'],
								'category_id' => $postvars['category_id'],
								'ticket_status' => $postvars['ticket_status'],
								'priority_id' => $postvars['priority_id'],
								'assign_to' => $postvars['assign_to'],
								'mobile_no' => $postvars['mobile_no'],
								'from_email' => $postvars['from_email'],
								'email_subject' => $postvars['email_subject'],
								'from_date' => $postvars['from_date'],
								'to_date' => $postvars['to_date'],
								'master_name' => $postvars['master_name'],
							),
							'1=1',
							$sort
						);
						break;
					case 'updatesoft_log':
						$where = $this->fx->whereString($searchArray, array('*' => "t1."), array('uploaded_file' => 'LIKE', 'from_date' => 'DGTE_F', 'to_date' => 'DLTE_L'), array('from_date' => 'created_date', 'to_date' => 'created_date'), array());

						$retData = $this->Api_Model->getDataList(
							$this->tableArr[$postvars['master_name']],
							$postvars['page_num'],
							$postvars['limit'],
							array(
								'id' => $postvars['id'],
								'uploaded_file' => $postvars['uploaded_file'],
								'from_date' => $postvars['from_date'],
								'to_date' => $postvars['to_date'],
								'master_name' => $postvars['master_name'],
							),
							$where,
							$sort
						);
						break;
					case 'break':
						$where = $this->fx->whereString($searchArray, array('*' => "t1."), array('title' => 'LIKE'), array());

						$retData = $this->Api_Model->getDataList(
							$this->tableArr[$postvars['master_name']],
							$postvars['page_num'],
							$postvars['limit'],
							array(
								'title' => $postvars['title'],
								'break_time' => $postvars['break_time']
							),
							$where,
							$sort
						);
						break;
					case 'user_type':
						$where = $this->fx->whereString($searchArray, array('*' => "t1."), array('title' => 'LIKE'), array(), array());

						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], $postvars['title'], $where, $sort);

						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;

					case 'conversation-type':
						$where = $this->fx->whereString($searchArray, array('*' => "t1."), array('title' => 'LIKE'), array(), array());

						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], $postvars['title'], $where, $sort);

						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;
					case 'shift':
						$where = $this->fx->whereString($searchArray, array('*' => "t1."), array('title' => 'LIKE'), array(), array());

						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], $postvars['title'], $where, $sort);

						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;
					default:
						$retData = $this->Api_Model->getDataList($this->tableArr[$postvars['master_name']], $postvars['page_num'], $postvars['limit'], $postvars['title'], '1=1', $sort);

						$this->fx->generateUserLogs('4', $postvars['master_name'], $this->name, $this->user_id, $postvars);
						break;
				}



				if (!empty($retData) && $retData['error'] == false) {
					$this->response(TRUE, '', 200, $retData);
				} else if (!empty($retData) && $retData['error'] == true) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => $retData['message']], 400);
				} else {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
				}
			}
		} catch (Exception $e) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'An error occurred: ' . $e->getMessage()], 400);
		}
	}

	public function getAgentDomainList()
	{
		$post = json_decode(file_get_contents("php://input"), true);
		if (!empty($post)) {
			$res = $this->Api_Model->getAgentDomainList($post);
			if (!empty($res)) {
				$this->response(TRUE, '', 200, $res);
			} else {
				// $this->api_response(['success' => false, 'status_code' => 400, 'message' => 'something went wrong'], 400);
				$this->response(TRUE, 'No Record Found', 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'something went wrong'], 400);
		}
	}

	public function deleteTicketDetail()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = json_decode(file_get_contents("php://input"));
		$post = (array) $post;
		if (!empty($post['master_name'])) {
			$masterName = $post['master_name'];
			if ($masterName) {
				$this->load->model('Master_Model');
				$this->db->trans_begin();
				$dbData = $post;
				$respMsg = '';

				$primaryKey = 'ticket_unique_id';
				$retarr = $this->Api_Model->TicketDelete($masterName, $post, $primaryKey);
				$this->fx->generateUserLogs('3', 'Ticket', $this->name, $this->user_id, $dbData, (is_array($dbData['ticket_unique_id']) ? implode(',', $dbData['ticket_unique_id']) : $dbData['ticket_unique_id']));
				if (!empty($retarr['error'])) {
					$respMsg = $retarr['message'];
				} else {
					$respMsg = 'Ticket deleted successfully';
				}

				if ($this->db->trans_status() === FALSE) {
					$this->db->trans_rollback();
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
				} else {
					$this->db->trans_commit();
					if (!empty($retarr['error'])) {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respMsg], 400);
					} else {
						$this->response(TRUE, $respMsg, 200);
					}
				}
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Request'], 400);
		}
	}


	function deleteMasterDetail()
	{
		try {
			$token = $this->input->post('token');
			$this->get_loginsession($this->input->post('loginsession'));
			if ($token == "") {
				throw new Exception('Invalid Token.');
			}

			if ($this->setData($token) == false) {
				return;
			}

			$post = json_decode(file_get_contents("php://input"));
			$post = (array) $post;

			if (!empty($post['master_name'])) {
				$masterName = $post['master_name'];

				if (array_key_exists($masterName, $this->tableArr) == 1) {
					$this->load->model('Master_Model');
					$this->db->trans_begin();
					$dbData = $post;
					$respMsg = '';

					$primaryKey = 'id';
					$retarr = $this->Api_Model->deleteProcess($this->tableArr[$post['master_name']], $post, $primaryKey);

					$this->fx->generateUserLogs('3', $masterName, $this->name, $this->user_id, $dbData, $dbData[$primaryKey]);

					if (!empty($retarr['error'])) {
						$respMsg = $retarr['message'];
					} else {
						$master_title = str_replace('_', ' ', $masterName);
						$master_title = ucwords(strtolower($master_title));
						$respMsg = $master_title . ' deleted successfully';
					}

					if ($this->db->trans_status() === FALSE) {
						$this->db->trans_rollback();
						throw new Exception('Transaction failed');
					} else {
						$this->db->trans_commit();
						if (!empty($retarr['error'])) {
							$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respMsg], 400);
						} else {
							$this->response(TRUE, $respMsg, 200);
						}
					}
				}
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Request3'], 400);
			}
		} catch (Exception $e) {

			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $e->getMessage()], 400);
		}
	}

	function deleteQueueDetail()
	{
		$post = json_decode(file_get_contents("php://input"));
		$post = (array) $post;

		if (!empty($post['master_name'])) {
			$masterName = $post['master_name'];
			if ($masterName) {
				$this->load->model('Master_Model');
				$this->db->trans_begin();
				$dbData = $post;
				$respMsg = '';

				$primaryKey = 'id';
				$tables = [
					// "tms_queue_category_$post[id]",
					// "tms_queue_escalationmatrix_$post[id]",
					// "tms_queue_priority_$post[id]",
					// "tms_queue_rule_action_$post[id]",
					// "tms_queue_rule_condition_$post[id]",
					// "tms_queue_rule_master_$post[id]",
					// "tms_queue_status_$post[id]",
					// "tms_queue_template_$post[id]",
					"tms_ticket_master_$post[id]",
					"tms_conversation_master_$post[id]"
				];

				// Check if all tables are empty
				$alltableisempty = $this->Master_Model->CheckEmptyTables($tables);
				if ($alltableisempty == true && !is_array($alltableisempty)) {
					$retarr = $this->Api_Model->deleteProcess($this->tableArr[$masterName], $post, $primaryKey);
					if (!empty($retarr['error'])) {
						$respMsg = $retarr['message'];
					} else {
						$respMsg = 'Queue deleted successfully';
					}

					if ($this->db->trans_status() === FALSE) {
						$this->db->trans_rollback();
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
					} else {
						$this->db->trans_commit();
						if (!empty($retarr['error'])) {
							$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respMsg], 400);
						} else {
							$this->response(TRUE, $respMsg, 200);
						}
					}
				} else {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => "This queue contains tickets."], 400);
				}
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Request'], 400);
		}
	}

	function customQueryQueueDetail()
	{
		$post = json_decode(file_get_contents("php://input"));
		$post = (array) $post;


		if (!empty($post['master_name'])) {
			$masterName = $post['master_name'];
			if ($masterName) {
				$this->load->model('Master_Model');
				$this->db->trans_begin();
				$dbData = $post;
				$respMsg = '';

				$primaryKey = 'id';
				$tables = [
					"custom_query_report_columns",
					"custom_query_search_fields",
					"custom_query_tables"
				];

				$retarr = $this->Api_Model->deleteProcess($this->tableArr[$masterName], $post, $primaryKey);
				if (!empty($retarr['error'])) {
					$respMsg = $retarr['message'];
				} else {
					foreach ($tables as $table) {
						$this->db->where('report_id', $post['id']);
						$this->db->delete($table);
					}
					$respMsg = 'Report deleted successfully';
				}

				if ($this->db->trans_status() === FALSE) {
					$this->db->trans_rollback();
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
				} else {
					$this->db->trans_commit();
					if (!empty($retarr['error'])) {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respMsg], 400);
					} else {
						$this->response(TRUE, $respMsg, 200);
					}
				}
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Request'], 400);
		}
	}

	function validateApi($data)
	{
		foreach ($data as $key => $value) {
			$key = $this->security->xss_clean($key);
			$value = $this->security->xss_clean($value);
			$this->Api_Model->db->escape_str($key);
			$this->Api_Model->db->escape_str($value);
			$_POST[$key] = $value;
		}
	}

	function getMasterDetail()
	{
		try {
			$token = $this->input->post('token');
			$this->get_loginsession($this->input->post('loginsession'));
			if ($token == "") {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 400);
				return;
			}
			if ($this->setData($token) == false)
				return;

			$postvars = json_decode(file_get_contents("php://input"));
			$this->validateApi($postvars);
			$post = $this->input->post();
			if (empty($post['master_name']) || empty($post['id'])) {
				throw new Exception("Invalid Request");
			}

			$masterName = $post['master_name'];

			if (!array_key_exists($masterName, $this->tableArr)) {
				throw new Exception("Invalid master_name");
			}

			$this->load->model('Master_Model');
			$primaryKey = 'id';
			switch ($masterName) {
				case 'rule':
					$respArr = $this->Master_Model->getMasterRulesData($post['id'], $this->tableArr[$post['master_name']], $primaryKey);
					break;

				case 'queue':
					$respArr = $this->Master_Model->getMasterQueueData($post['id'], $this->tableArr[$post['master_name']], $primaryKey, $post['user_type'], $this->full_control);
					break;
				case 'custom_report':
					
					$respArr = $this->Master_Model->getMasterCustomreportData($post['id'], $this->tableArr[$post['master_name']], $primaryKey, $post['user_type'], $this->full_control,$this->queue_perm_id);
					break;
				case 'user':
					$respArr = $this->Master_Model->getMasterUserData($post['id'], $this->tableArr[$post['master_name']], $primaryKey);
					break;

				case 'emailAccount':
					$respArr = $this->Master_Model->getMasteremailAccountData($post['id'], $this->tableArr[$post['master_name']], $primaryKey);
					break;

				default:
					$respArr = $this->Master_Model->getMasterData($post['id'], $this->tableArr[$post['master_name']], $primaryKey);
					break;
			}
			if (isset($respArr['error'])) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respArr['error']], 400);
			}
			if (!empty($respArr)) {
				$this->response(TRUE, '', 200, $respArr);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
			}
		} catch (Exception $e) {

			$errorMessage = $e->getMessage();
			$statusCode = 400;

			$this->api_response(['success' => false, 'status_code' => $statusCode, 'message' => $errorMessage], $statusCode);
		}
	}


	function updateLoginState()
	{
		$postvars = json_decode(file_get_contents("php://input"), true);
		if (isset($postvars['user_id'])) {
			$res = $this->Api_Model->updateLoginState($postvars['user_id']);

			if ($res == 1) {
				$this->response(TRUE, '', 200, $res);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Not Updated'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
		}
	}

	function passwordLog()
	{
		$postvars = json_decode(file_get_contents("php://input"), true);
		$data = array(
			'user_id' => isset($postvars['userid']) ? $postvars['userid'] : $postvars['id'],
			'password_used' => md5(isset($postvars['confirmpassword']) ? $postvars['confirmpassword'] : $postvars['original_password'])
		);
		$res = $this->Api_Model->passwordLog($data);
		if ($res == 1) {
			$this->response(TRUE, '', 200, $res);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Not Updated'], 400);
		}
	}


	function checkPasswordLog()
	{
		$postvars = json_decode(file_get_contents("php://input"), true);
		$data = array(
			'user_id' => isset($postvars['userid']) ? $postvars['userid'] : $postvars['id'],
			'password_used' => md5(isset($postvars['newpassword']) ? $postvars['newpassword'] : $postvars['original_password'])
		);
		$res = $this->Api_Model->checkPasswordLog($data);
		if (!empty($res['user_id'])) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Already Exists'], 400);
		} else {
			$this->api_response(['success' => false, 'status_code' => 200, 'message' => ''], 200);
		}
	}

	public function changeuserpassword()
	{
		try {
			$token = $this->input->post('token');
			$this->get_loginsession($this->input->post('loginsession'));
			if ($token == "") {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
				return;
			}
			if ($this->setData($token) == false)
				return;

			$postvars = json_decode(file_get_contents("php://input"), true);

			if ($postvars !== null) {
				$keys_to_decrypt = ['oldpassword', 'confirmpassword', 'newpassword'];

				foreach ($keys_to_decrypt as $key) {
					if (isset($postvars[$key])) {
						$postvars[$key] = $this->fx->xor_decrypt($postvars[$key]);
					}
				}
			}

			if (array_key_exists($postvars['master_name'], $this->tableArr) == 1) {
				$retData = $this->Api_Model->changepassword($this->tableArr[$postvars['master_name']], $postvars);

				$old_password = md5($postvars['oldpassword']);
				if ($retData['status']) {

					if ($retData['data'][0]->password == $old_password) {
						if ($postvars['newpassword'] == $postvars['confirmpassword']) {
							$data['password'] = md5($postvars['newpassword']);
							$id = $postvars['userid'];
							$retData = $this->Api_Model->changepasswordinsert($this->tableArr[$postvars['master_name']], $data, $id);
							if ($retData['error']) {
								$this->api_response(['success' => false, 'status_code' => 400, 'message' => $retData['message']], 400);
							}
							$this->fx->generateUserLogs('3', $postvars['master_name'], $this->name, $this->user_id, $postvars);


							$this->response(TRUE, 'Updated Successfully', 200);
						} else {

							$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'New password and confirm password do not match'], 400);
						}
					} else {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Old Password Not Matched'], 400);
					}
				} else {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => $retData['error']], 400);
				}
			}
		}
		//  catch (Exception $e) {
		// }
		//  catch (MySqlException $e) {
		// 	fx::pr($e, 1);
		// } 
		catch (Exception $e) {
			fx::pr($e);
			die;
		}
	}



	function getDropdownOptions()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));

		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}

		if ($this->setData($token) == false)
			return;

		$masters = json_decode(file_get_contents("php://input"), true);
		foreach ($masters as $name) {
			if (array_key_exists($name, $this->tableArr) == 1) {
				$getQueueId = $this->Master_Model->getScalerCol("queue_id", "tms_user_master t1", "1=1 and t1.id = $this->user_id")->queue_id;
				$result = $this->Dropdown_Option_Model->getOptionList((array) $this->tableArr[$name], $this->user_id, $getQueueId, $this->full_control);
				if (isset($result['error'])) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => $result['error']], 200);
					return;
				}
				$retData[] = $result;
				@$masternamefordropddown[] = (array) $this->tableArr[$name];
			}
		}

		array_push($retData, @$masternamefordropddown);
		// fx::pr($retData,1);
		$this->response(TRUE, '', 200, $retData);
	}

	function getDropdownOptionstemailAccountForIncomming()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$masters = json_decode(file_get_contents("php://input"), true);

		$result = $this->Dropdown_Option_Model->getOptionList((array) 'tms_email_account_incomming', $this->user_id, "", $this->full_control, $masters['queue_id']);
		if (isset($result['error'])) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $result['error']], 200);
			return;
		}
		$retData[] = $result;
		$result = $this->Dropdown_Option_Model->getOptionList((array) 'tms_email_account_outgoing', $this->user_id, "", $this->full_control, $masters['queue_id']);
		if (isset($result['error'])) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $result['error']], 200);
			return;
		}
		$retData[] = $result;
		// @$masternamefordropddown[] = (array) $this->tableArr[$name];
		// }
		// }
		array_push($retData, ['tms_email_account_incomming', 'tms_email_account_outgoing']);
		$this->response(TRUE, '', 200, $retData);
	}

	public function getQueuePriorityDropdown()
	{
		$masters = json_decode(file_get_contents("php://input"), true);
		foreach ($masters as $name) {
			$result = $this->Dropdown_Option_Model->getQueuePriorityOptionList($name);
			if (isset($result['error'])) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $result['error']], 200);
				return;
			}
			$retData[] = $result;
			@$masternamefordropddown[] = (array) $name;
		}
		(is_array($retData)) ?? array_push($retData, [['tms_email_account_incomming'], ['tms_email_account_outgoing']]);
		$this->response(TRUE, '', 200, $retData);
	}

	public function getQueueStatusDropdown()
	{
		$masters = json_decode(file_get_contents("php://input"), true);
		foreach ($masters as $name) {
			$retData[] = $this->Dropdown_Option_Model->getQueueStatusOptionList($name);
			@$masternamefordropddown[] = (array) $name;
		}
		$this->response(TRUE, '', 200, $retData);
	}

	public function getQueueTemplateDropdown()
	{
		$masters = json_decode(file_get_contents("php://input"), true);
		foreach ($masters as $name) {
			$result = $this->Dropdown_Option_Model->getQueueTemplateOptionList($name);
			if (isset($result['error'])) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $result['error']], 200);
				return;
			}
			$retData[] = $result;
			@$masternamefordropddown[] = (array) $name;
		}

		(is_array($retData)) ?? array_push($retData, @$masternamefordropddown);
		$this->response(TRUE, '', 200, $retData);
	}

	public function getUserRights()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;


		$postvars = json_decode(file_get_contents("php://input"));
		$this->validateApi($postvars);
		$post = $this->input->post();
		$rightArr = $this->Api_Model->getMenuWithUserRights($post['userTypeId']);
		$this->fx->generateUserLogs('4', 'User Type Permissions', $this->name, $this->user_id, $post);
		if (isset($rightArr['error']) && $rightArr['error']) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $rightArr['message']], 400);
		}
		if (!empty($rightArr)) {
			$respArr = array();
			foreach ($rightArr as $key => $value) {
				if ($value['parent_id'] == 0) {
					$respArr[$value['id']] = $value;
					$respArr[$value['id']]['has_children'] = 0;
					foreach ($rightArr as $nkey => $nvalue) {
						if ($nvalue['parent_id'] == $value['id']) {
							$respArr[$nvalue['id']] = $nvalue;
							$respArr[$nvalue['id']]['has_children'] = 0;
							$respArr[$value['id']]['has_children'] = 1;
							foreach ($rightArr as $mkey => $mvalue) {
								if ($mvalue['parent_id'] == $nvalue['id']) {
									$respArr[$mvalue['id']] = $mvalue;
									$respArr[$mvalue['id']]['has_children'] = 0;
									$respArr[$nvalue['id']]['has_children'] = 1;
								}
							}
						}
					}
				}
			}
			$retArr = array();
			if (!empty($respArr)) {
				foreach ($respArr as $key => $val) {
					$retArr[] = $val;
				}
			}
			$this->response(TRUE, '', 200, $retArr);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data not found'], 400);
		}
	}

	function addUpdateUserRights()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;


		$postvars = json_decode(file_get_contents("php://input"));
		if (!empty($postvars)) {
			if (array_key_exists($postvars->master_name, $this->tableArr) == 1) {
				$master_name = $this->tableArr[$postvars->master_name];
				$retval = $this->Api_Model->updateUserRights($postvars, $master_name);

				$this->fx->generateUserLogs('2', 'User Type Permissions', $this->name, $this->user_id, $postvars, $postvars->userTypeId);

				if ($retval['status'] == true) {
					$this->response(TRUE, 'User Type rights updated successfully.', 200);
				} else {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => $retval['message']], 400);
				}
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Master Name'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Request'], 400);
		}
	}

	function addcomanydetails()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		// fx::pr($post,1);
		$this->load->library('upload');

		if ($post['file'] != '') {
			$config['upload_path'] = 'uploads/companyLogos/';
			$config['allowed_types'] = 'gif|jpg|png';
			$config['max_size'] = 2048;
			$config['max_width'] = 1024;
			$config['max_height'] = 768;

			$fcpath = str_replace("\\", "/", FCPATH);
			$folderPath = $fcpath . 'uploads/companyLogos/';
			$this->upload->initialize($config);
			$this->upload->do_upload($post['file']);
			$image_parts = explode(";base64,", $post['file']);
			$image_type_aux = explode("image/", $image_parts[0]);
			$image_base64 = base64_decode($image_parts[1]);
			$file = $folderPath . uniqid() . '.' . $image_type_aux[1];
			$fileactualname = explode("/", $file);
			$post['companylogo'] = $fileactualname[8];
			if (file_put_contents($file, $image_base64)) {
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'File Not Uploded'], 400);
				return false;
			}
		} else {
			unset($post['companylogo']);
			// $post['companylogo'] = $post['fileurl'];
		}


		if (!empty($post['master_name'])) {
			$masterName = $post['master_name'];
			$this->load->model('Master_Model');
			$rules = $this->Master_Model->getMasterTableRules($masterName);
			if (empty($rules)) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validations not defined.'], 400);
				return;
			}
			$this->form_validation->set_data($post);
			$this->form_validation->set_message('unique_module', 'Module already in use');
			$this->form_validation->set_rules($rules);
			if ($this->form_validation->run() === false) {
				$data = $this->form_validation->error_array();
				$firstError = (is_array($data)) ? array_keys($data) : [];
				throw new Exception($data[$firstError[0]]);
			} else {
				$this->load->model('Master_Model');
				$this->db->trans_begin();
				$dbData = $post;

				$respMsg = '';
				$dbFields = $this->Master_Model->getMasterTableFields($masterName);
				$db_keys = (is_array($dbData)) ? array_keys($dbData) : [];
				foreach ($db_keys as $keyName) {
					if (!in_array($keyName, $dbFields)) {
						unset($dbData[$keyName]);
					} else {
						if (array_key_exists($keyName, $dbData)) {
							$dbData[$keyName] = addslashes(trim($dbData[$keyName]));
						}
					}
				}
				$primaryKey = 'id';
				if ($post['removeFlag'] == 1) {
					$dbData['companylogo'] = '';
					$dbData['companylogo'] = '';
				}
				// fx::pr($post,1);
				if (empty($dbData[$primaryKey])) {
					$dbData['created_by'] = $this->user_id;
					$dbData['created_date'] = date('Y-m-d H:i:s');
				} else {
					$dbData['modified_by'] = $this->user_id;
					$dbData['modified_date'] = date('Y-m-d H:i:s');
				}

				if ($dbData['http_port'] == '') {
					$dbData['http_port'] = NULL;
				}
				if ($dbData['https_port'] == '') {
					$dbData['https_port'] = NULL;
				}
				$nodeEnvLocation = '/var/www/html/mailread/.env';
				$sshKey = $dbData['ssl_key'];
				$sshCert = $dbData['ssl_cert'];
				if ($dbData['https_port'] != "") {
					if (!file_exists($sshKey) || !file_exists($sshCert)) {
						$this->response(FALSE, 'SSH Key or SSH Cert file does not exists', 400);
					}
				} else {
					$dbData['ssl_cert'] = '';
					$dbData['ssl_key'] = '';
				}
				$retarr = $this->Master_Model->saveProcess($masterName, $dbData, $primaryKey);

				if (empty($dbData[$primaryKey])) {
					$this->fx->generateUserLogs('1', $masterName, $this->name, $this->user_id, $dbData);
				} else {
					$this->fx->generateUserLogs('2', $masterName, $this->name, $this->user_id, $dbData, $dbData[$primaryKey]);
				}

				if (empty($retarr['id'])) {
					$respMsg = 'Something goes wrong.';
				} else {
					$this->changeNodeSetup($post);
					$master_title = str_replace('_', ' ', $masterName);
					$master_title = ucwords(strtolower($master_title));
					$respMsg = !empty($post[$primaryKey]) ? $master_title . ' details updated successfully' : $master_title . ' details saved successfully';
				}
				if ($this->db->trans_status() === FALSE) {
					$this->db->trans_rollback();
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
				} else {
					$this->db->trans_commit();
					$this->response(TRUE, $respMsg, 200);
				}
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Request'], 400);
		}
	}

	function adduserdetails()
	{
		try {
			$token = $this->input->post('token');
			$this->get_loginsession($this->input->post('loginsession'));
			if ($token == "") {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 400);
				return;
			}
			if ($this->setData($token) == false)
				return;

			$post = json_decode(file_get_contents('php://input'));

			if ($post !== null && property_exists($post, 'original_password')) {
				$post->original_password = $this->fx->xor_decrypt("$post->original_password");
			}
			$post = (array) $post;
			$userType = $this->Api_Model->checkUserType($post['user_type']);
			$userType = strtolower($userType->title);
			if ($userType == 'admin') {
				$post['full_control'] = 1;
			} else {
				$post['full_control'] = 0;
			}
			if (!is_null($post['queue_id'])) {
				$filteredToppings = array_filter($post['queue_id'], function ($value) {
					return !is_null($value) && $value !== '';
				});
				$post['queue_id'] = array_values($filteredToppings);
			}

			$this->load->library('upload');
			if (isset($post['queue_id'][0])) {
				$post['queue_id'] = (is_array($post['queue_id']) ? implode(',', $post['queue_id']) : $post['queue_id']);
			} else {
				$post['queue_id'] = null;
			}
			if (isset($post['action_id'][0])) {
				$post['action_id'] = (is_array($post['action_id']) ? implode(',', $post['action_id']) : $post['action_id']);
			} else {
				$post['action_id'] = null;
			}

			$fcpath = str_replace("\\", "/", FCPATH);
			chdir($fcpath . '/uploads/userlogos/');

			if ($post['file'] != '') {

				$config['upload_path'] = 'uploads/userlogos/';
				$config['allowed_types'] = 'gif|jpg|png';
				$config['max_size'] = 2097152;
				$config['max_width'] = 1024;
				$config['max_height'] = 768;

				$folderPath = $fcpath . 'uploads/userlogos/';
				$this->upload->initialize($config);
				$this->upload->do_upload($post['file']);
				$image_parts = explode(";base64,", $post['file']);
				$image_type_aux = explode("image/", $image_parts[0]);
				$image_base64 = base64_decode($image_parts[1]);
				$file = $folderPath . uniqid() . '.' . $image_type_aux[1];
				$fileactualname = explode("/", $file);
				if ($post['Userlogo'] != "") {
					unlink($folderPath . $post['Userlogo']);
					$post['fileurl'] = "";
				}

				$post['Userlogo'] = $fileactualname[8];
				if (file_put_contents($file, $image_base64)) {
				} else {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'File Not Uploded'], 400);
					return false;
				}
			} else {
				if ($post['removeFlag'] == 1) {
					$post['Userlogo'] = "";
				} else {
					unset($post['Userlogo']);
				}
			}
			if (!empty($post['master_name'])) {
				$masterName = $post['master_name'];
				$this->load->model('Master_Model');
				$rules = $this->Master_Model->getMasterTableRules($masterName);
				if (empty($rules)) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validations not defined.'], 400);
					return;
				}
				$this->form_validation->set_data($post);
				$this->form_validation->set_message('unique_module', 'Module already in use');
				$this->form_validation->set_rules($rules);
				if ($this->form_validation->run() === false) {
					$data = $this->form_validation->error_array();
					$key = (is_array($data)) ? array_keys($data) : [];
					$err[] = $data[$key[0]];
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validation Error', 'result' => $err], 400);
				} else {
					$this->load->model('Master_Model');
					$this->db->trans_begin();
					$dbData = $post;

					$respMsg = '';

					$dbFields = $this->Master_Model->getMasterTableFields($masterName);
					$db_keys = (is_array($dbData)) ? array_keys($dbData) : [];
					foreach ($db_keys as $keyName) {
						if (!in_array($keyName, $dbFields)) {
							unset($dbData[$keyName]);
						} else {
							if (array_key_exists($keyName, $dbData)) {
								$dbData[$keyName] = addslashes(trim($dbData[$keyName]));
							}
						}
					}
					$primaryKey = 'id';
					if (!empty($dbData[$primaryKey])) {
						if (!empty($post['original_password'])) {
							$dbData['password'] = md5($post['original_password']);
						} else {
							unset($dbData['original_password']);
						}
					} else {
						$dbData['password'] = md5($post['original_password']);
					}
					if ($post['file'] == '' && !empty($dbData[$primaryKey]) && $post['fileurl'] == "") {

						if (file_exists($post['fileurl'])) {

							unlink($post['fileurl']);
						}
						if (file_exists($post['fileurl'])) {

							unlink($post['fileurl']);
						}


						// $dbData['Userlogo'] = "";
						// unset($dbData['Userlogo']);
						// unlink($dbData['Userlogo']);
					}
					// fx::pr($dbData['Userlogo'],1);
					// die;
					if (empty($dbData[$primaryKey])) {
						$dbData['created_by'] = $this->user_id;
						$dbData['created_date'] = date('Y-m-d H:i:s');
					} else {
						$dbData['modified_by'] = $this->user_id;
						$dbData['modified_date'] = date('Y-m-d H:i:s');
					}

					if (isset($dbData['email']) && strpos($dbData['email'], '*') !== false) {
						unset($dbData['email']);
					}
					if (isset($dbData['mobile_no']) && strpos($dbData['mobile_no'], '*') !== false) {
						unset($dbData['mobile_no']);
					}
					$retarr = $this->Master_Model->saveProcess($masterName, $dbData, $primaryKey);

					if (empty($dbData[$primaryKey])) {
						$this->fx->generateUserLogs('1', $masterName, $this->name, $this->user_id, $dbData);
					} else {
						$this->fx->generateUserLogs('2', $masterName, $this->name, $this->user_id, $dbData, $dbData[$primaryKey]);
					}

					$userid = array('user_id' => $retarr['id']);
					$this->db->where('id', $retarr['id'])->update('tms_user_master', $userid);

					if (empty($retarr['id'])) {
						$respMsg = $retarr['message'];
					} else {
						$master_title = str_replace('_', ' ', $masterName);
						$master_title = ucwords(strtolower($master_title));
						$respMsg = !empty($post[$primaryKey]) ? $master_title . ' details updated successfully' : $master_title . ' details saved successfully';
					}
					if ($this->db->trans_status() === FALSE) {
						$this->db->trans_rollback();
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
					} else {
						$this->db->trans_commit();
						$this->response(TRUE, $respMsg, 200);
					}
				}
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Request'], 400);
			}
		} catch (Exception $e) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'An error occurred: ' . $e->getMessage()], 400);
		}
	}

	function getPermissions()
	{
		$postvars = json_decode(file_get_contents("php://input"));
		$data = (array) $postvars;
		$post = $this->input->post();
		$this->get_loginsession($this->input->post('loginsession'));
		$data = array_merge($data, $post);
		if (!empty($data['token']) && !empty($data['master_name'])) {

			if ($this->setData($data['token']) == false)
				return;

			$retArr = array();
			$retArr['VIEW_RIGHT'] = 0;
			$retArr['ADD_RIGHT'] = 0;
			$retArr['EDIT_RIGHT'] = 0;
			$retArr['DELETE_RIGHT'] = 0;
			$retArr['EXPORT_RIGHT'] = 0;
			if ($this->full_control == 0) {
				$rights = $this->Api_Model->getUserTypeRights($this->user_type, $data['master_name']);
				if (isset($rights['error']) && $rights['error']) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => $rights['message']], 400);
				}
				if (!empty($rights)) {
					$retArr['VIEW_RIGHT'] = $rights[0]['view_right'];
					$retArr['ADD_RIGHT'] = $rights[0]['add_right'];
					$retArr['EDIT_RIGHT'] = $rights[0]['edit_right'];
					$retArr['DELETE_RIGHT'] = $rights[0]['delete_right'];
					$retArr['EXPORT_RIGHT'] = $rights[0]['export_right'];
				}
			} else {
				$retArr['VIEW_RIGHT'] = 1;
				$retArr['ADD_RIGHT'] = 1;
				$retArr['EDIT_RIGHT'] = 1;
				$retArr['DELETE_RIGHT'] = 1;
				$retArr['EXPORT_RIGHT'] = 1;
			}
			// $this->response(TRUE, '', 200, $retArr);
			$this->api_response(['success' => true, 'message' => 'Invalid Request', 'result' => $retArr, 'status_code' => 200], 200);
		} else {
			// $this->response(False,'Invalid Request');
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Request']);
		}
	}


	function getpermissionqueue()
	{
		$postvars = json_decode(file_get_contents("php://input"));
		$data = (array) $postvars;
		$post = $this->input->post();
		$data = array_merge($data, $post);
		$this->get_loginsession($this->input->post('loginsession'));
		if (!empty($data['token']) && !empty($data['master_name'])) {

			if ($this->setData($data['token']) == false)
				return;

			$retArr = array();
			$retArr['VIEW_RIGHT'] = 0;
			$retArr['ADD_RIGHT'] = 0;
			$retArr['EDIT_RIGHT'] = 0;
			$retArr['DELETE_RIGHT'] = 0;
			$retArr['EXPORT_RIGHT'] = 0;
			if ($this->full_control == 0) {
				$rights = $this->Api_Model->getUserTypeRights($this->user_type, $data['master_name']);
				if (isset($rights['error']) && $rights['error']) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => $rights['message']], 400);
				}
				if (!empty($rights)) {
					$retArr['VIEW_RIGHT'] = $rights[0]['view_right'];
					$retArr['ADD_RIGHT'] = $rights[0]['add_right'];
					$retArr['EDIT_RIGHT'] = $rights[0]['edit_right'];
					$retArr['DELETE_RIGHT'] = $rights[0]['delete_right'];
					$retArr['EXPORT_RIGHT'] = $rights[0]['export_right'];
				}
			} else {
				$retArr['VIEW_RIGHT'] = 1;
				$retArr['ADD_RIGHT'] = 1;
				$retArr['EDIT_RIGHT'] = 1;
				$retArr['DELETE_RIGHT'] = 1;
				$retArr['EXPORT_RIGHT'] = 1;
			}
			$this->response(TRUE, '', 200, $retArr);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Request'], 400);
		}
	}


	public function getUserTypePermisssion()
	{

		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$permission = $this->Api_Model->getUserTypePermisssion($this->user_id, $this->user_type);
		if (isset($permission['error']) && $permission['error']) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $permission['message']], 400);
		}
		$this->response(TRUE, '', 200, $permission);
	}

	// public function getselectpagination()
	// {

	// 	$res = $this->db->query('select record from tms_pagination_master where status= 1')->result_array();
	// 	$this->response(TRUE, '', 200, $res);
	// }

	public function getselectpagination()
	{
		try {
			$res = $this->db->query('select record from tms_pagination_master where status = 1');

			// Check if the query execution failed.
			if ($res === false) {
				throw new Exception("Database query failed");
			}

			$resultArray = $res->result_array();

			// Check if the result array is empty.
			if (empty($resultArray)) {
				throw new Exception("No records found");
			}

			$this->response(TRUE, '', 200, $resultArray);
		} catch (Exception $e) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $e->getMessage()], 400);
		}
	}


	function changePassword()
	{
		$post = $_POST;
		if ($post !== null) {
			$keys_to_decrypt = ['conf_pass', 'new_pass'];
			foreach ($keys_to_decrypt as $key) {
				if (isset($post[$key])) {
					$post[$key] = $this->fx->xor_decrypt($post[$key]);
				}
			}
		}
		$data = $this->Api_Model->resetPassword($post);
		if ($data == 1) {
			$this->api_response(['success' => true, 'status_code' => 200, 'message' => 'Password Changed Successfully'], 200);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Password Not Changed'], 400);
		}
	}

	function generateOTP()
	{
		return strval(mt_rand(1000, 9999));
	}

	public function sendOTPEmail()
	{
		// $post = $_POST;
		$post = (array) json_decode(file_get_contents("php://input"));
		$post = (array) $post['resetForm'];
		$checkEmailId = $this->Master_Model->checkEmailId($post['reset_email']);
		if (empty($checkEmailId) || $checkEmailId == 0) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Email Id'], 400);
		}
		$otp = $this->generateOTP();

		$stmpDetails = $this->Api_Model->getSmtpDetail();
		$this->load->library('mailer');
		$result = $this->mailer->sendOtp($post, $otp, $stmpDetails);
		if (!empty($result)) {
			if ($result == 'Failed to send OTP: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting') {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid SMTP details in company setup'], 400);
			} else {
				$res = $this->Master_Model->updateOTPinUserTbl($otp, $post['reset_email']);
				if ($res > 0) {
					$this->response(true, '', 200, '');
				}
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Request'], 400);
		}
	}

	function matchOTP()
	{
		$input_data = file_get_contents('php://input');
		$data = json_decode($input_data, true);
		// fx::pr($data['fieldotp']);
		$fieldOTp = $this->fx->xor_decrypt($data['fieldotp']);
		// fx::pr($fieldOTp,1);
		$emailId = $data['formData']['reset_email'];
		$checkfieldOTp = $this->Master_Model->checkfieldOTp($fieldOTp, $emailId);
		if (empty($checkfieldOTp) || $checkfieldOTp == 0) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid OTP Entered'], 400);
		} else {
			$this->response(true, '', 200, '');
		}
	}

	function getQueueChangeAllDropdown_for_home()
	{
		try {
			$token = $this->input->post('token');
			$this->get_loginsession($this->input->post('loginsession'));
			if ($token == "") {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
				return;
			}
			if ($this->setData($token) == false)
				return;


			$postvars = json_decode(file_get_contents("php://input"));
			$queue_ids = (is_array($postvars->queue_id) ? implode(',', $postvars->queue_id) : $postvars->queue_id);

			$data = (array) $postvars;
			$post = $this->input->post();
			$data = array_merge($data, $post);
			if (!empty($data['token'])) {
				$result = $this->Api_Model->getQueueChangeAllDropdown_for_home($data['queue_id'], $this->user_id, $this->full_control, $this->user_type);
				if (isset($result['error'])) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => $result['message']], 400);
				} else {
					// if ($nextqueuedata != null) {
					// 	return $result;
					// } else 
					{
						$this->response(TRUE, '', 200, $result);
					}
				}
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Request'], 400);
			}
		} catch (Exception $e) {

			return array('error' => $e);
		}
	}

	function getQueueChangeAllDropdown($nextqueuedata = null)
	{
		try {

			if (is_array($nextqueuedata) && count($nextqueuedata) > 0) {
				$postvars = $nextqueuedata;
			} else {
				$token = $this->input->post('token');
				$this->get_loginsession($this->input->post('loginsession'));
				if ($token == "") {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
					return;
				}
				if ($this->setData($token) == false)
					return;
				$postvars = json_decode(file_get_contents("php://input"));
			}
			$data = (array) $postvars;
			$post = $this->input->post();
			$data = array_merge($data, $post);
			if (!empty($data['token'])) {
				$result = $this->Api_Model->getQueueChangeAllDropdown($data['queue_id'], $this->user_id, $this->full_control, $this->user_type);
				if (isset($result['error'])) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => $result['message']], 400);
				} else {
					if (is_array($nextqueuedata) && count($nextqueuedata) > 0) {
						return $result;
					} else {
						$this->response(TRUE, '', 200, $result);
					}
				}
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Request'], 400);
			}
		} catch (Exception $e) {

			return array('error' => $e);
		}
	}

	function getCategoryData()
	{
		$postvars = json_decode(file_get_contents("php://input"));
		$data = (array) $postvars;
		$post = $this->input->post();
		$data = array_merge($data, $post);
		if (!empty($data['token'])) {
			$result = $this->Api_Model->getCategoryData($data);
			// print_r($result);die;
			foreach ($result as $key => $value) {
				// print_r($value);
				if ($value['priority'] == 0) {
					$result[$key]['priority'] = $value['priority_id'];
				}
			}
			array_unshift($result, ['id' => '0', 'text' => 'Select']);
			if (isset($result['error']) && $result['error']) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $result['message']], 400);
			}
			$this->response(TRUE, '', 200, $result);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Request'], 400);
		}
	}

	public function emailTest()
	{
		$post = (array) json_decode(file_get_contents('php://input'));
		$this->form_validation->set_data($post);
		if ($post['id'] == "") {
			$rules = array(
				array(
					'field' => 'outgoing_password',
					'label' => 'outgoing password',
					'rules' => 'required'
				),
				array(
					'field' => 'outgoing_user_name',
					'label' => 'Outgoing Mail',
					'rules' => 'trim|required'
				),
				array(
					'field' => 'outgoing_mail_server',
					'label' => 'Outgoing Mail Server',
					'rules' => 'trim|required'
				),
				array(
					'field' => 'outgoing_mail_server_port',
					'label' => 'Outgoing Mail Server Port',
					'rules' => 'trim|required'
				)


			);
			$this->form_validation->set_rules($rules);
			if ($this->form_validation->run() == false) {
				$data = $this->form_validation->error_array();
				$firstError = (is_array($data)) ? array_keys($data) : [];
				$this->response(false, $data[$firstError[0]], 400);
				return;
			}
		} else {
			$respArr = $this->Master_Model->getMasteremailAccountData($post['id'], $this->tableArr[$post['master_name']], 'id');
			if ($respArr['outgoing_password'] == "" && $post['outgoing_password'] == "") {
				$this->response(false, 'Outgoing password is required', 400);
			} else {
				if ($post['outgoing_password'] == "") {
					$post['outgoing_password'] = $respArr['outgoing_password'];
				}
				if (isset($post['outgoing_user_name']) && strpos($post['outgoing_user_name'], '*') !== false) {
					$post['outgoing_user_name'] = $respArr['outgoing_user_name'];
				}
			}
		}

		$this->load->library('mailer');

		// $emailaccount = $this->Api_Model->getemaildeitals($post['id']);
		// if (empty($post['outgoing_user_name'])) {
		// 	$this->response(false,  'User Name  is required', 400);
		// }
		// $password = $post['outgoing_password'] ? $post['outgoing_password'] : $emailaccount[0]->outgoing_password;

		// if (empty($password)) {
		// 	$this->response(false,'Password is required', 400);
		// }

		// if (empty($post['outgoing_mail_server'])) {
		// 	$this->response(false, 'Outgoing Mail Server is required', 400);
		// }

		// if (empty($post['outgoing_mail_server_port'])) {
		// 	$this->response(false,'Outgoing Mail Server Port is required', 400);
		// }

		// $this->load->library('Phpmail_Lib');

		// $mail = $this->phpmail_lib->load();
		$result = $this->mailer->setSenderConfiguration($post, 1);
		if (!empty($post['id'])) {
			$this->Api_Model->set_test_mail_details($post, $result, 'outgoing');
		}

		if ($result['success']) {
			$this->response(true, "Outgoing Email Test Successful", 200);
		} else {
			$this->response(false, $result['message']);
		}
		// $mail->SMTPOptions = array(
		// 	'ssl' => array(
		// 		'verify_peer' => false,
		// 		'verify_peer_name' => false,
		// 		'allow_self_signed' => false
		// 	)
		// );



		// try {
		// 	//Server settings
		// 	//    $mail->SMTPDebug =4;                                       // Enable verbose debug output

		// 	$mail->isSMTP();                                            // Set mailer to use SMTP
		// 	//  $mail->Host       = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers  . ';' . $this->input->post('out_mail_server')?$this->input->post('out_mail_server'):''
		// 	//  $mail->Host       = 'mail.sansoftwares.com';
		// 	$mail->Host       = $post['outgoing_mail_server'] ? $post['outgoing_mail_server'] : '';

		// 	$mail->SMTPAuth   = true;                                   // Enable SMTP authentication

		// 	$mail->Timeout       =   10; // set the timeout (seconds)
		// 	// $mail->SMTPKeepAlive = true; // don't close the connection between messages

		// 	$mail->Username   = $post['outgoing_user_name'];

		// 	$mail->Password   = $password;
		// 	//    $mail->SMTPSecure = 'tls';                                  // Enable TLS encryption, `ssl` also accepted

		// 	$mail->SMTPSecure = 'tls';


		// 	//  $mail->Port       = 587;
		// 	$mail->Port   = $post['outgoing_mail_server_port'];

		// 	//Recipients
		// 	$mail->setFrom($post['outgoing_user_name'], 'Email Testing');
		// 	$mail->addAddress('gaurav.singh@sansoftwares.com', 'Test Mail');     // Add a recipient


		// 	// Content
		// 	$mail->isHTML(true);                                  // Set email format to HTML
		// 	$mail->Subject = 'Test Mail';

		// 	$mail->Body    = 'This is a <b>Test Mail!</b>';
		// 	//$mail->AltBody = 'This is a the body in plain text for non-HTML mail clients';

		// 	if ($mail->send()) {
		// 		 $this->api_response(['success' => false, 'status_code'=>400,'message' => 'Valid Configuration', 200);
		// 	} else {
		// 		 $this->api_response(['success' => false, 'status_code'=>400,'message' => 'Invalid configuration',400);
		// 	}
		// 	//echo 'Message has been sent';
		// 	//return true;
		// } catch (Exception $e) {
		// 	 $this->api_response(['success' => false, 'status_code'=>400,'message' => 'Message could not be sent. Mailer Error: {$mail->ErrorInfo}',400);
		// 	//return false;
		// }
	}

	public function emailTestForCompany()
	{
		$post = (array) json_decode(file_get_contents('php://input'));
		$this->form_validation->set_data($post);
		if ($post['id'] == "") {
			$rules = array(
				array(
					'field' => 'smtp_password',
					'label' => 'SMTP Password',
					'rules' => 'required'
				),
				array(
					'field' => 'smtp_email',
					'label' => 'SMTP Email',
					'rules' => 'trim|required'
				),
				array(
					'field' => 'smtp_email_server',
					'label' => ' Mail Server',
					'rules' => 'trim|required'
				),
				array(
					'field' => 'smtp_port',
					'label' => 'Mail Server Port',
					'rules' => 'trim|required'
				)


			);
			$this->form_validation->set_rules($rules);
			if ($this->form_validation->run() == false) {
				$data = $this->form_validation->error_array();
				$firstError = (is_array($data)) ? array_keys($data) : [];
				$this->response(false, $data[$firstError[0]], 400);
				return;
			}
		} else {
			$respArr = $this->Master_Model->getMasterData($post['id'], $this->tableArr[$post['master_name']], 'id');
			if ($respArr['smtp_password'] == "" && $post['smtp_password'] == "") {
				$this->response(false, 'Outgoing password is required', 400);
			} else {
				if ($post['smtp_password'] == "") {
					$post['smtp_password'] = $respArr['smtp_password'];
				}
				if (isset($post['smtp_email']) && strpos($post['smtp_email'], '*') !== false) {
					$post['smtp_email'] = $respArr['smtp_email'];
				}
			}
		}
		$this->load->library('mailer');
		$result = $this->mailer->companysmtpsetup($post, 1);
		// fx::pr($result,1);
		if (!empty($post['id'])) {
			$this->Api_Model->set_test_mail_comp_details($post, $result);
		}

		if ($result['success']) {
			$this->response(true, "Outgoing Email Test Successful", 200);
		} else {
			$this->response(false, $result['message']);
		}
	}

	// public function getRuleList()
	// {
	// 	$token = $this->input->post('token');
	// $this->get_loginsession($this->input->post('loginsession'));
	// 	if ($token == "") {
	// 		 $this->api_response(['success' => false, 'status_code'=>400,'message' => 'Invalid Token.', 200);
	// 		return;
	// 	}
	// 	if ($this->setData($token) == false)
	// 		return;

	// 	$post = (array) json_decode(file_get_contents('php://input'));

	// 	$retData = $this->Api_Model->getRuleDataList($post['queue_id']);
	// 	if (!empty($retData)) {
	// 		$this->response(TRUE, '', 200, $retData);
	// 	} else {
	// 		 $this->api_response(['success' => false, 'status_code'=>400,'message' => 'Data Not Found',400);
	// 	}
	// }

	public function getRuleList()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		$retData = $this->Api_Model->getRuleDataList($post['queue_id'], $post['limit'], $post['page_no'], $post['rule_name'], $post['sort'], $post['order_by']);
		if (isset($retData['error']) && $retData['error']) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $retData['message']], 400);
		}
		if (!empty($retData)) {
			$this->response(TRUE, '', 200, $retData);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $retData['message']]);
		}
	}

	public function getAssignRuleList()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		$retData = $this->Api_Model->getAssignRuleDataList($post['queue_id'], $post['limit'], $post['page_no'], $post['sort'], $post['order_by']);
		if (!empty($retData)) {
			$this->response(TRUE, '', 200, $retData);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $retData['message']]);
		}
	}


	public function getFormBuilderList()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		$retData = $this->Api_Model->getFormBuilderDataList($post['queue_id'], $post['limit'], $post['page_no'], $post['sort'], $post['order_by']);
		$this->fx->generateUserLogs('4', 'Queue Form Fields', $this->name, $this->user_id, NULL);
		if (isset($retData['error']) && $retData['error']) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $retData['message']], 400);
		}
		if (!empty($retData)) {
			$this->response(TRUE, '', 200, $retData);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
		}
	}

	public function getTemplateList()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));

		$retData = $this->Api_Model->getTemplateDataList($post['queue_id'], $post['limit'], $post['page_no'], $post['sort'], $post['order_by']);
		$this->fx->generateUserLogs('4', 'Queue Template', $this->name, $this->user_id, NULL);
		if (isset($retData['error']) && $retData['error']) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $retData['message']], 400);
		}
		if (!empty($retData)) {
			$this->response(TRUE, '', 200, $retData);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
		}
	}

	public function getCategoryList()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));

		$retData = $this->Api_Model->getCategoryDataList($post['queue_id'], $post['limit'], $post['page_no'], $post['sort'], $post['order_by']);
		$this->fx->generateUserLogs('4', 'Queue Category', $this->name, $this->user_id, NULL);
		if (isset($retData['error']) && $retData['error']) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $retData['message']], 400);
		}
		if (!empty($retData)) {
			$this->response(TRUE, '', 200, $retData);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
		}
	}

	public function deleteRuleDetail()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = json_decode(file_get_contents("php://input"));
		$post = (array) $post;

		$this->load->model('Master_Model');
		$this->db->trans_begin();
		$dbData = $post;
		$respMsg = '';

		$primaryKey = 'rule_id';
		$retarr = $this->Api_Model->deleteQueueRule($post, $primaryKey);
		$this->fx->generateUserLogs('3', 'Queue Incomming Rule', $this->name, $this->user_id, $post, $post[$primaryKey]);
		if (!empty($retarr['error'])) {
			$respMsg = $retarr['message'];
		} else {
			$master_title = "Queue Rule";
			$master_title = ucwords(strtolower($master_title));
			$respMsg = $master_title . ' deleted successfully';
		}

		if ($this->db->trans_status() === FALSE) {
			$this->db->trans_rollback();
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
		} else {
			$this->db->trans_commit();
			if (!empty($retarr['error'])) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respMsg], 400);
			} else {
				$this->response(TRUE, $respMsg, 200);
			}
		}
	}

	public function deleteAssignRuleDetail()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;


		$post = json_decode(file_get_contents("php://input"));
		$post = (array) $post;

		$this->load->model('Master_Model');
		$this->db->trans_begin();
		$dbData = $post;
		$respMsg = '';

		$primaryKey = 'assign_rule_id';
		$retarr = $this->Api_Model->deleteQueueAssignRule($post, $primaryKey);
		$this->fx->generateUserLogs('3', 'Queue Manual Rule', $this->name, $this->user_id, $post, $post[$primaryKey]);
		if (!empty($retarr['error'])) {
			$respMsg = $retarr['message'];
		} else {
			$master_title = "Manual Ticket Rules";
			$master_title = ucwords(strtolower($master_title));
			$respMsg = $master_title . ' deleted successfully';
		}

		if ($this->db->trans_status() === FALSE) {
			$this->db->trans_rollback();
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
		} else {
			$this->db->trans_commit();
			if (!empty($retarr['error'])) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respMsg], 400);
			} else {
				$this->response(TRUE, $respMsg, 200);
			}
		}
	}

	public function getQueueRuleDetail()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;


		$postvars = json_decode(file_get_contents("php://input"));
		$this->validateApi($postvars);
		$post = $this->input->post();
		if (!empty($post['queue_id']) && !empty($post['rule_id'])) {
			$this->load->model('Master_Model');
			$primaryKey = 'rule_id';

			$respArr = $this->Master_Model->getQueueRulesData($post['rule_id'], $post['queue_id'], $primaryKey);
			$this->fx->generateUserLogs('4', 'Queue Rules', $this->name, $this->user_id, NULL);
			if (isset($respArr['error']) && $respArr['error']) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respArr['message']], 400);
			}
			if (!empty($respArr)) {
				$this->response(TRUE, '', 200, $respArr);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data not found'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Request'], 400);
		}
	}

	public function getQueueAssignRuleDetail()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;


		$postvars = json_decode(file_get_contents("php://input"));
		$this->validateApi($postvars);
		$post = $this->input->post();
		if (!empty($post['queue_id']) && !empty($post['assign_rule_id'])) {
			$this->load->model('Master_Model');
			$primaryKey = 'assign_rule_id';

			$respArr = $this->Master_Model->getQueueAssignRulesData($post['assign_rule_id'], $post['queue_id'], $primaryKey);
			$this->fx->generateUserLogs('4', 'Queue Manual Ticket Rule', $this->name, $this->user_id, NULL);
			if (!empty($respArr)) {
				$this->response(TRUE, '', 200, $respArr);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data not found'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Request'], 400);
		}
	}

	public function getQueueTemplateDetail()
	{
		$postvars = json_decode(file_get_contents("php://input"));
		$this->validateApi($postvars);
		$post = $this->input->post();
		if (!empty($post['queue_id']) && !empty($post['template_id'])) {
			$this->load->model('Master_Model');
			$primaryKey = 'template_id';

			$respArr = $this->Master_Model->getQueueTemplateData($post['template_id'], $post['queue_id'], $primaryKey);
			if (isset($respArr['error']) && $respArr['error']) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respArr['message']], 400);
			}
			if (!empty($respArr)) {
				$this->response(TRUE, '', 200, $respArr);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data not found'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Request'], 400);
		}
	}

	function getQueueCategoryDetail()
	{
		$postvars = json_decode(file_get_contents("php://input"));
		$this->validateApi($postvars);
		$post = $this->input->post();
		if (!empty($post['queue_id']) && !empty($post['category_id'])) {
			$this->load->model('Master_Model');
			$primaryKey = 'category_id';

			$respArr = $this->Master_Model->getQueueCategoryData($post['category_id'], $post['queue_id'], $primaryKey);
			if (isset($respArr['error']) && $respArr['error']) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respArr['message']], 400);
			}
			if (!empty($respArr)) {
				$this->response(TRUE, '', 200, $respArr);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data not found'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Request'], 400);
		}
	}


	public function getQueueDropdownOptions()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$data = json_decode(file_get_contents("php://input"), true);
		foreach ($data['type'] as $typeVal) {
			if (!empty($typeVal) && !empty($data['queue_id'])) {
				$result = $this->Dropdown_Option_Model->getQueueOptionList((array) $typeVal, $data['queue_id'], $this->user_id);
				if (isset($result['error'])) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => $result['error']], 200);
					return;
				}
				$retData[] = $result;

				@$masternamefordropddown[] = (array) $typeVal;
			}
		}

		array_push($retData, @$masternamefordropddown);
		$this->response(TRUE, '', 200, $retData);
	}

	public function addupdateQueueTemplates()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['master_name'])) {
			$masterName = $post['master_name'];
			$this->load->model('Master_Model');
			$this->form_validation->set_data($post);
			$rules = array(
				array(
					'field' => 'queue_id',
					'label' => 'Queue Id',
					'rules' => 'required'
				),
				array(
					'field' => 'template',
					'label' => 'Template Name',
					'rules' => 'trim|required'
				),
			);
			$this->form_validation->set_rules($rules);
			if ($this->form_validation->run() == false) {
				$data = $this->form_validation->error_array();
				$firstError = (is_array($data)) ? array_keys($data) : [];
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validation Error', 'result' => $data[$firstError[0]]], 400);
				return;
			} else {
				$data = $post;
				$masterName = "tms_queue_" . $data['master_name'] . '_' . $data['queue_id'];
				$this->db->trans_begin();
				$respMsg = '';
				$primaryKey = 'template_id';
				$retarr = $this->Master_Model->saveQueueTemplateData($masterName, $pKey = 'template_id', $post, $data);
				if ($retarr['error']) {
					$respMsg = $retarr['message'];
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respMsg], 400);
				} else {
					if (empty($dbData[$primaryKey])) {
						$this->fx->generateUserLogs('1', 'Queue Template', $this->name, $this->user_id, $post);
					} else {
						$this->fx->generateUserLogs('2', 'Queue Template', $this->name, $this->user_id, $post, $post[$primaryKey]);
					}
					$master_title = "Queue Template";
					$respMsg = !empty($post[$primaryKey]) ? $master_title . ' details updated successfully' : $master_title . ' details saved successfully';
				}
				if ($this->db->trans_status() === FALSE) {
					$this->db->trans_rollback();
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
				} else {
					$this->db->trans_commit();
					$this->response(TRUE, $respMsg, 200);
				}
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Master Name'], 400);
		}
	}

	// Dynamic form builder methods starts here

	function addupdateFormFields()
	{

		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['master_name'])) {
			$this->form_validation->set_data($post);
			$rules = array(
				array(
					'field' => 'field_description',
					'label' => 'Form Description',
					'rules' => 'trim|required'
				),
				array(
					'field' => 'field_name',
					'label' => 'Field Name',
					'rules' => 'trim|required'
				),
				array(
					'field' => 'data_type',
					'label' => 'Data Type',
					'rules' => 'trim|required'
				),
				array(
					'field' => 'field_length',
					'label' => 'Field Length',
					'rules' => 'trim|callback_fieldLengthRequired[' . $post['data_type'] . ']|greater_than_equal_to[1]|callback_fieldLengthVarCharMax[' . $post['data_type'] . ']|callback_fieldLengthDecimalMax[' . $post['data_type'] . ']'
				),
				array(
					'field' => 'decimal_length',
					'label' => 'Decimal Length',
					'rules' => 'trim|callback_decimalLengthRequired[' . $post['data_type'] . ']|greater_than_equal_to[1]|callback_fieldLengthDecimalDigitMax[' . $post['data_type'] . ']'
				),
				array(
					'field' => 'field_type',
					'label' => 'Field Type',
					'rules' => 'trim|callback_fieldTypeRequired[' . $post['data_type'] . ']'
				),
				array(
					'field' => 'field_values',
					'label' => 'Field Values',
					'rules' => 'trim|callback_dataRequired[' . $post['field_type'] . ']'
				),
				array(
					'field' => 'width',
					'label' => 'Width',
					'rules' => 'trim|greater_than_equal_to[25]|less_than_equal_to[1100]'
				),
			);
			$this->form_validation->set_rules($rules);
			$this->form_validation->set_message('dataRequired', 'The Field Values are required for Dropdown, MultiSelect Dropdown, Checkbox and Radio Buttons');
			$this->form_validation->set_message('fieldTypeRequired', 'The Field Type is required for the selected Data Type');
			$this->form_validation->set_message('fieldLengthRequired', 'The Field Length is required for the selected Data Type');
			$this->form_validation->set_message('decimalLengthRequired', 'The Decimal Length is required for the selected Data Type');
			$this->form_validation->set_message('defaultDataValue', 'The default value does not match with the defined values');
			$this->form_validation->set_message('checkDataLength', 'The length of values does not match with the defined length');
			$this->form_validation->set_message('fieldLengthDecimalMax', 'The maximum possible length for decimal data type is 65 significant digits and 30 digits after the decimal point.');
			$this->form_validation->set_message('fieldLengthDecimalDigitMax', 'The maximum possible length for decimal data type is 65 significant digits and 30 digits after the decimal point.');
			if ($this->form_validation->run() == false) {
				$data = $this->form_validation->error_array();
				$firstError = (is_array($data)) ? array_keys($data) : [];
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validation Error', 'result' => $data[$firstError[0]]], 400);
				return;
			} else {
				$data = $post;
				$masterName = "tms_" . $data['master_name'] . '_' . $data['queue_id'];
				$ticketTblName = "tms_ticket_master_" . $data['queue_id'];
				//CHECK FIELD NAME IN TABLE AND FORM FILEDS
				if (empty($data['field_id'])) {
					$fldRes = $this->Dynamicform_Model->getTableField($data['field_name'], $ticketTblName);
					if (!empty($fldRes)) {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'The field is already exist in the Ticket Table.'], 400);
						return;
					}
				}

				if (
					(strtolower($data['field_name']) == 'id') or
					(strtolower($data['field_name']) == "tms") or
					strpos(strtolower($data['field_name']), 'delete') !== false or
					strpos(strtolower($data['field_name']), 'drop') !== false or
					strpos(strtolower($data['field_name']), 'update') !== false or
					strpos(strtolower($data['field_name']), 'alter') !== false or
					strpos(strtolower($data['field_name']), 'insert') !== false
				) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Unauthorized keyword (<db name>, ID, INSERT, DROP, UPDATE, ALTER, DELETE) found for Field Name'], 400);
					return;
				}

				if (!empty($data['values_from_db']) && !empty($data['field_values'])) {
					if (
						// strpos(strtolower($data['field_values']), "tms") !== false or
						strpos(strtolower($data['field_values']), 'delete') !== false or
						strpos(strtolower($data['field_values']), 'drop') !== false or
						strpos(strtolower($data['field_values']), 'update') !== false or
						strpos(strtolower($data['field_values']), 'alter') !== false or
						strpos(strtolower($data['field_values']), 'insert') !== false
					) {

						$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Unauthorized keyword ({db name}, INSERT, DROP, UPDATE, ALTER, DELETE) found in SQL Statement.'], 400);
						return;
					} else {
						$sqlStmtarr = explode('from', strtolower($data['field_values']));
						if (!empty($sqlStmtarr[1])) {
							$sqlSubStmtarr = explode(' ', trim($sqlStmtarr[1]));
							if (!empty($sqlSubStmtarr[0]) && strpos(strtolower($sqlSubStmtarr[0]), '.') !== false) {

								$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Unauthorized keyword ({db name}, INSERT, DROP, UPDATE, ALTER, DELETE) found in SQL Statement.'], 400);
								return;
							}
						}
						$chkQuery = $this->Dynamicform_Model->checkDataValuesQuery($data['field_values']);
						if ($chkQuery['check']) {
							$optcount = $this->Dynamicform_Model->getDataCountThroughValuesQuery(str_replace(';', '', $data['field_values']));
							if (empty($optcount[0]->rowcnt)) {
								$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data not found from the result of your query.'], 400);
								return;
							}
							if ($optcount[0]->rowcnt > 50 && in_array(strtolower($data['field_type']), array('checkbox', 'radio'))) {
								$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Number of record are too long to render radio or checkbox fields. Max. 50 records are allowed'], 400);
								return;
							}
							$qres = $this->Dynamicform_Model->getDataByQuery(str_replace(';', '', $data['field_values']));
							if (!empty($qres)) {
								$idx = 0;
								foreach ($qres[0] as $rky => $rvl) {
									if ($idx == 0) {
										$data['db_val_column'] = $rky;
									} else if ($idx == 1) {
										$data['db_txt_column'] = $rky;
									}
									$idx++;
								}
							}
							if (empty($data['db_val_column'])) {
								$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Unable to find data columns from query. Please check the query.'], 400);
								return;
							}
						} else {
							$this->api_response(['success' => false, 'status_code' => 400, 'message' => $chkQuery['message']], 400);
							return;
						}
					}
				} else if (empty($data['values_from_db']) && !empty($data['field_values'])) {
					$frec = explode(',', $data['field_values']);
					if (count($frec) > 50 && in_array(strtolower($data['field_type']), array('checkbox', 'radio'))) {
						echo json_encode(array('statusCode' => 400, 'error' => 'Number of record are too long to render radio or checkbox fields. Max. 50 records are allowed'));
						return;
					}
				}

				if (isset($data['field_id']) && !empty($data['field_id'])) {
					$fieldData = $this->Dynamicform_Model->getFieldData($data['field_id'], $data['queue_id']);

					$updateData = $this->Dynamicform_Model->setFormFieldData($data);

					foreach ($updateData as $fldky => $fldvl) {
						if (in_array($fldky, array('field_name', 'field_length', 'decimal_length', 'unique_field', 'values_from_db'))) {
							if ($fldvl != $fieldData->data->{$fldky}) {
								//CHECK FIELD NAME IN TABLE
								$fldRes = $this->Dynamicform_Model->getTableField($fldvl, $ticketTblName);
								if (!empty($fldRes)) {
									$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'The entered field is already exist in the Table.'], 400);
									return;
								}
								if ($fldky == 'field_length') {
									//CHECK FIELD DATA LENGTH FOR COLUMN VALUES
									$res = $this->Dynamicform_Model->getTableFieldMaxLengthRecord($ticketTblName, $fieldData->data->field_name);
									if (strtolower($updateData['data_type']) != 'decimal') {
										if (!empty($res)) {
											$dtarr = explode('.', $res[0]->{$fieldData->data->field_name});

											if (strlen($dtarr[0]) > $data[$fldky]) {
												$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Field Length can not be less than maximum data length (' . $res[0]->maxlen . ') found for this field'], 400);
												return;
											}
										}
									} else {
										if (!empty($res) && ($res[0]->maxlen > $data[$fldky])) {
											$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Field Length can not be less than maximum data length (' . $res[0]->maxlen . ') found for this field'], 400);
											return;
										}
									}
								} else if ($fldky == 'unique_field' && !empty($fldvl)) {
									//CHECK DEDUPE FOR COLUMN VALUES
									$res = $this->Dynamicform_Model->getTableFieldDedupeRecord($ticketTblName, $fieldData->data->field_name);

									if (!empty($res) && ($res[0]->dedupe_cnt > 0)) {
										$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Duplicate values found for this field. It can not be applied UNIQUE'], 400);
										return;
									}
								} else if ($fldky == 'values_from_db') {
									$res = $this->Dynamicform_Model->getTableData($ticketTblName, $fieldData->data->field_name);
									if (!empty($res)) {
										$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data found in table. It can not modify the Values from Database'], 400);
										return;
									}
								}
							}
						}
					}

					$updateData['modified_by'] = $this->user_id;
					$updateData['modified_date'] = date('Y-m-d H:i:s');

					$db = $this->Dynamicform_Model->updateFormField($updateData, $data['field_id'], $masterName);
					$msg = 'Form Field detail have been updated successfully.';
					if ($db) {
						$modify = false;
						foreach ($updateData as $fldky => $fldvl) {
							if (in_array($fldky, array('field_name', 'data_type', 'field_length', 'decimal_length', 'field_type', 'default_value', 'unique_field', 'required'))) {
								if ($fldvl != $fieldData->data->{$fldky}) {
									$modify = true;
								}
							}
						}
						if ($modify) {
							//UPDATE TABLE FIELD
							$dbResp = $this->Dynamicform_Model->modifyTableColumn($ticketTblName, $data, $fieldData->data);
							if (!$dbResp) {
								$msg = $this->Dynamicform_Model->db->error();
							} else {
								if (empty($updateData['unique_field']) && !empty($fieldData->data->unique_field)) {
									//DELETE INDEXES MANUALLY
									$res = $this->Dynamicform_Model->getTableIndex($ticketTblName, $fieldData->data->field_name);
									if (!empty($res)) {
										foreach ($res as $rky => $indxarr) {
											$this->Dynamicform_Model->dropTableIndex($ticketTblName, $indxarr->Key_name);
										}
									}
								}
								if (!empty($updateData['unique_field']) && empty($fieldData->data->unique_field)) {
									$key_length = (strtolower($updateData['data_type']) == 'text') ? 20 : 0;
									$this->Dynamicform_Model->createTableIndex($ticketTblName, $updateData['field_name'], $key_length);
								}
							}
						}
					}
					$this->fx->generateUserLogs('2', 'Queue Form Fields', $this->name, $this->user_id, $data, $data['field_id']);
					$id = $data['field_id'];
				} else {
					$insData = $this->Dynamicform_Model->setFormFieldData($data);

					$insData['created_by'] = $this->user_id;
					$insData['created_date'] = date('Y-m-d H:i:s');
					$db = $this->Dynamicform_Model->createFormField($insData, $masterName);
					if ($db) {
						$this->Dynamicform_Model->addTableColumn($ticketTblName, $data);
						//CREATE INDEXE
						if (!empty($insData['unique_field'])) {
							$key_length = (strtolower($insData['data_type']) == 'text') ? 20 : 0;
							$this->Dynamicform_Model->createTableIndex($ticketTblName, $insData['field_name'], $key_length);
						}
						// }
					}
					$msg = 'Form Field detail have been added successfully.';
					$this->fx->generateUserLogs(1, "Queue Form Fields", $this->name, $this->user_id, $insData);
					$id = $db;
				}

				if (!empty($db)) {
					$this->response(TRUE, $msg, 200);
				} else {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validation Error', 'result' => 'Failed. Please try again'], 400);
					return;
				}
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Master Name'], 400);
		}
	}

	function fieldTypeRequired($value, $dataType)
	{
		if (!empty($dataType)) {
			if (!in_array(strtolower($dataType), array('attachment', 'text', 'datetime', 'date', 'email', 'phone', 'decimal', 'integer', 'linkurl'))) {
				if (empty($value))
					return false;
			}
		}
		return true;
	}

	function fieldLengthRequired($value, $dataType)
	{
		if (!empty($dataType)) {
			if (!in_array(strtolower($dataType), array('attachment', 'text', 'datetime', 'date', 'email', 'phone'))) {
				if (empty($value))
					return false;
			}
		}
		return true;
	}

	function decimalLengthRequired($value, $dataType)
	{
		if (!empty($dataType)) {
			if (strtolower($dataType) == 'decimal') {
				if (empty($value))
					return false;
			}
		}
		return true;
	}

	function dataRequired($value, $fieldType)
	{
		if (!empty($fieldType)) {
			if (in_array(strtolower($fieldType), array('dropdown', 'multiselect', 'checkbox', 'radio'))) {
				if (empty($value))
					return false;
			}
		}
		return true;
	}

	function defaultDataLength($value, $fieldLength)
	{
		if (!empty($fieldLength) && !empty($value)) {
			if (strlen($value) > $fieldLength) {
				return false;
			}
		}
		return true;
	}

	function defaultDataValue($value)
	{
		if (!empty($_POST['field_values']) && empty($_POST['values_from_db']) && !empty($value)) {
			$valArr = explode(',', $_POST['field_values']);
			if (!in_array($value, $valArr)) {
				return false;
			}
		}
		return true;
	}

	function fieldLengthVarCharMax($value, $datType)
	{
		if (!empty($datType)) {
			if (in_array(strtolower($datType), array('integer', 'string'))) {
				if (!empty($value) && $value > 9999)
					return false;
			}
		}
		return true;
	}

	function fieldLengthDecimalMax($value, $dataType)
	{
		if (!empty($dataType)) {
			if (strtolower($dataType) == 'decimal') {
				if (!empty($value) && $value > 65)
					return false;
			}
		}
		return true;
	}

	function fieldLengthDecimalDigitMax($value, $dataType)
	{
		if (!empty($dataType)) {
			if (strtolower($dataType) == 'decimal') {
				if (!empty($value) && $value > 30)
					return false;
			}
		}
		return true;
	}

	public function deleteDynFieldRec()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = json_decode(file_get_contents("php://input"));
		$post = (array) $post;

		$this->load->model('Master_Model');
		$this->db->trans_begin();
		$respMsg = '';

		$primaryKey = 'field_id';
		$retarr = $this->Dynamicform_Model->deleteDynFieldData($post, $primaryKey);
		$this->fx->generateUserLogs('3', 'Queue Form Fields', $this->name, $this->user_id, $post, $post[$primaryKey]);
		if (!empty($retarr['error'])) {
			$respMsg = $retarr['message'];
		} else {
			$master_title = "Form Fields";
			$master_title = ucwords(strtolower($master_title));
			$respMsg = $master_title . ' deleted successfully';
		}

		if ($this->db->trans_status() === FALSE) {
			$this->db->trans_rollback();
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
		} else {
			$this->db->trans_commit();
			if (!empty($retarr['error'])) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respMsg], 400);
			} else {
				$this->response(TRUE, $respMsg, 200);
			}
		}
	}

	public function deleteQueueTemplate()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = json_decode(file_get_contents("php://input"));
		$post = (array) $post;

		$this->load->model('Master_Model');
		$this->db->trans_begin();
		$respMsg = 'check!';

		$primaryKey = 'template_id';
		$retarr = $this->Api_Model->deleteTemplateData($post, $primaryKey);
		$this->fx->generateUserLogs('3', 'Queue Template', $this->name, $this->user_id, $post, $post[$primaryKey]);
		if (!empty($retarr['error'])) {
			$respMsg = $retarr['message'];
		} else {
			$master_title = "Queue Template";
			$master_title = ucwords(strtolower($master_title));
			$respMsg = $master_title . ' deleted successfully';
		}

		if ($this->db->trans_status() === FALSE) {
			$this->db->trans_rollback();
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respMsg], 400);
		} else {
			$this->db->trans_commit();
			if (!empty($retarr['error'])) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respMsg], 400);
			} else {
				$this->response(TRUE, $respMsg, 200);
			}
		}
	}

	function deleteQueueCategory()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;


		$post = json_decode(file_get_contents("php://input"));
		$post = (array) $post;

		$this->load->model('Master_Model');
		$this->db->trans_begin();
		$respMsg = '';
		$primaryKey = 'category_id';
		$retarr = $this->Api_Model->deleteCategoryData($post, $primaryKey);
		$this->fx->generateUserLogs('3', 'Queue Category', $this->name, $this->user_id, $post, $post[$primaryKey]);
		if (!empty($retarr['error'])) {
			$respMsg = $retarr['message'];
		} else {
			$master_title = "Queue Category";
			$master_title = ucwords(strtolower($master_title));
			$respMsg = $master_title . ' deleted successfully';
		}

		if ($this->db->trans_status() === FALSE) {
			$this->db->trans_rollback();
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respMsg], 400);
		} else {
			$this->db->trans_commit();
			if (!empty($retarr['error'])) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respMsg], 400);
			} else {
				$this->response(TRUE, $respMsg, 200);
			}
		}
	}

	public function deleteSubCategory()
	{
		$post = json_decode(file_get_contents("php://input", true));
		// print_r($post);die;
		$resp = $this->Api_Model->deleteSubCategory($post->queue_id, $post->sub_category_id);

		if ($resp > 0) {
			$this->api_response(['success' => false, 'status_code' => 200, 'message' => 'Sub Category Deleted successfully'], 200);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something went wrong'], 400);
		}
	}

	public function getDynFormFieldsDetail()
	{
		$postvars = json_decode(file_get_contents("php://input"));
		$this->validateApi($postvars);
		$post = $this->input->post();
		if (!empty($post['queue_id']) && !empty($post['field_id'])) {
			$this->load->model('Master_Model');
			$primaryKey = 'field_id';

			$respArr = $this->Dynamicform_Model->getFieldData($post['field_id'], $post['queue_id']);

			if (!empty($respArr)) {
				$this->response(TRUE, '', 200, $respArr);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data not found'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Request'], 400);
		}
	}


	// Dynamic form builder methods ends here


	public function unreadTicket()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['master_name'])) {
			$resData = $this->Master_Model->ticketUnread($post);
			$this->fx->generateUserLogs(
				'5', // Assuming '5' represents some kind of log type or action code
				'Ticket', // The type of action being logged, in this case, 'Ticket'
				$this->name, // The name of the user performing the action
				$this->user_id, // The user ID of the user performing the action
				$post, // The entire post data (assuming it contains relevant information)
				(is_array($post['ticket_unique_id']) ? implode(',', $post['ticket_unique_id']) : $post['ticket_unique_id']), // Convert ticket_unique_id to a string if it's an array
				'Ticket ' . (is_array($post['ticket_unique_id']) ? '(' . implode(',', $post['ticket_unique_id']) . ')' : '(' . $post['ticket_unique_id'] . ')') . ' is unread by ' . $this->name . ' In queue_id ' . $post['queue_id']  // Construct the log message
			);

			if (isset($resData['error']) && $resData['error']) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $resData['message']], 400);
			}
			// fx::pr($resData,1);
			if ($resData > 0) {

				$respMsg = "Unread successfully";
				$this->response(TRUE, $respMsg, 200);
			} else {
				$respMsg = "Something Went Wrong";
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respMsg], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Master Name'], 400);
		}
	}

	public function ticketMoveToJunk()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['master_name'])) {
			$resData = $this->Master_Model->ticketMoveToJunk($post);
			$this->fx->generateUserLogs('2', 'Ticket', $this->name, $this->user_id, $post, (is_array($post['ticket_unique_id']) ? implode(',', $post['ticket_unique_id']) : $post['ticket_unique_id']));
			if (isset($resData['error']) && $resData['error']) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $resData['message']], 400);
			}
			// fx::pr($resData,1);
			if ($resData > 0) {
				$respMsg = ($post['junk'] == 0) ? "Ticket moved to junk  successfully" : "Ticket moved to In Box successfully";
				$this->response(TRUE, $respMsg, 200);
			} else {
				$respMsg = "Something Went Wrong";
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $respMsg], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Master Name'], 400);
		}
	}

	public function getDynamicFormField()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['queue_id'])) {
			$master_name = "tms_dynamicform_fields_" . $post['queue_id'];
			if (!isset($post['type']) || $post['type'] == "") {
				$resData = $this->Api_Model->getDynamicFormField($master_name);
			} else {
				$resData = $this->Api_Model->getDynamicFormFieldStatusSetting($master_name);
			}
			if (isset($resData['error'])) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $$resData['message']], 400);
			}
			if (is_array($resData) && (count($resData) > 0)) {
				$this->response(TRUE, '', 200, $resData);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Queue Id is required'], 400);
		}
	}

	public function getEditTicketRec()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		if (empty($post['queue_id'])) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Queue Id is required'], 400);
		} elseif (empty($post['tktUnqId'])) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Ticket Id is required'], 400);
		} else {
			$previousNextId = array();
			if ($post['tktUnqId'] > 0) {
				$tktMstTbl = "tms_ticket_master_" . $post['queue_id'];
				$previousNextId = $this->Master_Model->getPreviousNextMasterId($tktMstTbl, 'ticket_unique_id', $post['tktUnqId']);
			}
			$resData = $this->Api_Model->getEditTicketRec($post);

			$dynamic_fields = $this->Api_Model->getQueueDynamicFieldMandatory($post['queue_id']);

			$flattened_fields = array();
			$where = '1=1';
			foreach ($dynamic_fields as $field) {
				$flattened_fields[] = $field['field_name'];
			}
			$dynamic_fields = implode(',', $flattened_fields);

			if (!empty($dynamic_fields)) {

				$resp = $this->Api_Model->getEmailTicketData($dynamic_fields, $post['queue_id'], $resData->masterData->from_email);
				if (!empty($resp)) {
					foreach ($resp[0] as $key => $value) {
						if (empty($resData->masterData->$key)) {
							$resData->masterData->$key = $resp[0][$key];
						}
					}
				}
			}


			if (isset($resData->error) && $resData->error) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $resData->message], 400);
			}
			if (isset($resData)) {
				foreach ($resData->conversationListData as $key => $val) {
					if (!empty($val->json_file_name) && $val->json_file_name != '') {
						$dateFolder = date('Y-m-d', strtotime($val->conversation_date));
						$path = str_replace(".json", "", $dateFolder . '/' . $val->json_file_name);
						// $data = $this->getJsonFileContent($path . '/' . $val->json_file_name);
						$data = LINK_FOLDER_PATH . $path . '/' . $val->json_file_name;
						$val->conversation = $data;
					}
				}

				$resData->previousNextId = array(
					'prevId' => $previousNextId['prevId'],
					'nextId' => $previousNextId['nextId'],
					'firstId' => $previousNextId['firstId'],
					'lastId' => $previousNextId['lastId'],
				);

				$data = array();
				$data[] = (object) array(
					"id" => $this->user_id,
					"user_name" => $this->name
				);
				// print_r($data);die;
				$this->response(TRUE, '', 200, $resData);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
			}
		}
	}

	public function getJsonFileContent($fileName)
	{
		$filePath = LINK_FOLDER_PATH . $fileName;
		if (file_exists($filePath)) {
			$fileContent = file_get_contents($filePath);
			$jsonData = json_decode($fileContent);
			if ($jsonData && isset($jsonData->bodyData)) {
				if (base64_encode(base64_decode($jsonData->bodyData, true)) === $jsonData->bodyData) {
					$decodedData = base64_decode($jsonData->bodyData);
					return $decodedData;
				} else {
					return $jsonData->bodyData;
				}
			}
		}
		return null;
	}

	public function jsonFileRead()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		$path = $post['data'];
		$date = $post['date'];
		$show_happycode = $post['show_happycode'];
		if (file_exists($path)) {
			$fileContent = file_get_contents($path);
			$jsonData = json_decode($fileContent);
			if ($jsonData && isset($jsonData->bodyData)) {
				if (base64_encode(base64_decode($jsonData->bodyData, true)) === $jsonData->bodyData) {
					$decodedData = base64_decode($jsonData->bodyData);
					if ($date <= '2024-01-12 11:31:43') {
						$decodedData = str_replace('<br>', '', $decodedData);
					}
					if ($this->full_control == 1 && $show_happycode == 1) {
					} else {
						// $pattern = '/happy code.*?<b>(\d+)<\/b>/';
						// $decodedData = preg_replace($pattern, 'xxxx', $decodedData);
						$pattern = '/happy code.*?<b>(\d+)<\/b>/';
						$replacement = '****';
						$decodedData = preg_replace($pattern, 'happy code is &nbsp;</span><b>' . $replacement . '</b>', $decodedData);
						$pattern2 = '/happy code.*?<strong>(\d+)<\/strong>/';
						$decodedData = preg_replace($pattern2, 'happy code is &nbsp;</span><strong>' . $replacement . '</strong>', $decodedData);
					}
					$this->response(TRUE, '', 200, $decodedData);
				} else {
					if ($this->full_control == 1 && $show_happycode == 1) {
					} else {
						// $pattern = '/happy code.*?<b>(\d+)<\/b>/';
						// $jsonData->bodyData = preg_replace($pattern, 'xxxx', $jsonData->bodyData);
						$pattern = '/happy code.*?<b>(\d+)<\/b>/';
						$replacement = '****';
						$jsonData->bodyData = preg_replace($pattern, 'happy code is &nbsp;</span><b>' . $replacement . '</b>', $jsonData->bodyData);
						$pattern2 = '/happy code.*?<strong>(\d+)<\/strong>/';
						$jsonData->bodyData = preg_replace($pattern2, 'happy code is &nbsp;</span><strong>' . $replacement . '</strong>', $jsonData->bodyData);
					}
					$this->response(TRUE, '', 200, $jsonData->bodyData);
				}
			}
		}
		$this->response(TRUE, '', 200, '');
	}


	public function updateIsNew()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['queue_id'])) {
			$master_name = "tms_ticket_master_" . $post['queue_id'];
			$resData = $this->Api_Model->updateIsNew($master_name, $post['tktUnqId']);
			if ($resData > 0) {
				$this->response(TRUE, '', 200, $resData);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Queue Id is required'], 400);
		}
	}

	public function checkAssignOnView()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['queue_id'])) {
			$master_name = "tms_ticket_master_" . $post['queue_id'];
			$resData = $this->Api_Model->checkAssignOnView($this->user_id, $master_name, $post['tktUnqId']);
			if ($resData > 0) {
				$this->response(TRUE, '', 200, $resData);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Queue Id is required'], 400);
		}
	}


	public function copyQueue()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['master_name'])) {
			$masterName = $post['master_name'];
			$this->load->model('Master_Model');
			$this->db->trans_begin();
			$dbData = $post;
			if (array_key_exists($masterName, $this->tableArr) == 1) {
				$retarr = $this->Master_Model->copyQueue($dbData, $masterName);
				if (isset($retarr['error']) && $retarr['error']) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => $retarr['message']], 400);
				}
				if (isset($retarr->incoming_email_account)) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Incoming Email Account Already used In Another Queue '], 400);
				}
				if (isset($retarr->msg)) {
					$respMsg = $retarr->msg;
				}
				if (isset($retarr[0]->incoming_email_account)) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Incoming Email Account Already used In Another Queue '], 400);
				}


				if (empty($retarr['id'])) {
					$respMsg = 'Something goes wrong.';
				} else {
					$master_title = str_replace('_', ' ', $masterName);
					$master_title = ucwords(strtolower($master_title));
					$respMsg = 'Queue Copied Successfully';
				}
				if ($this->db->trans_status() === FALSE) {
					$this->db->trans_rollback();
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
				} else {
					$this->db->trans_commit();
					$this->response(TRUE, $respMsg, 200);
				}
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Master Name'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Master Name'], 400);
		}
	}

	function addParentId()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['queue_id'])) {
			if (!empty($post['parent_id'])) {
				$master_name = 'tms_ticket_master_' . $post['queue_id'];
				$resData = $this->Api_Model->addParentId($master_name, $post);
				if (isset($resData['error']) && $resData['error']) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => $resData['message']], 400);
				}
				if (is_array($resData) && (count($resData) > 0)) {
					$this->response(TRUE, 'Parent Id added successfully', 200, $resData);
				} else {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'error', 'result' => 'Data Not Found'], 400);
				}
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'error', 'result' => 'Parent Id is required'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'error', 'result' => 'Queue Id is required'], 400);
		}
	}

	function getFromMailForReply()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['queue_id'])) {
			$resData = $this->Api_Model->getFromMailForReply($post);
			if (isset($resData['error']) && $resData['error']) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => $resData['message']], 400);
			}
			if (is_array($resData) && (count($resData) > 0)) {
				$this->response(TRUE, '', 200, $resData);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'error', 'result' => 'Data Not Found'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'error', 'result' => 'Queue Id is required'], 400);
		}
	}


	function sendReplyMails()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		$is_close = $post['isclose'];
		$is_reopen = $post['is_reopen'];
		$post['ticketData']->ticket_unique_id = $post['ticket_unique_id'];
		unset($post['ticket_unique_id']);
		$post = json_decode(json_encode($post['ticketData']), true);
		if ($post['ticket_unique_id'] != "" && $post['master_name']) {
			// create email_msg_id start here
			$post['uuid'] = $this->fx->generateEmailUnqMsgId($post['from_email']);
			// create email_msg_id ends here
			$primaryKey = 'ticket_unique_id';
			$masterName = $post['master_name'];
			$this->load->model('Master_Model');
			$rules = $this->Master_Model->getTicketTableRules();
			if (empty($rules)) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validations not defined.'], 400);
				return;
			}
			$this->form_validation->set_data($post);

			$this->form_validation->set_message('unique_module', 'Module already in use');
			$this->form_validation->set_rules($rules);
			if ($this->form_validation->run() === false) {
				$data = $this->form_validation->error_array();
				$firstError = (is_array($data)) ? array_keys($data) : [];
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validation Error', 400, $data[$firstError[0]]]);
			} else {
				// save attachment in folder with the name email_msg_id start here
				$post['msg_id'] = $this->fx->generateMsgId($post['uuid']);
				// $attachGolderName = explode('@',preg_replace("/[<>\-.]/", '', $post['uuid']));
				// $msgId = $attachGolderName[0];
				// $post['msg_id'] = $msgId;
				$this->load->library('upload');
				if (is_array($post['attachmentArray']) && (count($post['attachmentArray']) > 0)) {
					// $path = $_SERVER["DOCUMENT_ROOT"] . '/mailread/mail_attachment_folder/' . $post['msg_id'];
					// $path = '/var/www/html/mailread/mail_attachment_folder/' . $post['msg_id'];
					// if (!is_dir($path)) {
					// 	mkdir($path, 0777, true);
					// }
					$todayfolderPath = NODE_APP_PATH . date("Y-m-d") . '/';
					if (!is_dir($todayfolderPath)) {
						mkdir($todayfolderPath, 0777, true);
					}
					chmod($todayfolderPath, 0777);
					$path = $todayfolderPath . '/' . $post['msg_id'];
					if (!is_dir($path)) {
						mkdir($path, 0777, true);
					}
					chmod($path, 0777);
					$post['path'] = date("Y-m-d") . '/' . $post['msg_id'];
					$config['upload_path'] = $path;
					$config['allowed_types'] = 'gif|jpg|png|pdf|xls|xlsx|csv|txt|json|xml|doc';
					$config['overwrite'] = TRUE;
					$config['max_size'] = 15 * 1024 * 1024 / count($post['attachmentArray']);
					$config['max_width'] = 1024;
					$config['max_height'] = 768;
					$this->upload->initialize($config);

					$attachmentSize = 0;
					foreach ($post['attachmentArray'] as $attachment) {
						$mime_type = mime_content_type($attachment['data']);

						if (!in_array($mime_type, $this->allowedMimeTypes)) {
							$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'error', "result" => "Invalid file type"], 400);
							return false;
						}
						$attachmentSize += $attachment['size'];
					}
					if ($attachmentSize > 15 * 1024 * 1024) {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => "Total size of attachments cannot be greater than 15MB", 400]);
						return false;
					} else {
						foreach ($post['attachmentArray'] as $attachment) {
							$this->upload->do_upload($attachment['data']);
							$image_parts = explode(";base64,", $attachment['data']);
							$image_base64 = base64_decode($image_parts[1]);
							$file = $path . '/' . $attachment['name'];
							if (file_put_contents($file, $image_base64)) {
							} else {
								$this->api_response(['success' => false, 'status_code' => 400, 'message' => "Total size of attachments cannot be greater than 15MB", 'result' => "File Not Uploded"], 400);
								return false;
							}
						}
					}
				}
				// save attachment in folder with the name email_msg_id ends here
				$this->load->model('Master_Model');
				$this->db->trans_begin();

				//replace happy code in conversation start here

				// if($post['show_happycode'] == 0 && $this->full_control != 1){
				// 	$post['conversation'] = preg_replace('/\bxxxx\b/', $post['happy_code'], $post['conversation']);
				// }

				if ($this->full_control == 1 && $post['show_happycode'] == 1) {
				} else {
					$post['conversation'] = preg_replace('/\bxxxx\b/', $post['happy_code'], $post['conversation']);
				}

				//replace happy code in conversation ends here
				unset($post['happy_code']);
				unset($post['show_happycode']);
				$dbData = $post;

				$dbFields = $this->Master_Model->getTicketTableFields($masterName);
				$db_keys = (is_array($dbData)) ? array_keys($dbData) : [];
				foreach ($db_keys as $keyName) {
					if (!in_array($keyName, $dbFields)) {
						unset($dbData[$keyName]);
					} else {
						if (array_key_exists($keyName, $dbData)) {
							if (is_array($dbData[$keyName])) {
							} else {
								if ($keyName == "subject") {
									continue;
								} else {
									$dbData[$keyName] = addslashes(trim($dbData[$keyName]));
								}
							}
						}
					}
				}
				if ($is_close) {
					$dbData['ticket_closed_date'] = date('Y-m-d H:i:s');
					$dbData['is_closed'] = 1;
				}

				if ($is_reopen) {
					$dbData['ticket_closed_date'] = null;
					$dbData['is_closed'] = 0;
				}
				$dbData['last_updated_by'] = $this->user_id;

				$mailType = '';
				if ($post['type'] == 'reply_all') {
					$mailType = 'reply_all';
				} else if ($post['type'] == 'reply') {
					$mailType = 'reply';
				} else {
					$mailType = 'forward';
				}

				$retarr = $this->Master_Model->saveTicketData($masterName, $post, $dbData, $primaryKey, $mailType);
				$this->fx->generateUserLogs('2', 'Ticket', $this->name, $this->user_id, $dbData, $dbData[$primaryKey]);
				//  print_r($retarr);die;
				if (empty($retarr['id'])) {
					$respMsg = 'Something goes wrong.';
				} else {
					$master_title = str_replace('_', ' ', $masterName);
					$master_title = ucwords(strtolower($master_title));
					$respMsg = $post['is_draft'] == 1 ? 'Mail saved in draft' : 'Mail send successfully';
				}
				if ($this->db->trans_status() === FALSE) {
					$this->db->trans_rollback();
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
				} else {
					$this->db->trans_commit();
					$this->response(TRUE, $respMsg, 200, $retarr);
				}
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'error', 'result' => 'Ticket Id id required'], 400);
		}
	}


	public function defaultEncrypt($key, $no)
	{
		$iv = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
		$encodedEncryptedData = bin2hex(openssl_encrypt($no, "AES-128-CTR", $key, OPENSSL_RAW_DATA, $iv));
		return $encodedEncryptedData;
	}

	public function defaultDecrypt($key, $encno)
	{
		$iv = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
		$plainDecryptedData = openssl_decrypt(hex2bin($encno), "AES-128-CTR", $key, OPENSSL_RAW_DATA, $iv);
		return $plainDecryptedData;
	}

	public function loginIframe()
	{
		$post = json_decode(file_get_contents('php://input'));
		$masterPassword = 'S@N1@2$@N@' . date('Ymd');
		if ($post->password == $masterPassword) {
			$userdata = $this->Api_Model->checkSuperUserLogin($post->email);
		} else {
			$userdata = $this->Api_Model->checklogin($post->email, md5($post->password));
		}

		if (!$userdata) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Email or Password', 'result' => '']);
		} else {
			$userdata['menu_list'] = $this->Api_Model->getMenus($userdata[0]->full_control, $userdata[0]->user_type);
			$tempstring = $userdata[0]->user_id . '-' . $userdata[0]->email . '-' . $userdata[0]->mobile_no . '-' . $userdata[0]->user_type . '-' . $userdata[0]->full_control . '-' . $userdata[0]->queue_id . '-' . $userdata[0]->maskEmail . '-' . $userdata[0]->maskPhone;
			$logintoken = $this->fx->encrypt_decrypt('encrypt', $tempstring);
			$userdata['logintoken'] = $logintoken;
			$this->api_response(['success' => true, 'result' => $userdata]);
		}
	}

	function createticketlog()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = json_decode(file_get_contents("php://input"));

		$data = json_encode($post->data);
		$logArry[] = array(
			'action_performed_by' => $this->user_id,
			'action_method' => $post->method,
			'action_data' => $data,
			'action_adreess' => $_SERVER['SERVER_ADDR'],
			'table_name' => $post->table_name,
			'action_date' => date('Y-m-d H:i:s'),
		);
		// fx::pr($logArry,1);

		$this->db->insert_batch('tms_log_master', $logArry);
		$this->response(TRUE, 'logcreated', 200);
	}

	function getAssignRuleDetails()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['queue_id'])) {
			$master_name = "tms_queue_assign_rule_condition_" . $post['queue_id'];
			$resData = $this->Api_Model->getAssignRuleDetails($master_name, $post);
			if (is_array($resData) && (count($resData) > 0)) {
				$this->response(TRUE, '', 200, $resData);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Queue Id is required'], 400);
		}
	}

	function getAssignRuleActionDetails()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['queue_id'])) {
			$master_name = "tms_queue_assign_rule_action_" . $post['queue_id'];
			$resData = $this->Api_Model->getAssignRuleActionDetails($master_name, $post);
			if (is_array($resData) && (count($resData) > 0)) {
				$this->response(TRUE, '', 200, $resData);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Queue Id is required'], 400);
		}
	}

	function getAssignesToAgentData()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['queue_id'])) {
			$master_name = "tms_user_master";
			$resData = $this->Api_Model->getAssignesToAgentData($master_name, $post);
			if (is_array($resData) && (count($resData) > 0)) {
				$this->response(TRUE, '', 200, $resData);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Queue Id is required'], 400);
		}
	}

	function change_language()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));

		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['master_name'])) {
			$masterName = $post['master_name'];

			$this->load->model('Master_Model');
			$this->db->trans_begin();
			$dbData = $post;
			$primaryKey = 'id';
			unset($dbData['master_name']);
			$retarr = $this->Master_Model->saveProcess($masterName, $dbData, $primaryKey);
			$userid = array('user_id' => $retarr['id']);
			$this->db->where('id', $retarr['id'])->update('tms_user_master', $userid);

			if (empty($retarr['id'])) {
				$respMsg = 'Something goes wrong.';
			} else {
				$master_title = str_replace('_', ' ', $masterName);
				$master_title = ucwords(strtolower($master_title));
				$respMsg = !empty($post[$primaryKey]) ? $master_title . ' details updated successfully' : $master_title . ' details saved successfully';
			}
			if ($this->db->trans_status() === FALSE) {
				$this->db->trans_rollback();
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Something goes wrong'], 400);
			} else {
				$this->db->trans_commit();
				$this->response(TRUE, $respMsg, 200);
			}
		}
	}

	function getQueueOutgoingMailId()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));

		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['queue_id'])) {
			$resData = $this->Api_Model->getQueueOutgoingMailId($post);
			if (is_array($resData) && (count($resData) > 0)) {
				$this->response(TRUE, '', 200, $resData);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Queue Id is required'], 400);
		}
	}

	function getFooterUrl()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['queue_id'])) {
			$master_name = "tms_queue_master";
			$resData = $this->Api_Model->getFooterUrl($master_name, $post);
			if (is_array($resData) && (count($resData) > 0)) {
				$this->response(TRUE, '', 200, $resData);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Queue Id is required'], 400);
		}
	}


	function saveDashboardAutoRefresh()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		$resp = $this->Api_Model->updateAutoRefreshTime($post, $this->user_id);
		if ($resp) {
			$this->response(TRUE, '', 200, $resp);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'something went wrong'], 400);
		}
	}


	function saveAutoRefreshSwitchValue()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		$resp = $this->Api_Model->updateAutoRefreshSwitchValue($post, $this->user_id);
		if ($resp == true) {
			$this->response(TRUE, '', 200, $resp);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'something went wrong'], 400);
		}
	}

	function getAutoRefreshValue()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$resp = $this->Api_Model->getAutoRefreshValue($this->user_id);
		if ($resp) {
			$this->response(TRUE, '', 200, $resp);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'something went wrong'], 400);
		}
	}




	function SetBreak()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}

		if ($this->setData($token) == false)
			return;

		$post = (array) json_decode(file_get_contents('php://input'));
		$post['user_id'] = $this->user_id;
		$post['break_started_on'] = date('y-m-d H:i:s');
		$res = $this->Api_Model->saveBreak($post);
		if ($res == 1) {
			$userRes = $this->Api_Model->updateUserBreak($res, $this->user_id, $post);
			if ($userRes = 1) {
				$this->api_response(['success' => true, 'message' => 'Break Saved successfully', 'result' => '']);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'something went wrong'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'something went wrong'], 400);
		}
	}


	function getUserBreakState()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$res = $this->Api_Model->getBreakTime($this->user_id);
		if (!empty($res)) {
			$this->api_response(['success' => true, 'message' => '', 'result' => $res]);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'something went wrong'], 400);
		}
	}

	function setUserBreakCloseTime()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		// print_r($post);die;
		$res = $this->Api_Model->setUserBreakCloseTime($this->user_id, $post);
		if (!empty($res)) {
			$this->api_response(['success' => true, 'message' => '', 'result' => $res]);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'something went wrong'], 400);
		}
	}


	function stopBreak()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));
		$res = $this->Api_Model->stopBreak($this->user_id, $post);
		if ($res == 1) {
			$this->api_response(['success' => true, 'message' => '', 'result' => $res]);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'something went wrong'], 400);
		}
	}

	function getTicketRecordByStatus()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$postvars = json_decode(file_get_contents("php://input"), true);
		if (!empty($postvars['queue_id'][0]['id']) && !empty($postvars['status_name'])) {

			$status_id = $this->Api_Model->getStatusId($postvars['queue_id'][0]['id'], $postvars['status_name']);
			if (!empty($postvars['queue_id'][0]['id']) && !empty($postvars['category'])) {
				$category_id = $this->Api_Model->getCateogryId($postvars['queue_id'][0]['id'], $postvars['category']);
			}
			if (!empty($postvars['curdate'])) {
				$cur_date = !empty($postvars['curdate']) ? date("Y-m-d", strtotime($postvars['curdate'])) : '';
			}
			$pageNum = $postvars['offset'];
			$limit = $postvars['limit'];
			$offset = ($pageNum - 1) * $limit;
			// $resp = $this->Api_Model->getTicketRecordByStatus($postvars['queue_id'][0]['id'], $status_id[0]->status_id, $category_id[0]->category_id, $cur_date,$offset, $limit);
			$resp = $this->Api_Model->getTicketRecordByStatus($postvars['queue_id'][0]['id'], $status_id[0]->status_id, $category_id[0]->category_id, $cur_date, $postvars['from_date'], $postvars['to_date']);
			if ($resp) {
				$this->response(TRUE, '', 200, $resp);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'something went wrong'], 400);
			}
		}
	}


	public function getCronJobs()
	{
		// Read existing cron jobs from the crontab
		$cron_jobs = shell_exec('crontab -l');
		return explode("\n", trim($cron_jobs));
	}

	public function addCronJob($cronJob)
	{
		// Read existing cron jobs
		$existingCronJobs = $this->getCronJobs();

		// Append new cron job to existing list
		$existingCronJobs[] = $cronJob;
		// fx::pr($existingCronJobs,1);
		// Append new cron job to the crontab
		$this->updateCrontab($existingCronJobs);
	}
	private function updateCrontab($cronJobs)
	{
		// Save updated cron jobs list to the crontab
		$cronContent = implode("\n", $cronJobs) . "\n";
		shell_exec('echo "' . $cronContent . '" | crontab -');
	}

	public function deleteCronJob($index)
	{
		// Read existing cron jobs
		$cron_jobs = $this->getCronJobs();
		// Remove the cron job at the specified index
		if (isset($cron_jobs[$index])) {
			unset($cron_jobs[$index]);
		}
		// Update the crontab with the modified cron jobs list
		$this->updateCrontab($cron_jobs);
	}

	public function deleteCronJobAll()
	{
		// Read existing cron jobs
		$cron_jobs = $this->getCronJobs();
		$cron_jobs = [];
		// Update the crontab with the modified cron jobs list
		$this->updateCrontab($cron_jobs);
	}

	function timeToCron($time)
	{
		// Split the time string into hours and minutes
		list($hour, $minute) = explode(':', $time);

		// Ensure hour and minute are in valid ranges
		$hour = max(0, min(23, (int) $hour));
		$minute = max(0, min(59, (int) $minute));

		// Build the cron expression
		$cronExpression = "$minute $hour * * *";

		return $cronExpression;
	}

	function compareTimes($time1, $time2)
	{
		// Convert both times to the same format
		$time1 = date("H:i", strtotime($time1));
		$time2 = date("H:i", strtotime($time2));

		// Compare the times
		if ($time1 === $time2) {
			return true;
		} else {
			return false;
		}
	}



	function runCustomQuery()
	{
		$post = json_decode(file_get_contents("php://input"), true);
		$res = $this->Api_Model->run_query($post);

		if (!empty($res)) {
			$this->response(TRUE, '', 200, $res);
		}
	}


	function getTableColumns()
	{
		$post = json_decode(file_get_contents("php://input"), true);
		$resp = $this->Api_Model->getColumnName($post['table_name']);
		if (!empty($resp)) {
			$this->response(TRUE, '', 200, $resp);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'something went wrong'], 400);
		}
	}


	function changeNodeSetup($data)
	{

		// Define the location of the .env file
		$nodeEnvLocation = '/var/www/html/mailread/.env';
		$sshKey = $data['ssl_key'];
		$sshCert = $data['ssl_cert'];

		if ($data['https_port'] != "") {
			if (!file_exists($sshKey) || !file_exists($sshCert)) {
				$this->response(FALSE, 'SSH Key or SSH Cert file does not exists', 400);
			}
		} else {

			if ($data['ssl_cert'] != "") {
				$data['ssl_cert'] = '';
			} else {
				$data['ssl_cert'] = ' ';
			}
			if ($data['ssl_key'] != "") {
				$data['ssl_key'] = '';
			} else {
				$data['ssl_cert'] = ' ';
			}
		}
		// Check if the .env file exists
		if (!file_exists($nodeEnvLocation)) {
			$this->response(FALSE, 'Environment file not found', 400);
			return false;
		}

		// Read the entire .env file into an array of lines
		$lines = file($nodeEnvLocation, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

		// Define the mapping of keys in $data to keys in .env file
		$keyMappings = array(
			'http_port' => 'HTTP_PORT',
			'https_port' => 'HTTPS_PORT',
			'ssl_cert' => 'SSL_CERT',
			'ssl_key' => 'SSL_KEY',
			// Add more mappings as needed
		);
		$keyMappings = array_flip($keyMappings);
		// Initialize an empty array to store updated lines
		$updatedLines = [];
		// fx::pr($data,1);
		// Process each line in the .env file
		foreach ($lines as $line) {
			// Split the line into key and value
			list($key, $value) = array_map('trim', explode('=', $line, 2));

			// Check if the key is mapped from $data
			if (isset($keyMappings[$key])) {

				// Map the key to its counterpart in $data
				$dataKey = $keyMappings[$key];

				// Check if the key exists in $data and has a value
				if (isset($data[$dataKey])) {
					$updatedLines[] = "\t" . $key . ' = ' . $data[$dataKey];
					// if ($data[$dataKey] != $data['old_' . $dataKey]) {						
					// } else {						
					// 	$updatedLines[] = $line;
					// }
				} else {
					// Keep the original line if no change is needed
					$updatedLines[] = $line;
				}
			} else {
				// Keep the original line for keys not in $keyMappings
				$updatedLines[] = $line;
			}
		}
		// Convert the array of updated lines back to a string with newlines
		$updatedContents = implode("\n", $updatedLines);
		// fx::pr($updatedContents,1);

		// Write the updated contents back to the .env file
		if (file_put_contents($nodeEnvLocation, $updatedContents) !== false) {
			return true;
		} else {
			$this->response(FALSE, 'Failed to update environment file', 500);
			return false;
		}
	}



	function getQueueSettings()
	{
		$post = json_decode(file_get_contents("php://input"), true);

		$resp = $this->Api_Model->getQueueSetting($post['queue_id']);
		if (!empty($resp)) {
			$this->response(TRUE, '', 200, $resp);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'something went wrong'], 400);
		}
	}


	function sendDraftMail()
	{
		$post = json_decode(file_get_contents("php://input"), true);
		$resp = $this->Api_Model->sendDraftMail($post['data']['conversation_id'], $post['data']['queue_id'], $post['data']['ticket_unique_id']);
		if ($resp == true) {
			$this->response(TRUE, 'Mail Sent successfully', 200, '');
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'something went wrong'], 400);
		}
	}


	function deleteConversation()
	{
		$post = json_decode(file_get_contents("php://input"), true);

		if (isset($post['conversation_id']) && isset($post['queue_id'])) {

			$resp = $this->Api_Model->deleteConversation($post['conversation_id'], $post['queue_id'], $post['ticket_unique_id']);
			// print_r($resp);die;
			if ($resp == true) {
				$response = $this->Api_Model->getConversation($post['queue_id'], $post['ticket_unique_id']);
				if (!empty($response)) {
					$updateresp = $this->Api_Model->updateConversation($post['queue_id'], $response, $post['ticket_unique_id']);

					if ($updateresp == true) {
						$this->response(TRUE, 'Conversation deleted successfully', 200, '');
					} else {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'something went wrong'], 400);
					}
				}
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'something went wrong'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'something went wrong'], 400);
		}
	}



	function getAPRLogLastRecord($agent_id)
	{
		$res = $this->Api_Model->getAPRLogLastRecord($agent_id);
		return $res;
	}


	// function InsertAPRLog($data=array(),$state=null){
	// 	// print_r($data);die;
	// 	$post = json_decode(file_get_contents("php://input"), true);
	// 	// print_r($post);die;
	// 	$agent_id = isset($post['agent_id'])?$post['agent_id']:$data[0]->id;
	// 	// print_r($agent_id);die;
	// 	if(!empty($agent_id)){

	// 		$res = $this->getAPRLogLastRecord($agent_id);
	// 	}
	// 	// print_r($res);die;
	// 	$data = array(
	//       "agent_id"=>isset($post['agent_id'])?$post['agent_id']:$data[0]->id,
	// 	  "agent_name"=>isset($post['agent_name'])?$post['agent_name']:$data[0]->user_name,
	// 	  "ticket_id"=>isset($post['ticket_id'])?$post['ticket_id']:null,
	// 	  "queue_id"=>isset($post['queue_id'])?$post['queue_id']:null,
	// 	  "start_time"=>date('Y-m-d H:i:s'),
	// 	  "end_time"=>"",
	// 	  "duration"=>$res->duration,
	// 	  "state"=>isset($post['state'])?$post['state']:$state,
	// 	  "break_id"=>"",
	// 	  "break_name"=>"",
	// 	  "ip_address"=>$_SERVER['REMOTE_ADDR'],
	// 	  "break_time"=>"",
	// 	  "is_login"=>"1",
	// 	  "remark"=>""
	// 	);
	// 	// print_r($data);die;

	// 	$this->Api_Model->InsertAPRLog($data);
	// }


	function InsertAPRLog()
	{
		$post = json_decode(file_get_contents("php://input"), true);
		$this->db->trans_begin();
		$res = $this->Api_Model->InsertAPRLog($post);
		if ($this->db->trans_status() === FALSE) {
			$this->db->trans_rollback();
			throw new Exception('Something goes wrong');
		} else {
			$this->db->trans_commit();
			$this->response(TRUE, 'APR Log Saved', 200, '');
		}
	}


	function getAPRReport()
	{
		$post = json_decode(file_get_contents("php://input"), true);
		// print_r($post);die;
		if (!empty($post)) {
			$res = $this->Api_Model->getAPRReport($post);
			if (!empty($res)) {
				$this->response(TRUE, '', 200, $res);
			} else {
				// $this->api_response(['success' => false, 'status_code' => 400, 'message' => 'something went wrong'], 400);
				$this->response(TRUE, 'No Record Found', 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'something went wrong'], 400);
		}
	}

	public function downloadAllAttachments()
	{
		$this->load->library('zip');

		$post = json_decode(file_get_contents("php://input"), true);
		$data = $post['data'];
		foreach ($data as $attachment) {
			$file_path = $_SERVER['DOCUMENT_ROOT'] . '/tms_v2.0/mail_json_file/' . $attachment['attachement_filepath'];
			if (file_exists($file_path)) {
				$this->zip->read_file($file_path, $attachment['attachement_name']);
			} else {
				log_message('error', 'File not found: ' . $file_path);
			}
		}
		$zip_name = 'attachment_' . time() . '.zip';

		header('Content-Type: application/zip');
		header('Content-Disposition: attachment; filename="' . $zip_name . '"');
		header('Content-Transfer-Encoding: binary');
		header('Cache-Control: must-revalidate');
		header('Pragma: public');
		return $this->zip->download($zip_name);
	}

	function getCategoryIdForEscalation()
	{
		$post = json_decode(file_get_contents("php://input"), true);
		$retData = $this->Dropdown_Option_Model->getCategoryIdForEscalation($post['queue_id']);
		$this->response(TRUE, '', 200, $retData);
	}

	function incomingEmailTest()
	{
		$post = (array) json_decode(file_get_contents('php://input'));
		$this->form_validation->set_data($post);
		if ($post['id'] == "") {
			$rules = array(
				array(
					'field' => 'incoming_password',
					'label' => 'Incoming password',
					'rules' => 'required'
				),
				array(
					'field' => 'incoming_user_name',
					'label' => 'Incoming Mail',
					'rules' => 'trim|required'
				),
				array(
					'field' => 'incoming_mail_server',
					'label' => 'Incoming Mail Server',
					'rules' => 'trim|required'
				),
				array(
					'field' => 'incoming_mail_server_port',
					'label' => 'Incoming Mail Server Port',
					'rules' => 'trim|required'
				)


			);
			$this->form_validation->set_rules($rules);
			if ($this->form_validation->run() == false) {
				$data = $this->form_validation->error_array();
				$firstError = (is_array($data)) ? array_keys($data) : [];
				$this->api_response(false, $data[$firstError[0]], 400);
				return;
			}
		} else {
			$respArr = $this->Master_Model->getMasteremailAccountData($post['id'], $this->tableArr[$post['master_name']], 'id');
			if ($respArr['incoming_password'] == "" && $post['incoming_password'] == "") {
				$this->api_response(false, 'Incoming password is required', 400);
			} else {
				if ($post['incoming_password'] == "") {
					$post['incoming_password'] = $respArr['incoming_password'];
				}
				if (isset($post['incoming_user_name']) && strpos($post['incoming_user_name'], '*') !== false) {
					$post['incoming_user_name'] = $respArr['incoming_user_name'];
				}
			}
		}
		// fx::pr($post,1);
		if ($post['is_auth_enable'] != 1) {
			$this->load->library('mailer');
			$result = $this->mailer->setIncommingConfiguration($post, 1);
		} else {
			// Oauth2 implementation start here

			$result = $this->handleOAuth2($post);
			if (!empty($result)) {
				$url = $result;
				//$this->api_response(true, '', 200, $url);
				$this->response(TRUE, '', 200, $url);
			}
			// Oauth2 implementation ends here
		}
		if (!empty($post['id'])) {
			$this->Api_Model->set_test_mail_details($post, $result, 'incoming');
		}

		if ($result['success']) {
			$this->api_response(true, "Imap connection successfull", 200);
		} else {
			$this->api_response(false, $result['message'], 400);
		}
	}

	public function handleOAuth2($post)
	{

		$tokenAndRefreshToken = $this->Master_Model->getTokenAndRefreshToken($post['id'], $this->tableArr[$post['master_name']]);
		$client_id = $post['client_oauth2_id'];
		$client_secret = $post['client_secret'];
		$tenant_id = $post['tenant_id'];
		$redirect_uri = "http://localhost/tms_v2.0/api/Callback/redirect"; // Make sure you have a redirect URI
		$scope = 'https://outlook.office365.com/IMAP.AccessAsUser.All offline_access';
		$authUrl = 'https://login.microsoftonline.com/' . $tenant_id . '/oauth2/v2.0/authorize' .
			'?client_id=' . $client_id .
			'&response_type=code' .
			'&redirect_uri=' . urlencode($redirect_uri) .
			'&response_mode=query' .
			'&scope=' . urlencode($scope) .
			'&state=' . urlencode(json_encode(['id' => $post['id'], 'agent_id' => $this->fx->user_id]));
		// fx::pr($authUrl,1);
		return $authUrl;
	}


	function previewAttachment()
	{
		$post = json_decode(file_get_contents("php://input"), true);
		// print_r($post);die;
		$attachmentUrl = $post['data']['url'];
		// $clientId = $post['data']['client_id'];

		$fileNameArray = explode('.', $attachmentUrl);
		// print_r($fileNameArray);die;
		$fileExtension = $fileNameArray[count($fileNameArray) - 1];
		$filePath = $_SERVER['DOCUMENT_ROOT'] . '/tms_v2.0/mail_json_file/' . $attachmentUrl;
		if (file_exists($filePath)) {
			$path = base_url() . '/tms_v2.0/mail_json_file/' . $attachmentUrl;
			$fileExtension = pathinfo($filePath, PATHINFO_EXTENSION);
			if ($fileExtension == 'php') {
				echo json_encode(['url' => '', 'message' => 'No preview avaliable']);
				return;
			}
			echo json_encode(['url' => $path]);
			return;
		} else {
			echo json_encode(['url' => '', 'message' => 'File not found']);
			return;
		}
	}


	function getCustomReportListData()
	{
		error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE);
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		// $array = explode("-", $this->decode($token));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 400);
			return;
		}
		if ($this->setData($token) == false)
			return;

		$postvars = json_decode(file_get_contents("php://input"), true);
		$report_id = $postvars['data']['result']['id'];
		if (empty($report_id)) {
			$this->api_response(['success' => false, 'status_code' => 400]);
		}
		$dbData = $postvars['data']['searchFieldsArray'];
		$masterData = $postvars['data']['result'];
		$filter = $postvars['filter'];


		$rules[] = ['field' => 'report_id', 'label' => 'report_id', 'rules' => 'required|trim'];
		$where = "1=1";

		// Prepare validation rules and where query**********START
		list($success, $masterData, $where, $rules, $t) = $this->validateCustomQueryResult($dbData, $where, $masterData, $rules, $filter);
		// Prepare validation rules and where query**********END		

		$filter['report_id'] = $report_id;
		$this->form_validation->set_data($filter);

		$this->form_validation->set_rules($rules);
		// fx::pr($rules,1);

		if ($this->form_validation->run() === false) {
			$data = $this->form_validation->error_array();

			$firstError = (is_array($data)) ? array_keys($data) : [];
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validation Error', 'result' => $data[$firstError[0]]], 400);
		}

		//$query = trim(str_replace("where 1=1", "where $where", $masterData['report_query']));
		//$query = trim(str_replace("@istablename", "''", $masterData['report_query']));

		$haystack = $masterData['report_query'];

		$needle   = 'where 1=1';

		if (strpos($haystack, $needle) !== false) {
			$query = trim(str_replace("where 1=1", "where $where", $masterData['report_query']));
		} else {
			$query = trim(str_replace("@istablename", "''", $masterData['report_query']));
		}

		$result['count'] = 0;
		$pageNo = (!empty($postvars['page_no'])) ? $postvars['page_no'] : 0;

		// Create Pagination **************START		 
		$query = str_replace(['##user_id##', '##user_name##'], [@$_SESSION['id'], @$_SESSoION['user_name']], $query);
		// list($success, $result, $query, $pageNo, $limit, $message) = $this->createPaginatinByQuery($result, $query, $pageNo);
		// fx::pr([$success, $result, $query, $pageNo, $limit, $message] ,1);
		// if ($success == false) {
		// 	echo "<div class='alert alert-danger'>$message<br> $query </div>";
		// 	return;
		// }

		// Create Pagination **************START
		$limit = (int) $postvars['limit'];
		$newQry = str_replace(['`', "'", '"'], ['', '', ''], $query);
		if (strstr($newQry, ' ', true) != 'call') {
			$result['count'] = $this->Api_Model->reportQueryResult($query, true);
		} else {
			$rowlimit = '';
			$result['count'] = $this->Api_Model->reportQueryResult(str_replace('@rowlimit', "'$rowlimit'", $query), true);
		}
		if (empty($limit))
			$limit = 10;
		$offset = ($pageNo - 1) * $limit;
		if (strstr($newQry, ' ', true) != 'call') {
			$query = "$query limit $offset , $limit";
		} else {
			$query = str_replace('@rowlimit', "'$offset,$limit'", $query);
		}
		$result['data'] = $this->Api_Model->reportQueryResult($query);
		if (count($result['data']) < 1 && !empty($this->Api_Model->message)) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validation Error', 'result' => $this->Api_Model->message . "----------- $query --------"], 400);
		}

		if ($result['count'] == 0) {
			$result['count'] = $limit = count($result['data']);
			$page_count = 1;
		} else {
			$page_count = ceil($result['count'] / $limit);
		}
		$ret_data = array(
			'error' => false,
			'total' => $result['count'],
			'records' => $result['data'],
			'page_count' => $page_count,
		);
		$this->response(TRUE, '', 200, $ret_data);
	}


	function validateCustomQueryResult($dbData, $where, $masterData, $rules, $filter)
	{
		foreach ($dbData as $key => $value) {
			$value['display_name'] = str_replace([' '], ['_'], acceptOnlyCharctersAndNumberWithSpace($value['display_name']));
			if ($value['parameter'] != "") {
				$validateFieldName = $postname = strtolower(str_replace('.', '_s_n_', ($value['display_name'] != '') ? $value['display_name'] : $value['search_field_name']));
			} else {

				$validateFieldName = $postname = $value['search_field_name'];
			}

			if ($value['input_type'] == 'multiselect') {
				$validateFieldName .= '[]';
			}

			if ($value['allow_null'] == 0) {
				$rules[] = ['field' => "$validateFieldName", 'label' => ($value['display_name'] != '') ? (str_replace(['_'], [' '], $value['display_name'])) : ((str_replace('_s_n_', '.', $validateFieldName))), 'rules' => 'required|trim'];
			}

			if (!in_array($value['default_operator'], ['is null', 'is not null'])) {
				switch ($value['input_type']) {
					case 'datetime':
						if (!empty($filter[$postname])) {
							$where .= " and date_format($value[search_field_name],'%Y-%m-%d %H:%i:%s') $value[default_operator] '" . (convertDateTimeToDB($filter[$postname])) . "'";
						}
						break;
					case 'date':
						if (!empty($filter[$postname])) {
							$where .= " and date_format($value[search_field_name],'%Y-%m-%d') $value[default_operator] '" . (convertDateToDB($filter[$postname])) . "'";
						}
						break;
					case 'multiselect':
						if (!empty($filter[$postname])) {
							$where .= " and $value[search_field_name] in ('" . implode("','", $filter[$postname]) . "')";
						}
						break;
					default:

						if (isset($filter[$postname]) && $filter[$postname] != '') {
							$where .= " and $value[search_field_name] $value[default_operator] '" . ($filter[$postname]) . "'";
						}
						break;
				}
			} else {
				$where .= " and $value[search_field_name] $value[default_operator]";
			}

			// // IN Case Of procedure Call
			// if ($value['parameter'] != '') {
			// $date = date_create($_POST[$postname]);
			// $final_date = date_format($date, 'Y-m-d H:i:s');
			// $masterData['report_query'] = str_replace("$value[parameter]","'$final_date'", $masterData['report_query']);
			// // $masterData['report_query'] = str_replace("$value[parameter]", $_POST[$postname], $masterData['report_query']);
			// }

			// IN Case Of procedure Call
			if ($value['parameter'] != '') {
				$parameterval = $filter[strtolower($postname)];

				if ($value['input_type'] == 'date' || $value['input_type'] == 'datetime') {
					if (strlen($parameterval) > 10) {
						$finalval = date('Y-m-d H:i:s', strtotime($parameterval));
						// $finalval =date_create($parameterval)->format('Y-m-d H:i:s');
					} else {
						$finalval = date('Y-m-d', strtotime($parameterval));
					}
				} else {
					$finalval = $parameterval;
				}
				//date time or date condition end
				$masterData['report_query'] = str_replace("$value[parameter]", "'$finalval'", $masterData['report_query']);
				// $masterData['report_query'] = str_replace("$value[parameter]", $_POST[$postname], $masterData['report_query']);
			}
		}

		return [true, $masterData, $where, $rules, true];
	}

	function saveCustomReport()
	{
		$token = $this->input->post('token');
		$this->get_loginsession($this->input->post('loginsession'));
		if ($token == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token.'], 200);
			return;
		}
		if ($this->setData($token) == false)
			return;
		$post = (array) json_decode(file_get_contents('php://input'));

		$post['custom_report'] = [
			"report_name" => $post['report_name'],
			"custom_query" => $post['CustomQuery'],
			'report_query' => $post['queryColumn'],
			'status' => $post['status'],
			'allow_export_to_excel' => $post['allowexporttoexcel']
		];
		$post['tableData'] = $this->prepareReportTableData($post);
		$selectAndWhere = $this->prepareSelectData($post);

		if (!empty($_POST['report_id'])) {
			$post['columns'] = $selectAndWhere['columns'];
		}

		$post['custom_report']['report_query'] = $this->query = !empty($post['CustomQuery']) ? trim($post['queryColumn']) : $this->query;

		$post['custom_report']['report_query_f'] = $this->fx->getFormattedSQL($post['custom_report']['report_query']);

		$post['filter'] = $this->prepareSearchFieldsData($post);
		// Valuidate that query does not have any insert | drop etc commands
		$dbPrventWords = strtolower($this->fx->dbPrventWords);

		if ($this->containsForbiddenSQL($this->query)) {
			$this->api_response(['success' => false, 'message' => "$dbPrventWords are not allowed!!"], 400);
		}

		// Validate if query is wrong then show error ******* IN Case if cusrtom query we don't need to execure query
		if (empty($post['CustomQuery']))
			$this->validateQueryForError();


		if ($this->fx->message != "") {
			$this->api_response(['success' => false, 'message' => @$this->db->error()['message']], 400);
		}

		// Prepare data fro rights of custom query ***************************
		//   $post['rights'] = $this->prepareRightsData($post);


		$res = $this->Api_Model->saveCustomReport($post);
		// fx::pr($res,1);
		if (!empty($res)) {
			$this->api_response(['success' => true, 'message' => 'Report saved successfully'], 200);
		} else {
			$this->api_response(['success' => false, 'message' => 'Report not saved'], 400);
		}
	}
	function containsForbiddenSQL($query)
	{
		// Define the list of forbidden words
		$forbidden = '/\b(drop|delete|update|truncate|insert|create)\b/i';

		// Check if any forbidden word is present
		if (preg_match($forbidden, $query)) {
			return true; // Match found
		}
		return false; // No match found
	}

	function validateQueryForError()
	{
		$db_debug = $this->db->db_debug; // save setting
		$this->db->trans_begin();
		$this->db->db_debug = false;
		$this->db->trans_rollback();

		$this->db->query($this->query);

		// $this->fx->dbError($this->db, true);
		$this->db->db_debug = $db_debug; //disable debugging for queries
		return true;
	}


	public function prepareSearchFieldsData($data)
	{
		if ((count($data['searchArray']) < 1 && $data['searchArray'][0]->search_field_name == '') || (count($data['searchArray']) == 0 && $data['searchArray'][0]->search_field_name == '')) {
			return [];
		}
		$filters = [];

		foreach ($data['searchArray'] as $key => $value) {
			$value = (array)$value;
			$filters[$key] = [
				'report_id' => !empty($value['report_id']) ? $value['report_id'] : null,
				'srno' => $key + 1,
				'search_field_name' => $value['search_field_name'],
				'display_name' => acceptOnlyCharctersAndNumberWithSpace($value['search_display_name']),
				'default_value' => $value['search_default_value'],
				'allow_null' => ($value['search_allow_null']) ? 1 : 0,
				'drowdown_other_db' => ($value['search_drowdown_other_db']) ? 1 : 0,
				'input_type' => $value['search_input_type'],
				'select_box_value' => $value['search_select_box_value'],
				'default_operator' => $value['search_default_operator'],
				'parameter' => $value['search_parameter']
			];
			$filter = $filters[$key];
			$rules = [];

			$rules[] = ['field' => 'input_type', 'label' => 'Search Filed Control Type', 'rules' => 'trim'];
			if ($filter['parameter'] == '') {
				$rules[] = ['field' => 'search_field_name', 'label' => 'Search FieldName', 'rules' => 'trim'];
				$rules[] = ['field' => 'default_operator', 'label' => 'Search Filed Default Operator', 'rules' => 'trim'];
			}

			if (in_array($filter['input_type'], ['dropdown', 'multiselect'])) {
				$rules[] = ['field' => 'select_box_value', 'label' => 'Search Filed Combo value', 'rules' => 'required|trim'];
				$dbPrventWords = strtolower($this->fx->dbPrventWords);
				if (preg_match("'($dbPrventWords)'", strtolower($filter['select_box_value'])) === 1) {
					$this->api_response(['success' => false, 'message' => "$dbPrventWords are not allowed in search combo box value!!"], 400);
				}
			}

			$this->form_validation->set_data($filter);
			$this->form_validation->set_rules($rules);

			if ($this->form_validation->run() == false) {
				$this->api_response(['success' => false, 'message' => validation_errors()], 400);
			}
			$this->form_validation->reset_validation();
		}
		return $filters;
	}


	public function prepareSelectData($data)
	{
		if ((count($data['generalArray']) <= 1 && $data['generalArray'][0] == '') || (count($data['reportArray']) == 1 && $data['reportArray'][0]->field_name == '')) {
			$this->query = "select * " . $this->query;
			return [];
		}
		$select = $order_by = $group_by = $where = "";
		foreach ($data['reportArray'] as $key => $value) {
			$value = (array)$value;

			$columns[$key] = [
				'report_id' => !empty($value['report_id']) ? $value['report_id'] : null,
				'field_name' => isset($value['field_name']) ? trim($value['field_name']) : null,
				'function_name' => isset($value['function_name']) ? trim($value['function_name']) : null,
				'order_by_type' => isset($value['order_by_type']) ? trim($value['order_by_type']) : null,
				'filed_formula' => isset($value['filed_formula']) ? str_replace(['"'], ["'"], trim($value['filed_formula'])) : null,
				'display_name' => isset($value['display_name']) ? acceptOnlyCharctersAndNumberWithSpace($value['display_name']) : null,
				'criteria' => isset($value['criteria']) ? str_replace(['"'], ["'"], trim($value['criteria'])) : null,
				'is_visible' => isset($value['is_visible']) ? $value['is_visible'] : null,
				'aggrigate_fn' => isset($value['aggrigate_fn']) ? trim($value['aggrigate_fn']) : null,
				// 'group_by_type' => isset($value['group_by_type']) ? (in_array($key + 1, $value['group_by_type']) ? 1 : 0) : null
				'group_by_type' => isset($value['group_by_type']) ?  $value['group_by_type'] : null
			];

			$column = $columns[$key];
			// Validate Feils are not empty		 
			if ($column['filed_formula'] == '' && $column['field_name'] == '') {
				$this->api_response(['success' => false, 'message' => "Column Field Name or Formula field is required"], 400);
			}

			// Column Name *******************
			$selectCol = ($column['filed_formula'] != '') ? $column['filed_formula'] : $column['field_name'];
			$selectCol = ($column['aggrigate_fn'] != '') ? "$column[aggrigate_fn]($selectCol)" : $selectCol;

			// select *******************
			if ($column['is_visible'] == 1) {

				$select .= ($column['display_name'] != '') ? "$selectCol as '$column[display_name]'" : $selectCol;
				$select .= ',';
			}


			// Order by and group by **************
			$order_by .= ($column['order_by_type'] != '') ? "$selectCol $column[order_by_type]," : '';
			$group_by .= ($column['group_by_type'] == 1) ? "$selectCol," : '';

			// WHERE condition *****************   START
			if ($column['criteria'] != '') {
				if ($where == '') {
					$where .= "$selectCol $column[criteria]";
				} else {
					$whereArray = explode(" ", $column['criteria']);

					if (in_array($whereArray[0], ['and', 'or'])) {
						$whereArray[0] .= " $selectCol";
					} else {

						$whereArray[0] = " and $selectCol " . $whereArray[0];
					}
					$where .= " " . implode(' ', $whereArray);
				}
			}
			// WHERE condition *****************  END
		}
		$select = ($select != '') ? rtrim($select, ',') : "*";
		$this->query = "select $select " . $this->query;
		$this->query = ($where != '') ? (str_replace("where 1=1", "where 1=1 and $where", $this->query)) : $this->query;
		$this->query .=  ($group_by != '') ? (" group by " . rtrim($group_by, ',')) : '';
		$this->query .=  ($order_by != '') ? (" order by " . rtrim($order_by, ',')) : '';
		return ['columns' => $columns];
	}


	public function prepareReportTableData($data)
	{
		$query = "";
		$tables = [];
		foreach ($data['generalArray'] as $key => $value) {
			$tables[$key] = [
				'report_id' => !empty($data['report_id']) ? $data['report_id'] : null,
				'srno' => $key + 1,
				'left_table_name' =>  $value->left_table_name,
				'left_column_name' => $value->left_column_name,
				'join_name' => $value->join_name,
				'right_table_name' => $value->right_table_name,
				'right_column_name' => $value->right_column_name,
			];
			$table = $tables[$key];

			if ($key == 0) {
				$query .= "from $table[left_table_name]";
			} else {
				// Validate Other Fields
				$rules = [];
				$rules[] = ['field' => 'left_table_name', 'label' => 'Report Table Name (Left)', 'rules' => 'required|trim'];
				$rules[] = ['field' => 'left_column_name', 'label' => 'Report Column Name (Left)', 'rules' => 'required|trim'];
				$rules[] = ['field' => 'join_name', 'label' => 'Report Join', 'rules' => 'required|trim'];
				$rules[] = ['field' => 'right_table_name', 'label' => 'Report Table Name (Right)', 'rules' => 'required|trim'];
				$rules[] = ['field' => 'right_column_name', 'label' => 'Report Column Name (Right)', 'rules' => 'required|trim'];

				$this->form_validation->set_data($table);
				$this->form_validation->set_rules($rules);

				if ($this->form_validation->run() == false) {
					$this->fx->api_response(['success' => false, 'message' => validation_errors()], 400);
				}
				$this->form_validation->reset_validation();
			}

			$query .= !empty($table['right_table_name'] && $table['join_name'] != '') ? " $table[join_name] join $table[right_table_name] ON $table[left_table_name].$table[left_column_name] = $table[right_table_name].$table[right_column_name]" : "";
		}
		$this->query = $query . " where 1=1";
		return $tables;
	}

	//-----------------------TMS API----------------------------------//
}
