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


class App 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",
	);

	// function __construct()
	// {
	// 	error_reporting(E_ALL);
	// 	parent::__construct();
	// 	$this->fx->validateCORS();
	// 	$this->load->model('Api_Model');
	// 	$this->load->model('Dropdown_Option_Model');
	// 	$this->load->model('Dynamicform_Model');
	// 	$this->load->model('Formcontent_Model');
	// 	$this->load->model('Master_Model');
	// 	$this->load->model('App_Model');
	// 	$this->load->model('Externalapi_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 = '';
	// 	$this->load->library('table');
	// 	$this->table = new Table();
	// 	$this->CI = &get_instance();
	// }
	private function convertHeaderToPost($headerData)
	{
		foreach ($headerData as $key => $value) {
			if (strtolower($key) == 'token' || strtolower($key) == 'loginsession' || strtolower($key) == 'isloginwithmaster' || strtolower($key) == 'accesstoken') {
				$_POST[strtolower($key)] = $value;
				// break;
			}
		}
	}
	function __construct()
	{
		parent::__construct();

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

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


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

	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,
		);
		$this->output
			->set_status_header($status_code)
			->set_content_type('application/json')
			->set_output(json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))->_display();;
		// echo json_encode($response);
		exit;
	}

	// ------------------------------------------TMS APP------------------------------

	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;
	}

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

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

	// Get Queue Details
	public function queues()
	{
		$postvar = json_decode(file_get_contents("php://input"));
		$header = $this->input->request_headers();
		$header = array_change_key_case($header, CASE_LOWER);
		if (empty($header['token'])) {
			$this->response(false, 'Token is required', 401);
		}

		// $compAccessToken = $this->checkAccessToken($header['token']);
		$accessToken = $this->App_Model->getAccessToken($header['token']);
		if ($accessToken->api_access_token) {
			$clientId = $accessToken->client_id;
		} else {
			$this->response(false, 'Invalid token', 401);
		}
		if ((!isset($postvar->email) || $postvar->email == "") && (!isset($postvar->phone) || $postvar->phone == "")) {
			$this->response(false, 'Either Email or Phone is required', 400);
		}



		//get queue details using client_id
		$queueDetails = $this->App_Model->getQueueDetails($clientId);

		// Add ticket counts with status for each queue
		foreach ($queueDetails as &$queue) {
			$queueId = $queue->id;
			$ticketCounts = $this->App_Model->getTicketCountsByStatus($queueId, $clientId, $postvar->email, $postvar->phone);

			$queue->ticket_counts = $ticketCounts;
		}

		if ($queueDetails) {
			$this->response(true, 'Queue details retrieved successfully', 200, $queueDetails);
			// $this->output
			// 	->set_content_type('application/json')
			// 	->set_output(json_encode(['status' => 'success', 'data' => $queueDetails]));
		} else {
			$this->response(false, 'No queues found', 404);
			// $this->output
			// 	->set_content_type('application/json')
			// 	->set_output(json_encode(['status' => 'error', 'message' => 'No queue details found']));
		}
	}

	// get Dynamic Form List
	public function getAllFormList()
	{
		$token = $this->input->post('token');
		$header = $this->input->request_headers();
		$header = array_change_key_case($header, CASE_LOWER);
		if (empty($header['token'])) {
			$this->response(false, 'Token is required', 401);
		}

		$postvars = json_decode(file_get_contents("php://input"), true);
		$post = $postvars;
		if (!empty($post)) {
			$queue_id = isset($post['queue_id']) ? $post['queue_id'] : null;
			if (!$queue_id) {
				$this->response(FALSE, 'Queue Id is required', 400);
				return;
			}

			$form_id = $post['queue_id'];
			$formFields = $this->Formcontent_Model->getFormFieldsByFormId($form_id);
			foreach ($formFields->data as $key => $val) {
				$val->db_res = '';
				if ($val->values_from_db == 1) {
					$dbQuery = stripslashes($val->field_values);
					$val->db_res = $this->db->query($dbQuery)->result();
				}
			}
			$envArr = array(
				'form_id' => $form_id,
				'formFields' => $formFields->data,
			);
			if (is_array($envArr) && count($envArr) > 0) {
				$this->response(TRUE, '', 200, $envArr);
			} else {
				$this->response(FALSE, 'Data Not Found', 400);
			}
		} else {
			$this->response(FALSE, 'Queue Id is required', 400);
		}
	}

	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;


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

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

			$queueName = $postvar->queue_name;
			$queue_id =  $this->Master_Model->getScalerCol("id", "tms_queue_master", "queue = '$queueName'")->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,
			// );

			$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 = $queueDefData['start_mode']->id;
			$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);
			}
			// }
		}
	}


	// Get Ticket Details
	function getConversationDetails()
	{
		$header = $this->input->request_headers();
		// fx::pr($header,1);
		$compAccessToken = $this->checkAccessToken($header['token']);
		if (!$compAccessToken) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Invalid Token'], 400);
		}

		$post = json_decode(file_get_contents('php://input'));
		// fx::pr($post,1);    
		if (!isset($post->queue_id) || $post->queue_id == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Queue Id is required'], 400);
		}

		if ($post->ticket_id == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'ticket Id is required'], 400);
		}

		$post->type = isset($post->type) && $post->type == 'pending' ? 'pending' : 'all';
		$con = " 1=1 ";
		if ($post->ticket_id != "") {
			$con .= " and (t1.ticket_unique_id = '$post->ticket_id' OR t1.ticket_id = '$post->ticket_id')";
		}

		$res = $this->Master_Model->getTicketDetail($post->queue_id, $con, $post->type);
		if (!isset($res->data[0])) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'ticket Id is Wrong'], 400);
		}
		$postdata = [
			'tktUnqId' => $res->data[0]->ticket_unique_id,
			'queue_id' => $post->queue_id
		];

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

			foreach ($resData->conversationAttachmentListData as $key => $val) {
				if (!empty($val->attachement_filepath) && $val->attachement_filepath != '') {					
					$data  = base_url() . 'mail_json_file/' . $val->attachement_filepath;					
					$val->attachement_filepath = $data;
				}
			}
			$this->response(TRUE, '', 200, $resData);
		} else {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Data Not Found'], 400);
		}
	}

	// Get Tickets IN Queue
	function getTicketDetailIvr()
	{
		$header = $this->input->request_headers();
		$header = array_change_key_case($header, CASE_LOWER);
		$compAccessToken = $this->checkAccessToken($header['token']);
		// $getClientId = $this->getClientId($header['token']);
		// $agentId = $this->Externalapi_Model->getAgentId($agentName, $getClientId->client_id);
		// $planDetails = $this->Api_Model->currentPlan($getClientId->client_id);
		// if ($planDetails->plan_id == 0 || empty($planDetails->plan_id) || $planDetails->plan_id == '' || $planDetails->plan_id == null) {
		// 	$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Plan is not active'], 400);
		// }
		$post = json_decode(file_get_contents('php://input'));
		if (!isset($post->queue_name) || $post->queue_name == "") {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Queue Name is required'], 400);
		}
		$queue_id = $this->Master_Model->getScalerCol("id", "tms_queue_master", "queue = '$post->queue_name'")->id;
		if (empty($queue_id)) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Incorrect Queue Data'], 400);
		}

		if ($post->mobile_no == "" && $post->ticket_id == "" && $post->email == "") {

			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Either Mobile No, Ticket Id or Email is required'], 400);
		}
		$status_type = ($post->status_type) ? $post->status_type : '0';

		if ($post->mobile_no != "") {
			$res = $this->App_Model->getTicketDetailFromNo($post->mobile_no, $queue_id, $status_type);
			if ($res->count > 0) {
				$this->response(TRUE, '', 200, $res);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'No Record Found'], 400);
			}
		} else if ($post->ticket_id != "") {
			$res = $this->App_Model->getTicketDetailFromTicketId($post->ticket_id, $queue_id, $status_type);
			if ($res->count > 0) {
				$this->response(TRUE, '', 200, $res);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'No Record Found'], 400);
			}
		} else if ($post->email != "") {
			$res = $this->App_Model->getTicketDetailFromEmail($post->email, $queue_id, $status_type);
			if ($res->count > 0) {
				$this->response(TRUE, '', 200, $res);
			} else {
				$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'No Record Found'], 400);
			}
		}
	}

	// EXTRA FUNCTIONS--------START


	function checkFolderSize($clientId, $plan_storage_size)
	{
		$folders = [
			$_SERVER['DOCUMENT_ROOT'] . '/tms-client/api/' . CLIENT_UPLOAD_FOLDER . '/' . CLIENT_FOLDER_PREFIX . $this->client_id,
			'/var/www/html/readmail_app/mail_json_file/client_' .  $clientId . '/'
		];
		$maxSize = $plan_storage_size * 1024 * 1024 * 1024;
		$results = 0;
		foreach ($folders as $folderPath) {
			$folderSize = $this->fx->folderSize($folderPath);
			$results += $folderSize;
		}
		if ($results > $maxSize) {
			$this->api_response(['success' => false, 'status_code' => 400, 'message' => 'Storage Limit Exceeded'], 400);
		}
	}

	function getBase64FileSize($base64String)
	{
		// Check if the string contains metadata (e.g., "data:image/jpeg;base64,")
		if (strpos($base64String, ',') !== false) {
			// Extract the Base64-encoded portion after the comma
			$base64String = explode(',', $base64String)[1];
		}

		// Calculate the size of the Base64 string
		$base64Length = strlen($base64String);

		// Count padding characters '='
		$padding = substr_count($base64String, '=');

		// Calculate file size in bytes
		$fileSize = ($base64Length * 3 / 4) - $padding;

		return (int)$fileSize; // Return as an integer
	}


	function generateRandomFileName($extension)
	{
		// Ensure the extension is in lowercase and remove any leading dot
		$extension = ltrim(strtolower($extension), '.');

		// Generate a unique file name using uniqid() and append the extension
		$fileName = uniqid('file_', true) . '.' . $extension;

		return $fileName;
	}
	function getFileExtensionFromBase64($base64String)
	{
		// Check if metadata is present
		if (preg_match('/^data:([a-zA-Z0-9\/]+);base64,/', $base64String, $matches)) {
			// Extract MIME type (e.g., "image/jpeg")
			$mimeType = $matches[1];

			// Map MIME type to file extension
			$mimeToExt = [
				'image/jpeg' => 'jpeg',
				'image/png' => 'png',
				'image/gif' => 'gif',
				'application/pdf' => 'pdf',
				'text/plain' => 'txt',
				'application/vnd.ms-excel' => 'xls', // Excel files (older format)
				'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx', // Excel files (newer format)
				'text/csv' => 'csv', // CSV files
				'application/json' => 'json', // JSON files
				'application/xml' => 'xml', // XML files
				'text/xml' => 'xml', // XML files (alternative MIME type)
				'application/msword' => 'doc', // Word document (older format)
				'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx', // Word document (newer format)
			];


			return $mimeToExt[$mimeType] ?? null;
		}
		return null;
	}
	public function checkAccessToken($token)
	{
		$accessToken = $this->App_Model->getAccessToken($token);
		if ($accessToken->api_access_token) {
			return True;
		} else {
			return False;
		}
	}

	// function getClientId($token)
	// {
	// 	return $this->App_Model->getClientId($token);
	// }


	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;
	}

	// EXTRA FUNCTIONS--------END
}
