<?php
class Master_Model extends CI_Model
{
	//MASTER DETAIL
	private $tableName = array(
		'user_type' => 'tms_user_type',
		"action" => "tms_action_master",
		"shift" => "tms_shift_master",
		"user" => "tms_user_master",
		"company" => "tms_company_master",
		"priority" => "tms_priority_master",
		"emailAccount" => "tms_email_account",
		"pagination" => "tms_pagination_master",
		"category" => "tms_category_master",
		"sub-category" => "tms_subcategory_master",
		"status" => "tms_status_master",
		"rule" => "tms_rule_master",
		"rule_condition" => "tms_rule_condition",
		"queue" => "tms_queue_master",
		"template" => "tms_template_master",
		"escalation-matrix" => "tms_escalationmatrix_master",
		"user_log" => "tms_log_master",
		"login_log" => "tms_login_log",
		"ticket" => "tms_new_ticket",
		"field-group" => "tms_field_group",
		"conversation-type" => "tms_conversation_type_master",
		"break" => "tms_break_master",
	);

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

	// function getMasterData($id, $masterName, $primaryKey = 'id')
	// {
	// 	$select = array('*');
	// 	$this->db->select($select);
	// 	$this->db->where(array($primaryKey => $id));
	// 	$this->db->from($masterName);
	// 	$query = $this->db->get();
	// 	$result = $query->row_array();
	// 	return $result;
	// }

	function getMasterData($id, $masterName, $primaryKey = 'id')
	{
		try {
			$select = array("t1.*, t2.user_name as created_by, t3.user_name as modified_by,DATE_FORMAT(t1.created_date,'%d-%m-%Y %H:%i:%s') as created_date,DATE_FORMAT(t1.modified_date,'%d-%m-%Y %H:%i:%s') as modified_date");
			$this->db->select($select);
			$this->db->where(array('t1.' . $primaryKey => $id));
			$this->db->from("$masterName as  t1");
			$this->db->join('tms_user_master t2', "t2.id=t1.created_by", 'LEFT');
			$this->db->join('tms_user_master t3', "t3.id=t1.modified_by", 'LEFT');
			$query = $this->db->get();
			// fx::pr($this->db->error(),1);
			if ($this->db->error()['code'] == 1451) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			if ($query === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			$result = $query->row_array();

			return $result;
		} catch (Exception $e) {
			return array('error' => $e->getMessage());
		}
	}

	// function getMasteremailAccountData($id, $masterName, $primaryKey = 'id')
	// {

	// 	$this->db->select('t1.*,is_valid,message,check_on,email_account_id');
	// 	$this->db->from("$masterName t1");
	// 	$this->db->join('tms_mail_test', 't1.id = tms_mail_test.email_account_id', 'left');
	// 	$this->db->where('t1.id', $id);
	// 	$this->db->order_by('tms_mail_test.check_on', 'DESC');
	// 	$this->db->limit(1);

	// 	$query = $this->db->get();
	// 	$result = $query->row_array();

	// 	return $result;
	// }

	function getMasteremailAccountData($id, $masterName, $primaryKey = 'id')
	{
		try {
			$this->db->select("t1.*,t2.user_name as created_by,t3.user_name as modified_by,DATE_FORMAT(t1.created_date,'%d-%m-%Y %H:%i:%s') as created_date,DATE_FORMAT(t1.modified_date,'%d-%m-%Y %H:%i:%s') as modified_date");
			$this->db->from("$masterName t1");
			// $this->db->join('tms_mail_test', 't1.id = tms_mail_test.email_account_id', 'left');
			$this->db->join('tms_user_master t2', 't2.id = t1.created_by', 'left');
			$this->db->join('tms_user_master t3', 't3.id = t1.modified_by', 'left');
			$this->db->where('t1.id', $id);
			// $this->db->order_by('tms_mail_test.check_on', 'DESC');
			$this->db->limit(1);

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

			if ($this->db->error()['code'] == 1451) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			if ($query === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			$result = $query->row_array();

			$this->db->select('is_valid,message,check_on,email_account_id');
			$this->db->from("$masterName t1");
			$this->db->join('tms_mail_test t2', 't1.id = t2.email_account_id', 'left');
			$this->db->where('t1.id', $id);
			$this->db->group_start();
			$this->db->where('t2.type', 'outgoing');
			$this->db->group_end();
			$this->db->order_by('t2.check_on', 'DESC');
			$this->db->limit(1);
			$query2 = $this->db->get();
			$result['outgoing'] = $query2->row_array();

			//Outgoing email test data ends here

			//Incoming email test data start here

			$this->db->select('is_valid,message,check_on,email_account_id');
			$this->db->from("$masterName t1");
			$this->db->join('tms_mail_test t2', 't1.id = t2.email_account_id', 'left');
			$this->db->where('t1.id', $id);
			$this->db->group_start();
			$this->db->where('t2.type', 'incoming');
			$this->db->group_end();
			$this->db->order_by('t2.check_on', 'DESC');
			$this->db->limit(1);
			$query2 = $this->db->get();
			$result['incoming'] = $query2->row_array();

			return $result;
		} catch (Exception $e) {

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

	// function getMasterUserData($id, $masterName, $primaryKey = 'id')
	// {
	// 	$select = array('*');
	// 	$this->db->select($select);
	// 	$this->db->where(array($primaryKey => $id));
	// 	$this->db->from($masterName);
	// 	$query = $this->db->get();
	// 	$result = $query->row_array();
	// 	$result['queue_id'] = explode(",", $result['queue_id']);
	// 	$result['action_id'] = explode(",", $result['action_id']);
	// 	return  array('result' => $result);
	// }

	function getMasterUserData($id, $masterName, $primaryKey = 'id')
	{
		try {
			$select = array("t1.*, t2.user_name AS created_by,  t3.user_name as modified_by,DATE_FORMAT(t1.created_date,'%d-%m-%Y %H:%i:%s') as created_date,DATE_FORMAT(t1.modified_date,'%d-%m-%Y %H:%i:%s') as modified_date");
			$this->db->select($select);
			$this->db->where(array('t1.' . $primaryKey => $id));
			$this->db->from($masterName . ' t1');
			$this->db->join($masterName . ' t2', 't1.created_by = t2.id', 'left'); // Corrected join syntax
			$this->db->join($masterName . ' t3', 't1.modified_by = t3.id', 'left'); // Corrected join syntax
			$query = $this->db->get();
			if ($this->db->error()['code'] == 1451) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			if ($query === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			$result = $query->row_array();

			if (!empty($result['queue_id'])) {
				$result['queue_id'] = explode(",", $result['queue_id']);
			} else {
				$result['queue_id'] = array();
			}

			if (!empty($result['action_id'])) {
				$result['action_id'] = explode(",", $result['action_id']);
			} else {
				$result['action_id'] = array();
			}

			return array('result' => $result);
		} catch (Exception $e) {
			return array('error' => $e->getMessage());
		}
	}

	function CheckEmptyTables($tables)
	{

		$emptyTables = array();
		$notEmpty = [];
		foreach ($tables as $table) {
			// Get the count of rows in the table
			$this->db->from($table);
			$count = $this->db->count_all_results();
			if ($count === 0) {
				// Table is empty
				$emptyTables[] = $table;
			} else {
				$notEmpty[] = $table;
			}
		}

		if (count($emptyTables) === count($tables)) {
			return true;
		} else {
			return $notEmpty;
		}
	}


	// function getMasterRulesData($id, $masterName, $primaryKey = 'id')
	// {
	// 	$select = array('*');
	// 	$this->db->select($select);
	// 	$this->db->where(array($primaryKey => $id));
	// 	$this->db->from($masterName);
	// 	$query = $this->db->get();
	// 	$result = $query->row_array();


	// 	$select = array('*');
	// 	$this->db->select($select);
	// 	$this->db->where('rule_id', $id);
	// 	$this->db->from('tms_rule_condition');
	// 	$query1 = $this->db->get();
	// 	$result1 = $query1->result_array();

	// 	$select = array('*');
	// 	$this->db->select($select);
	// 	$this->db->where('rule_id', $id);
	// 	$this->db->from('tms_rule_action');
	// 	$query2 = $this->db->get();
	// 	$result2 = $query2->result_array();

	// 	return  array('result' => $result, 'result1' => $result1, 'result2' => $result2);
	// }

	function getMasterRulesData($id, $masterName, $primaryKey = 'id')
	{
		try {
			$select = array('*');
			$this->db->select($select);
			$this->db->where(array($primaryKey => $id));
			$this->db->from($masterName);
			$query = $this->db->get();

			if ($this->db->error()['code'] == 1451) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			if ($query === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			$result = $query->row_array();

			$select = array('*');
			$this->db->select($select);
			$this->db->where('rule_id', $id);
			$this->db->from('tms_rule_condition');
			$query1 = $this->db->get();

			if ($this->db->error()['code'] == 1451) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			if ($query1 === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			$result1 = $query1->result_array();

			$select = array('*');
			$this->db->select($select);
			$this->db->where('rule_id', $id);
			$this->db->from('tms_rule_action');
			$query2 = $this->db->get();

			if ($this->db->error()['code'] == 1451) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			if ($query2 === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			$result2 = $query2->result_array();

			return array('result' => $result, 'result1' => $result1, 'result2' => $result2);
		} catch (Exception $e) {

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

	// function getMasterQueueData($id, $masterName, $primaryKey = 'id')
	// {
	// 	$select = array('*');
	// 	$this->db->select($select);
	// 	$this->db->where(array($primaryKey => $id));
	// 	$this->db->from($masterName);
	// 	$query = $this->db->get();
	// 	$result = $query->row_array();
	// 	$result['catagory'] = explode(",", $result['catagory']);
	// 	$result['statustype'] = explode(",", $result['statustype']);


	// 	$select = array('*');
	// 	$this->db->select($select);
	// 	$this->db->where('queue_id', $id);
	// 	$this->db->from('tms_queue_email');
	// 	$query1 = $this->db->get();
	// 	$result1 = $query1->result_array();

	// 	$select = array('*');
	// 	$this->db->select($select);
	// 	$this->db->from('tms_queue_category_' . $id);
	// 	$categoryquery = $this->db->get();
	// 	$categoryresult = $categoryquery->result_array();

	// 	$select = array('*');
	// 	$this->db->select($select);
	// 	$this->db->from('tms_queue_priority_' . $id);
	// 	$priorityquery = $this->db->get();
	// 	$priorityresult = $priorityquery->result_array();

	// 	$select = array('*');
	// 	$this->db->select($select);
	// 	$this->db->from('tms_queue_status_' . $id);
	// 	$statusquery = $this->db->get();
	// 	$statusresult = $statusquery->result_array();

	// 	$select = array('*');
	// 	$this->db->select($select);
	// 	$this->db->from('tms_queue_escalationmatrix_' . $id);
	// 	$escalationquery = $this->db->get();
	// 	$escalationresult = $escalationquery->result_array();

	// 	return  array('result' => $result, 'result1' => $result1, 'categoryResult' => $categoryresult, 'priorityResult' => $priorityresult, 'statusResult' => $statusresult, 'escalationResult' => $escalationresult);
	// }
	function getresult($table, $where = '1= 1')
	{
		$select = array('*');
		$this->db->select($select);
		$this->db->where($where);
		$this->db->from($table);
		$categoryquery = $this->db->get();

		if ($this->db->error()['code'] == 1451) {
			throw new Exception("MySQL Error: " . $this->db->error()['message']);
		}

		if ($categoryquery === false) {
			throw new Exception("MySQL Error: " . $this->db->error()['message']);
		}

		$categoryresult = $categoryquery->row_array();
		return $categoryresult;
	}

	function getMasterQueueData($id, $masterName, $primaryKey = 'id', $user_type, $full_control)
	{
		try {
			$select = array("t1.*, t2.user_name as created_by, t3.user_name as modified_by,DATE_FORMAT(t1.created_date,'%d-%m-%Y %H:%i:%s') as created_date,DATE_FORMAT(t1.modified_date,'%d-%m-%Y %H:%i:%s') as modified_date");
			$this->db->select($select);
			$this->db->where(array('t1.' . $primaryKey => $id));
			$this->db->from($masterName . " t1");
			$this->db->join('tms_user_master t2', 't2.id = t1.created_by', 'left');
			$this->db->join('tms_user_master t3', 't3.id = t1.modified_by', 'left');
			$query = $this->db->get();

			if ($this->db->error()['code'] == 1451) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			if ($query === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			$result = $query->row_array();
			$result['catagory'] = explode(",", $result['catagory']);
			$result['statustype'] = explode(",", $result['statustype']);

			$select = array('*');
			$this->db->select($select);
			$this->db->where('queue_id', $id);
			$this->db->from('tms_queue_email');
			$query1 = $this->db->get();

			if ($this->db->error()['code'] == 1451) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			if ($query1 === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			$result1 = $query1->result_array();

			$select = array('*');
			$this->db->select($select);
			$this->db->from('tms_queue_category_' . $id);
			$categoryquery = $this->db->get();

			if ($this->db->error()['code'] == 1451) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			if ($categoryquery === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			$categoryresult = $categoryquery->result_array();

			$select = array('*');
			$this->db->select($select);
			$this->db->from('tms_queue_priority_' . $id);
			$priorityquery = $this->db->get();

			if ($this->db->error()['code'] == 1451) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			if ($priorityquery === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			$priorityresult = $priorityquery->result_array();

			$select = array('*');
			$this->db->select($select);
			$this->db->from('tms_queue_status_' . $id . ' as t1');
			if ($full_control !== '1') {
				$this->db->join("tms_statuspermission_" . $id . " t2", "t2.status_id = t1.status_id", 'left');

				$this->db->where('t2.user_type', $user_type);
				$this->db->where('t2.is_checked', '1');
			}
			$statusquery = $this->db->get();
			if ($this->db->error()['code'] == 1451) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			if ($statusquery === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			$statusresult = $statusquery->result_array();

			$select = array('*');
			$this->db->select($select);
			$this->db->from('tms_queue_status_setting');
			$this->db->where('queue_id', $id);
			$statusSettingquery = $this->db->get();

			if ($this->db->error()['code'] == 1451) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			if ($statusSettingquery === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			$statusSettingresult = $statusSettingquery->result_array();
			// fx::pr($statusSettingresult,1);

			$select = array('*');
			$this->db->select($select);
			$this->db->from('tms_queue_escalationmatrix_' . $id);
			$escalationquery = $this->db->get();

			if ($this->db->error()['code'] == 1451) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			if ($escalationquery === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			$escalationresult = $escalationquery->result_array();

			return array(
				'result' => $result,
				'result1' => $result1,
				'categoryResult' => $categoryresult,
				'priorityResult' => $priorityresult,
				'statusResult' => $statusresult,
				'statusSettingResult' => $statusSettingresult,
				'escalationResult' => $escalationresult
			);
		} catch (Exception $e) {
			// Handle exceptions here, e.g., log the error or return an error message
			return array('error' => $e->getMessage());
		}
	}







	function getMasterTableFields($masterName)
	{
		try {
			$sql = "SHOW COLUMNS FROM " . $this->tableName[$masterName];
			$exec = $this->db->query($sql);
			// fx::pr($exec);
			$exec = $exec;

			if ($this->db->error()['code'] == 1451) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			if ($exec === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}
			$result = $exec->result_array();
			$retArr = array();
			foreach ($result as $key => $value) {
				$retArr[] = $value['Field'];
			}

			return $retArr;
		} catch (Exception $e) {
			// Handle exceptions here, e.g., log the error or return an error message
			return array('error' => $e->getMessage());
		}
	}

	public function getTicketTableFields($masterName)
	{
		$sql = "SHOW COLUMNS FROM " . $masterName;
		$exec = $this->db->query($sql);
		$result = $exec->result_array();
		$retArr = array();
		foreach ($result as $key => $value) {
			$retArr[] = $value['Field'];
		}
		return $retArr;
	}

	public function getQueueFields($masterName)
	{
		$sql = "SHOW COLUMNS FROM " . $masterName;
		$exec = $this->db->query($sql);
		$result = $exec->result_array();
		$retArr = array();
		foreach ($result as $key => $value) {
			$retArr[] = $value['Field'];
		}
		return $retArr;
	}


	function preSaveProcess($masterName, $data)
	{
		$table = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
		if ($masterName == 'MASTER_PAGINATION') {
			if (!empty($table)) {
				if (!empty($data['is_default'])) {
					$this->db->update($table, array('is_default' => 0));
				}
			}
		}
		return true;
	}

	function savePagination($masterName, $data, $pKey = 'id')
	{

		if (!empty($masterName)) {
			$id = $data[$pKey];
			unset($data[$pKey]);
			if (empty($id)) { // create 
				$res = $this->db->insert($masterName, $data);
				$id = $this->db->insert_id();
				if ($data['is_default'] == 1) {
					$this->db->set('is_default', false)->where('id !=', $id)->update($masterName);
				}
			} else { // edit
				$res = $this->db->where('id', $id)->update($masterName, $data);
			}
			if ($res == 1) {
				if ($data['is_default'] == 1) {
					$this->db->set('is_default', false)->where('id !=', $id)->update($masterName);
				}
				$res = array('error' => false, 'id' => $id);
			} else {
				$res = array('error' => true, 'id' => 0);
			}
			return $res;
		}
	}

	// function saveProcess($masterName, $data, $pKey = 'id')
	// {
	// 	$table = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
	// 	if (!empty($table)) {
	// 		$data = is_array($data) ? $data : (array) $data;
	// 		// if(isset($data['customer_email_template'])){
	// 		// 	$data['customer_email_template'] = json_encode($data['customer_email_template']);
	// 		// }
	// 		$id = $data[$pKey];
	// 		unset($data[$pKey]);
	// 		if (empty($id)) { // create 
	// 			$this->db->insert($table, $data);
	// 			$id = $this->db->insert_id();
	// 		} else { // edit 
	// 			$this->db->where($pKey, $id)->update($table, $data);
	// 			// fx::pr($this->db->last_query(),1);
	// 		}
	// 		$res = array('error' => false, 'id' => $id);
	// 	} else {
	// 		$res = array('error' => true, 'id' => 0);
	// 	}
	// 	return $res;
	// }

	function saveProcess($masterName, $data, $pKey = 'id')
	{
		try {
			$table = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
			if (!empty($table)) {
				$data = is_array($data) ? $data : (array) $data;
				$id = $data[$pKey];
				unset($data[$pKey]);
				if (empty($id)) { // create 
					$this->db->insert($table, $data);
					$id = $this->db->insert_id();
				} else { // edit 
					$this->db->where($pKey, $id)->update($table, $data);
				}
				$res = array('error' => false, 'id' => $id);
			} else {
				$res = array('error' => true, 'id' => 0);
			}
			return $res;
		} catch (Exception $e) {
			return array('error' => true, 'id' => 0, 'message' => 'Database error: ' . $e->getMessage());
		}
	}


	function saveStatusPermission($statusData, $post)
	{
		try {
			$table = "tms_statuspermission_$post[queue_id]";
			$id = $statusData['id'];
			$userType = $post['user_type'];
			$this->db->where('user_type', $userType);
			$this->db->delete($table);
			$this->db->insert_batch($table, $statusData);
			$id = $this->db->insert_id();

			$res = array('error' => false, 'id' => $id);
			return $res;
		} catch (Exception $e) {
			return array('error' => true, 'id' => 0, 'message' => 'Database error: ' . $e->getMessage());
		}
	}

	function getStatusPermissionList($data)
	{
		$masterName = 'tms_statuspermission_' . $data['queue_id'];
		try {
			$this->db->select('*');
			$this->db->from($masterName);
			$this->db->where('user_type', $data['user_type_id']);
			$res = $this->db->get();
			if ($res === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}
			return $res->result_array();
		} catch (Exception $e) {
			return array('error' => true, 'message' => $e->getMessage());
		}
	}

	function changePassword($data)
	{
		if ($data['ency_password'] !== '') {
			$this->db->set('is_login', '0', FALSE);
			$this->db->set('password', ' ' . $this->db->escape($data['ency_password']) . '', FALSE);
			$this->db->where('email', $data['reset_email']);
			$this->db->update('tms_user_master');
			if ($this->db->affected_rows() > 0) {
				// Password updated successfully
				$response = array(
					'success' => true,
					'message' => 'Password updated successfully',
				);
			} else {
				// Password update failed
				$response = array(
					'success' => false,
					'message' => 'Failed to update password',
				);
			}
			return $response;
		}
	}


	function saveconversationtype($masterName, $data, $pKey = 'id')
	{
		if (empty($masterName)) {
			return array('error' => true, 'id' => 0, 'message' => 'Master name is required.');
		}

		// Check if there's a current default record
		$currentDefault = $this->db->get_where($masterName, ['is_default' => true])->row();

		$id = isset($data[$pKey]) ? $data[$pKey] : null;
		unset($data[$pKey]);

		if (empty($id)) {
			$this->db->insert($masterName, $data);
			$id = $this->db->insert_id();

			if ($data['is_default'] == 1) {
				$this->db->set('is_default', false)->where('id !=', $id)->update($masterName);
			}
		} else {
			if (empty($currentDefault) && empty($data['is_default'])) {
				return array('error' => true, 'id' => 0, 'message' => 'There should be at least one default conversation type.');
			}

			$this->db->where('id', $id)->update($masterName, $data);

			if ($data['is_default'] == 1) {
				$this->db->set('is_default', false)->where('id !=', $id)->update($masterName);
			}
		}

		$afterOperationDefault = $this->db->get_where($masterName, ['is_default' => true])->row();
		if (empty($afterOperationDefault)) {
			return array('error' => true, 'id' => 0, 'message' => 'There should be at least one default conversation type.');
		}

		return array('error' => false, 'id' => $id);
	}

	// public function saveQueueCategoryData($masterName, $post)
	// {
	// if (isset($post['categoryArray'])) {
	// 	foreach ($post['categoryArray'] as $key => $val) {
	// 		// $categoryArray[] = array(
	// 		// 	'categor_id' => $val->category_id,
	// 		// 	'category_name' => $val->category,
	// 		// 	'sub_category' => $val->subcategory,
	// 		// );
	// 	}
	// $this->db->insert_batch($masterName, $categoryArray);
	// $id =  $this->db->insert_id();
	// if($id > 0){
	// 	$res = array('error' => false, 'id' => $id);
	// }else{
	// 	$res = array('error' => true, 'id' => '');
	// }
	// return $res;
	// }
	// if (isset($post['categoryArray'])) {
	// 	$success_count = 0;
	// 	$error_count = 0;
	// 	foreach ($post['categoryArray'] as $key => $val) {
	// 		$data = array(
	// 			'category_name' => $val->category,
	// 			'sub_category' => $val->subcategory,
	// 		);
	// 		$category_id = $val->category_id;
	// 		if (!empty($category_id)) {
	// 			// Update existing category
	// 			$this->db->where('category_id', $category_id);
	// 			$this->db->update($masterName, $data);
	// 			$affected_rows = $this->db->affected_rows();
	// 			if ($affected_rows >= 0) {
	// 				$success_count++;
	// 			} else {
	// 				$error_count++;
	// 			}
	// 		} else {
	// 			// Insert new category
	// 			$this->db->insert($masterName, $data);
	// 			$insert_id = $this->db->insert_id();
	// 			if ($insert_id > 0) {
	// 				$success_count++;
	// 			} else {
	// 				$error_count++;
	// 			}
	// 		}
	// 	}
	// 	if ($error_count == 0) {
	// 		// All operations were successful
	// 		return array('error' => false);
	// 	} else {
	// 		// There were some errors
	// 		return array('error' => true);
	// 	}
	// }

	public function saveQueueCategoryData($masterName, $pKey = 'category_id', $post, $data)
	{
		$data = is_array($data) ? $data : (array) $data;
		// print_r($post);die;
		$id = $data[$pKey];
		$queue_id = $post['queue_id'];
		unset($post['queue_id']);
		unset($post[$pKey]);
		if (!empty($masterName)) {
			if (empty($id)) { // create 
				$this->db->where("category_name='$data[category_name]'", NULL, false);
				$dtCount = $this->db->count_all_results($masterName);
				if ($dtCount == 0) {
					$this->db->insert($masterName, $data);
					$id = $this->db->insert_id();

					foreach ($post['subCategoryResult'] as $key => $val) {
						$subCategoryResult[] = array(
							'category_id' => $id,
							'sub_category_name' => $val->subcategory_name,
							'message' => $val->message,
							'priority_id' => $val->priority_id,
							'default' => $val->default ? 1 : 0,
						);
					}
					$this->db->insert_batch("tms_queue_sub_category_$queue_id", $subCategoryResult);
					// print_r($this->db->last_query());die;
				} else {
					$res = array('error' => true, 'id' => 0, 'message' => "Category already exists");
					return $res;
				}
			} else {
				$this->db->where("category_name='$data[category_name]' and category_id!=$data[category_id]", NULL, false);
				$dtCount = $this->db->count_all_results($masterName);
				$this->db->where("category_id='$data[category_id]'", NULL, false);
				$ticketCount = $this->db->count_all_results("tms_ticket_master_$queue_id");

				if ($ticketCount != 0 && $data['status'] == 0) {
					$res = array('error' => true, 'id' => 0, 'message' => "Cannot Inactive '$data[category_name]' category because it is referenced by the ticket table");
					return $res;
				}

				if ($dtCount == 0) {
					// print_r($masterName);die;
					$this->db->where($pKey, $id)->update($masterName, $data);

					if (isset($data['default']) && $data['default'] == '1') {
						// Remove default from other categories
						$this->db->where('category_id !=', $id) // Exclude the current category
							->where('default', '1') // Only target categories that are currently set as default
							->update($masterName, ['default' => '0']); // Set their default to 0
					}

					// $this->db->where('category_id', $id);
					// $this->db->delete("tms_queue_sub_category_$queue_id");
					// print_r($this->db->last_query());die;
					// print_r($post['subCategoryResult']);die;
					foreach ($post['subCategoryResult'] as $key => $val) {
						$subCategoryData = array(
							'category_id' => $id,
							'sub_category_name' => $val->subcategory_name,
							'message' => $val->message,
							'priority_id' => $val->priority_id,
							'default' => $val->default ? 1 : 0,
						);

						// Check if sub_category_id is not empty
						if (!empty($val->sub_category_id)) {
							// Update the existing record
							$this->db->where('sub_category_id', $val->sub_category_id);
							$this->db->update("tms_queue_sub_category_$queue_id", $subCategoryData);
						} else {
							// Insert a new record
							$this->db->insert("tms_queue_sub_category_$queue_id", $subCategoryData);
						}
					}
					// print_r($this->db->last_query());die;
					// $this->db->insert_batch("tms_queue_sub_category_$queue_id", $subCategoryResult);
				} else {
					$res = array('error' => true, 'id' => 0, 'message' => "Category already exists");
					return $res;
				}
			}
			$res = array('error' => false, 'id' => $id);
		} else {
			$res = array('error' => true, 'id' => 0);
		}
		return $res;
	}

	public function saveQueuePriorityData($post, $masterName, $idField = 'priority_id')
	{
		$priorityArray = array();
		$error_count = 0;
		$deleted_count = 0;

		// Get an array of existing IDs
		$existingIds = $this->db->select($idField)->get($masterName)->result_array();
		$existingIds = array_column($existingIds, $idField);

		// Build an array of data to insert or update
		foreach ($post['priorityArray'] as $key => $val) {
			$priorityArray[] = array(
				$idField => $val->priority_id,
				'priority_name' => $val->priority_name,
				'colour_code' => $val->colour_code,
				'tat' => $val->tat_time,
				'order_no' => $val->order_no,
				'is_default' => ($val->is_default == "") ? 0 : 1,
				'tat_time_min' => $val->tat_time_min,
			);
		}
		// Update existing records
		foreach ($priorityArray as $priority) {
			$id = $priority[$idField];
			unset($priority[$idField]);

			if (!empty($id)) {
				$this->db->where($idField, $id);
				$this->db->update($masterName, $priority);

				// if ($this->db->affected_rows() == 0) {
				// 	$error_count++;
				// }
			} else {
				$this->db->insert($masterName, $priority);

				if ($this->db->affected_rows() == 0) {
					$error_count++;
				}
			}

			// Remove ID from existing IDs array if it is present
			if (($key = array_search($id, $existingIds)) !== false) {
				unset($existingIds[$key]);
			}
		}

		// Delete records that were not included in the update
		if (!empty($existingIds)) {
			$this->db->where_in($idField, $existingIds);
			$this->db->delete($masterName);

			if ($this->db->affected_rows() == 0) {
				$error_count++;
			}
		}

		// Determine success or failure based on error and delete counts
		if ($error_count > 0) {
			$res = array('error' => true);
		} else {
			$res = array('error' => false);
		}

		return $res;
	}

	// public function saveQueueStatusData($post, $masterName, $idField = 'status_id', $queueId)
	// {
	// 	$statusArray = array();
	// 	$error_count = 0;

	// 	// Get an array of existing IDs
	// 	$existingIds = $this->db->select($idField)->get($masterName)->result_array();
	// 	$existingIds = array_column($existingIds, $idField);

	// 	// Build an array of data to insert or update
	// 	foreach ($post->statusArray as $key => $val) {
	// 		$statusArray[] = array(
	// 			$idField => $val->status_id,
	// 			'status_name' => $val->status_name,
	// 			'colour_code' => $val->colour_code,
	// 			'ticket_status_type' => $val->ticket_status_type,
	// 			'incomming_mail_status' => ($val->incomming_mail_status == "") ? 0 : 1,
	// 			'order_no' => $val->order_no,
	// 			'is_default' => ($val->is_default == "") ? 0 : 1,
	// 			'is_close_status' => ($val->is_close_status == "") ? 0 : 1,
	// 			'template_id' => $val->template_id,
	// 			'customer_email' => ($val->customer_email == "") ? 0 : 1,
	// 			'customer_sms' => ($val->customer_sms == "") ? 0 : 1,
	// 			'customer_wp' => ($val->customer_wp == "") ? 0 : 1,
	// 			'user_email' => ($val->user_email == "") ? 0 : 1,
	// 			'user_sms' => ($val->user_sms == "") ? 0 : 1,
	// 			'user_wp' => ($val->user_wp == "") ? 0 : 1,
	// 		);
	// 	}

	// 	// Update existing records
	// 	foreach ($statusArray as $status) {
	// 		$id = $status[$idField];
	// 		unset($status[$idField]);

	// 		if (!empty($id)) {
	// 			$this->db->where($idField, $id);
	// 			$this->db->update($masterName, $status);

	// 			// if ($this->db->affected_rows() == 0) {
	// 			// 	$error_count++;
	// 			// }
	// 		} else {
	// 			$this->db->insert($masterName, $status);

	// 			if ($this->db->affected_rows() == 0) {
	// 				$error_count++;
	// 			}
	// 		}

	// 		// Remove ID from existing IDs array if it is present
	// 		if (($key = array_search($id, $existingIds)) !== false) {
	// 			unset($existingIds[$key]);
	// 		}
	// 	}

	// 	// Delete records that were not included in the update
	// 	if (!empty($existingIds)) {
	// 		$this->db->where_in($idField, $existingIds);
	// 		$this->db->delete($masterName);

	// 		if ($this->db->affected_rows() == 0 ) {

	// 			$error_count++;
	// 		}
	// 		if ($this->db->affected_rows() == -1 ) {

	// 			$error_count++;				
	// 		}

	// 		$this->db->where_in("status_id", $existingIds);
	// 		$this->db->delete("tms_statuspermission_$queueId");

	// 		if ($this->db->affected_rows() == 0) {
	// 			$error_count++;
	// 		}
	// 		if ($this->db->affected_rows() == -1 ) {

	// 			$error_count++;
	// 		}

	// 	}

	// 	// Determine success or failure based on error and delete counts
	// 	if ($error_count > 0) {

	// 		$res = array('error' => true, 'message' => $this->db->error());
	// 	} else {
	// 		$res = array('error' => false, 'message' => '');
	// 	}

	// 	return $res;
	// }

	public function saveQueueStatusData($post, $masterName, $idField = 'status_id', $queueId)
	{

		// Start transaction
		$this->db->trans_begin();

		try {
			$statusArray = array();
			$error_count = 0;

			// Get an array of existing IDs
			$existingIds = $this->db->select($idField)->get($masterName)->result_array();
			$existingIds = array_column($existingIds, $idField);

			// Build an array of data to insert or update
			foreach ($post->statusArray as $key => $val) {
				$statusArray[] = array(
					$idField => $val->status_id,
					'status_name' => $val->status_name,
					'colour_code' => $val->colour_code,
					'ticket_status_type' => $val->ticket_status_type,
					'incomming_mail_status' => ($val->incomming_mail_status == "") ? 0 : 1,
					'order_no' => $val->order_no,
					'is_default' => ($val->is_default == "") ? 0 : 1,
					'is_close_status' => ($val->is_close_status == "") ? 0 : 1,
					'template_id' => $val->template_id,
					'customer_email' => ($val->customer_email == "") ? 0 : 1,
					'customer_sms' => ($val->customer_sms == "") ? 0 : 1,
					'customer_wp' => ($val->customer_wp == "") ? 0 : 1,
					'user_email' => ($val->user_email == "") ? 0 : 1,
					'user_sms' => ($val->user_sms == "") ? 0 : 1,
					'user_wp' => ($val->user_wp == "") ? 0 : 1,
				);
			}

			// Update existing records
			foreach ($statusArray as $status) {
				$id = $status[$idField];
				unset($status[$idField]);

				if (!empty($id)) {
					$this->db->where($idField, $id);
					$this->db->update($masterName, $status);

					// if ($this->db->affected_rows() == 0) {
					// 	$error_count++;
					// }
				} else {
					$this->db->insert($masterName, $status);

					if ($this->db->affected_rows() == 0) {
						$error_count++;
					}
				}

				// Remove ID from existing IDs array if it is present
				if (($key = array_search($id, $existingIds)) !== false) {
					unset($existingIds[$key]);
				}
			}

			// Delete records that were not included in the update
			if (!empty($existingIds)) {
				$this->db->where_in($idField, $existingIds);
				$this->db->delete($masterName);
				$error = $this->db->error();
				if (!empty($error['code'])) {
					// An error occurred during the delete operation
					throw new Exception($error['message']);
				}

				if ($this->db->affected_rows() == 0 || $this->db->affected_rows() == -1) {
					$error_count++;
				}

				$this->db->where_in("status_id", $existingIds);
				$this->db->delete("tms_statuspermission_$queueId");
				$error = $this->db->error();
				if (!empty($error['code'])) {
					// An error occurred during the delete operation
					throw new Exception($error['message']);
				}

				if ($this->db->affected_rows() == 0 || $this->db->affected_rows() == -1) {
					$error_count++;
				}
			}

			// Commit transaction
			// fx::pr($this->db->error(),1);
			$this->db->trans_commit();
			// Determine success or failure based on error count
			if ($error_count > 0) {
				$res = array('error' => true, 'message' => $this->db->error()['message']);
			} else {
				$res = array('error' => false, 'message' => '');
			}

			return $res;
		} catch (Exception $e) {
			// Rollback transaction on exception
			$this->db->trans_rollback();

			// Log the error
			log_message('error', 'Database transaction failed: ' . $e->getMessage());

			// Return an error response
			return array('error' => true, 'message' => "Database transaction failed." . $e->getMessage());
		}
	}


	public function saveQueueEscalationData($post, $masterName, $idField = 'escalation_id')
	{
		$escalationArray = array();
		$error_count = 0;

		// Get an array of existing IDs
		$existingIds = $this->db->select($idField)->get($masterName)->result_array();
		$existingIds = array_column($existingIds, $idField);

		// Build an array of data to insert or update
		foreach ($post['escalationArray'] as $key => $val) {
			$escalationArray[] = array(
				$idField => $val->escalation_id,
				'priority_id' => $val->priority_id,
				'days' => $val->days,
				'hours' => $val->hours,
				'minute' => $val->minute,
				// 'emails' => $val->email,
				// 'mobile_no' => $val->mobile_no,
				'shift_id' => $val->shift_id,
				'template_id' => $val->template_id,
				'send_email' => ($val->send_email != "") ? 1 : 0,
				'send_sms' => ($val->send_sms != "") ? 1 : 0,
				'send_email_agent' => ($val->send_email_agent != "") ? 1 : 0,
				'active' => ($val->active != "") ? 1 : 0,
				'level' => $val->level,
				'agent_template_id' => $val->agent_template_id,
				'category_id' => is_array($val->category_id) ? implode(', ', $val->category_id) : $val->category_id,
				'cat_email' => $val->cat_email,
				'subcategory_id' => is_array($val->subcategory_id) ? implode(', ', $val->subcategory_id) : $val->subcategory_id
			);
			if (strpos($val->email, '*') == false) {
				$escalationArray[count($escalationArray) - 1]['emails'] = $val->email;
			}
			if (strpos($val->mobile_no, '*') == false) {
				$escalationArray[count($escalationArray) - 1]['mobile_no'] = $val->mobile_no;
			}
		}
		// Update existing records

		foreach ($escalationArray as $escalation) {
			$id = $escalation[$idField];
			unset($escalation[$idField]);

			if (!empty($id)) {
				$this->db->where($idField, $id);
				$this->db->update($masterName, $escalation);

				// if ($this->db->affected_rows() == 0) {
				// 	$error_count++;
				// }
			} else {
				$this->db->insert($masterName, $escalation);

				if ($this->db->affected_rows() == 0) {
					$error_count++;
				}
			}

			// Remove ID from existing IDs array if it is present
			if (($key = array_search($id, $existingIds)) !== false) {
				unset($existingIds[$key]);
			}
		}

		// Delete records that were not included in the update
		if (!empty($existingIds)) {
			$this->db->where_in($idField, $existingIds);
			$this->db->delete($masterName);

			if ($this->db->affected_rows() == 0) {
				$error_count++;
			}
		}

		// Determine success or failure based on error and delete counts
		if ($error_count > 0) {
			$res = array('error' => true);
		} else {
			$res = array('error' => false);
		}

		return $res;
	}

	public function saveQueueStatusSettingData($post, $masterName, $idField = 'id')
	{
		$statusSettingArray = array();
		$error_count = 0;
		$existingIds = $this->db->select($idField)->where('queue_id', $post['statusSettingArray'][0]->queue_id)->get($masterName)->result_array();
		$existingIds = array_column($existingIds, $idField);
		foreach ($post['statusSettingArray'] as $key => $val) {
			$fieldName = $this->getDynamicFieldName($val->field_id, $val->queue_id);
			if (count($fieldName) > 0) {
				$name = $fieldName['field_name'];
			}
			$statusSettingArray[] = array(
				$idField => $val->id,
				'queue_id' => $val->queue_id,
				'status_id' => $val->status_id,
				'template_id' => $val->template_id,
				'field_id' => $val->field_id,
				'field_name' => $name,
				'field_value' => $val->field_value,
				'to_email' => $val->to_email,
				'customer_email' => ($val->customer_email != "") ? 1 : 0,
			);
			if (strpos($val->to_email, '*') == false) {
				$statusSettingArray[count($statusSettingArray) - 1]['to_email'] = $val->to_email;
			}
		}

		// Update existing records
		foreach ($statusSettingArray as $statusSetting) {
			$id = $statusSetting[$idField];

			unset($statusSetting[$idField]);

			if (!empty($id)) {
				$this->db->where($idField, $id);
				$this->db->update($masterName, $statusSetting);
			} else {
				$this->db->insert($masterName, $statusSetting);

				if ($this->db->affected_rows() == 0) {
					$error_count++;
				}
			}

			// Remove ID from existing IDs array if it is present
			if (($key = array_search($id, $existingIds)) !== false) {
				unset($existingIds[$key]);
			}
		}

		// Delete records that were not included in the update
		if (!empty($existingIds)) {
			$this->db->where_in($idField, $existingIds);
			$this->db->delete($masterName);
			if ($this->db->affected_rows() == 0) {
				$error_count++;
			}
		}

		// Determine success or failure based on error and delete counts
		if ($error_count > 0) {
			$res = array('error' => true);
		} else {
			$select = array('*');
			$this->db->select($select);
			$this->db->from("$masterName");
			$this->db->where('queue_id', $post['queue_id']);
			$statusSettingquery = $this->db->get();
			if ($this->db->error()['code'] == 1451) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			if ($statusSettingquery === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			$res['srarysSettingArray'] = $statusSettingquery->result_array();
			$res['error'] = false;
		}

		return $res;
	}

	public function getDynamicFieldName($fieldId, $queueId)
	{
		$this->db->select("t2.field_name");
		$this->db->from("tms_dynamicform_fields_" . $queueId . " t2");
		$this->db->where("t2.field_id", $fieldId);
		return $this->db->get()->row_array();
	}

	// public function validateQueueRuledata($masterName)
	// {
	// 	$post = (array) json_decode(file_get_contents('php://input'));
	// 	$orderno = trim($post['order_no']);
	// 	if($orderno > 0){
	// 		$this->db->select('*');
	// 		$this->db->from($masterName);
	// 		$this->db->where('rule_id !=', $post['rule_id']);
	// 		$this->db->where('order_no', (int)$post['order_no']);
	// 		$count = $this->db->get()->num_rows();
	// 		$res = array('count' => $count);
	// 	}else if($orderno == 0){
	// 		$res = array('error' => true);
	// 	}
	// 	return $res;
	// }

	public function saveQueueRuledata($masterName, $pKey = 'rule_id', $post, $data)
	{
		$data = is_array($data) ? $data : (array) $data;
		$id = $data[$pKey];
		$queue_id = $post['queue_id'];
		unset($post['queue_id']);
		unset($post[$pKey]);

		if (!empty($masterName)) {
			if (empty($id)) { // create 
				$this->db->insert($masterName, $data);
				$id = $this->db->insert_id();

				foreach ($post['conditionArray'] as $key => $val) {
					$conditionarray[] = array(
						'evaluate_on' => $val->evaluate_on,
						'operator' => $val->operator,
						'evaluate_value' => $val->evaluate_value,
						'rule_id' => $id,
					);
				}
				$this->db->insert_batch("tms_queue_rule_condition_$queue_id", $conditionarray);

				$actionnarray = array(
					'action' => $post['action'],
					'action_value' => is_array($post['action_value']) ? implode(', ', $post['action_value']) : $post['action_value'],
					'rule_id' => $id,
				);

				$this->db->insert("tms_queue_rule_action_$queue_id", $actionnarray);
			} else { // edit 
				$this->db->where($pKey, $id)->update($masterName, $data);

				$this->db->where('rule_id', $id);
				$this->db->delete("tms_queue_rule_condition_$queue_id");

				$this->db->where('rule_id', $id);
				$this->db->delete("tms_queue_rule_action_$queue_id");

				foreach ($post['conditionArray'] as $key => $val) {
					$conditionarray[] = array(
						'evaluate_on' => $val->evaluate_on,
						'operator' => $val->operator,
						'evaluate_value' => $val->evaluate_value,
						'rule_id' => $id,
					);
				}
				$this->db->insert_batch("tms_queue_rule_condition_$queue_id", $conditionarray);

				$actionnarray = array(
					'action' => $post['action'],
					'action_value' => is_array($post['action_value']) ? implode(', ', $post['action_value']) : $post['action_value'],
					'rule_id' => $id,
				);
				$this->db->insert("tms_queue_rule_action_$queue_id", $actionnarray);
			}
			$res = array('error' => false, 'id' => $id);
		} else {
			$res = array('error' => true, 'id' => 0);
		}
		return $res;
	}

	// public function saveQueueAssignRuleData($masterName, $pKey = 'assign_rule_id', $post, $data)
	// {
	// 	$data = is_array($data) ? $data : (array) $data;
	// 	$id = $data[$pKey];
	// 	$queue_id = $post['queue_id'];
	// 	unset($post['queue_id']);
	// 	unset($post[$pKey]);
	// 	if (!empty($masterName)) {
	// 		if (empty($id)) { // create 
	// 			$this->db->insert($masterName, $data);
	// 			$id = $this->db->insert_id();

	// 			foreach ($post['conditionArray'] as $key => $val) {
	// 				$conditionarray[] = array(
	// 					'evaluate_on' => $val->evaluate_on,
	// 					'operator' => $val->operator,
	// 					'evaluate_value' => $val->evaluate_value,
	// 					'assign_rule_id' =>  $id,
	// 				);
	// 			}
	// 			$this->db->insert_batch("tms_queue_assign_rule_condition_$queue_id", $conditionarray);

	// 			$actionnarray = array(
	// 				'action' => $post['action'],
	// 				'action_value' => is_array($post['action_value']) ? implode(', ', $post['action_value']) : $post['action_value'],
	// 				'assign_rule_id' =>  $id,
	// 				'assign_to_login' => ($post['assign_to_login'] == "") ? "0" : $post['assign_to_login']
	// 			);

	// 			$this->db->insert("tms_queue_assign_rule_action_$queue_id", $actionnarray);
	// 		} else { // edit 
	// 			$this->db->where($pKey, $id)->update($masterName, $data);

	// 			$this->db->where('assign_rule_id', $id);
	// 			$this->db->delete("tms_queue_assign_rule_condition_$queue_id");

	// 			$this->db->where('assign_rule_id', $id);
	// 			$this->db->delete("tms_queue_assign_rule_action_$queue_id");

	// 			foreach ($post['conditionArray'] as $key => $val) {
	// 				$conditionarray[] = array(
	// 					'evaluate_on' => $val->evaluate_on,
	// 					'operator' => $val->operator,
	// 					'evaluate_value' => $val->evaluate_value,
	// 					'assign_rule_id' =>  $id,
	// 				);
	// 			}
	// 			$this->db->insert_batch("tms_queue_assign_rule_condition_$queue_id", $conditionarray);

	// 			$actionnarray = array(
	// 				'action' => $post['action'],
	// 				'action_value' => is_array($post['action_value']) ? implode(', ', $post['action_value']) : $post['action_value'],
	// 				'assign_rule_id' =>  $id,
	// 				'assign_to_login' => ($post['assign_to_login'] == "") ? "0" : $post['assign_to_login']
	// 			);
	// 			$this->db->insert("tms_queue_assign_rule_action_$queue_id", $actionnarray);
	// 		}
	// 		$res = array('error' => false, 'id' => $id);
	// 	} else {
	// 		$res = array('error' => true, 'id' => 0);
	// 	}
	// 	return $res;
	// }


	public function validateQueueAssignRuledata($masterName)
	{
		$post = (array) json_decode(file_get_contents('php://input'));
		$orderno = trim($post['order_no']);

		if ($orderno > 0) {
			$this->db->select('*');
			$this->db->from($masterName);
			$this->db->where('assign_rule_id !=', $post['assign_rule_id']);
			$this->db->where('order_no', (int) $post['order_no']);
			$count = $this->db->get();
			if ($count !== FALSE) {
				$count->num_rows();
			}
			$res = array('count' => $count->num_rows());
		} else if ($orderno == 0) {
			$res = array('error' => true);
		}
		return $res;
	}
	public function saveQueueAssignRuleData($masterName, $pKey = 'assign_rule_id', $post, $data)
	{
		$data = is_array($data) ? $data : (array) $data;
		$id = $data[$pKey];
		$queue_id = $post['queue_id'];
		unset($post['queue_id']);
		unset($post[$pKey]);
		try {
			if (!empty($masterName)) {
				if (empty($id)) { // create 
					$this->db->insert($masterName, $data);
					$id = $this->db->insert_id();

					foreach ($post['conditionArray'] as $key => $val) {
						$conditionarray[] = array(
							'evaluate_on' => $val->evaluate_on,
							'operator' => $val->operator,
							'evaluate_value' => $val->evaluate_value,
							'assign_rule_id' => $id,
						);
					}
					$this->db->insert_batch("tms_queue_assign_rule_condition_$queue_id", $conditionarray);

					$actionnarray = array(
						'action' => $post['action'],
						'action_value' => is_array($post['action_value']) ? implode(', ', $post['action_value']) : $post['action_value'],
						'assign_rule_id' => $id,
						'assign_to_login' => ($post['assign_to_login'] == "") ? "0" : $post['assign_to_login']
					);

					$this->db->insert("tms_queue_assign_rule_action_$queue_id", $actionnarray);
				} else { // edit 
					$this->db->where($pKey, $id)->update($masterName, $data);

					$this->db->where('assign_rule_id', $id);
					$this->db->delete("tms_queue_assign_rule_condition_$queue_id");

					$this->db->where('assign_rule_id', $id);
					$this->db->delete("tms_queue_assign_rule_action_$queue_id");

					foreach ($post['conditionArray'] as $key => $val) {
						$conditionarray[] = array(
							'evaluate_on' => $val->evaluate_on,
							'operator' => $val->operator,
							'evaluate_value' => $val->evaluate_value,
							'assign_rule_id' => $id,
						);
					}
					$this->db->insert_batch("tms_queue_assign_rule_condition_$queue_id", $conditionarray);

					$actionnarray = array(
						'action' => $post['action'],
						'action_value' => is_array($post['action_value']) ? implode(', ', $post['action_value']) : $post['action_value'],
						'assign_rule_id' => $id,
						'assign_to_login' => ($post['assign_to_login'] == "") ? "0" : $post['assign_to_login']
					);
					$this->db->insert("tms_queue_assign_rule_action_$queue_id", $actionnarray);
				}
				$res = array('error' => false, 'id' => $id);
			} else {
				$res = array('error' => true, 'id' => 0);
			}
		} catch (Exception $e) {
			// Handle the database exception here, you can log it or perform any other necessary actions
			$res = array('error' => true, 'id' => 0, 'message' => $e->getMessage());
		}

		return $res;
	}

	public function saveQueueTemplateData($masterName, $pKey = 'template_id', $post, $data)
	{
		$data = is_array($data) ? $data : (array) $data;
		$decodedTemplate = html_entity_decode($data['customer_email_template']);
		$data['customer_email_template'] = $decodedTemplate;
		$id = $data[$pKey];
		$queue_id = $data['queue_id'];
		unset($data['queue_id']);
		unset($data[$pKey]);
		unset($data['method']);
		unset($data['master_name']);

		if (!empty($masterName)) {

			if (empty($id)) {

				$this->db->where("template='$data[template]'", NULL, false);
				$dtCount = $this->db->count_all_results($masterName);

				if ($dtCount == 0) {
					$this->db->insert($masterName, $data);

					$id = $this->db->insert_id();
				} else {
					$res = array('error' => true, 'id' => 0, 'message' => "Template already exists");
					return $res;
				}
			} else {
				// $this->db->where("template_id='$id'", NULL, false);
				// $ticketCount = $this->db->count_all_results("tms_queue_status_$queue_id");

				// if ($ticketCount != 0 && $data['status'] == 0) {
				// 	$res = array('error' => true, 'id' => 0, 'message' => "Cannot Inactive '$data[template]' template because it is referenced by the Status table");
				// 	return $res;
				// }

				if ($data['status'] == 0) {
					$this->db->where("template_id='$id'", NULL, false);
					$ticketCountStatus = $this->db->count_all_results("tms_queue_status_$queue_id");

					$this->db->where("template_id='$id' or agent_template_id = '$id'", NULL, false);
					$ticketCountAnotherTable = $this->db->count_all_results("tms_queue_escalationmatrix_$queue_id");
					// fx::pr($ticketCountAnotherTable,1);
					if ($ticketCountStatus != 0 || $ticketCountAnotherTable != 0) {

						$res = array('error' => true, 'id' => 0, 'message' => "Cannot Inactive '$data[template]' template because it is referenced by another table and its status is currently inactive.");
						return $res;
					}
				}

				$this->db->where("template='$data[template]' and template_id!=$post[template_id]", NULL, false);
				$dtCount = $this->db->count_all_results($masterName);
				if ($dtCount == 0) {
					$this->db->set($data, FALSE);
					$this->db->where($pKey, $id)->update($masterName);
					// fx::pr($this->db->last_query(),1);
				} else {
					$res = array('error' => true, 'id' => 0, 'message' => "Template already exists");
					return $res;
				}
			}
			$res = array('error' => false, 'id' => $id);
		} else {
			$res = array('error' => true, 'id' => 0);
		}
		return $res;
	}


	function saverule($masterName, $data, $pKey = 'id', $post)
	{
		$table = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
		if (!empty($table)) {
			$data = is_array($data) ? $data : (array) $data;
			$id = $data[$pKey];
			unset($data[$pKey]);
			if (empty($id)) { // create 
				$this->db->insert($table, $data);
				$id = $this->db->insert_id();

				foreach ($post['conditionArray'] as $key => $val) {
					$conditionarray[] = array(
						'evaluate_on' => $val->evaluate_on,
						'operator' => $val->operator,
						'evaluate_value' => $val->evaluate_value,
						'rule_id' => $id,
					);
				}
				$this->db->insert_batch('tms_rule_condition', $conditionarray);

				foreach ($post['actionArray'] as $key => $val) {
					$actionnarray[] = array(
						'action' => $val->action,
						'action_value' => $val->action_value,
						'rule_id' => $id,
					);
				}
				$this->db->insert_batch('tms_rule_action', $actionnarray);
			} else { // edit 
				$this->db->where($pKey, $id)->update($table, $data);

				$this->db->where('rule_id', $id);
				$this->db->delete('tms_rule_condition');

				$this->db->where('rule_id', $id);
				$this->db->delete('tms_rule_action');

				foreach ($post['conditionArray'] as $key => $val) {
					$conditionarray[] = array(
						'evaluate_on' => $val->evaluate_on,
						'operator' => $val->operator,
						'evaluate_value' => $val->evaluate_value,
						'rule_id' => $id,
					);
				}
				$this->db->insert_batch('tms_rule_condition', $conditionarray);

				foreach ($post['actionArray'] as $key => $val) {
					$actionnarray[] = array(
						'action' => $val->action,
						'action_value' => $val->action_value,
						'rule_id' => $id,
					);
				}
				$this->db->insert_batch('tms_rule_action', $actionnarray);
			}
			$res = array('error' => false, 'id' => $id);
		} else {
			$res = array('error' => true, 'id' => 0);
		}
		return $res;
	}



	// function savequeue($masterName, $data, $pKey = 'id', $post)
	// {
	// 	$table = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
	// 	if (!empty($table)) {
	// 		$data = is_array($data) ? $data : (array) $data;
	// 		$id = $data[$pKey];
	// 		unset($data[$pKey]);
	// 		if (empty($id)) { // create 
	// 			$this->db->insert($table, $data);
	// 			$id = $this->db->insert_id();

	// 			$sql = file_get_contents(FCPATH . "/assets/queue_db_script/queue_db_script.sql");
	// 			$sqls = explode(';', $sql);
	// 			array_pop($sqls);
	// 			foreach ($sqls as $statement) {
	// 				$query = str_replace('##QID##', $id, $statement);
	// 				$query = str_replace('##QID##', $id, $query) . ";";
	// 				$this->db->query($query);
	// 			}
	// 			$this->db->close();
	// 			$this->load->database();

	// 			// $DynamicData['queue_name'] = $data['queue'];
	// 			// $DynamicData['queue_id'] = $id;
	// 			// $DynamicData['status'] = $data['status'];
	// 			// $DynamicData['createdOn'] = date('Y-m-d H:i:s');
	// 			// $DynamicData['createdBy'] = $data['created_by'];


	// 			// $this->db->insert('tms_dynamic_form', $DynamicData);

	// 			foreach ($post['emailArray'] as $key => $val) {
	// 				$emailarray[] = array(
	// 					'incoming_email_account' => $val->incoming_email_account,
	// 					'outgoing_email_account' => $val->outgoing_email_account,
	// 					'queue_id' =>  $id,
	// 				);
	// 			}
	// 			$this->db->insert_batch('tms_queue_email', $emailarray);

	// 			foreach ($post['templateArray'] as $key => $val) {
	// 				$templatearray[] = array(
	// 					'action' => $val->action,
	// 					'template' => $val->template,
	// 					'customer_email' => $val->customer_email,
	// 					'consumer_sms' => $val->consumer_sms,
	// 					'customer_wp' => $val->customer_wp,
	// 					'user_email' => $val->user_email,
	// 					'user_sms' => $val->user_sms,
	// 					'user_wp' => $val->user_wp,
	// 					'queue_id' =>  $id,
	// 				);
	// 			}
	// 			$this->db->insert_batch('tms_queue_template', $templatearray);
	// 		} else { // edit 
	// 			$this->db->where($pKey, $id)->update($table, $data);


	// 			// $DynamicData['queue_name'] = $data['queue'];
	// 			// $DynamicData['queue_id'] = $id;
	// 			// $DynamicData['status'] = $data['status'];
	// 			// $DynamicData['createdOn'] = date('Y-m-d H:i:s');
	// 			// $DynamicData['createdBy'] = $data['modified_by'];

	// 			// $this->db->where('queue_id', $id)->update('tms_dynamic_form', $DynamicData);

	// 			// $this->db->insert_batch('tms_dynamic_form', $DynamicData);

	// 			$this->db->where('queue_id', $id);
	// 			$this->db->delete('tms_queue_email');

	// 			$this->db->where('queue_id', $id);
	// 			$this->db->delete('tms_queue_template');

	// 			foreach ($post['emailArray'] as $key => $val) {
	// 				$emailarray[] = array(
	// 					'incoming_email_account' => $val->incoming_email_account,
	// 					'outgoing_email_account' => $val->outgoing_email_account,
	// 					'queue_id' =>  $id,
	// 				);
	// 			}
	// 			$this->db->insert_batch('tms_queue_email', $emailarray);

	// 			foreach ($post['templateArray'] as $key => $val) {
	// 				$templatearray[] = array(
	// 					'action' => $val->action,
	// 					'template' => $val->template,
	// 					'customer_email' => $val->customer_email,
	// 					'consumer_sms' => $val->consumer_sms,
	// 					'customer_wp' => $val->customer_wp,
	// 					'user_email' => $val->user_email,
	// 					'user_sms' => $val->user_sms,
	// 					'user_wp' => $val->user_wp,
	// 					'queue_id' =>  $id,
	// 				);
	// 			}
	// 			$this->db->insert_batch('tms_queue_template', $templatearray);
	// 		}
	// 		$res = array('error' => false, 'id' => $id);
	// 	} else {
	// 		$res = array('error' => true, 'id' => 0);
	// 	}
	// 	return $res;
	// }

	public function savequeue($masterName, $data, $pKey = 'id', $post)
	{
		$this->db->trans_start();
		// Perform database operations here
		$table = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
		if (!empty($table)) {
			$data = is_array($data) ? $data : (array) $data;
			$id = $data[$pKey];
			unset($data[$pKey]);
			if (empty($id)) { // create 
				$this->db->insert($table, $data);
				$id = $this->db->insert_id();
				$sql = file_get_contents(FCPATH . "/assets/queue_db_script/queue_db_script.sql");
				$sqls = explode(';', $sql);
				array_pop($sqls);

				$emailArray = $post['emailArray'];
				$count = count($emailArray);

				for ($i = 0; $i < $count; $i++) {
					for ($j = $i + 1; $j < $count; $j++) {
						if ($emailArray[$i]->incoming_email_account == $emailArray[$j]->incoming_email_account) {
							return array($emailArray[$i]);
						}
					}
				}


				foreach ($post['emailArray'] as $key => $val) {
					$this->db->select('*');
					$this->db->from('tms_queue_email');
					$this->db->where('incoming_email_account', (int) $val->incoming_email_account);
					$res = $this->db->get()->row();
					if (isset($res->incoming_email_account)) {
						return $res;
					}
				}


				foreach ($sqls as $statement) {
					$query = str_replace('##QID##', $id, $statement);
					$query = str_replace('##QID##', $id, $query) . ";";
					$this->db->query($query);
				}
				$this->db->close();
				$this->load->database();

				foreach ($post['emailArray'] as $key => $val) {
					$emailarray[] = array(
						'incoming_email_account' => $val->incoming_email_account,
						'outgoing_email_account' => $val->outgoing_email_account,
						'queue_id' => $id,
					);
				}
				$this->db->insert_batch('tms_queue_email', $emailarray);
			} else { // edit 

				$this->db->where($pKey, $id)->update($table, $data);
				$this->db->where('queue_id', $id);
				$this->db->delete('tms_queue_email');

				// $this->db->where('queue_id', $id);
				// $this->db->delete('tms_queue_template');

				$emailArray = $post['emailArray'];
				$count = count($emailArray);

				for ($i = 0; $i < $count; $i++) {
					for ($j = $i + 1; $j < $count; $j++) {
						if ($emailArray[$i]->incoming_email_account == $emailArray[$j]->incoming_email_account) {
							return array($emailArray[$i]);
						}
					}
				}

				foreach ($post['emailArray'] as $key => $val) {
					$this->db->select('*');
					$this->db->from('tms_queue_email');
					$this->db->where('incoming_email_account', (int) $val->incoming_email_account);
					$res = $this->db->get()->row();
					if (isset($res->incoming_email_account)) {
						return $res;
					}
				}

				foreach ($post['emailArray'] as $key => $val) {
					$emailarray[] = array(
						'incoming_email_account' => $val->incoming_email_account,
						'outgoing_email_account' => $val->outgoing_email_account,
						'queue_id' => $id,
					);
				}
				$this->db->insert_batch('tms_queue_email', $emailarray);
			}
			$res = array('error' => false, 'id' => $id);
		} else {
			$res = array('error' => true, 'id' => 0);
		}

		// End the transaction
		if ($this->db->trans_status() === false) {
			$this->db->trans_rollback();
			$res = array('error' => true, 'id' => 0);
		} else {
			$this->db->trans_commit();
			$res = array('error' => false, 'id' => $id);
		}
		return $res;
	}



	function saveUser($masterName, $data, $pKey = 'id')
	{
		if (!empty($masterName)) {
			$data = is_array($data) ? $data : (array) $data;
			$password = md5($data['original_password']);
			$data += ['password' => $password];
			$id = $data[$pKey];
			unset($data[$pKey]);
			if (empty($id)) { // create 
				$this->db->insert($masterName, $data);
				$id = $this->db->insert_id();
				$this->db->set('user_id', $id);
				$this->db->where('id', $id)->update($masterName);
			} else { // edit 
				$this->db->where($pKey, $id)->update($masterName, $data);
			}
			$res = array('error' => false, 'id' => $id);
		} else {
			$res = array('error' => true, 'id' => 0);
		}
		return $res;
	}

	function saveShift($masterName, $data, $pKey = 'id')
	{
		if (!empty($masterName)) {
			$data = is_array($data) ? $data : (array) $data;
			$id = $data[$pKey];
			unset($data[$pKey]);
			if (empty($id)) { // create 
				$this->db->insert($masterName, $data);
				$id = $this->db->insert_id();
			} else { // edit 
				$this->db->where($pKey, $id)->update($masterName, $data);
			}
			$res = array('error' => false, 'id' => $id);
		} else {
			$res = array('error' => true, 'id' => 0);
		}
		return $res;
	}

	function deleteProcess($masterName, $data, $pKey = 'id')
	{
		try {

			$table = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
			if (!empty($table)) {
				$data = is_array($data) ? $data : (array) $data;
				$id = $data[$pKey];
				if (!empty($id)) {
					if ($this->db->delete($table, array($pKey => $id))) {
						$res = array('error' => false, 'message' => 'Record deleted');
					} else {
						$error = $this->db->error();
						if ($error['code'] == '') {
							throw new Exception('Something goes wrong.');
						} else {
							throw new Exception('Something goes wrong.');
						}
					}
				} else {
					throw new Exception('Invalid Request');
				}
			} else {
				throw new Exception('Invalid Request');
			}
		} catch (Exception $e) {
			$res = array('error' => true, 'message' => $e->getMessage());
		}
		return $res;
	}

	function masterEmailAccountRules($ruleForAdd)
	{
		$rules[] = array(
			'field' => 'email',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueEmailValidate'))),
			'errors' => array('msg' => 'Email already exists')
		);
		$rules[] = array('field' => 'server_type', 'label' => 'Server type', 'rules' => 'required');
		$rules[] = array('field' => 'display_name', 'label' => 'Display Name ', 'rules' => 'required');


		$rules[] = array('field' => 'incoming_user_name', 'label' => 'Incoming User Name', 'rules' => 'required');

		$rules[] = array('field' => 'incoming_password', 'label' => 'Incoming Password', 'rules' => ($ruleForAdd) ? "" : "required");
		// $rules[] = array('field' => 'outgoing_password', 'label' => 'Outgoing Password', 'rules' => ($ruleForAdd) ? "" : "required");

		$rules[] = array('field' => 'outgoing_user_name', 'label' => 'Outgoing User Name', 'rules' => 'required');

		$rules[] = array('field' => 'incoming_mail_server', 'label' => 'Incoming Mail Server', 'rules' => 'required');
		// $rules[] = array('field' => 'outgoing_mail_server_port', 'label' => 'Outgoing Mail Server  Port', 'rules' => 'required');
		// $rules[] = array('field' => 'incoming_mail_server_port', 'label' => 'Incoming Mail  Port', 'rules' => 'required');
		$rules[] = array('field' => 'outgoing_mail_server', 'label' => 'Outgoing  Mail Server', 'rules' => 'required');
		// $rules[] = array('field' => 'outgoing_mail_server_port', 'label' => 'Outgoing Mail Server  Port', 'rules' => 'required');
		return $rules;
	}

	function getMasterTableRules($masterName, $ruleForAdd = true)
	{
		if (strpos($masterName, 'tms_queue_rule_master_') === 0) {
			$masterName = "queue_rules";
		} else if (strpos($masterName, 'tms_queue_assign_rule_master_') === 0) {
			$masterName = "queue_assign_rules";
		}
		switch ($masterName) {
			case 'user':
				return $this->masterUserRules();
				break;
			case 'shift':
				return $this->masterShiftRules();
				break;
			case 'company':
				return $this->masterComapnyRules();
				break;
			case 'priority':
				return $this->masterPriorityRules();
				break;
			case 'emailAccount':
				return $this->masterEmailAccountRules($ruleForAdd);
				break;
			case 'pagination':
				return $this->masterPaginationRules();
				break;
			case 'sub-category':
				return $this->masterSubCategoryRules();
				break;
			case 'status':
				return $this->masterStatusRules();
				break;
			case 'queue_rules':
				return $this->masterRuleRules();
				break;
			case 'queue_assign_rules':
				return $this->masterQueueAssignRuleRules();
				break;
			case 'queue':
				return $this->masterQueueRules();
				break;
			case 'template':
				return $this->masterTemplateRules();
				break;
			// case 'ticket':
			// 	return $this->masterTicketRules();
			// 	break;
			case 'field-group':
				return $this->masterFieldGroupRules();
				break;
			case 'conversation-type':
				return $this->masterConversationTypeRules();
				break;
			case 'break':
				return $this->masterBreakRules();
				break;
			default:
				return $this->masterRules();
				break;
		}
	}

	public function getTicketTableRules()
	{
		$rules[] = array('field' => 'queue_id', 'label' => 'Queue', 'rules' => 'required');
		$rules[] = array('field' => 'from_email', 'label' => 'From Email', 'rules' => 'required');
		// $rules[] = array('field' => 'to_email', 'label' => 'Email To', 'rules' => 'required');
		// $rules[] = array('field' => 'subject', 'label' => 'Subject', 'rules' => 'required');
		$rules[] = array('field' => 'priority_id', 'label' => 'Priority', 'rules' => 'required');
		$rules[] = array('field' => 'conversation', 'label' => 'Remarks', 'rules' => 'required');
		$rules[] = array('field' => 'status_id', 'label' => 'Ticket Status', 'rules' => 'required');
		return $rules;
	}


	function masterFieldGroupRules()
	{

		$rules[] = array(
			'field' => 'title',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueTitleValidate'))),
			'errors' => array('msg' => 'Field Group  already exists')
		);
		$rules[] = array(
			'field' => 'order_no',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueOrdeValidate'))),
			'errors' => array('msg' => 'Order No already exists')
		);
		$rules[] = array('field' => 'field_type', 'label' => 'Field Type', 'rules' => 'required');
		return $rules;
	}

	// function masterTicketRules()
	// {
	// 	$rules[] = array('field' => 'queue_id', 'label' => 'Queue', 'rules' => 'required');
	// 	$rules[] = array('field' => 'email_from', 'label' => ' Email From', 'rules' => 'required');
	// 	$rules[] = array('field' => 'email_to', 'label' => 'Email To', 'rules' => 'required');
	// 	$rules[] = array('field' => 'subject', 'label' => 'Subject', 'rules' => 'required');
	// 	$rules[] = array('field' => 'priority_id', 'label' => 'Priority', 'rules' => 'required');
	// 	$rules[] = array('field' => 'conversation', 'label' => 'Conversation', 'rules' => 'required');
	// 	$rules[] = array('field' => 'ticket_status', 'label' => 'Ticket Status', 'rules' => 'required');
	// 	return $rules;
	// }


	function masterTemplateRules()
	{
		$rules[] = array(
			'field' => 'template',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniquetemplateValidate'))),
			'errors' => array('msg' => 'Template already exists')
		);
		return $rules;
	}

	public function masterConversationTypeRules()
	{
		$rules[] = array(
			'field' => 'title',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueTitleValidate'))),
			'errors' => array('msg' => 'Conversation Type already exists')
		);
		return $rules;
	}

	function masterQueueRules()
	{
		$rules[] = array(
			'field' => 'queue',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueQueueValidate'))),
			'errors' => array('msg' => 'Queue already exists')
		);
		// $rules[] = array('field' => 'priority_id', 'label' => 'Priority', 'rules' => 'required');
		// $rules[] = array('field' => 'incomming_male_status', 'label' => 'Incoming Mail Status', 'rules' => 'required');
		$rules[] = array('field' => 'before_assign_shift', 'label' => 'Before Assign Shift', 'rules' => 'required');
		$rules[] = array('field' => 'dont_read_mail_before', 'label' => 'Dont Read Mail Before', 'rules' => 'required');
		$rules[] = array('field' => 'auto_assign_setting', 'label' => 'Auto Assign Setting', 'rules' => 'required');
		// $rules[] = array('field' => 'incoming_email_account', 'label' => 'Incoming Email Account', 'rules' => 'required');
		// $rules[] = array('field' => 'outgoing_email_account', 'label' => 'Outgoing Email Account', 'rules' => 'required');
		return $rules;
	}


	function masterRuleRules()
	{

		$rules[] = array(
			'field' => 'rule_name',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueRuleNameValidate'))),
			'errors' => array('msg' => 'Rule already exists')
		);


		$rules[] = array(
			'field' => 'order_no',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueOrdeValidate'))),
			'errors' => array('msg' => 'Order No already exists')
		);
		return $rules;
	}

	function masterQueueAssignRuleRules()
	{

		$rules[] = array(
			'field' => 'rule_name',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueAssignRuleNameValidate'))),
			'errors' => array('msg' => 'Manual Rule already exists')
		);


		$rules[] = array(
			'field' => 'order_no',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueAssignOrderValidate'))),
			'errors' => array('msg' => 'Order No already exists')
		);
		return $rules;
	}

	function masterPriorityRules()
	{
		$rules[] = array(
			'field' => 'name',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueNameValidate'))),
			'errors' => array('msg' => 'Name already exists')
		);

		$rules[] = array(
			'field' => 'colour_code',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueColourCodeValidate'))),
			'errors' => array('msg' => 'Colour Code already exists')
		);
		$rules[] = array('field' => 'tat', 'label' => 'TaT', 'rules' => 'required');
		$rules[] = array('field' => 'order_no', 'label' => 'Order Number', 'rules' => 'required');

		return $rules;
	}

	public function masterStatusRules()
	{
		$rules[] = array(
			'field' => 'title',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueTitleValidate'))),
			'errors' => array('msg' => 'Ticket Status Already exists')
		);

		$rules[] = array(
			'field' => 'colour_code',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueColourCodeValidate'))),
			'errors' => array('msg' => 'Colour Code already exists')
		);

		$rules[] = array('field' => 'ticket_type', 'label' => 'Ticket Status Type', 'rules' => 'required');
		return $rules;
	}

	public function uniqueColourCodeValidate()
	{
		$post = (array) json_decode(file_get_contents('php://input'));
		$masterName = $post['master_name'];
		$tableName = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
		if (!empty($post['id'])) {
			$is_exist = $this->db->where('colour_code', $post['colour_code'])->where_not_in('id', array($post['id']))->get($tableName)->row();
		} else {
			$is_exist = $this->db->where('colour_code', $post['colour_code'])->get($tableName)->row();
		}
		return ($is_exist) ? false : true;
	}

	function masterComapnyRules()
	{
		$rules[] = array(
			'field' => 'name',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueNameValidate'))),
			'errors' => array('msg' => 'Name already exists')
		);
		$rules[] = array(
			'field' => 'email',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueEmailValidate'))),
			'errors' => array('msg' => 'Email already exists')
		);
		// $rules[] = array('field' => 'emailserver', 'label' => 'Email Server', 'rules' => 'required');
		// $rules[] = array('field' => 'pagesize', 'label' => 'Page Size', 'rules' => 'required');
		$rules[] = array('field' => 'mailassignlimit', 'label' => 'Assign Limit', 'rules' => 'required');
		$rules[] = array('field' => 'assigntimegap', 'label' => 'Assign Time Gap', 'rules' => 'required');

		return $rules;
	}

	function companysaveProcess($masterName, $data, $pKey = 'id')
	{
		$table = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
		if (!empty($table)) {
			$data = is_array($data) ? $data : (array) $data;
			$id = $data[$pKey];
			unset($data[$pKey]);
			if (empty($id)) { // create 
				$this->db->insert($table, $data);
				$id = $this->db->insert_id();
			} else { // edit 
				$this->db->where($pKey, $id)->update($table, $data);
			}
			$res = array('error' => false, 'id' => $id);
		} else {
			$res = array('error' => true, 'id' => 0);
		}
		return $res;
	}

	function validateForm($post, $rules)
	{

		$this->form_validation->set_data((array) $post);
		$this->form_validation->set_rules($rules);

		if ($this->form_validation->run() === FALSE) {
			$data = $this->form_validation->error_array();
			$data['error'] = true;
			echo json_encode($data);
			die;
		}
	}

	function masterUserRules()
	{
		$rules[] = array(
			'field' => 'name',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueNameValidate'))),
			'errors' => array('msg' => 'Name already exists')
		);
		$rules[] = array(
			'field' => 'email',
			'label' => '',
			'rules' => array(array('msg', array($this, 'uniqueEmailValidateforuser'))),
			'errors' => array('msg' => 'Email already exists')
		);
		$rules[] = array(
			'field' => 'mobile_no',
			'label' => '',
			'rules' => array(array('msg', array($this, 'uniqueMobilenoValidate'))),
			'errors' => array('msg' => 'Mobile No already exists')
		);
		$rules[] = array(
			'field' => 'user_name',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueUsernameValidate'))),
			'errors' => array('msg' => 'User Name already exists')
		);
		return $rules;
	}

	function masterSubCategoryRules()
	{
		$rules[] = array('field' => 'category_id', 'label' => 'Category', 'rules' => 'required');

		$rules[] = array(
			'field' => 'title',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueCategoryValidate'))),
			'errors' => array('msg' => 'Sub Category already exists')
		);
		return $rules;
	}


	function masterRules()
	{
		$rules[] = array('field' => 'title', 'label' => 'Title', 'rules' => 'required|min_length[2]|max_length[100]');
		$rules[] = array(
			'field' => 'title',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueTitleValidate'))),
			'errors' => array('msg' => 'Already exists')
		);
		return $rules;
	}

	public function masterShiftRules()
	{
		$rules[] = array('field' => 'title', 'label' => 'Title', 'rules' => 'required|min_length[2]|max_length[100]');
		$rules[] = array(
			'field' => 'title',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueTitleValidate'))),
			'errors' => array('msg' => 'Already exists')
		);
		$rules[] = array('field' => 'time_from', 'label' => 'Time_From', 'rules' => 'required');
		$rules[] = array('field' => 'time_to', 'label' => 'Time To', 'rules' => 'required');

		return $rules;
	}


	public function uniqueUsernameValidate()
	{
		$post = (array) json_decode(file_get_contents('php://input'));
		$masterName = $post['master_name'];
		$tableName = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
		if (!empty($post['id'])) {
			$is_exist = $this->db->where('user_name', trim($post['user_name']))->where_not_in('id', array(trim($post['id'])))->get($tableName)->row();
		} else {
			$is_exist = $this->db->where('user_name', trim($post['user_name']))->get($tableName)->row();
		}
		return ($is_exist) ? false : true;
	}

	public function uniqueNameValidate()
	{
		$post = (array) json_decode(file_get_contents('php://input'));
		$masterName = $post['master_name'];
		$tableName = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
		if (!empty($post['id'])) {
			$is_exist = $this->db->where('name', trim($post['name']))->where_not_in('id', array(trim($post['id'])))->get($tableName)->row();
		} else {
			$is_exist = $this->db->where('name', trim($post['name']))->get($tableName)->row();
		}
		return ($is_exist) ? false : true;
	}

	public function uniqueEmailValidate()
	{
		$post = (array) json_decode(file_get_contents('php://input'));
		$masterName = $post['master_name'];
		$tableName = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
		if (!empty($post['id'])) {
			$is_exist = $this->db->where('email', trim($post['email']))->where_not_in('id', array(trim($post['id'])))->get($tableName)->row();
		} else {
			$is_exist = $this->db->where('email', trim($post['email']))->get($tableName)->row();
		}
		return ($is_exist) ? false : true;
	}


	public function uniqueEmailValidateforuser()
	{
		$post = (array) json_decode(file_get_contents('php://input'));
		$masterName = $post['master_name'];
		$tableName = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
		if (empty($post['email'])) {
			return true;
		}
		if (!empty($post['id'])) {
			$is_exist = $this->db->where('email', trim($post['email']))->where('id !=', trim($post['id']))->get($tableName)->row();
		} else {
			$is_exist = $this->db->where('email', trim($post['email']))->get($tableName)->row();
		}
		return ($is_exist) ? false : true;
	}

	public function uniqueMobilenoValidate()
	{
		$post = (array) json_decode(file_get_contents('php://input'));
		$masterName = $post['master_name'];
		$mobile_no = $post['mobile_no'];
		$tableName = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
		if (empty($mobile_no)) {
			return true;
		}
		if (!empty($post['id'])) {
			$is_exist = $this->db->where('mobile_no', trim($post['mobile_no']))->where_not_in('id', array(trim($post['id'])))->get($tableName)->row();
		} else {
			$is_exist = $this->db->where('mobile_no', trim($post['mobile_no']))->get($tableName)->row();
		}
		return ($is_exist) ? false : true;
	}

	function masterPaginationRules()
	{
		$rules[] = array(
			'field' => 'record',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniquePaginationValidate'))),
			'errors' => array('msg' => 'Value already exists')
		);

		$rules[] = array('field' => 'status', 'label' => 'Status', 'rules' => 'required|min_length[1]|max_length[1]|numeric');
		return $rules;
	}

	function uniqueTitleValidate()
	{
		$post = (array) json_decode(file_get_contents('php://input'));
		$masterName = $post['master_name'];
		$tableName = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
		if (!empty($post['id'])) {
			$is_exist = $this->db->where('title', trim($post['title']))->where_not_in('id', array(trim($post['id'])))->get($tableName)->row();
		} else {
			$is_exist = $this->db->where('title', trim($post['title']))->get($tableName)->row();
		}

		return ($is_exist) ? false : true;
	}

	function uniqueRuleNameValidate()
	{
		$post = (array) json_decode(file_get_contents('php://input'));
		$masterName = $post['master_name'];
		if (!empty($post['rule_id'])) {
			$is_exist = $this->db->where('rule_name', trim($post['rule_name']))->where_not_in('rule_id', array(trim($post['rule_id'])))->get($masterName)->row();
		} else {
			$is_exist = $this->db->where('rule_name', trim($post['rule_name']))->get($masterName)->row();
		}

		return ($is_exist) ? false : true;
	}

	function uniqueAssignRuleNameValidate()
	{
		$post = (array) json_decode(file_get_contents('php://input'));
		$masterName = $post['master_name'];
		if (!empty($post['assign_rule_id'])) {
			$is_exist = $this->db->where('rule_name', trim($post['rule_name']))->where_not_in('assign_rule_id', array(trim($post['assign_rule_id'])))->get($masterName)->row();
		} else {
			$is_exist = $this->db->where('rule_name', trim($post['rule_name']))->get($masterName)->row();
		}

		return ($is_exist) ? false : true;
	}

	// function uniqueTitleValidate()
	// {
	// 	try {
	// 		$post = (array) json_decode(file_get_contents('php://input'));
	// 		$masterName = $post['master_name'];
	// 		$tableName = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';

	// 		if (!empty($post['id'])) {
	// 			$this->db->where('title', trim($post['title']))
	// 				->where_not_in('id', array(trim($post['id'])));
	// 		} else {
	// 			$this->db->where('title', trim($post['title']));
	// 		}

	// 		$query = $this->db->get($tableName);

	// 		if ($query === false) {
	// 			throw new Exception("Error executing database query.");
	// 		}

	// 		$is_exist = $query->row();

	// 		return ($is_exist) ? false : true;
	// 	} catch (Exception $e) {
	// 		// Handle the exception or log the error message
	// 		return array(
	// 			'error' => true,
	// 			'message' => $e->getMessage()
	// 		);
	// 	}
	// }

	function uniquePaginationValidate()
	{
		$post = (array) json_decode(file_get_contents('php://input'));
		if (!empty($post['id'])) {
			$is_exist = $this->db->where('record', trim($post['record']))->where_not_in('id', array(trim($post['id'])))->get('tms_pagination_master')->row();
		} else {
			$is_exist = $this->db->where('record', trim($post['record']))->get('tms_pagination_master')->row();
		}
		return ($is_exist) ? false : true;
	}

	function uniqueCategoryValidate()
	{
		$post = (array) json_decode(file_get_contents('php://input'));
		$masterName = $post['master_name'];
		$category_id = trim($post['category_id']);
		$tableName = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
		if (!empty($post['id'])) {
			$is_exist = $this->db->where("title = '$post[title]' and category_id = '$category_id'")->where_not_in('id', array(trim($post['id'])))->get($tableName)->row();
		} else {
			$is_exist = $this->db->where("title = '$post[title]' and category_id = '$category_id'")->get($tableName)->row();
		}
		return ($is_exist) ? false : true;
	}


	function uniqueOrdeValidate()
	{
		$post = (array) json_decode(file_get_contents('php://input'));
		$masterName = $post['master_name'];
		$orderno = trim($post['order_no']);
		if (!empty($post['rule_id'])) {
			$is_exist = $this->db->where("order_no = '$orderno'")->where_not_in('rule_id', array(trim($post['rule_id'])))->get($masterName)->row();
		} else {
			$is_exist = $this->db->where("order_no = '$orderno'")->get($masterName)->row();
		}
		return ($is_exist) ? false : true;
	}

	function uniqueAssignOrderValidate()
	{
		$post = (array) json_decode(file_get_contents('php://input'));
		$masterName = $post['master_name'];
		$orderno = trim($post['order_no']);
		if (!empty($post['assign_rule_id'])) {
			$is_exist = $this->db->where("order_no = '$orderno'")->where_not_in('assign_rule_id', array(trim($post['assign_rule_id'])))->get($masterName)->row();
		} else {
			$is_exist = $this->db->where("order_no = '$orderno'")->get($masterName)->row();
		}
		return ($is_exist) ? false : true;
	}


	function uniqueQueueValidate()
	{
		$post = (array) json_decode(file_get_contents('php://input'));
		$masterName = $post['master_name'];
		$queuename = trim($post['queue']);
		$tableName = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
		if (!empty($post['id'])) {
			$is_exist = $this->db->where("queue = '$queuename'")->where_not_in('id', array(trim($post['id'])))->get($tableName)->row();
		} else {
			$is_exist = $this->db->where("queue = '$queuename'")->get($tableName)->row();
		}
		return ($is_exist) ? false : true;
	}

	function uniquetemplateValidate()
	{
		$post = (array) json_decode(file_get_contents('php://input'));
		$masterName = $post['master_name'];
		$templatename = trim($post['template']);
		$tableName = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
		if (!empty($post['id'])) {
			$is_exist = $this->db->where("template = '$templatename'")->where_not_in('id', array(trim($post['id'])))->get($tableName)->row();
		} else {
			$is_exist = $this->db->where("template = '$templatename'")->get($tableName)->row();
		}
		return ($is_exist) ? false : true;
	}

	// public function getQueueRulesData($rule_id, $queue_id, $primaryKey = 'rule_id')
	// {
	// 	$select = array('*');
	// 	$this->db->select($select);
	// 	$this->db->where(array($primaryKey => $rule_id));
	// 	$this->db->from("tms_queue_rule_master_$queue_id");
	// 	$query = $this->db->get();
	// 	$result = $query->row_array();


	// 	$select = array('*');
	// 	$this->db->select($select);
	// 	$this->db->where('rule_id', $rule_id);
	// 	$this->db->from("tms_queue_rule_condition_$queue_id");
	// 	$ruleConditionQry = $this->db->get();
	// 	$ruleConditionResult = $ruleConditionQry->result_array();

	// 	$select = array('*');
	// 	$this->db->select($select);
	// 	$this->db->where('rule_id', $rule_id);
	// 	$this->db->from("tms_queue_rule_action_$queue_id");
	// 	$ruleActionQry = $this->db->get();
	// 	$ruleActionResult = $ruleActionQry->result_array();

	// 	return  array('result' => $result, 'ruleConditionResult' => $ruleConditionResult, 'ruleActionResult' => $ruleActionResult);
	// }

	public function getQueueRulesData($rule_id, $queue_id, $primaryKey = 'rule_id')
	{
		try {
			$select = array('*');

			// Fetch data from tms_queue_rule_master_$queue_id table
			$this->db->select($select);
			$this->db->where(array($primaryKey => $rule_id));
			$this->db->from("tms_queue_rule_master_$queue_id");
			$query = $this->db->get();

			// Check for query execution errors
			if ($query === false) {
				throw new Exception("Error fetching data from tms_queue_rule_master_$queue_id table");
			}

			$result = $query->row_array();

			// Fetch data from tms_queue_rule_condition_$queue_id table
			$this->db->select($select);
			$this->db->where('rule_id', $rule_id);
			$this->db->from("tms_queue_rule_condition_$queue_id");
			$ruleConditionQry = $this->db->get();

			// Check for query execution errors
			if ($ruleConditionQry === false) {
				throw new Exception("Error fetching data from tms_queue_rule_condition_$queue_id table");
			}

			$ruleConditionResult = $ruleConditionQry->result_array();

			// Fetch data from tms_queue_rule_action_$queue_id table
			$this->db->select($select);
			$this->db->where('rule_id', $rule_id);
			$this->db->from("tms_queue_rule_action_$queue_id");
			$ruleActionQry = $this->db->get();

			// Check for query execution errors
			if ($ruleActionQry === false) {
				throw new Exception("Error fetching data from tms_queue_rule_action_$queue_id table");
			}

			$ruleActionResult = $ruleActionQry->row_array();

			return array('result' => $result, 'ruleConditionResult' => $ruleConditionResult, 'ruleActionResult' => $ruleActionResult);
		} catch (Exception $e) {
			// Handle the exception here, you can log it or return an error response.
			return array(
				'error' => true,
				'message' => $e->getMessage()
			);
		}
	}

	// public function getQueueAssignRulesData($assign_rule_id, $queue_id, $primaryKey = 'assign_rule_id')
	// {
	// 	$select = array('*');
	// 	$this->db->select($select);
	// 	$this->db->where(array($primaryKey => $assign_rule_id));
	// 	$this->db->from("tms_queue_assign_rule_master_$queue_id");
	// 	$query = $this->db->get();
	// 	$result = $query->row_array();


	// 	$select = array('*');
	// 	$this->db->select($select);
	// 	$this->db->where('assign_rule_id', $assign_rule_id);
	// 	$this->db->from("tms_queue_assign_rule_condition_$queue_id");
	// 	$ruleConditionQry = $this->db->get();
	// 	$assignRuleConditionResult = $ruleConditionQry->result_array();

	// 	$select = array('*');
	// 	$this->db->select($select);
	// 	$this->db->where('assign_rule_id', $assign_rule_id);
	// 	$this->db->from("tms_queue_assign_rule_action_$queue_id");
	// 	$ruleActionQry = $this->db->get();
	// 	$assignRuleActionResult = $ruleActionQry->row_array();

	// 	return  array('result' => $result, 'assignRuleConditionResult' => $assignRuleConditionResult, 'assignRuleActionResult' => $assignRuleActionResult);
	// }
	public function getQueueAssignRulesData($assign_rule_id, $queue_id, $primaryKey = 'assign_rule_id')
	{
		try {
			$select = array('*');
			$this->db->select($select);
			$this->db->where(array($primaryKey => $assign_rule_id));
			$this->db->from("tms_queue_assign_rule_master_$queue_id");
			$query = $this->db->get();
			if ($query === false) {
				throw new Exception("Error fetching data from tms_queue_assign_rule_master_$queue_id table");
			}
			$result = $query->row_array();

			$select = array('*');
			$this->db->select($select);
			$this->db->where('assign_rule_id', $assign_rule_id);
			$this->db->from("tms_queue_assign_rule_condition_$queue_id");
			$ruleConditionQry = $this->db->get();
			if ($ruleConditionQry === false) {
				throw new Exception("Error fetching data from tms_queue_assign_rule_condition_$queue_id table");
			}
			$assignRuleConditionResult = $ruleConditionQry->result_array();

			$select = array('*');
			$this->db->select($select);
			$this->db->where('assign_rule_id', $assign_rule_id);
			$this->db->from("tms_queue_assign_rule_action_$queue_id");
			$ruleActionQry = $this->db->get();
			if ($ruleActionQry === false) {
				throw new Exception("Error fetching data from tms_queue_assign_rule_action_$queue_id table");
			}
			$assignRuleActionResult = $ruleActionQry->row_array();

			return array('result' => $result, 'assignRuleConditionResult' => $assignRuleConditionResult, 'assignRuleActionResult' => $assignRuleActionResult);
		} catch (Exception $e) {
			// Handle the exception here, e.g., log the error or return an error response.
			// You can also rethrow the exception if needed.
			// For example, you can throw a custom exception with a meaningful message.
			throw new Exception('An error occurred while fetching data: ' . $e->getMessage());
		}
	}

	public function getQueueTemplateData($template_id, $queue_id, $primaryKey = 'template_id')
	{
		try {
			$select = array('*');

			// Fetch data from tms_queue_template_$queue_id table
			$this->db->select($select);
			$this->db->where(array($primaryKey => $template_id));
			$this->db->from("tms_queue_template_$queue_id");
			$query = $this->db->get();

			// Check if the query execution failed.
			if ($query === false) {
				throw new Exception("Error fetching data from tms_queue_template_$queue_id table");
			}

			// Retrieve the result as an array.
			$result = $query->row_array();

			// Check if the result is empty.
			if (empty($result)) {
				throw new Exception("No record found for the specified template ID");
			}

			return array('result' => $result);
		} catch (Exception $e) {
			// Handle the exception here, you can log it or return an error response.
			return array(
				'error' => true,
				'message' => $e->getMessage()
			);
		}
	}

	// function getQueueCategoryData($category_id, $queue_id, $primaryKey = 'category_id')
	// {
	// 	$select = array('*');
	// 	$this->db->select($select);
	// 	$this->db->from("tms_queue_category_$queue_id t1");
	// 	$this->db->where(array("t1.$primaryKey" => $category_id));
	// 	$query = $this->db->get();
	// 	$result = $query->row_array();

	// 	$select = array('*');
	// 	$this->db->select($select);
	// 	$this->db->where($primaryKey, $category_id);
	// 	$this->db->from("tms_queue_sub_category_$queue_id");
	// 	$subCategoryQry = $this->db->get();
	// 	$subCategoryResult = $subCategoryQry->result_array();

	// 	return  array('result' => $result, 'subCategoryResult' => $subCategoryResult);
	// }
	public function getQueueCategoryData($category_id, $queue_id, $primaryKey = 'category_id')
	{
		try {
			$select = array('*');

			// Fetch data from tms_queue_category_$queue_id table
			$this->db->select($select);
			$this->db->from("tms_queue_category_$queue_id t1");
			$this->db->where(array("t1.$primaryKey" => $category_id));
			$query = $this->db->get();

			// Check if the query execution failed.
			if ($query === false) {
				throw new Exception("Error fetching data from tms_queue_category_$queue_id table");
			}

			// Retrieve the result as an array.
			$result = $query->row_array();

			// Fetch data from tms_queue_sub_category_$queue_id table
			$this->db->select($select);
			$this->db->where($primaryKey, $category_id);
			$this->db->from("tms_queue_sub_category_$queue_id");
			$subCategoryQry = $this->db->get();

			// Check if the query execution failed.
			if ($subCategoryQry === false) {
				throw new Exception("Error fetching sub-category data from tms_queue_sub_category_$queue_id table");
			}

			$subCategoryResult = $subCategoryQry->result_array();

			return array('result' => $result, 'subCategoryResult' => $subCategoryResult);
		} catch (Exception $e) {
			// Handle the exception here, you can log it or return an error response.
			return array(
				'error' => true,
				'message' => $e->getMessage()
			);
		}
	}


	function saveTicketData($masterName, $postData, $data, $pKey = 'ticket_unique_id', $replyType = '')
	{

		try {
			$this->load->library('Dynamicformcontent');
			$table = $masterName;

			if (!empty($table)) {
				$this->db->trans_begin();
				$data = is_array($data) ? $data : (array) $data;
				$queue_id = $data['queue_id'];
				// if ($replyType != "reply") {
				// 	$dynData = $this->dynamicformcontent->setDynamicFieldDataArray($queue_id, $data);
				// 	$data = array_merge($data, $dynData['data']);
				// }
				if (!empty($data['assigned_to'])) {
					$data['is_assigned'] = 1;
					$data['assigned_on'] = date('Y-m-d H:i:s');
				} else {
					$data['is_assigned'] = 0;
					unset($data['assigned_by']);
				}
				$id = $data[$pKey];
				unset($data[$pKey]);
				if ($postData['is_replied_mail'] == 1 || $postData['is_forward_mail'] == 1) {
					unset($data['subject']);
					unset($data['from_email']);
					unset($data['to_email']);
				}

				if (empty($id) || ($postData['moved_ticket'] == 1)) { // create 
					$this->db->insert($table, $data);
					$id = $this->db->insert_id();


					$ticketPrifix  = $this->ticketSeries($queue_id);

					if (!empty($ticketPrifix)) {
						$Prefix = explode('[', $ticketPrifix, 2);
						$dbData['ticket_prefix'] = $Prefix[0];
						// print_r($dbData);die;
						$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 . $id;
						if (strlen($ticketSeries) > 20) {
							$ticketPrifix = '0';
							$ticketNo = '0';
						}
						// print_r($ticketSeries);die;
						$data['ticket_id'] = $ticketSeries;
						// print_r($dbData);die;
					} else {
						return  array('error' => true, 'message' => 'Ticket Prefix is required');
					}

					if ($data['assigned_to']) {
						$dataup = $this->db->where('ticket_unique_id', $id)->update("tms_ticket_master_$queue_id", array('is_assigned' => 1, 'assigned_to' => $data['assigned_to'], 'assigned_by' => $data['ticket_created_by'], 'assigned_on' => date('Y-m-d H:i:s'), 'ticket_id' => $data['ticket_id']));

						if ($dataup == 1) {
							$insert_arr = array(
								'queue_id' => $queue_id,
								'ticket_id' => $id,
								'assigned_by' => $data['ticket_created_by'],
								'assigned_to' => $data['assigned_to'],
								'last_assigned' => 0,
							);
							$this->db->insert('user_assign_logs', $insert_arr);
						}
					} else {
						$dataup = $this->db->where('ticket_unique_id', $id)->update("tms_ticket_master_$queue_id", array('ticket_id' => $data['ticket_id']));
					}

					$type = "new ticket";
					$status = "none";
				} else {
					if ($postData['prev_priority_id'] != $postData['priority_id']) {
						$data['priority_changed_on'] = date('Y-m-d H:i:s');
					}
					if ($postData['is_replied_mail'] == 1 || $postData['is_forward_mail'] == 1) {
						unset($data['is_assigned']);
					} else {
						$query = $this->db->get_where($table, array($pKey => $id));
						$result = $query->row();
						// fx::pr($this->db->last_query(),1);

						$assigned_to = $result->assigned_to;
						if ($data['assigned_to'] != $assigned_to) {
							$dataup = $this->db->where('ticket_unique_id', $id)->update("tms_ticket_master_$queue_id", array('is_assigned' => 1, 'assigned_to' => $data['assigned_to'], 'assigned_by' => $data['last_updated_by'], 'assigned_on' => $data['last_updated_on']));
							if ($dataup == 1) {

								$insert_arr = array(
									'queue_id' => $queue_id,
									'ticket_id' => $id,
									'assigned_by' => $data['last_updated_by'],
									'assigned_to' => $data['assigned_to'],
									'last_assigned' => $assigned_to,
								);
								$this->db->insert('user_assign_logs', $insert_arr);
							}
						}
					}

					if (!empty($data['assigned_to'])) {
						unset($data['assigned_on']);
					}

					// if ($postData['prev_status_id'] == $postData['status_id'] && $postData['status_id'] == ) {}


					$this->db->where($pKey, $id)->update($table, $data);
					// fx::pr($this->db->last_query(),1)
					// fx::pr($replyType,1);
					if ($replyType == "") {
						if ($postData['prev_status_id'] == $postData['status_id']) {
							$type = "detail updated";
							$status = "None";
						} else {
							$type = "status changed ";
							$status = "New";
						}
					} else if ($replyType == "forward") {
						$type = "forward";
						$status = "New";
					} else if ($replyType == "reply_all") {
						$type = "reply_all";
						$status = "New";
					} else if ($replyType == "resend_happy_code") {
						$type = "resend happy code";
						$status = "New";
					} else {
						$type = "reply";
						$status = "New";
					}
				}
				$postData['account_id'] = $this->Master_Model->getScalerCol("outgoing_email_account", "tms_queue_email t1", "1=1 and t1.queue_id = '$postData[queue_id]'")->outgoing_email_account;


				$postData['login_id'] = isset($data['last_updated_by']) ? $data['last_updated_by'] : $data['ticket_created_by'];


				if ($type != "new ticket" && $type != "resend happy code") {
					$conversation_last_id = $this->insertConversationData(false, $status, $type, $postData, $data['ticket_id'], $id);
					$conversation_id = $this->db->insert_id();
					// print_r($conversation_last_id);die;
					$this->insertAttachmentData($postData, $data, $id, $conversation_id);
					$this->fx->createMailJsonFile($postData);
				}
				if ($type == "resend happy code") {
					$mailData = $this->Api_Model->getEmailData($postData['queue_id'], $postData['account_id'], $postData['is_auto']);
					$this->loadEmailTemplateData($replyType, $status, $type, $mailData, $id, $postData);
					$postData = [];
				}

				// fx::pr($type,1);
				if ($postData['is_replied_mail'] == 1 || $postData['is_forward_mail'] == 1) {
					if ($postData['prev_status_id'] != $postData['status_id']) {

						$autoreply_enabled = $this->Master_Model->getScalerCol("auto_reply", "tms_queue_master t1", "1=1 and t1.id = '$postData[queue_id]'")->auto_reply;
						if ($autoreply_enabled == 1) {
							$stop_outgoing_email = $this->Master_Model->getScalerCol("stop_outgoing_email", "tms_email_account t1", "1=1 and t1.email = '$postData[from_email]'")->stop_outgoing_email;
							if ($stop_outgoing_email == 0) {
								// block condition here for autoreply start here
								$blockEmailIds = $this->Master_Model->getScalerCol("block_email_for_auto_reply", "tms_queue_master t1", "1=1 and t1.id = '$postData[queue_id]'")->block_email_for_auto_reply;
								if (!empty($blockEmailIds)) {
									if (($postData['is_auto'] == 0) ? !empty($postData['to_email']) : !empty($postData['from_email'])) {
										$blockEmailIdsArr = explode(',', $blockEmailIds);
										if ($postData['is_auto'] == 0) {
											$toEmailArr = explode(',', $postData['to_email']);
										} else {
											$toEmailArr = explode(',', $postData['from_email']);
										}
										if (count($blockEmailIdsArr) > 0 && count($toEmailArr) > 0) {

											$blockedMatchingEmails = array_intersect($blockEmailIdsArr, $toEmailArr);
										}
									}
								}

								// block condition here for autoreply ends here

								//block domain condition for autoreply start here
								$blockDomains = $this->Master_Model->getScalerCol("block_domains_for_auto_reply", "tms_queue_master t1", "1=1 and t1.id = '$postData[queue_id]'")->block_domains_for_auto_reply;
								if (!empty($blockDomains)) {

									$blockDomainArr = explode(',', $blockDomains);
									if (($postData['is_auto'] == 0) ? !empty($postData['to_email']) : !empty($postData['from_email'])) {

										if ($postData['is_auto'] == 0) {
											$toEmailArr = explode(',', $postData['to_email']);
										} else {
											$toEmailArr = explode(',', $postData['from_email']);
										}
										if (count($blockDomainArr) > 0 && count($toEmailArr) > 0) {

											$blockedDoaminCount = 0;
											foreach ($toEmailArr as $email) {
												$domain = explode('@', $email)[1];
												if (in_array($domain, $blockDomainArr)) {
													$blockedDoaminCount++;
												}
											}
										}
									}
								}
								$mailData = $this->Api_Model->getEmailData($postData['queue_id'], $postData['account_id'], $postData['is_auto']);
								if ($mailData != "") {
									if ($type == "new ticket") {
										$type = "auto reply email";
										$status = "New";
									} else if ($type == "reply") {
										$type = "status changed ";
										$status = "New";
										$replyType = "reply";
									} else if ($type == "reply_all") {
										$type = "status changed ";
										$status = "New";
										$replyType = "reply_all";
									} else if ($type == "forward") {
										$type = "status changed ";
										$status = "New";
										$replyType = "forward";
									} else if ($replyType == "resend_happy_code") {
										$type = "resend happy code";
										$status = "New";
									}


									// if (count($blockedMatchingEmails) == 0 && $blockedDoaminCount == 0) {
									// 	$this->loadEmailTemplateData($replyType, $status, $type, $mailData, $id, $postData);
									// }
									if ($blockedMatchingEmails == NULL && $blockedDoaminCount == NULL) {
										$this->loadEmailTemplateData($replyType, $status, $type, $mailData, $id, $postData);
									} else if (count($blockedMatchingEmails) == 0 && $blockedDoaminCount == 0) {
										$this->loadEmailTemplateData($replyType, $status, $type, $mailData, $id, $postData);
									}
								}
							}
						}
					}
				} else {
					$autoreply_enabled = $this->Master_Model->getScalerCol("auto_reply", "tms_queue_master t1", "1=1 and t1.id = '$postData[queue_id]'")->auto_reply;
					if ($autoreply_enabled == 1) {
						$stop_outgoing_email = $this->Master_Model->getScalerCol("stop_outgoing_email", "tms_email_account t1", "1=1 and t1.email = '$postData[from_email]'")->stop_outgoing_email;
						if ($stop_outgoing_email == 0 || $postData['moved_ticket'] == 1) {
							// block condition here for autoreply start here
							$blockEmailIds = $this->Master_Model->getScalerCol("block_email_for_auto_reply", "tms_queue_master t1", "1=1 and t1.id = '$postData[queue_id]'")->block_email_for_auto_reply;

							if (!empty($blockEmailIds)) {
								$blockEmailIdsArr = explode(',', $blockEmailIds);
								if (($postData['is_auto'] == 0) ? !empty($postData['to_email']) : !empty($postData['from_email'])) {

									if ($postData['is_auto'] == 0) {
										$toEmailArr = explode(',', $postData['to_email']);
									} else {
										$toEmailArr = explode(',', $postData['from_email']);
									}
									if (count($blockEmailIdsArr) > 0 && count($toEmailArr) > 0) {
										$blockedMatchingEmails = array_intersect($blockEmailIdsArr, $toEmailArr);
									}
								}
							}
							// block condition here for autoreply ends here

							//block domain condition for autoreply start here
							$blockDomains = $this->Master_Model->getScalerCol("block_domains_for_auto_reply", "tms_queue_master t1", "1=1 and t1.id = '$postData[queue_id]'")->block_domains_for_auto_reply;

							if (!empty($blockDomains)) {
								$blockDomainArr = explode(',', $blockDomains);
								if (($postData['is_auto'] == 0) ? !empty($postData['to_email']) : !empty($postData['from_email'])) {
									if ($postData['is_auto'] == 0) {
										$toEmailArr = explode(',', $postData['to_email']);
									} else {
										$toEmailArr = explode(',', $postData['from_email']);
									}
									if (count($blockDomainArr) > 0 and count($toEmailArr) > 0) {
										$blockedDoaminCount = 0;
										foreach ($toEmailArr as $email) {
											$domain = explode('@', $email)[1];
											if (in_array($domain, $blockDomainArr)) {
												$blockedDoaminCount++;
											}
										}
									}
								}
							}
							//block domain condition for autoreply ends here

							$mailData = $this->Api_Model->getEmailData($postData['queue_id'], $postData['account_id'], $postData['is_auto']);

							if ($mailData != "") {
								if ($type == "new ticket") {
									$type = "auto reply email";
									$status = "New";
								} else if ($type == "reply") {
									$type = "status changed ";
									$status = "New";
									$replyType = "reply";
								} else if ($type == "reply_all") {
									$type = "status changed ";
									$status = "New";
									$replyType = "reply_all";
								} else if ($type == "resend happy code") {
									$replyType = "resend happy code";
									$status = "New";
								} else if ($postData['moved_ticket'] == 1 && $stop_outgoing_email == 1) {
									$type = "auto reply email";
									$status = "None";
								} else if ($postData['moved_ticket'] == 1 && $stop_outgoing_email == 0) {
									$type = "auto reply email";
									$status = "New";
								}

								// if (count($blockedMatchingEmails) == 0 && $blockedDoaminCount == 0) {
								// 	$resdata = $this->loadEmailTemplateData($replyType, $status, $type, $mailData, $id, $postData);
								// }

								if ($blockedMatchingEmails == NULL && $blockedDoaminCount == NULL) {
									$resdata = $this->loadEmailTemplateData($replyType, $status, $type, $mailData, $id, $postData);
								} else if (count($blockedMatchingEmails) == 0 && $blockedDoaminCount == 0) {
									$resdata = $this->loadEmailTemplateData($replyType, $status, $type, $mailData, $id, $postData);
								}
							}
						}
					}
				}
				//status setting work start here
				//check if there is status setting data for the queue start here
				$statusSettingEnable = $this->checkStatusSettingData($postData['queue_id'], $postData['status_id']);
				// fx::pr($statusSettingEnable,1);
				if (is_array($statusSettingEnable) && count($statusSettingEnable) > 0) {
					//check if dynamic filed presed is equal to the status setting dynamic filed and filed value start here
					// For reply and forward case start here
					if ($postData['is_replied_mail'] == 1 || $postData['is_forward_mail'] == 1) {
						foreach ($statusSettingEnable as $setting) {
							$fieldVal = $this->getFieldVal($postData['queue_id'], $postData['ticket_id'], $setting->field_name);
							if (is_array($fieldVal) && count($fieldVal) > 0) {
								if ($setting['customer_email'] == 1 && $fieldVal[$setting['field_name']] == $setting['field_value']) {
									$postData['to_email'] = $setting['to_email'];
									$resdata = $this->loadEmailTemplateData('', 'New', 'auto reply email', $mailData, $id, $postData, $setting['template_id']);
								}
							}
						}
						// For reply and forward case ends here
					} else {
						// For new ticket,update ticket start here

						//check if dynamic filed presed is equal to the status setting dynamic filed and filed value ends here
						// if ($statusSettingEnable['customer_email'] == 1 && $data == $statusSettingEnable['field_value']) {
						// 	$postData['to_email'] = $statusSettingEnable['to_email'];
						// 	$resdata = $this->loadEmailTemplateData('', 'New', 'auto reply email', $mailData, $id, $postData, $statusSettingEnable['template_id']);
						// }
						foreach ($statusSettingEnable as $setting) {
							if (array_key_exists($setting->field_name, $postData)) {
								$data =  $postData[$setting->field_name];
								if ($setting->customer_email == 1 && $data == $setting->field_value) {
									$postData['to_email'] = $setting->to_email;
									$resdata = $this->loadEmailTemplateData(
										'',
										'New',
										'auto reply email',
										$mailData,
										$id,
										$postData,
										$setting->template_id
									);
									break; // Exit the loop once a match is found
								}
							}
						}
						// For new ticket,update ticket ends here
					}
				}
				//check if there is status setting data for the queue ends here
				//status setting work ends here

				//  print_r($conversation_id);die;
				if ($this->db->trans_status() === FALSE) {
					$this->db->trans_rollback();
				} else {
					$this->db->trans_commit();
				}
				if (is_array($resdata) && count($resdata) > 0) {
					$res = array('error' => false, 'id' => $id, 'next_queue_data' => $resdata);
				} else {
					$res = array('error' => false, 'id' => $id, 'conversation_id' => $conversation_id != 0 ? $conversation_id : $conversation_last_id);
				}
			} else {
				$res = array('error' => true, 'id' => 0);
			}
		} catch (Exception $e) {
			// Handle the exception here, you can log it or take appropriate actions
			$res = array('error' => true, 'message' => $e->getMessage());
		}
		// print_r($res);die;
		return $res;
	}

	public function getFieldVal($queue_id, $ticket_id, $field)
	{
		$this->db->select($field);
		$this->db->from('tms_ticket_master_' . $queue_id);
		$this->db->where('ticket_id', $ticket_id);
		$res = $this->db->get();
		return $res->row_array();
	}

	public function checkStatusSettingData($queueId, $statusId)
	{
		$this->db->select('*');
		$this->db->from('tms_queue_status_setting');
		$this->db->where('queue_id', $queueId);
		$this->db->where('status_id', $statusId);
		$res = $this->db->get();
		return $res->result();
	}

	public function updateChildTicketStatus($masterName, $postData, $data, $status, $type)
	{
		$this->db->select('t1.ticket_unique_id');
		$this->db->from("$masterName t1");
		$this->db->where("t1.parent_id", $postData['ticket_id']);
		$resdata = $this->db->get()->result();
		$childTicketIds = array();
		foreach ($resdata as $key => $val) {
			$childTicketIds[] = $val->ticket_unique_id;
		}

		foreach ($childTicketIds as $key => $id) {
			$this->db->where('ticket_unique_id', $id)->update("$masterName", array('status_id' => $data['status_id']));

			$this->insertConversationData(false, $status, $type, $postData, $data['ticket_id'], $id);

			$conversation_id = $this->db->insert_id();

			$this->insertAttachmentData($postData, $data, $id, $conversation_id);
		}
	}

	public function insertConversationData($email_type = '', $status = NULL, $type, $postData, $ticket_id, $ticket_unq_id)
	{
		// print_r($postData);die;
		$masterName = "tms_conversation_master_" . $postData['queue_id'];
		$postDataArr = array();
		$postDataArr[] = $postData;
		$conversationData = array();
		if ($email_type == false && $type == "status changed ") {
			$status = "none";
		}

		if ($type == "new ticket" && $postData['moved_ticket'] == 1) {
			$status = "none";
		}

		if ($type == "auto reply sms" || $type == "auto reply whatsapp" || $type == 'resend happy code') {
			$status = "New";
		}

		if ($postData['is_draft'] == 1) {
			$status = "None";
		}

		foreach ($postDataArr as $key => $val) {
			$conversationData[] = array(
				'conversation_date' => date('Y-m-d H:i:s'),
				'conversation_type' => $type,
				'ticket_unique_id' => $ticket_unq_id,
				'ticket_id' => $ticket_id,
				'mobile_no' => $val['mobile_no'],
				'email_uid' => (isset($val['email_uid']) ? $val['email_uid'] : NULL),
				'account_id' => (isset($val['account_id']) ? $val['account_id'] : NULl),
				'from_email' => $val['from_email'],
				'to_email' => (isset($val['to_email']) ? $val['to_email'] : NULl),
				'cc_email' => (isset($val['cc_email']) ? $val['cc_email'] : NULl),
				'bcc_email' => (isset($val['bcc_email']) ? $val['bcc_email'] : NULl),
				'subject' => (isset($val['subject']) ? $val['subject'] : NULl),
				'category_id' => (isset($val['category_id']) ? $val['category_id'] : NULl),
				'subcategory_id' => (isset($val['subcategory_id']) ? $val['subcategory_id'] : NULl),
				'status_id' => (isset($val['status_id']) ? $val['status_id'] : NULl),
				'priority_id' => (isset($val['priority_id']) ? $val['priority_id'] : NULl),
				'queue_id' => (isset($val['queue_id']) ? $val['queue_id'] : NULl),
				'login_id' => (isset($val['login_id']) ? $val['login_id'] : NULl),
				'email_status' => ($type == "auto reply email" || $type == "new ticket" || $type == "status changed " || $type == "reply" || $type == "reply_all" || $type == "all" || $type == "auto reply user" || $type == "forward" || $type == "resend happy code") ? $status : NULL,
				'sms_status' => ($type == "auto reply sms") ? $status : NULL,
				'whatsapp_status' => ($type == "auto reply whatsapp") ? $status : NULL,
				'email_message_id' => $val['uuid'],
				'no_of_try' => NULL,
				'max_try' => 3,
				'sms_no_of_try' => NULL,
				'sms_max_try' => 3,
				'fetch_xml_uid' => NULL,
				'hold_date' => NULL,
				'is_draft' => $postData['is_draft'],
				'json_file_name' => $val['msg_id'] . ".json",
				'footer_url' => (($type == "new ticket" || $type == "reply" || $type == "reply_all" || $type = "forward") && (isset($val['footer_url']))) ? $val['footer_url'] : null,

			);
		}
		if ($type == "detail updated") {
			unset($conversationData[0]['from_email']);
			unset($conversationData[0]['cc_email']);
			unset($conversationData[0]['to_email']);
		}
		if ($email_type == false && $type == "status changed ") {
			unset($conversationData[0]['from_email']);
			unset($conversationData[0]['cc_email']);
			unset($conversationData[0]['to_email']);
		}
		// print_r($postData);die;
		if (empty($postData['conversation_id'])) {
			// print_r('here');die;
			return $this->db->insert_batch($masterName, $conversationData);
		} else {
			// print_r('There');die;
			// $conversationData['conversation_id'] = $postData;
			$this->db->where('conversation_id', $postData['conversation_id']);
			$res = $this->db->update($masterName, $conversationData[0]);
			//  print_r($res);die;
			if ($res == 1) {
				$this->db->set('is_draft', 0);
				$this->db->where('ticket_unique_id', $ticket_unq_id);
				$this->db->update('tms_ticket_master_' . $postData['queue_id']);
				// print_r($this->db->last_query());die;
				return $postData['conversation_id'];
			} else {
				return false;
			}
		}
	}

	public function insertAttachmentData($postData, $data, $ticket_id, $conversation_id)
	{
		// fx::pr($postData,1);
		$masterName = "tms_conversation_attachements_" . $data['queue_id'];
		$postDataArr = array();
		$postDataArr[] = $postData;
		$conversationAttachmentData = array();

		if (is_array($postDataArr[0]['attachmentArray']) && count($postDataArr[0]['attachmentArray']) > 0) {
			foreach ($postDataArr[0]['attachmentArray'] as $key => $val) {
				$conversationAttachmentData[] = array(
					'ticket_id' => $data['ticket_id'],
					'ticket_unique_id' => $ticket_id,
					'conversation_id' => $conversation_id,
					'attachement_name' => $val['name'],
					'content_type' => $val['type'],
					'attachement_filepath' => $postData['path'] . '/' . $val['name']
				);
			};
		}
		// fx::pr($conversationAttachmentData,1);
		if (count($conversationAttachmentData) > 0) {
			return $this->db->insert_batch($masterName, $conversationAttachmentData);
		}
	}

	public function loadEmailTemplateData($replyType = '', $status, $type, $mailData, $ticket_unq_id, $post, $tempId = "")
	{
		if ($post['is_auto'] == 1 && ($replyType == 'reply' || $replyType == 'reply_all' || $replyType == 'forward')) {
			$fromMail = $post['to_email'];
			$toMail = $post['def_to_email'];
			$post['to_email'] = $fromMail;
			$post['from_email'] = $toMail;
			$post['account_id'] = '';
		} else if ($post['is_auto'] == 1) {
			if ($post['moved_ticket'] == 1) {
				$fromMail = $post['to_email'];
				$toMail = $post['def_to_email'];
				$post['to_email'] = $fromMail;
				$post['from_email'] = $toMail;
				$post['account_id'] = '';
			} else {
				$fromMail = $post['from_email'];
				$toMail = $post['to_email'];
				$post['to_email'] = $fromMail;
				$post['from_email'] = $toMail;
				$post['account_id'] = '';
			}
		}
		if (!empty($ticket_unq_id)) {
			$ticketData = $this->Api_Model->getTicketData($ticket_unq_id, $post['queue_id']);
			if ($ticketData != "") {
				if (!empty($ticketData->assigned_to)) {
					$assignedToUserData = $this->Api_Model->getassignedToUserData($ticketData->assigned_to);
				}

				$dynamic_master_name = "tms_dynamicform_fields_" . $post['queue_id'];
				$dynamicFormData = $this->Api_Model->getDynamicFormField($dynamic_master_name);
				if ($post['footer_url'] != "") {
					$post['conversation'] .= '<br><br><br><br><img src="cid:footer" width="' . $post['footer_width'] . '">';
				}
				if ($post['next_queue_id'] != "") {
					$new_ticket_id_res = $this->getNextQueueTicketId($post['next_queue_id']);
					if (count($new_ticket_id_res) > 0) {
						$new_ticket_id = $new_ticket_id_res['ticket_id'];
					}
				}

				if (isset($post['category_id']) && $post['category_id'] != '') {
					// fx::pr($this->tableName['QUEUE_CAT'],1);
					$categoryName = $this->Master_Model->getScalerCol("category_name", "tms_queue_category_" . $post['queue_id'] . " as t1", "1=1 and t1.category_id = '$post[category_id]'")->category_name;
				}

				if (isset($post['subcategory_id']) && $post['subcategory_id'] != '') {
					$subCategoryName = $this->Master_Model->getScalerCol("sub_category_name", "tms_queue_sub_category_" . $post['queue_id'] . " as t1", "1=1 and t1.sub_category_id = '$post[subcategory_id]'")->sub_category_name;
				}

				$statusName = $this->getStatusName($post['queue_id'], $ticketData->status_id);
				$priorityName = $this->getPriorityName($post['queue_id'], $ticketData->priority_id);
				$created_date = new DateTime($ticketData->created_date);
				$current_time = new DateTime();
				$interval = $created_date->diff($current_time);
				$duration = $interval->format('%H:%I:%S');
				$dataArray = array(
					'ticket_id' => $ticketData->ticket_id,
					'new_ticket_id' => ($post['next_queue_id'] != "") ? $new_ticket_id : '',
					'ticket_unique_id' => $ticket_unq_id,
					'email_message' => $post['conversation'],
					'agent_name' => isset($assignedToUserData) ? $assignedToUserData->user_name : '',
					'agent_mobile_number' => isset($assignedToUserData) ? $assignedToUserData->mobile_no : '',
					'signature' => isset($assignedToUserData) ? $assignedToUserData->signature : '',
					'mobile_no' => (isset($post['mobile_no'])) ? $post['mobile_no'] : Null,
					'person_name' => (isset($post['person_name'])) ? $post['person_name'] : Null,
					'cc_email' => isset($post['cc_email']) ? $post['cc_email'] : '',
					'last_updated_on' => isset($ticketData->last_updated_on) ? $ticketData->last_updated_on : '',
					'subject' => ($post['is_replied_mail'] == 1 || $post['is_forward_mail'] == 1) ? (isset($post['def_subject']) ? $post['def_subject'] : '') : (isset($post['subject']) ? $post['subject'] : ''),
					'to_email' => isset($post['to_email']) ? $post['to_email'] : '',
					'from_email' => isset($post['from_email']) ? $post['from_email'] : '',
					'happy_code' => isset($ticketData->happy_code) ? $ticketData->happy_code : '',
					'remarks' => isset($post['conversation']) ? $post['conversation'] : '',
					'ticket_link' => '<a href="http://localhost:4200/ticket-search?backLink=ticket-search&queue_id=' . $post['queue_id'] . '&ticket_unique_id=' . $ticket_unq_id . '">' . $statusName->status_name . '</a>',
					'duration' => $duration,
					'category' => ($categoryName != '') ? $categoryName : '',
					'sub_category' => ($subCategoryName != '') ? $subCategoryName : '',
					'status' => ($statusName->status_name != '') ? $statusName->status_name : '',
					'priority' => ($priorityName->priority_name != '') ? $priorityName->priority_name : '',
					'assigned_on' => ($ticketData->assigned_on != '') ? $ticketData->assigned_on : '',
					'assigned_by' => ($ticketData->assigned_by != '') ? $ticketData->assigned_by : '',
					'created_date' => ($ticketData->created_date != '') ? $ticketData->created_date : '',
				);
				$dynData = array();
				if (count($dynamicFormData) > 0) {
					foreach ($dynamicFormData as $val) {
						$fieldName = $val['field_name'];
						if (isset($ticketData->$fieldName)) {
							$dynData[] = array(
								$fieldName => $ticketData->$fieldName
							);
						}
					}
				}
				$dataArray = array_merge($dataArray, ...$dynData);

				if ($tempId == "") {
					$tempData = $this->Api_Model->getTemplateData($post['status_id'], $post['queue_id']);
					if ($replyType == 'resend_happy_code') {
						$tempData = $this->Api_Model->getTemplateData($post['status_id'], $post['queue_id']);
						$tempData->customer_email = 1;
						$tempData->template_id = $post['happycode_template'];
						$templateDbarray = $this->Api_Model->getTemplateDetails($tempData->template_id, $post['queue_id']);
						if ($templateDbarray[0]->customer_sms_template != "") {
							$tempData->customer_sms = 1;
						}
					}
				}

				if ($tempData || $tempId != '') {
					if ($tempData->customer_email == 1 || $tempId != '') {
						if ($tempId != "") {
							$templateDbarray = $this->Api_Model->getTemplateDetails($tempId, $post['queue_id']);
						} else {
							$templateDbarray = $this->Api_Model->getTemplateDetails($tempData->template_id, $post['queue_id']);
						}
						$finalTemplate = $this->fx->setEailSMSTemplate("Email", $templateDbarray, $dataArray, $dynamic_master_name);
						if ($finalTemplate['emilSubject'] != "" && $finalTemplate['emilBody'] != "") {
							$autoReplyUnqMsgId = $this->fx->generateEmailUnqMsgId($post['from_email']);
							$autoReplyMsgId = $this->fx->generateMsgId($autoReplyUnqMsgId);
							$conversationInsertData = array(
								'queue_id' => $post['queue_id'],
								'mobile_no' => $post['mobile_no'],
								'email_uid' => (isset($post['email_uid']) ? $post['email_uid'] : NULL),
								'account_id' => (isset($mailData->id) ? $mailData->id : NULL),
								'from_email' => $mailData->outgoing_user_name,
								'to_email' => (isset($post['to_email']) ? $post['to_email'] : NULL),
								'cc_email' => (isset($post['cc_email']) ? $post['cc_email'] : NULL),
								'bcc_email' => (isset($post['bcc_email']) ? $post['bcc_email'] : NULL),
								'subject' => $finalTemplate['emilSubject'],
								'category_id' => (isset($post['category_id']) ? $post['category_id'] : NULL),
								'subcategory_id' => (isset($post['subcategory_id']) ? $post['subcategory_id'] : NULL),
								'status_id' => (isset($post['status_id']) ? $post['status_id'] : NULL),
								'priority_id' => (isset($post['priority_id']) ? $post['priority_id'] : NULL),
								'assigned_to' => (isset($post['assigned_to']) ? $post['assigned_to'] : NULL),
								'email_status' => $status,
								'sms_status' => null,
								'whatsapp_status' => null,
								'uuid' => $autoReplyUnqMsgId,
								'msg_id' => $autoReplyMsgId,
								'conversation' => $finalTemplate['emilBody']
							);

							if ($type != "detail updated") {
								if ($replyType != 'resend_happy_code') {
									$type = "auto reply email";
								}
								$this->insertConversationData(true, $status, $type, $conversationInsertData, $ticketData->ticket_id, $ticket_unq_id);
								// fx::pr($post['attachmentArray'],1)
								if (isset($post['attachmentArray']) && is_array($post['attachmentArray']) && !empty($post['attachmentArray'][0]['data'])) {
									$conversation_id = $this->db->insert_id();
									$data['ticket_id'] = $ticketData->ticket_id;
									$data['queue_id'] = $post['queue_id'];
									$this->insertAttachmentData($post, $data, $ticket_unq_id, $conversation_id);
								}
							}
							$this->fx->createMailJsonFile($conversationInsertData);
						}
					}
					if ($tempData->user_email == 1) {
						$templateDbarray = $this->Api_Model->getTemplateDetails($tempData->template_id, $post['queue_id']);
						$finalTemplate = $this->fx->setEailSMSTemplate("UserEmail", $templateDbarray, $dataArray, $dynamic_master_name);
						if ($finalTemplate['emilSubject'] != "" && $finalTemplate['emilBody'] != "") {
							$autoReplyUnqMsgId = $this->fx->generateEmailUnqMsgId($post['from_email']);
							$autoReplyMsgId = $this->fx->generateMsgId($autoReplyUnqMsgId);

							if ($post['assigned_to'] == 'open_to_queue') {
								$agentMailId = NULL;
							} else {
								$agentMailId = $this->getScalerCol("email", "tms_user_master", "id = $post[assigned_to]")->email;
							}
							$conversationInsertData = array(
								'queue_id' => $post['queue_id'],
								'mobile_no' => $post['mobile_no'],
								'email_uid' => (isset($post['email_uid']) ? $post['email_uid'] : NULL),
								'account_id' => (isset($mailData->id) ? $mailData->id : NULL),
								'from_email' => $mailData->outgoing_user_name,
								'to_email' => (isset($agentMailId) ? $agentMailId : NULL),
								'cc_email' => '',
								'bcc_email' => '',
								'subject' => $finalTemplate['emilSubject'],
								'category_id' => (isset($post['category_id']) ? $post['category_id'] : NULL),
								'subcategory_id' => (isset($post['subcategory_id']) ? $post['subcategory_id'] : NULL),
								'status_id' => (isset($post['status_id']) ? $post['status_id'] : NULL),
								'priority_id' => (isset($post['priority_id']) ? $post['priority_id'] : NULL),
								'assigned_to' => (isset($post['assigned_to']) ? $post['assigned_to'] : NULL),
								'email_status' => $status,
								'sms_status' => null,
								'whatsapp_status' => null,
								'uuid' => $autoReplyUnqMsgId,
								'msg_id' => $autoReplyMsgId,
								'conversation' => $finalTemplate['emilBody']
							);
							if ($type != "detail updated") {
								$type = "auto reply user";
								$this->insertConversationData(true, $status, $type, $conversationInsertData, $ticketData->ticket_id, $ticket_unq_id);
								$conversation_id = $this->db->insert_id();
							}
							$this->fx->createMailJsonFile($conversationInsertData);
						}
					}
					if ($tempData->customer_sms == 1) {
						if (isset($post['mobile_no']) && $post['mobile_no'] == "") {
							return;
						}
						$templateDbarray = $this->Api_Model->getTemplateDetails($tempData->template_id, $post['queue_id']);
						$finalTemplate = $this->fx->setEailSMSTemplate("SMS", $templateDbarray, $dataArray, $dynamic_master_name);
						if ($finalTemplate['smsBody'] != "") {
							$autoReplyUnqMsgId = $this->fx->generateEmailUnqMsgId($post['from_email']);
							$autoReplyMsgId = $this->fx->generateMsgId($autoReplyUnqMsgId);
							if ($post['assigned_to'] == 'open_to_queue') {
								$agentMailId = NULL;
							} else {
								$agentMailId = $this->getScalerCol("email", "tms_user_master", "id = $post[assigned_to]")->email;
							}

							$conversationInsertData = array(
								'queue_id' => $post['queue_id'],
								'mobile_no' => $post['mobile_no'],
								'email_uid' => (isset($post['email_uid']) ? $post['email_uid'] : NULL),
								'subject' => $finalTemplate['emilSubject'],
								'category_id' => (isset($post['category_id']) ? $post['category_id'] : NULL),
								'subcategory_id' => (isset($post['subcategory_id']) ? $post['subcategory_id'] : NULL),
								'status_id' => (isset($post['status_id']) ? $post['status_id'] : NULL),
								'priority_id' => (isset($post['priority_id']) ? $post['priority_id'] : NULL),
								'assigned_to' => (isset($post['assigned_to']) ? $post['assigned_to'] : NULL),
								'email_status' => Null,
								'sms_status' => $status,
								'whatsapp_status' => null,
								'uuid' => $autoReplyUnqMsgId,
								'msg_id' => $autoReplyMsgId,
								'conversation' => $finalTemplate['smsBody']
							);
							if ($type != "detail updated") {
								$type = "auto reply sms";
								$this->insertConversationData(true, $status, $type, $conversationInsertData, $ticketData->ticket_id, $ticket_unq_id);
								$conversation_id = $this->db->insert_id();
							}
							$this->fx->createMailJsonFile($conversationInsertData);
						}
					}
					if ($tempData->customer_wp == 1) {
						if (isset($post['mobile_no']) && $post['mobile_no'] == "") {
							return;
						}
						$templateDbarray = $this->Api_Model->getTemplateDetails($tempData->template_id, $post['queue_id']);
						$finalTemplate = $this->fx->setEailSMSTemplate("Whatsapp", $templateDbarray, $dataArray, $dynamic_master_name);
						$autoReplyUnqMsgId = $this->fx->generateEmailUnqMsgId($post['from_email']);
						$autoReplyMsgId = $this->fx->generateMsgId($autoReplyUnqMsgId);
						if ($post['assigned_to'] == 'open_to_queue') {
							$agentMailId = NULL;
						} else {
							$agentMailId = $this->getScalerCol("email", "tms_user_master", "id = $post[assigned_to]")->email;
						}

						if ($finalTemplate['whatsappBody'] != "") {
							$conversationInsertData = array(
								'queue_id' => $post['queue_id'],
								'mobile_no' => $post['mobile_no'],
								'email_uid' => (isset($post['email_uid']) ? $post['email_uid'] : NULL),
								'subject' => $finalTemplate['emilSubject'],
								'category_id' => (isset($post['category_id']) ? $post['category_id'] : NULL),
								'subcategory_id' => (isset($post['subcategory_id']) ? $post['subcategory_id'] : NULL),
								'status_id' => (isset($post['status_id']) ? $post['status_id'] : NULL),
								'priority_id' => (isset($post['priority_id']) ? $post['priority_id'] : NULL),
								'assigned_to' => (isset($post['assigned_to']) ? $post['assigned_to'] : NULL),
								'email_status' => null,
								'sms_status' => null,
								'whatsapp_status' => $status,
								'uuid' => $autoReplyUnqMsgId,
								'msg_id' => $autoReplyMsgId,
								'conversation' => $finalTemplate['whatsappBody']
							);
							if ($type != "detail updated") {
								$type = "auto reply whatsapp";
								$this->insertConversationData(true, $status, $type, $conversationInsertData, $ticketData->ticket_id, $ticket_unq_id);
								$conversation_id = $this->db->insert_id();
							}
							$this->fx->createMailJsonFile($conversationInsertData);
						}
					}
					if ($post['next_queue_id'] != "") {
						return $new_ticket_id_res;
					}
				} else {
					$msgStr = " No Template assigned";
					return $msgStr;
				}
			}
		}
	}

	public function getStatusName($queueId, $statusId)
	{
		$MasterName = 'tms_queue_status_' . $queueId;
		$this->db->select('status_name');
		$this->db->from($MasterName);
		$this->db->where('status_id', $statusId);
		return $this->db->get()->row();
	}

	public function getPriorityName($queueId, $priorityId)
	{
		$MasterName = 'tms_queue_priority_' . $queueId;
		$this->db->select('priority_name');
		$this->db->from($MasterName);
		$this->db->where('priority_id', $priorityId);
		// $this->db->where('queue_id', $queueId);
		return $this->db->get()->row();
	}

	// public function getScalerCol($column, $table, $where, $masterDb = NULL)
	// {
	// 	// print_r($where);
	// 	$this->db->select($column);
	// 	if ($masterDb == 1) {
	// 		$this->db->from($table);
	// 	} else {
	// 		$this->db->from($table);
	// 	}
	// 	$this->db->where($where, NULL, false);
	// 	// $this->db->get();
	// 	// print_r($this->db->last_query());
	// 	return $this->db->get()->row();
	// }

	public function getScalerCol($column, $table, $where, $masterDb = NULL)
	{
		$this->db->select($column);
		if ($masterDb == 1) {
			$this->db->from($table);
		} else {
			$this->db->from($table);
		}
		$this->db->where($where, NULL, false);
		// $this->db->get();
		// print_r($this->db->last_query());
		return $this->db->get()->row();
	}

	public function ticketSeries($queue_id)
	{
		$this->db->select('ticket_prefix');
		$this->db->from('tms_queue_master');
		$this->db->where('id', $queue_id);
		return $this->db->get()->row()->ticket_prefix;
	}

	// public function ticketMoveToJunk($data)
	// {
	// 	if (is_array($data['ticket_unique_id'])) {
	// 		$this->db->where_in('ticket_unique_id', $data['ticket_unique_id']);
	// 	} else {
	// 		$this->db->where(array('ticket_unique_id' => $data['ticket_unique_id']));
	// 	}
	// 	if (isset($data['delete']) && $data['delete'] == 1) {
	// 		$this->db->update($data['master_name'], array('is_junk' => 0, 'is_deleted_ticket' => '0'));
	// 	} else {
	// 		if ($data['junk'] == 1) {
	// 			$this->db->update($data['master_name'], array('is_junk' => 0));
	// 		} else {
	// 			$this->db->update($data['master_name'], array('is_junk' => 1));
	// 		}
	// 	}

	// 	// fx::pr($this->db->last_query(),1);
	// 	return $this->db->affected_rows();
	// }

	public function ticketUnread($data)
	{
		// Set 'is_new' to 1 for the specified records
		$this->db->set('is_new', 1);

		// Set the condition for updating the records
		$this->db->where_in('ticket_unique_id', $data['ticket_unique_id']);

		// Perform the update
		$this->db->update($data['master_name']);

		// Check if the update was successful
		return $this->db->affected_rows() > 0;
	}

	public function ticketMoveToJunk($data)
	{

		try {
			if (is_array($data['ticket_unique_id'])) {
				$this->db->where_in('ticket_unique_id', $data['ticket_unique_id']);
			} else {
				$this->db->where(array('ticket_unique_id' => $data['ticket_unique_id']));
			}

			if (isset($data['delete']) && $data['delete'] == 1) {
				$this->db->update($data['master_name'], array('is_junk' => 0, 'is_deleted_ticket' => '0'));
			} else {
				if ($data['junk'] == 1) {
					$this->db->update($data['master_name'], array('is_junk' => 0));
				} else {
					$this->db->update($data['master_name'], array('is_junk' => 1));
				}
			}

			// Check if the update operation was successful.
			if ($this->db->affected_rows() === false) {
				throw new Exception("Error updating records");
			}

			return $this->db->affected_rows();
		} catch (Exception $e) {
			// Handle the exception here, you can log it or return an error response.
			return array(
				'error' => true,
				'message' => $e->getMessage()
			);
		}
	}

	public function bulk_escalation_timing($id)
	{
		$this->db->select('bulk_escalation_timing'); // Replace 'your_field_name' with the actual field name
		$this->db->where('id', $id);
		$query = $this->db->get("tms_queue_master"); // Replace 'your_table_name' with the actual table name
		if ($query->num_rows() > 0) {
			$row = $query->row();

			return $row->bulk_escalation_timing; // Replace 'your_field_name' with the actual field name
		} else {
			return false; // Or handle no result found case according to your application's logic
		}
	}

	// function copyQueue($data, $masterName)
	// {
	// 	$table = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
	// 	if (!empty($table)) {
	// 		$this->db->select('*');
	// 		$this->db->from("$table t1");
	// 		$this->db->where('t1.id', $data['queue_id']);
	// 		$prevousQueueData = $this->db->get()->row();

	// 		unset($prevousQueueData->id);
	// 		$prevousQueueData->queue = $data['queue'];
	// 		$this->db->trans_start();
	// 		$this->db->insert($table, $prevousQueueData);
	// 		$id = $this->db->insert_id();
	// 		$sql = file_get_contents(FCPATH . "/assets/queue_db_script/queue_db_script.sql");
	// 		$sqls = explode(';', $sql);
	// 		array_pop($sqls);

	// 		if ($data['incoming_email_account'] > 0 && $data['outgoing_email_account'] > 0) {

	// 			$this->db->select('*');
	// 			$this->db->from('tms_queue_email');
	// 			$this->db->where('incoming_email_account', (int)$data['incoming_email_account']);
	// 			$res = $this->db->get()->row();
	// 			if (isset($res->incoming_email_account)) {
	// 				return $res;
	// 			}
	// 		}

	// 		foreach ($sqls as $statement) {
	// 			$query = str_replace('##QID##', $id, $statement);
	// 			$query = str_replace('##QID##', $id, $query) . ";";
	// 			$this->db->query($query);
	// 		}
	// 		$this->db->close();
	// 		$this->load->database();
	// 		$emailarray = array(
	// 			'incoming_email_account' => $data['incoming_email_account'],
	// 			'outgoing_email_account' => $data['outgoing_email_account'],
	// 			'queue_id' =>  $id,
	// 		);
	// 		$this->db->insert('tms_queue_email', $emailarray);

	// 		$query = $this->db->query("CALL copyQueue($data[queue_id],$id)")->row();
	// 		if (isset($query->Error_Message)) {
	// 			$res = array('error' => true, 'id' => 0, 'msg' => $query['Error_Message']);
	// 			return $res;
	// 		}

	// 		if ($this->db->trans_status() === false) {
	// 			$this->db->trans_rollback();
	// 			$res = array('error' => true, 'id' => 0);
	// 		} else {
	// 			$this->db->trans_commit();
	// 			$res = array('error' => false, 'id' => $id);
	// 		}
	// 		$res = array('error' => false, 'id' => $id);
	// 	} else {
	// 		$res = array('error' => true, 'id' => 0);
	// 	}

	// 	return $res;
	// }

	public function copyQueue($data, $masterName)
	{
		try {
			$table = array_key_exists($masterName, $this->tableName) ? $this->tableName[$masterName] : '';
			if (empty($table)) {
				throw new Exception("Invalid master name");
			}

			$this->db->select('*');
			$this->db->from("$table t1");
			$this->db->where('t1.id', $data['queue_id']);
			$prevousQueueData = $this->db->get()->row();

			if (!$prevousQueueData) {
				throw new Exception("Previous queue data not found");
			}

			unset($prevousQueueData->id);
			$prevousQueueData->queue = $data['queue'];
			$this->db->trans_start();
			$this->db->insert($table, $prevousQueueData);
			$id = $this->db->insert_id();

			if (!$id) {
				throw new Exception("Error inserting new queue data");
			}

			$sql = file_get_contents(FCPATH . "/assets/queue_db_script/queue_db_script.sql");
			$sqls = explode(';', $sql);
			array_pop($sqls);

			if ($data['incoming_email_account'] > 0 && $data['outgoing_email_account'] > 0) {
				$this->db->select('*');
				$this->db->from('tms_queue_email');
				$this->db->where('incoming_email_account', (int) $data['incoming_email_account']);
				$res = $this->db->get()->row();

				if ($res && isset($res->incoming_email_account)) {
					throw new Exception("Email account already exists");
				}
			}

			foreach ($sqls as $statement) {
				$query = str_replace('##QID##', $id, $statement);
				$query = str_replace('##QID##', $id, $query) . ";";
				$this->db->query($query);
			}

			$this->db->close();
			$this->load->database();
			$emailarray = array(
				'incoming_email_account' => $data['incoming_email_account'],
				'outgoing_email_account' => $data['outgoing_email_account'],
				'queue_id' => $id,
			);
			$this->db->insert('tms_queue_email', $emailarray);

			$query = $this->db->query("CALL copyQueue($data[queue_id],$id)")->row();
			if ($query && isset($query->Error_Message)) {
				throw new Exception("Error during stored procedure execution: " . $query->Error_Message);
			}

			if ($this->db->trans_status() === false) {
				$this->db->trans_rollback();
				throw new Exception("Transaction rollback");
			} else {
				$this->db->trans_commit();
			}

			$res = array('error' => false, 'id' => $id);
		} catch (Exception $e) {
			// Handle the exception here, you can log it or return an error response.
			$res = array('error' => true, 'id' => 0, 'message' => $e->getMessage());
		}

		return $res;
	}

	public function getPreviousNextMasterId($table_name, $key, $id)
	{
		$prevId = $nextId = NULL;
		if ($id > 0) {
			$resultPrev = $this->db->select("MAX($key) as id")
				->where("$key<$id", NULL, false)
				->where("is_junk", 0)
				->where("is_deleted_ticket", 0)
				->get($table_name);

			if ($resultPrev !== FALSE && $resultPrev->num_rows() > 0) {
				$prevId = $resultPrev->row()->id;
			} else {
				$prevId = 0;
			}

			$resultNext = $this->db->select("min($key) as id")
				->where("$key>$id", NULL, FALSE)
				->where("is_junk", 0)
				->where("is_deleted_ticket", 0)
				->get($table_name);

			if ($resultNext !== FALSE && $resultNext->num_rows() > 0) {
				$nextId = $resultNext->row()->id;
			} else {
				$nextId = 0;
			}
		}
		$firstId = $this->db->select("min($key) as id")->where("is_junk", 0)
			->where("is_deleted_ticket", 0)->get($table_name)->row()->id;
		$lastId = $this->db->select("max($key) as id")->where("is_junk", 0)
			->where("is_deleted_ticket", 0)->get($table_name)->row()->id;

		return array('prevId' => ($prevId != NULL) ? $prevId : 0, 'nextId' => ($nextId != NULL) ? $nextId : 0, 'firstId' => ($firstId != NULL) ? $firstId : 0, 'lastId' => ($lastId != NULL) ? $lastId : 0);
	}

	function getNextQueueTicketId($queueId)
	{
		$ticketPrifix = $this->ticketSeries($queueId);
		$ticketNo = $this->getScalerCol("ifnull(max(cast(ticket_unique_id as signed)),0)+1 ticketNo", "tms_ticket_master_" . $queueId, "1=1")->ticketNo;
		if (!empty($ticketPrifix)) {
			$Prefix = explode('[', $ticketPrifix, 2);
			$res['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';
			}
			$res['ticket_id'] = $ticketSeries;
		}
		return $res;
	}

	function getConversationData($ticketUnqId, $queueId)
	{
		$masterName = "tms_conversation_master_" . $queueId;
		$this->db->select('conversation_id,json_file_name,conversation_date');
		$this->db->where('ticket_unique_id', $ticketUnqId);
		$this->db->from($masterName);
		$this->db->order_by('conversation_id', 'desc');
		return $this->db->get()->result();
	}

	function insertMovedQueueLog($data)
	{
		return $this->db->insert('move_to_another_queue_log', $data);
	}


	// function getTicketDetailFromNo($mobile_no, $queueId,$type='all')
	// {
	// 	$masterName = "tms_ticket_master_" . $queueId;
	// 	$statusMasterName = "tms_queue_status_" . $queueId;

	// 	$this->db->select("t1.ticket_id,t2.user_name,t3.status_name,t1.mobile_no,t1.phone_no,t1.subject,ifnull(t4.user_name,'Auto') as assigned_by");
	// 	$this->db->from("$masterName as t1");
	// 	$this->db->join("tms_user_master t2", "t1.assigned_to = t2.id", "left");
	// 	$this->db->join("$statusMasterName as t3", "t3.status_id = t1.status_id ", "left");
	// 	$this->db->join("tms_user_master t4", "t1.assigned_by = t2.id", "left");
	// 	$this->db->where("t1.mobile_no", $mobile_no);
	// 	if($type == 'pending'){
	// 		$this->db->where("t3.ticket_status_type !=", 1);
	// 	}
	// 	$this->db->where("t1.is_junk", "0");
	// 	$this->db->where("t1.is_deleted_ticket", "0");
	// 	$tempdb = clone $this->db;
	// 	$count = $tempdb->count_all_results();
	// 	$data = $this->db->get();
	// 	return (object) array('count' => $count, 'data' => $data->result());
	// }


	function getTicketDetail($queueId, $con = '1=1', $type = 'all')
	{
		$masterName = "tms_ticket_master_" . $queueId;
		$statusMasterName = "tms_queue_status_" . $queueId;

		$this->db->select("t1.ticket_unique_id,t1.ticket_id,t2.user_name,t3.status_name,t1.mobile_no,t1.phone_no,t1.subject,ifnull(t4.user_name,'Auto') as assigned_by");
		$this->db->from("$masterName as t1");
		$this->db->join("tms_user_master t2", "t1.assigned_to = t2.id", "left");
		$this->db->join("$statusMasterName as t3", "t3.status_id = t1.status_id ", "left");
		$this->db->join("tms_user_master t4", "t1.assigned_by = t2.id", "left");
		$this->db->where($con);
		if ($type == 'pending') {
			$this->db->where("t3.ticket_status_type !=", 1);
		}
		$this->db->where("t1.is_junk", "0");
		$this->db->where("t1.is_deleted_ticket", "0");
		$tempdb = clone $this->db;
		$count = $tempdb->count_all_results();
		$data = $this->db->get();
		// fx::pr($this->db->last_query(),1);
		return (object) array('count' => $count, 'data' => $data->result());
	}




	// function getTicketDetailFromTicketId($ticketId, $queueId,$type = 'all')
	// {
	// 	$masterName = "tms_ticket_master_" . $queueId;
	// 	$statusMasterName = "tms_queue_status_" . $queueId;

	// 	$this->db->select("t1.ticket_id,t2.user_name,t3.status_name,t1.mobile_no,t1.subject,ifnull(t4.user_name,'Auto') as assigned_by");
	// 	$this->db->from("$masterName as t1");
	// 	$this->db->join("tms_user_master t2", "t1.assigned_to = t2.id", "left");
	// 	$this->db->join("tms_user_master t4", "t1.assigned_by = t2.id", "left");
	// 	$this->db->join("$statusMasterName as t3", "t3.status_id = t1.status_id ", "left");
	// 	$this->db->where("(t1.ticket_unique_id = '$ticketId' OR t1.ticket_id = '$ticketId')");
	// 	if($type == 'pending'){
	// 		$this->db->where("t3.ticket_status_type !=", 1);

	// 	}
	// 	$this->db->where("t1.is_junk", "0");
	// 	$this->db->where("t1.is_deleted_ticket", "0");
	// 	$tempdb = clone $this->db;
	// 	$count = $tempdb->count_all_results();
	// 	$data = $this->db->get();
	// 	return (object) array('count' => $count, 'data' => $data->result());
	// }


	function checkEmailId($emailId)
	{
		$this->db->select('*');
		$this->db->from('tms_user_master');
		$this->db->where('email', $emailId);
		$query = $this->db->get();
		return ($query->num_rows() > 0) ? true : false;
	}

	function checkfieldOTp($otp, $emailId)
	{
		$this->db->select('*');
		$this->db->from('tms_user_master');
		$this->db->where('email', $emailId);
		$this->db->where('otp', $otp);
		$query = $this->db->get();
		return ($query->num_rows() > 0) ? true : false;
	}

	function updateOTPinUserTbl($otp, $emailId)
	{
		$this->db->set('otp', $otp)->where('email =', $emailId)->update('tms_user_master');
		if ($this->db->affected_rows() === false) {
			throw new Exception("Error updating records");
		} else {
			return $this->db->affected_rows();
		}
	}

	public function masterBreakRules()
	{
		$rules[] = array('field' => 'title', 'label' => 'Title', 'rules' => 'required|min_length[2]|max_length[50]');
		$rules[] = array(
			'field' => 'title',
			'label' => '',
			'rules' => array('required', array('msg', array($this, 'uniqueTitleValidate'))),
			'errors' => array('msg' => 'Already exists')
		);
		$rules[] = array('field' => 'break_time', 'label' => 'Break Time', 'rules' => 'required');
		$rules[] = array('field' => 'status', 'label' => 'Status', 'rules' => 'required');


		return $rules;
	}

	public function checkCategoryMandetory($queue_id)
	{
		$this->db->select("*");
		$this->db->from("tms_queue_category_" . $queue_id);
		$this->db->where("default", "1");
		return $this->db->get()->row();
	}

	function getTokenAndRefreshToken($id, $tableName)
	{
		$this->db->select('incoming_user_name,token,refresh_token,client_oauth2_id,client_secret,tenant_id');
		$this->db->from($tableName);
		$this->db->where('id', $id);
		return $this->db->get()->row_array();
	}

	function saveTokenForEmail($token, $refreshToken, $id, $is_incoming = true)
	{

		if ($is_incoming) {
			$arr = array(
				'token' => $token,
				'refresh_token' => $refreshToken,
			);
		} else {
			$arr = array(
				'outgoing_token' => $token,
				'outgoing_refresh_token' => $refreshToken,
			);
		}
		$this->db->where('id', $id);
		$this->db->update('tms_email_account', $arr);
		if ($this->db->affected_rows() === false) {
			throw new Exception("Error updating records");
		} else {
			return $this->db->affected_rows();
		}
	}


	function saveTestCongifOfMail($email_id, $client_id, $agent_id, $formType, $type, $message, $email, $is_valid)
	{
		$data = array(
			'is_valid' => ($is_valid == true) ? 1 : 0,
			'message' =>  $message,
			'check_by' => $agent_id,
			'email_account_id' => $email_id,
			'email_id' => $email,
			'form_type' => $formType,
			'type' => $type
		);
		$mailTestTable = 'tms_mail_test';

		$this->db->where('email_account_id', $email_id);
		$this->db->where('type', $type);
		$this->db->delete("$mailTestTable");

		$this->db->insert($mailTestTable, $data);
	}

	// Custom Report START............

	public function getTableColumns($table_name)
	{
		$query = $this->db->query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" . $table_name . "' AND TABLE_SCHEMA = 'tms'");
		return $query->result_array();
	}
	function getMasterCustomreportData($id, $masterName, $primaryKey = 'id', $user_type, $full_control, $queueIds = 0)
	{
		try {
			$this->db->where(array('t1.' . $primaryKey => $id));
			$this->db->from("$masterName t1");
			$customReportData = $this->db->get();

			if ($this->db->error()['code'] == 1451) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			if ($customReportData === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			$result = $customReportData->row_array();
			$report_id  =  $result['id'];

			if (empty($report_id)) {
				throw new Exception("Report not found");
			}


			$this->db->where("t1.report_id", $report_id);
			$this->db->from("custom_query_tables t1");
			$this->db->order_by("t1.id asc");
			$tables = $this->db->get();

			if ($this->db->error()['code'] == 1451) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			if ($tables === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}
			$tables = $tables->result_array();


			$this->db->where("t1.report_id", $report_id);
			$this->db->from("custom_query_report_columns t1");
			$this->db->order_by("t1.id asc");
			$columnsArray = $this->db->get();

			if ($this->db->error()['code'] == 1451) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			if ($columnsArray === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}
			$columnsArray = $columnsArray->result_array();



			$this->db->where("t1.report_id", $report_id);
			$this->db->from("custom_query_search_fields t1");
			$this->db->order_by("t1.id asc");
			$searchFieldsArray = $this->db->get();

			if ($this->db->error()['code'] == 1451) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}

			if ($searchFieldsArray === false) {
				throw new Exception("MySQL Error: " . $this->db->error()['message']);
			}
			$searchFieldsArray = $searchFieldsArray->result_array();
			foreach ($searchFieldsArray as &$field) {
				if ($field['drowdown_other_db'] == "1" && !empty($field['select_box_value'])) {
					// Execute the query from 'select_box_value' to fetch dropdown options
					$dropdownQuery = $field['select_box_value'];

					if (strpos($dropdownQuery, '@adduserwisequeue') !== false && !empty($queueIds)) {
						$dropdownQuery = str_replace('@adduserwisequeue', "WHERE id in (" . $queueIds . " )", $dropdownQuery);
					} else {
						$dropdownQuery = str_replace('@adduserwisequeue', '', $dropdownQuery);
					}

					$dropdownResult = $this->db->query($dropdownQuery)->result_array();
					if (!empty($dropdownResult)) {
						$firstRow = reset($dropdownResult); // Get the first row
						$keys = array_keys($firstRow); // Get column names dynamically

						if (count($keys) >= 2) {
							$valueKey = $keys[0]; // First column as value
							$textKey = $keys[1];  // Second column as text

							$dropdownOptions = [];
							foreach ($dropdownResult as $row) {
								$dropdownOptions[$row[$valueKey]] = $row[$textKey]; // Assign value-text pair
							}
							// Convert to JSON or another forma
							$field['dropdown_options'] = $dropdownOptions;
						} else {
							$field['dropdown_options'] = []; // Handle cases with insufficient columns
						}

						// // Identify the correct key dynamically
						// if (!empty($dropdownResult)) {
						// 	$firstRow = reset($dropdownResult); // Get the first row
						// 	$keyName = array_key_first($firstRow); // Get the first key dynamically

						// 	// Extract values based on the identified key
						// 	$optionsArray = array_column($dropdownResult, $keyName);
						// 	$field['dropdown_options'] = implode(',', $optionsArray);
						// } else {
						// 	$field['dropdown_options'] = ''; // Handle empty results
					}
				} else {
					$field['dropdown_options'] = $field['select_box_value'];
				}
			}
			// fx::pr(	$searchFieldsArray ,1);


			$colounmsdd = $this->getTables($report_id);
			$colounms = [];
			foreach ($colounmsdd  as $table) {
				$table_name = $table['table_name']; // Extract table name

				if (!empty($table_name)) {
					// Fetch columns for the current table
					$columns = $this->getTableColumns($table_name);

					foreach ($columns as $col) {
						$colounms[] = ['id' => $table_name . '.' . $col['COLUMN_NAME'], 'text' => $table_name . '.' . $col['COLUMN_NAME']];
					}
				}
			}


			return array(
				'result' => $result,
				'columnsArray' => $columnsArray,
				'searchFieldsArray' => $searchFieldsArray,
				'tables' => $tables,
				'colounms' => $colounms
			);
		} catch (Exception $e) {
			// Handle exceptions here, e.g., log the error or return an error message
			return array('error' => $e->getMessage());
		}
	}

	public function getTables($report_id)
	{
		$query = $this->db->query("
			SELECT DISTINCT left_table_name AS table_name FROM custom_query_tables WHERE report_id = ?
			UNION
			SELECT DISTINCT right_table_name AS table_name FROM custom_query_tables WHERE report_id = ?
		", [$report_id, $report_id]); // Pass report_id twice for both conditions

		return $query->result_array();
	}
	// Custom Report END............
}
