<?php
defined('BASEPATH') or exit('No direct script access allowed');


class CrmApi extends CI_Controller
{
	private $tableArr = array(
		"user_type" => "tms_user_type",
		"action" => "tms_action_master",
		"shift" => "tms_shift_master",
		"usertype" => "user_type",
		"user" => "tms_user_master",
		"type_rights" => "tms_user_type_rights",
		"company" => "tms_company_master",
		"priority" => "tms_priority_master",
		"emailAccount" => "tms_email_account",
		"pagination" => "tms_pagination_master",
		"manager" => "manager",
		"category" => "tms_category_master",
		"sub-category" => "tms_subcategory_master",
		"status" => "tms_status_master",
		"rule" => "tms_rule_master",
		"queue" => "tms_queue_master",
		"template" => "tms_template_master",
		"escalation-matrix" => "tms_escalationmatrix_master",
		"user_log" => "tms_log_master",
		'tms_log' => "tms_log",
		"login_log" => "tms_login_log",
		"ticket" => "tms_new_ticket",
		"field-group" => "tms_field_group",
		"ticket_status_type" => "ticket_status_type",
		"conversation-type" => "tms_conversation_type_master",
		"emailAccountForIncomming" => "tms_email_account_incomming",
	);
	public $url = 'https://iffcokisancollection.chatbot.team/v1/waMedia/getMedia';

	public $encdnckey = 'Sansoftwares';
	public $access_token = '';

	function __construct()
	{
		parent::__construct();
		// error_reporting(0);
		// $this->fx->validateCORS();
		$this->fx->validateCORS();
		if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
			// Send an empty response body
			exit();
		}
		error_reporting(0);
		$this->load->model('Api_Model');
		$this->load->model('Dropdown_Option_Model');
		$this->load->model('Dynamicform_Model');
		$this->load->model('Formcontent_Model');
		$this->load->model('Externalapi_Model');
		$this->load->model('Master_Model');
		$this->load->model('CrmApi_Model');
		$this->load->library('Dbquery');
		$this->user_id = '';
		$this->user_email = '';
		$this->user_mobile = '';
		$this->user_type = '';
		$this->full_control = '';
		$this->queue_perm_id = '';
		$this->maskEmail = '';
		$this->maskPhone = '';
	}


	function api()
	{
		$post = json_decode(file_get_contents("php://input"));
		if (!empty(empty($post->method))) {
			call_user_func_array(array($this->api_model, $post->method), array($post));
		}
	}

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

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

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

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

	public function NewTicket()
	{
		$post = json_decode(file_get_contents('php://input'));
		$headers = getallheaders();
		if ($headers['token'] != '*1Sansoftwares#') {
			$this->api_response(['success' => false, 'message' => 'Invalid Token']);
		}

		if ($post->ticketData->queue == '') {
			$this->api_response(['success' => false, 'message' => 'Queue Can Not Be Blank',]);
		}
		$queue_id = $this->CrmApi_Model->getqueue_id($post->ticketData->queue);
		if (empty($queue_id)) {
			$this->api_response(['success' => false, 'message' => $post->ticketData->queue . '  Queue is Invalid',]);
		}
		$post->ticketData->queue_id = $queue_id[0]->id;
		$dyData = $post->dynamicData;

		$priority = $this->CrmApi_Model->getPriority($queue_id[0]->id);
		$getQueueEmail = $this->CrmApi_Model->getQueueEmail($queue_id[0]->id);
		$getStatus = $this->CrmApi_Model->getStatus($queue_id[0]->id);
		$post->ticketData->from_email = $getQueueEmail[0]['email'];
		$post->ticketData->priority_id = $priority[0]->priority_id;
		$post->ticketData->status_id = $getStatus[0]->status_id;
		$post->ticketData->master_name = 'tms_ticket_master_' . $queue_id[0]->id;
		$post = json_decode(json_encode($post->ticketData), true);

		if ($dyData != '') {

			foreach ($dyData as $key => $val) {
				$post['df_' . $key] = $val;
			}
		}
		// create email_msg_id start here
		$post['uuid'] = $this->fx->generateEmailUnqMsgId($post['from_email']);
		// create email_msg_id ends here

		if (!empty($post['master_name'])) {
			$primaryKey = 'ticket_unique_id';
			$masterName = $post['master_name'];
			$this->load->model('Master_Model');
			$rules = $this->Master_Model->getTicketTableRules();
			if (empty($rules)) {
				$this->response(FALSE, 'Validations not defined.', 400);
				return;
			}
			$this->load->library('Dynamicformcontent');

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

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

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

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

					$attachmentSize = 0;
					foreach ($post['attachmentArray'] as $attachment) {
						$attachmentSize += $attachment['size'];
					}
					if ($attachmentSize > 15 * 1024 * 1024) {
						$this->response(FALSE, 'error', 400, "Total size of attachments cannot be greater than 15MB");
						return false;
					} else {
						foreach ($post['attachmentArray'] as $attachment) {
							$this->upload->do_upload($attachment['data']);
							$image_parts = explode(";base64,", $attachment['data']);
							$image_base64 = base64_decode($image_parts[1]);
							$file = $path . '/' . $attachment['name'];
							if (file_put_contents($file, $image_base64)) {
							} else {
								$this->response(FALSE, 'error', 400, "File Not Uploded");
								return false;
							}
						}
					}
				}
				// save attachment in folder with the name email_msg_id ends here

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

				$dbFields = $this->Master_Model->getTicketTableFields($masterName);
				$db_keys = array_keys($dbData);
				foreach ($db_keys as $keyName) {

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

				$is_happycode = $this->Master_Model->getScalerCol("is_happycode", "tms_queue_master", "1=1 and id = $dbData[queue_id]")->is_happycode;
				if ($is_happycode == 1) {
					$dbData['happy_code'] = rand(1000, 9999);
				}
				$dbData['assigned_by'] = $this->user_id;
				if (empty($dbData[$primaryKey])) {
					$dbData['ticket_created_by'] = $this->user_id;
					$dbData['created_date'] = date('Y-m-d H:i:s');
				} else {
					if (empty($dbData['ticket_created_by'])) {
						$dbData['ticket_created_by'] = $this->user_id;
						$dbData['created_date'] = date('Y-m-d H:i:s');
					}
					$dbData['last_updated_by'] = $this->user_id;
					$dbData['last_updated_on'] = date('Y-m-d H:i:s');
				}
				$dbData['is_new'] = 1;
				$retarr = $this->Master_Model->saveTicketData($masterName, $post, $dbData, $primaryKey);
				if (empty($retarr['id'])) {
					$respMsg = 'Something goes wrong.';
				} else {
					$master_title = str_replace('_', ' ', $masterName);
					$master_title = ucwords(strtolower($master_title));
					$respMsg = !empty($post[$primaryKey]) ? 'Ticket details updated successfully :' . $ticketSeries :  'Ticket details saved successfully :' . $ticketSeries;
				}
				if ($this->db->trans_status() === FALSE) {
					$this->db->trans_rollback();
					$this->response(FALSE, 'Something goes wrong', 400);
				} else {
					$this->db->trans_commit();
					$this->response(TRUE, $respMsg, 200, $ticketSeries);
				}
			}
		} else {
			$this->response(FALSE, 'Invalid Master Name', 400);
		}
	}

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

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

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

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


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

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

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

			if ($row->is_login == 1 && (strtolower($this->input->post('isloginwithmaster')) !== "false" ||  ($this->loginsession == $row->login_session || $default_cont))) {
			} else {
				$this->api_response(['success' => false, 'status_code' => 402, 'message' => 'Token Expired', 'loginsession' => $row->login_session], 402);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 402, 'message' => 'Token Expired'], 402);
		}

		$this->user_id = $this->db->escape_str($array[0]);
		$this->user_email = $this->db->escape_str($array[1]);
		$this->user_mobile = $this->db->escape_str($array[2]);
		$this->user_type = $this->db->escape_str($array[3]);
		$this->full_control = $this->db->escape_str($array[4]);
		$this->queue_perm_id = $this->db->escape_str($array[5]);
		$this->maskEmail = $this->db->escape_str($array[6]);
		$this->maskPhone = $this->db->escape_str($array[7]);
		$this->manager_id = $this->db->escape_str($array[10]);
		$this->allTicket = $this->db->escape_str($array[11]);
		$this->priority_change_flag = $this->db->escape_str($array[12]);
		$this->open_to_queue = $this->db->escape_str($array[13]);
		$this->name = $this->db->escape_str($array[14]);


		return true;
	}


	public function updateLoginStatus($userdata, $type)
	{
		$this->Api_Model->updateLoginStatus($userdata, $type);
	}

	function updateLoginStatusCRM($userdata, $type)
	{
		$this->Api_Model->updateLoginStatusCRM($userdata, $type);
	}


	public function checkqueue()
	{
		$post = json_decode(file_get_contents('php://input'));
		if (isset($post->ticketData->queue)) {
			$queue = $this->CrmApi_Model->getqueue($post->ticketData->queue);
			if (!empty($queue)) {
				$this->response(TRUE, 'success', 200, $queue);
			} else {
				$this->response(FALSE, 'Invalid Queue', 400);
			}
		} else {
			$this->response(FALSE, 'Invalid Queue', 400);
		}
	}

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

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

	// 	$this->updateLoginStatusCRM($postvars->agent_name, "logout");
	// 	$query = $this->db->query("SELECT id FROM tms_user_master WHERE user_name = ?", array($postvars->agent_name));
	// 	$result = $query->result();
	// 	$queue = $this->Api_Model->queueData($result[0]->id,1);
	// 	if (isset($queue->error)) {
	// 		$this->api_response(['success' => false, 'status_code' => 400, 'message' => $queue->message], 400);
	// 	}
	// 	$logArry[] = array(
	// 		'user_name' => $postvars->agent_name,
	// 		'user_id' => $result[0]->id,
	// 		'user_type' => $this->user_type,
	// 		'queue_id' => $queue->queue_id,
	// 		'status' => 'logout',
	// 		'ip_address' => $_SERVER['REMOTE_ADDR'],
	// 		'logout_from' => 'crm'
	// 	);

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




	//--------------------------- Updated Code-------------------------------------------------

	public function loginIframe()
	{
		$post = json_decode(file_get_contents('php://input'));

		$token = $post->data;
		$res = json_decode($this->fx->encrypt_decrypt('decrypt', $token));

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

		$userdetails = $this->Getuserdetails($this->user_id);
		$post->email = $userdetails[0]->email;
		$post->password = $userdetails[0]->password;
		$MasterPassword = 'S@N1@2$@N@' . date('Ymd');
		if ($post->password == $MasterPassword) {
			$userdata = $this->Api_Model->checkSuperUserLogin($post->email);
		} else {
			$userdata = $this->Api_Model->checklogin($post->email, $post->password);
		}
		if (!$userdata) {
			$this->api_response(['success' => false, 'message' => 'Invalid Email or Password', 'result' => '']);
		} else {
			// $queue_id = $this->CrmApi_Model->getqueue_id($post->ticketData->queue);
			// if (empty($queue_id)) {
			// 	$this->api_response(['success' => false, 'message' => $post->ticketData->queue . '  Queue is Invalid', 'result' => '']);
			// }
			// $this->LoginLog($post, $userdata);
			$userdata['company_detail'] = $this->Api_Model->companyDetails();
			// $this->updateLoginStatus($userdata[0]->id, "login");

			$userdata['menu_list'] = $this->Api_Model->getMenus($userdata[0]->full_control, $userdata[0]->user_type);
			$tempstring = $userdata[0]->user_id . '-' . $userdata[0]->email . '-' . $userdata[0]->mobile_no . '-' . $userdata[0]->user_type . '-' . $userdata[0]->full_control . '-' . $userdata[0]->queue_id . '-' . $userdata[0]->maskEmail . '-' . $userdata[0]->maskPhone . '-' . $userdata[0]->crm_theme . '-' . $userdata[0]->crm_pcolor . '-' . $userdata[0]->manager_id . '-' . $userdata['company_detail']['all_ticket'] . '-' . $userdata[0]->priority_change_flag . '-' . $userdata[0]->open_to_queue . '-' . $userdata[0]->name;
			$logintoken = $this->fx->encrypt_decrypt('encrypt', $tempstring);
			$userdata['logintoken'] = $logintoken;
			// $userdata['new_ticket'] = $
			// $postDetails = json_decode($res->postData);
			$this->api_response(['success' => true, 'result' => $userdata, 'postData' => $res->postData]);
		}
	}

	function Getuserdetails($user)
	{
		$userdetails = $this->CrmApi_Model->userdetailsbyuserid($user);
		return $userdetails;
	}

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

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

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

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

		$logArry[] = array(
			'user_name' => $userdata->user_name,
			'user_id' => $userdata->id,
			'user_type' => $userdata->user_type,
			'user_data' => $data,
			'queue_id' => $userdata->queue_id,
			'ip_address' => $_SERVER['REMOTE_ADDR'],
			'auth_type' => 10,
			'status' => 'logout'
		);
		$this->db->insert_batch('tms_login_log', $logArry);
	}

	function fetchFileDetailsAndBase64($url)
	{
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HEADER, true);
		curl_setopt($ch, CURLOPT_NOBODY, true);
		$headers = curl_exec($ch);

		// Get content type and file size
		$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
		$fileSize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);

		curl_close($ch);


		// $fileContent = @file_get_contents($url);
		$fileContent = @file_get_contents($url);  // suppress warning

if ($fileContent === false) {
    $error = error_get_last();
    $errorMessage = isset($error['message']) ? $error['message'] : 'Unknown error';
    $this->api_response([
        'success' => false,
        'status_code' => 400,
        'message' => 'Failed to fetch file content: ' . $errorMessage
    ], 400);
    return false;
}
		// fX::pr($fileContent,1);

		if ($fileContent === false) {
			return false;
		}

		$base64Content = base64_encode($fileContent);

		$result = new stdClass();
		$result->name = basename(parse_url($url, PHP_URL_PATH));
		$result->type = $contentType;
		$result->size = $fileSize;
		$result->data = "data:$contentType;base64,$base64Content";
		return [(array)$result];
	}


	function AddAttachmentInTicket()
	{
		$postvar = json_decode(file_get_contents("php://input"));
		$header = $this->input->request_headers();
		$header = array_change_key_case($header, CASE_LOWER);
		$compAccessToken = $this->checkAccessToken($header['token']);
		if ($compAccessToken != 1) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token'], 400);
		}
		if (!isset($postvar->queue_name) || $postvar->queue_name == "") {

			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Queue Name is required'], 400);
		}
		$postvar->queue_id =  $this->Master_Model->getScalerCol("id", "tms_queue_master", "queue = '$postvar->queue_name'")->id;
		if ($postvar->ticket_id == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Ticket Id is required'], 400);
		}

		// fx::pr($postvar,1);
		if (isset($postvar->Attech_file_json)) {
			if ($postvar->Attech_file_json->messages[0]->type != 'text') {
				// fx::pr(json_encode(["media"=>$postvar->Attech_file_json->message->messages]),1);

				$curl = curl_init();
				curl_setopt_array($curl, array(
					CURLOPT_URL => $this->url, // 'https://iffcokisancollection.chatbot.team/v1/waMedia/getMedia' 
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_ENCODING => '',
					CURLOPT_MAXREDIRS => 10,
					CURLOPT_TIMEOUT => 0,
					CURLOPT_FOLLOWLOCATION => true,
					CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					CURLOPT_CUSTOMREQUEST => 'POST',
					CURLOPT_POSTFIELDS => json_encode(["media" => $postvar->Attech_file_json->messages]),
					CURLOPT_HTTPHEADER => array(
						'CHATBOT-TEAM-API-KEY: NlP1oEliVwcertbgYR3OrCcTDbwXnAK',
						'Content-Type: application/json',
					),
				));

				$response = curl_exec($curl);

				curl_close($curl);

				$media = json_decode($response);
				if ($media->meta->status) {
					$postvar->attachmentArray  = (array)$this->fetchFileDetailsAndBase64($media->response[0]->file_url);
					
					if ($postvar->attachmentArray == false) {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Attachment cannot be retrieved!'], 400);
					}
				} else {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Attachment cannot be retrieved!'], 400);
					return false;
				}
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Attachment cannot be retrieved!'], 400);
			}
		} else {

			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Attachment cannot be retrieved!'], 400);
		}
		$conversationData =  $this->CrmApi_Model->get_last_conversation($postvar->queue_id, $postvar->ticket_id);
		if ($conversationData == null) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Ticket Id is not Created!'], 400);
		}
		$postvar = (array)$postvar;
		$postvar['msg_id']  = pathinfo($conversationData->json_file_name, PATHINFO_FILENAME);
		$todayfolderPath = NODE_APP_PATH . date("Y-m-d") . '/';
		if (!is_dir($todayfolderPath)) {
			mkdir($todayfolderPath, 0777, true);
		}
		chmod($todayfolderPath, 0777);
		$path = $todayfolderPath . '/' . $postvar['msg_id'];
		if (!is_dir($path)) {
			mkdir($path, 0777, true);
		}
		chmod($path, 0777);
		$postvar['path'] = date("Y-m-d") . '/' . $postvar['msg_id'];

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

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

				if (!in_array($mime_type, ['image/gif', 'image/jpeg', 'image/png', 'application/pdf', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'text/csv', 'text/plain', 'application/json', 'application/xml', 'application/msword', 'application/zip', 'application/rar'])) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'error', "result" => "Invalid file type"], 400);
					return false;
				}
				$attachmentSize += $attachment['size'];
			}
			if ($attachmentSize > 15 * 1024 * 1024) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Total size of attachments cannot be greater than 15MB', 400]);
				return false;
			} else {
				foreach ($postvar['attachmentArray'] as $attachment) {
					$this->upload->do_upload($attachment['data']);
					$image_parts = explode(";base64,", $attachment['data']);
					// fX::pr($image_parts,1);
					$image_base64 = base64_decode($image_parts[1]);
					$file = $path . '/' . $attachment['name'];
					if (file_put_contents($file, $image_base64)) {
					} else {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => "File Not Uploded", 400]);
						return false;
					}
				}
				$jsonpath = NODE_APP_PATH . $post['path'] . '/' . $conversationData->json_file_name;
				$jsonString  = json_decode(file_get_contents($jsonpath), true);
				// fX::pr($jsonString,0);
				if (!isset($jsonString['attachmentData'])) {
					$jsonString['attachmentData'] = [];
				}
				foreach ($postvar['attachmentArray'] as $attachment) {
					$mime_type = mime_content_type($attachment['data']);
					$found = false;
					foreach ($jsonData['attachmentData'] as $existingAttachment) {
						if ($existingAttachment['filename'] === $attachment['filename']) {
							$found = true;
							break;
						}
					}
					if (!$found) {
						$jsonString['attachmentData'][] = [
							'filename' => $attachment['name'],
							'contentType' => $mime_type
						];
					}
				}
				// fx::pr($jsonString ,1);
				$jsonString = json_encode($jsonString, JSON_UNESCAPED_UNICODE);

				// Save updated JSON string to file
				if (file_put_contents($jsonpath, $jsonString) !== false) {
				} else {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Failed to update JSON file: ' . $jsonpath, 400]);
				}
			}
		}

		$this->Master_Model->insertAttachmentData($postvar, ['queue_id' => $conversationData->queue_id, 'ticket_id' => $conversationData->ticket_id], $conversationData->ticket_unique_id, $conversationData->conversation_id);

		$this->response(TRUE, "Attechment add in $conversationData->ticket_id", 200);
	}

	function raiseTicket()
	{

		// $postvar = json_decode(stripslashes(json_encode($_POST, JSON_UNESCAPED_UNICODE)));
		$postvar = json_decode(file_get_contents("php://input"));

		$dynamicFields = $postvar->data->dynamicData;

		$header = $this->input->request_headers();
		$header = array_change_key_case($header, CASE_LOWER);
		$compAccessToken = $this->checkAccessToken($header['token']);

		// $postvar = $postvar->data->ticketData;

		$newDynamicData = new stdClass();

		foreach ($postvar->data->dynamicData as $key => $val) {
			$lowerDynamicField = 'df_' . strtolower($key);
			$newDynamicData->$lowerDynamicField = $val;
		}

		// Replace the original dynamicData object with the new one
		$postvar->data->dynamicData = $newDynamicData;


		$mergedArray = array_merge((array) $postvar->data->ticketData, (array) $postvar->data->dynamicData, array('queue_name' => $postvar->queue_name));
		$mergedObject = (object) $mergedArray;
		$postvar = $mergedObject;
		$start_mode = $this->Master_Model->getScalerCol("id", "tms_conversation_type_master", "is_default = '1'")->id;


		if (empty($postvar->queue_name)) {

			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Queue Name is required'], 400);
		} else if ($compAccessToken != 1) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token'], 400);
		} else {


			if (empty($postvar->to_email)) {

				// $this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Email Id is required'], 400);
				$start_mode  = $this->Master_Model->getScalerCol("id", "tms_conversation_type_master", "title = 'Chat'")->id;
				if (empty($postvar->mobile_no)) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Mobile Number is required'], 400);
				}

				if (empty($postvar->mobile_no)) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Mobile Number is required'], 400);
				}
				
				

			}
			$queueName = $postvar->queue_name;
			$queue_id =  $this->Master_Model->getScalerCol("id", "tms_queue_master", "queue = '$queueName'")->id;
			if(!empty($postvar->mobile_no) && !empty($postvar->queue_name)) {
				// Check if a ticket already exists today for this mobile number
				$today = date('Y-m-d');
				$this->db->where('mobile_no', $postvar->mobile_no);
				$this->db->where('DATE(created_at)', $today);
				$existing_ticket = $this->db->get('tms_ticket_master_' . $queue_id)->row(); 
				
				if ($existing_ticket) {
					$this->api_response([
						'success' => false,
						'status_code' => 409,
						'message' => 'A ticket for this mobile number already exists today.'
					], 409);
				}
			}

			if(!empty($postvar->assigned_name)){
				$assigned_to = $postvar->assigned_name;
				unset($postvar->assigned_name);
				$assigned_to_id = $this->Master_Model->getScalerCol("id", "tms_user_master", "user_name = '$assigned_to'")->id;
				if (empty($assigned_to_id)) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Assigned User is not valid'], 400);
				}
				$postvar->assigned_to = $assigned_to_id;
			}


			
			if (empty($queue_id)) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Incorrect Queue Data'], 400);
			}

			$queueDefData = $this->Externalapi_Model->getQueueDefData($queue_id);

			$conversationData = $postvar->conversation;

			// $post = array(
			//     'queue_id'     => $queue_id,
			//     'person_name'  => $postvar->person_name,
			//     'category_id'  => $postvar->category,
			//     'subcategory_id'  => $postvar->subCategory,
			//     'mobile_no'=> $postvar->mobile_no,
			//     'from_email' => $queueDefData['from_mailid']->email,
			//     'to_email' =>  $postvar->to_email,
			//     'conversation' => $conversationData[0],
			//     'priority_id' => $queueDefData['def_priority']->priority_id,
			//     'status_id' => $queueDefData['def_status']->status_id,
			//     'subject' => $postvar->subject,
			//     'start_mode' =>  $queueDefData['start_mode']->id,
			//     'is_junk' =>  '0',
			//     'is_deleted' =>  '0',     
			//     // 'queue_id'     => $queue_id,
			// );
			if (!empty($postvar->category_name)) {
				$category = $this->Master_Model->getScalerCol("category_id,status", "tms_queue_category_$queue_id", "category_name = '" . addslashes($postvar->category_name) . "'");
				if (!empty($category)) {
					if ($category->status != 1) {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Category is inactive'], 400);
						return;
					}
					unset($postvar->category_name);
					$postvar->category_id = $category->category_id;
				} else {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Category Name'], 400);
					return;
				}
				if (!empty($category)) {
					unset($postvar->category_name);
					$postvar->category_id = $category->category_id;
				} else {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Category Name'], 400);
					return;
				}
			}

			if (!empty($postvar->subcategory_name)) {
				$subcategory = $this->Master_Model->getScalerCol("sub_category_id, category_id", "tms_queue_sub_category_$queue_id", "sub_category_name = '" . addslashes($postvar->subcategory_name) . "'");
				if (!empty($subcategory)) {
					if (!empty($postvar->category_id) && $subcategory->category_id == $postvar->category_id) {
						unset($postvar->subcategory_name);
						$postvar->subcategory_id = $subcategory->sub_category_id;
					} else {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Subcategory does not match the Category'], 400);
						return;
					}
				} else {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Subcategory Name'], 400);
					return;
				}
			}
			$postvar->queue_id = $queue_id;
			$postvar->remarks = $postvar->conversation;
			$postvar->conversation = $conversationData;
			$postvar->priority_id = $queueDefData['def_priority']->priority_id;
			$postvar->status_id = $queueDefData['def_status']->status_id;
			$postvar->start_mode = $start_mode;
			$postvar->from_email = $queueDefData['from_mailid']->email;
			$postvar->toEmailId = $postvar->to_email;
			$postvar->is_junk = '0';
			$postvar->is_deleted = '0';
			$postvar->queueDefData = '';
			$postvar->master_name = 'tms_ticket_master_' . $queue_id;
			// fx::pr($postvar, 1);
			$primaryKey = 'ticket_unique_id';
			$postvar->uuid = $this->fx->generateEmailUnqMsgId($queueDefData['from_mailid']->email);

			if (!empty($dynamicFields)) {
				$this->load->library('Dynamicformcontent');
				$rules = $this->dynamicformcontent->getDynamicFieldValidationArray($postvar->queue_id, $postvar->master_name, isset($postvar->$primaryKey) ? $postvar->$primaryKey : '');
				if (is_array($rules) && count($rules) > 0) {
					$this->form_validation->set_data((array)$postvar);
					$this->form_validation->set_message('unique_module', 'Module already in use');
					$this->form_validation->set_rules($rules);
					if ($this->form_validation->run() === false) {
						$data = $this->form_validation->error_array();
						$firstError = (is_array($data)) ? array_keys($data) : [];
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Validation Error', 'result' => $data[$firstError[0]]], 400);
					}
				}
			}
			// fx::pr(json_decode(base64_decode($postvar->file)));
			// if (isset($postvar->Attech_file_json)) {
			// 	if ($postvar->Attech_file_json->message->messages[0]->type != 'text') {
			// 		// fx::pr(json_encode(["media"=>$postvar->Attech_file_json->message->messages]),1);

			// 		$curl = curl_init();
			// 		curl_setopt_array($curl, array(
			// 			CURLOPT_URL => 'https://iffcokisancollection.chatbot.team/v1/waMedia/getMedia',
			// 			CURLOPT_RETURNTRANSFER => true,
			// 			CURLOPT_ENCODING => '',
			// 			CURLOPT_MAXREDIRS => 10,
			// 			CURLOPT_TIMEOUT => 0,
			// 			CURLOPT_FOLLOWLOCATION => true,
			// 			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			// 			CURLOPT_CUSTOMREQUEST => 'POST',
			// 			CURLOPT_POSTFIELDS => json_encode(["media" => $postvar->Attech_file_json->message->messages]),
			// 			CURLOPT_HTTPHEADER => array(
			// 				'CHATBOT-TEAM-API-KEY: NlP1oEliVwcertbgYR3OrCcTDbwXnAK',
			// 				'Content-Type: application/json',							
			// 			),
			// 		));

			// 		$response = curl_exec($curl);

			// 		curl_close($curl);

			// 		$media = json_decode($response);
			// 		if ($media->meta->status) {
			// 			$postvar->attachmentArray  = $this->fetchFileDetailsAndBase64($media->response[0]->file_url);
			// 			if($postvar->attachmentArray == false){
			// 				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Attachment cannot be correct!', 400]);
			// 			}

			// 		} else {
			// 			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Attachment cannot be correct!', 400]);
			// 			return false;
			// 		}
			// 	}else{
			// 		fx::pr($postvar->Attech_file_json->message->messages[0],1);
			// 		// $postvar->remarks = $postvar->Attech_file_json->message->messages[0]->text
			// 	}
			// }else{
			$postvar->attachmentArray = json_decode(base64_decode($postvar->file));
			// }



			// else{
			// fx::pr($postvar->attachmentArray,1);
			// fx::pr($postvar->attachmentArray ,1);
			$postvar->msg_id = $this->fx->generateMsgId($postvar->uuid);

			if (is_array($postvar->attachmentArray) && (count($postvar->attachmentArray)) > 0) {
				foreach ($postvar->attachmentArray as $key => $attachment) {
					$postvar->attachmentArray[$key] = (array) $attachment;
				}

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

				$attachmentSize = 0;
				foreach ($postvar->attachmentArray as $attachment) {
					$attachmentSize += $attachment['size'];
				}
				if ($attachmentSize > 15 * 1024 * 1024) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Total size of attachments cannot be greater than 15MB', 400]);
					return false;
				} else {
					foreach ($postvar->attachmentArray as $attachment) {
						$this->upload->do_upload($attachment['data']);
						$image_parts = explode(";base64,", $attachment['data']);
						$image_base64 = base64_decode($image_parts[1]);

						$file = $path . '/' . $attachment['name'];
						if (file_put_contents($file, $image_base64)) {
						} else {
							$this->api_response(['success' => false, 'status_code' => 400, 'message' => "File Not Uploded"], 400);
							return false;
						}
					}
				}
			}

			$primaryKey = 'ticket_unique_id';
			$masterName = "tms_ticket_master_" . $queue_id;
			$ticketPrifix = $this->ticketSeries($queue_id);

			$ticketNo = $this->Master_Model->getScalerCol("ifnull(max(cast(ticket_unique_id as signed)),0)+1 ticketNo", $masterName, "1=1")->ticketNo;
			if (!empty($ticketPrifix)) {
				$Prefix = explode('[', $ticketPrifix, 2);
				$postvar->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';
				}
				$postvar->ticket_id = $ticketSeries;
			} else {
				return    $this->response(TRUE, 'Error', 400, 'Ticket Prefix is required');
			}

			// $post['uuid'] = $this->fx->generateEmailUnqMsgId($queueDefData['from_mailid']->email);

			$blockEmailIds = $this->Master_Model->getScalerCol("block_email_for_ticket_generate", "tms_queue_master t1", "1=1 and t1.id = '$queue_id'")->block_email_for_ticket_generate;

			if ($blockEmailIds != "") {
				$blockEmailIdsArr = explode(',', $blockEmailIds);

				if (!empty($postvar->toEmailId)) {
					$toEmailArr = explode(',', $postvar->toEmailId);
					if (count($blockEmailIdsArr) > 0 && count($toEmailArr) > 0) {
						$matchingEmails = array_intersect($blockEmailIdsArr, $toEmailArr);
						$stringMatchingEmails = (is_array($matchingEmails) ? implode(',', $matchingEmails) : $matchingEmails);
						if (count($matchingEmails) > 0) {
							return    $this->response(TRUE, 'Error', 400, 'To Email id ("' . $stringMatchingEmails . '") is blocked for ticket generation');
						}
					}
				}
			}
			// block email for ticket generation ends here

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

			// block domain for ticket generation emds here
			$is_happycode = $this->Master_Model->getScalerCol("is_happycode", "tms_queue_master", "1=1 and id = $queue_id")->is_happycode;
			if ($is_happycode == 1) {
				$postvar->happy_code = rand(1000, 9999);
			}

			$postvar->ticket_created_by = "1";
			$postvar->created_date = date('Y-m-d H:i:s');
			$postvar->is_new = 1;

			$dbData = (array)$postvar;
			$postvar =  (array)$postvar;
			// fx::pr($dbData,1);
			$dbFields = $this->Master_Model->getTicketTableFields($masterName);
			$db_keys = array_keys($dbData);
			foreach ($db_keys as $keyName) {

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

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


	function loginApi()
	{
		$header = $this->input->request_headers();
		$header = array_change_key_case($header, CASE_LOWER);
		$post = json_decode(file_get_contents("php://input"));
		if (isset($header['token']) && $header['token'] != "") {
			$compAccessToken = $this->checkAccessToken($header['token']);
			if ($compAccessToken == 1) {
				if (isset($post->agent) && $post->agent != '') {

					$userdata = $this->CrmApi_Model->checkUserLogin($post);
					if (!empty($userdata)) {
						if ($userdata->status == 0) {
							$this->api_response(['success' => true, 'result' => 'Inactive user']);
						}
						// $queueId = $this->CrmApi_Model->getQueueId($post);

						// if (!empty($queueId)) {
						// if (property_exists($userdata, 'queue_id')) {
						// $queueIdsArray = explode(',', $userdata->queue_id);
						// if (in_array($queueId->id, $queueIdsArray)) {
						$userdata->company_detail = $this->Api_Model->companyDetails();
						$session_id = $this->fx->generate_session_id();
						$tempstring = $userdata->user_id . '-' . $userdata->email . '-' . $userdata->mobile_no . '-' . $userdata->user_type . '-' . $userdata->full_control . '-' . $userdata->queue_id . '-' . $userdata->maskEmail . '-' . $userdata->maskPhone . '-' . $userdata->crm_theme . '-' . $userdata->crm_pcolor . '-' . $userdata->manager_id . '-' . $userdata->company_detail['all_ticket'] . '-' . $userdata->priority_change_flag . '-' . $userdata->open_to_queue . '-' . $userdata->name;
						$logintoken = $this->fx->encrypt_decrypt('encrypt', $tempstring);
						$userdata->logintoken = $logintoken;
						if ($userdata->is_login == 1) {
							$resp = $this->CrmApi_Model->updateLoginState($userdata->user_id, 'logout');
							// $this->logoutLog($post, $userdata);
							$this->CrmApi_Model->updateLoginState($userdata->user_id, 'login', $session_id);
							$this->LoginLog($post, $userdata);
							$this->api_response(['success' => true, 'result' => 'Logged In Successfully', 'data' => $userdata->logintoken]);
						} else {
							$this->CrmApi_Model->updateLoginState($userdata->user_id, 'login', $session_id);
							$this->LoginLog($post, $userdata);
							$this->api_response(['success' => true, 'result' => 'Logged In Successfully', 'data' => $userdata->logintoken]);
						}
					} else {
						$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Agent not found in TMS'], 400);
					}
					// } else {
					// 	$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Queue ID does not match'], 400);
					// }
					// } else {
					// 	$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Queue'], 400);
					// }
					// } else {
					// 	$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
					// }
				} else {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Agent not found in TMS'], 400);
				}
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Unauthorized access'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Token is required'], 400);
		}
	}


	function LogoutApi()
	{
		$header = $this->input->request_headers();
		$header = array_change_key_case($header, CASE_LOWER);
		$post = json_decode(file_get_contents("php://input"));

		$compAccessToken = $this->checkAccessToken($header['token']);

		if ($compAccessToken == 1) {
			$userdata = $this->CrmApi_Model->checkUserLogin($post);
			if (!empty($userdata)) {
				$this->CrmApi_Model->updateLoginState($userdata->user_id, 'logout');
				if ($userdata->is_login != 0) {
					$this->logoutLog($post, $userdata);
				}
				$this->api_response(['success' => true, 'result' => 'Logout Successfully']);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Agent not found in TMS'], 400);
			}
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Unauthorized Access'], 400);
		}
	}

	function checkAccessToken($token)
	{
		$accessToken = $this->CrmApi_Model->getAccessToken();
		if ($accessToken->api_access_token == $token) {
			return True;
		} else {
			return False;
		}
	}

	function OpenTMSIframe()
	{
		$header = $this->input->request_headers();
		$header = array_change_key_case($header, CASE_LOWER);
		$post = json_decode(file_get_contents("php://input"));
		$compAccessToken = $this->checkAccessToken($header['token']);

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


		if ($compAccessToken == 1) {
			$queueName = $post->queue_name;
			if ($queueName != '') {
				$queueId = $this->CrmApi_Model->getQueueId($queueName);
				$queueIdsArray = explode(',', $this->queue_perm_id);
				if (!in_array($queueId->id, $queueIdsArray)) {
					$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Queue'], 400);
				}
			}

			$userDetails = $this->fx->encrypt_decrypt('decrypt', $post->token);

			if ($post->type == 'iframe' && !isset($post->data) && !isset($post->data->ticketData)) {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data is required'], 400);
			}

			// $userData['userData'] = $userDetails;
			// $postData['postData'] = $post->data;
			// if ($post->type == "iframeticketsearch") {
			// 	$postData['postData']->ticketData->queue_id = $queueId->id;
			// }
			// $mainData = array_merge($userData, $postData);
			$userData['userData'] = $userDetails;
			if ($post->type == "iframe") {
				$postData['postData'] = $post->data;
				$postData['postData']->ticketData->queue_id = $queueId->id;
				$mainData = array_merge($userData, $postData);
			} else {
				$mainData = $userData;
			}
			$stringData = json_encode($mainData);
			$token = $this->fx->encrypt_decrypt('encrypt', $stringData);
			$compressedData = gzcompress($token, 9);
			// $encodedToken = base64_encode($compressedData);

			if ($post->type == 'iframe') {
				$this->api_response([
					'success' => true,
					'result' => 'Success',
					'data' => base_url() . '/new-ticket?type=' . $post->type . '?token=' . $token
				], 200);
			} else if ($post->type == 'iframeticketsearch') {
				$this->api_response([
					'success' => true,
					'result' => 'Success',
					'data' => base_url() . '/iframeticketsearch?type=' . $post->type . '?token=' . $token
				], 200);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Type'], 400);
			}
		}
	}



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