<?php
	require_once('../db.php');
	require '../include/helper_functions/data_request.php';
	function getBaseUrl() {
	    $scheme = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
	    // Get the host (domain name)
	    $host = $_SERVER['HTTP_HOST'];
	    // Construct the base URL
	    $base_url = 'http://' . $host;
	    return $base_url;
	}

	function defalt_voice_message($voice_name) {
	    $base_url = base_url();

	    // Clean filename to remove harmful characters
	    $safe_name = basename(preg_replace('/[^a-zA-Z0-9_\.\-]/', '', $voice_name));

	    // Validate and enforce allowed extensions
	    $allowed_extensions = ['wav', 'mp4'];
	    $ext = pathinfo($safe_name, PATHINFO_EXTENSION);

	    if (!in_array($ext, $allowed_extensions)) {
	        // Default to .wav if no valid extension is present
	        $safe_name .= '.wav';
	    }

	    $message_url = $base_url . "/audio_messages/" . $safe_name;

	    // Escape URL for XML
	    $safe_url = htmlspecialchars($message_url, ENT_QUOTES | ENT_XML1, 'UTF-8');

	    return "<Play>$safe_url</Play>";
	}

	// function base_url(){
	// 	$actual_link = (empty($_SERVER['HTTPS']) ? 'http' : 'https') . "://$_SERVER[HTTP_HOST]";
	// 	return $actual_link;
	// }

	function base_url() {
	    // Default to localhost if not set
	    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';

	    // Remove anything except letters, numbers, dots, and hyphens
	    $host = preg_replace('/[^a-zA-Z0-9.\-]/', '', $host);

	    // Avoid double dots or malformed domains
	    $host = preg_replace('/\.+/', '.', $host);

	    // Limit length to prevent abuse
	    $host = substr($host, 0, 255);

	    // Final validation (optional but safe)
	    if (!filter_var("http://$host", FILTER_VALIDATE_URL)) {
	        $host = 'localhost';
	    }

	    // Determine scheme
	    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';

	    return "$scheme://$host";
	}

	function format_number($input) {
	    // Split main number and extension(s)
	    $parts = explode(',', $input);
	    $main_number = $parts[0];
	    $extensions = array_slice($parts, 1); // All parts after the first

	    // Remove all non-numeric characters from main number
	    $main_number = preg_replace('/[^0-9]/', '', $main_number);

	    // Format the main number
	    if (strlen($main_number) === 10) {
	        $main_number = '1' . $main_number;
	    } elseif (strlen($main_number) === 11 && substr($main_number, 0, 1) === '0') {
	        $main_number = '44' . substr($main_number, 1);
	    } elseif (strlen($main_number) === 12 && substr($main_number, 0, 2) === '00') {
	        $main_number = '44' . substr($main_number, 2);
	    }

	    // Add the + prefix
	    $formatted = '+' . $main_number;

	    // Reattach the extensions, if any
	    if (!empty($extensions)) {
	        $formatted .= ',' . implode(',', $extensions);
	    }

	    return $formatted;
	}


	function caller_id_format($phone_number){
		$formatted_number = substr($phone_number, 2);
		return $formatted_number;
	}

	// function make_curl_request($type, $url, $method, $data="", $signalwire_credentials=[], $headers="") {
	// 	if(($type == "socket") || ($type == "req_open_door") || (isset($signalwire_credentials['id']) && !empty($signalwire_credentials['id']))){
	// 		if(($type != "socket") && ($type != "req_open_door")){
	// 			$space_url = $signalwire_credentials['space_url'];
	// 			$project_id = $signalwire_credentials['project_id'];
	// 			$api_token = $signalwire_credentials['api_token'];
	// 		}

	// 		$base_url = base_url();
				
	// 		// Initialize cURL
	// 	    $ch = curl_init($url);
	// 	    if($type == "remove_participant"){
	// 	    	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
	// 	    }
	// 	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	// 	    if(!empty($headers)){
	// 	    	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	// 	    }
	// 	    if($type == "status_check"){
	// 	    	curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	// 	    }
	// 	    if($method == "post"){
	// 	    	curl_setopt($ch, CURLOPT_POST, true);
	// 	    	if(!empty($data)){
	// 		    	curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
	// 		    }
	// 	    }
	// 	    // Block redirects (helps against SSRF)
	//         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);

	//         // Secure TLS
	//         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
	//         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
	// 	    if(($type != "socket") && ($type != "req_open_door")){
	// 	    	curl_setopt($ch, CURLOPT_USERPWD, "$project_id:$api_token");
	// 	    }
	// 	    $response = curl_exec($ch);
	// 	    if (curl_errno($ch)) {
	//             error_log("cURL error [$type]: " . curl_error($ch));
	//         }
	// 	    curl_close($ch);		   
	// 	    return $response;
	// 	}

	// }

	function make_curl_request($type, $url, $method, $data="", $signalwire_credentials=[], $headers="") {
	    if(($type == "socket") || ($type == "req_open_door") || (isset($signalwire_credentials['id']) && !empty($signalwire_credentials['id']))){
	        if(($type != "socket") && ($type != "req_open_door")){
	            $space_url  = $signalwire_credentials['space_url'];
	            $project_id = $signalwire_credentials['project_id'];
	            $api_token  = $signalwire_credentials['api_token'];
	        }

	        $base_url = base_url();
	            
	        // Initialize cURL
	        $ch = curl_init($url);

	        // Handle DELETE
	        if($type == "remove_participant"){
	            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
	        }

	        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	        // Extra headers
	        if(!empty($headers)){
	            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	        }

	        // Auth for status_check type
	        if($type == "status_check"){
	            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	        }

	        // Handle POST
	        if($method == "post"){
	            curl_setopt($ch, CURLOPT_POST, true);
	            if(!empty($data)){
	                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
	            }
	        }

	        // Block redirects (helps against SSRF)
	        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);

	        // Secure TLS
	        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
	        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

	        // Basic Auth for SignalWire
	        if(($type != "socket") && ($type != "req_open_door")){
	            curl_setopt($ch, CURLOPT_USERPWD, "$project_id:$api_token");
	        }

	        $response = curl_exec($ch);

	        if (curl_errno($ch)) {
	            error_log("cURL error [$type]: " . curl_error($ch));
	        }

	        curl_close($ch);           
	        return $response;
	    }

	    return false;
	}


	function get_call_data($call_id){
		$call_data = fetchDataSingle('call_histories', ['id' => $call_id]);
		if(isset($call_data['id']) && !empty($call_data['id'])){
			return $call_data;
		}
		else{
			return "";
		}
	}

	function save_call($call_sid, $from_number, $to_number, $call_status){
		$get_visitor = fetchDataSingle('visitor_call_data', ['visitor_number' => $from_number]);
		if(isset($get_visitor['id']) && !empty($get_visitor['cnam'])){
			$cnam = $get_visitor['cnam'];
		}
		else{
			$cnam = get_cname($from_number, $to_number);
			$vs_tab_name = "visitor_call_data";
	        $vs_tab_data = [
	        	'call_sid' => $call_sid,
	        	'visitor_number' => $from_number,
	            'cnam' => $cnam,
	            'cname_date' => date('Y-m-d'),
	        ];
	        insertData($vs_tab_name, $vs_tab_data);
		}
		$property = fetchDataSingle('my_numbers', ['phone_number' => $to_number, 'deleted_at' => null]);
		$tab_name = "call_histories";
        $tab_data = [
        	'property_id' => $property['property_id'],
            'call_sid' => $call_sid,
            'from_number' => $from_number,
            'to_number' => $to_number,
            'status' => $call_status,
            'cnam' => $cnam,
        ];
        insertData($tab_name, $tab_data);

        
	}	

	function get_call_flow($to_number){
		$sql = "SELECT mcf.*, mn.id as my_number_id, mn.property_id, mn.user_id as number_buyer_id, mn.dealer_id FROM my_numbers mn LEFT JOIN my_call_flow mcf ON mn.property_id = mcf.property_id WHERE mn.phone_number = :to_number AND mn.deleted_at IS NULL";
            $params = [':to_number' => $to_number];
            $phone_numbers = fetchSingleDataWithJoins($sql, $params);
            return $phone_numbers;
	}

	function get_singalwire_credentials($number){
		$sql = "SELECT sg.*, fn.phone_sid FROM my_numbers fn LEFT JOIN signalwire_settings sg ON sg.id = fn.signalwire_id WHERE fn.phone_number = :phone_number AND sg.is_active= :is_active AND fn.deleted_at IS NULL";
		$params = ['is_active' => 1, ':phone_number' => $number];
		$signalwire_credentials = fetchSingleDataWithJoins($sql, $params);
		return $signalwire_credentials;
	}

	function send_sms_to_owner($call_id, $to_number, $from_number, $body){
		$first_user_number = get_number_disturb($to_number, 1, $call_id, "first_number");
        $second_user_number = get_number_disturb($to_number, 2, $call_id, "second_number");
        $third_user_number = get_number_disturb($to_number, 3, $call_id, "third_number");
		if(!empty($first_user_number)){
			$number = $first_user_number;
		}
		else if(!empty($second_user_number)){
			$number = $second_user_number;	
		}
		else if(!empty($third_user_number)){
			$number = $third_user_number;
		}
		if(!empty($number)){
			$signalwire_credentials = get_singalwire_credentials($to_number);
			$project_id = $signalwire_credentials['project_id'];
			$space_url = $signalwire_credentials['space_url'];
			if(isset($signalwire_credentials['id']) && !empty($signalwire_credentials['id'])){
				$owner_number = format_number($number);
				$url = "https://$space_url/api/laml/2010-04-01/Accounts/$project_id/Messages.json";
				$base_url = base_url();
				$statusCallback = $base_url . "/signalwire_call/message_call_back.php";
				$data = [
					    'To' => $number,
					    'From' => $to_number,
					    'Body' => $body,
					    'StatusCallback' => $statusCallback,
					];
				$response = make_curl_request("sms", $url, 'post', $data, $signalwire_credentials);
				$responseData = json_decode($response, true);
				if(isset($responseData['sid']) && !empty($responseData['sid'])){	
					return $responseData['sid'];
				}

			}
		}
	}

	function calculate_message_amount($to_number, $messageSid) {

		$my_number = fetchDataSingle('my_numbers', ['phone_number' => $to_number, 'deleted_at' => null]);
		$property_id = $my_number['property_id'];
		$signalwire_credentials = get_singalwire_credentials($to_number);

	    $projectId = $signalwire_credentials['project_id'];
	    $spaceUrl  = $signalwire_credentials['space_url'];
	    $authToken = $signalwire_credentials['api_token'];  

	    // ✅ Fetch a single message by SID (not the send endpoint!)
	    $url = "https://$spaceUrl/api/laml/2010-04-01/Accounts/$projectId/Messages/$messageSid.json";

	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_URL, $url);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($ch, CURLOPT_HTTPGET, true); // ✅ force GET
	    curl_setopt($ch, CURLOPT_USERPWD, "$projectId:$authToken");

	    $response = curl_exec($ch);

	    if (curl_errno($ch)) {
	        error_log("cURL Error (calculate_message_amount): " . curl_error($ch));
	        return;
	    }

	    curl_close($ch);

	    $data = json_decode($response, true);

	    if (isset($data['price'])) {
	        $price = $data['price'];
	    } else {
	        $price = "0.00415"; // fallback
	    }

	    deduct_message_cost($property_id, $price);
	}


	function call_to_owner($from_number, $owner_number, $call_id){
		$signalwire_credentials = get_singalwire_credentials($from_number);
		if(isset($signalwire_credentials['id']) && !empty($signalwire_credentials['id'])){

			$project_id = $signalwire_credentials['project_id'];
			$space_url = $signalwire_credentials['space_url'];
			$url = "https://$space_url/api/laml/2010-04-01/Accounts/$project_id/Calls.json";
	        $base_url = base_url();
			$owner_number = format_number($owner_number);
			$gete_no = format_number($from_number);
	        $conference_url = $base_url . "signalwire_call/personB_connect.php?call_id=$call_id";
	        $statusCallbackUrl = $base_url . "signalwire_call/check_active.php";
	        $data = [
	            'From' => $gete_no,
	            'To' => $owner_number,
	            'Url' => $conference_url,
	            'StatusCallback' => $statusCallbackUrl,
	            'StatusCallbackMethod' => 'POST',
	            'StatusCallbackEvent' => ['completed', 'no-answer', 'busy', 'failed']
	        ];
			$response = make_curl_request("sms", $url, "post", $data, $signalwire_credentials);		
		}
	}

	function call_to_sg_owner($from_number, $owner_number, $call_id){
		$signalwire_credentials = get_singalwire_credentials($from_number);
		if(isset($signalwire_credentials['id']) && !empty($signalwire_credentials['id'])){
			$space_url = $signalwire_credentials['space_url'];
			$project_id = $signalwire_credentials['project_id'];
			$api_token = $signalwire_credentials['api_token'];
			$base_url = base_url();
			$owner_number = format_number($owner_number);
			
			$gete_no = format_number($from_number); // The SignalWire phone number you're sending from
			$url = "https://$space_url/api/laml/2010-04-01/Accounts/$project_id/Calls.json";

	        $callbackUrl = $base_url . "/signalwire_call/personBst_connect.php?call_id=$call_id";
	        // Prepare the data to send in the request
	        $data = [
	            'From' => $gete_no,
	            'To' => $owner_number,
	            'Url' => $callbackUrl,
			    
	        ];

	        $response = make_curl_request("property_user", $url, 'post', $data, $signalwire_credentials);

	        // if ($response === false) {
	        //     error_log("Error: " . curl_error($ch));
	        // } else {
	        //     $responseData = json_decode($response, true);
	        //     if (isset($responseData['sid'])) {
	            
	        //     } else {

	        //     }
	        // }
		}
	}

	function call_back_status_digit($call_sid, $call_status){
		$number_check = fetchDataSingle('call_histories', ['call_sid' => $call_sid]);
		if(isset($number_check['id'])){
			if($number_check['is_digit_press'] == 0){
				$to_number = $number_check['to_number'];
				$from_number = $number_check['from_number'];
				$cnam = $number_check['cnam'];
				$call_id = $number_check['id'];
				$call_flow = get_call_flow($to_number);
				if(isset($call_flow['id'])){
					if(empty($number_check['call_cost'])){
		        		$price = check_status($to_number, $number_check['call_sid'], 'price');
		        		$deduct_cost = deduct_call_cost($number_check['id'], $number_check['property_id'], $price);
		        	}
					if(($call_flow['is_hang_up_message'] == 1) && ($number_check['is_first_digit'] == 0)){
						$gate = get_door($to_number);
						$body = $cnam . " " . $from_number . " ended call at " . $gate['door_name'];
						$messageSid = send_sms_to_owner($call_id, $to_number, $from_number, $body);
			        	// calculate_message_amount($call_id, $to_number, $messageSid);
			        }
				}
			}

			$update_data = [
	            'status' => $call_status,
	        ];
	        $where = 'call_sid = :call_sid';
	        $params = ['call_sid' => $call_sid];
	        $updateSuccess = updateTable('call_histories', $update_data, $where, $params);
		}
	}

	function update_call_status($call_sid, $field_name, $status){
		$update_data = [
            $field_name => $status,
        ];
        $where = 'call_sid = :call_sid';
        $params = ['call_sid' => $call_sid];
        $updateSuccess = updateTable('call_histories', $update_data, $where, $params);
	}

	function update_call($call_id, $field_name, $value){
		$update_data = [
            $field_name => $value,
        ];
        $where = 'id = :id';
        $params = ['id' => $call_id];
        $updateSuccess = updateTable('call_histories', $update_data, $where, $params);
	}

	function update_table_data($table_name, $visitor_id, $field_name, $value){
		$update_data = [
            $field_name => $value,
        ];
        $where = 'id = :id';
        $params = ['id' => $visitor_id];
        $updateSuccess = updateTable($table_name, $update_data, $where, $params);
	}

	function fetch_table_data($table_name, $field_name, $value){
		$data = fetchDataSingle($table_name, [$field_name => $value]);
		return $data;
	}

	function get_socket_url($url, $call_id, $dtmf_url){
		$data = [
		    'conf_sid' => $call_id,  // New TwiML URL
			'dtmf_url' => $dtmf_url
		];
		$response = make_curl_request("socket", $url, 'post', $data);
		// Check for errors
		$responseData = json_decode($response, true);

		// Check if the response has a 'url' field
		if (isset($responseData['url'])) {
			update_call($call_id, 'socket_response_url', $responseData['url']);
		} else {
		    return 0;
		}
	}
	
	function call_socket_url($call_sid, $new_twiml_url, $from_number){
		$signalwire_credentials = get_singalwire_credentials($from_number);
		$space_url = $signalwire_credentials['space_url'];
		$project_id = $signalwire_credentials['project_id'];
		$auth_token = $signalwire_credentials['api_token'];
		
		$api_url = "https://$space_url/api/laml/2010-04-01/Accounts/$project_id/Calls/$call_sid.json";
		$data = array(
			'Url' => $new_twiml_url,  // New TwiML URL
			'Method' => 'POST'        // Method to use for the new URL request (POST or GET)
		);
		make_curl_request("socket_call", $api_url, 'post', $data, $signalwire_credentials);
	}

	function second_person_play($conferenceSid, $message_url, $from_number){
	   	$signalwire_credentials = get_singalwire_credentials($from_number);
		if(isset($signalwire_credentials['id']) && !empty($signalwire_credentials['id'])){
			$space_url = $signalwire_credentials['space_url'];
			$project_id = $signalwire_credentials['project_id'];
			$auth_token = $signalwire_credentials['api_token'];
			if (!preg_match('/^[a-z0-9-]+\.signalwire\.com$/', $space_url)) {
                throw new Exception("Invalid SignalWire space URL.");
            }
		    // API endpoint to play a message in the conference
		    $url = "https://$space_url/api/laml/2010-04-01/Accounts/$project_id/Conferences/$conferenceSid.json";
		    $message_url = htmlspecialchars($message_url, ENT_QUOTES | ENT_XML1, 'UTF-8');
		    $parsed = parse_url($message_url);
	    	
	    	$trusted_host = parse_url(base_url(), PHP_URL_HOST);

	    	if (!isset($parsed['scheme'], $parsed['host']) ||
		        !in_array($parsed['scheme'], ['http', 'https']) ||
		        $parsed['host'] !== $trusted_host) {
		        error_log("Blocked SSRF attempt: $message_url");
		        return false; // Block the request
		    }
		    // Data to play a message (Say) to the conference
		    $data = array(
		        'AnnounceUrl' => $message_url, // The URL of the TwiML to play the announcement
		        'AnnounceMethod' => 'GET', // HTTP method for the AnnounceUrl (GET or POST)
		    );

		    make_curl_request("second_person_play", $url, 'post', $data, $signalwire_credentials);
		}
	}
	
	function stream_connect(){
		header('Content-Type: text/xml');
            echo '<?xml version="1.0" encoding="UTF-8"?>';
            echo "<Response>
                    <Connect> 
                        <Stream url='wss://callstream-6b64fe9b1f4d.herokuapp.com/callStreaming?call_sid=251' /> 
                    </Connect>
                  </Response>";
	}

	function call_socket($call_id){
		$base_url = base_url();
		$ch = curl_init();

		// set URL and other appropriate options
		curl_setopt($ch, CURLOPT_URL, $base_url . "/signalwire_call/socket_url.php?call_id=$call_id");
		curl_setopt($ch, CURLOPT_HEADER, 0);

		// grab URL and pass it to the browser
		curl_exec($ch);

		// close cURL resource, and free up system resources
		curl_close($ch);
	}

	function stream_conference($conference_sid, $call_id, $from_number){
		
		$base_url = base_url();
		$signalwire_credentials = get_singalwire_credentials($from_number);
		$space_url = $signalwire_credentials['space_url'];
		$project_id = $signalwire_credentials['project_id'];
		$api_token = $signalwire_credentials['api_token'];
		$sip_url = $signalwire_credentials['sip_url'] . "?call_id=" . urlencode($call_id);
		
		$gete_no = format_number($from_number); 
		$url = "https://$space_url/api/laml/2010-04-01/Accounts/$project_id/Calls.json";

        $callbackUrl = $base_url . "/signalwire_call/personBst_connect.php?call_id=$call_id";
        // Prepare the data to send in the request
        $data = [
            'From' => $gete_no,
            'To' => $sip_url,
            'Url' => $callbackUrl,
        ];

        $headers = [
		    'Content-Type: application/x-www-form-urlencoded',
		];

		make_curl_request("stream_conference", $url, 'post', $data, $signalwire_credentials, $headers);

	}

	function check_status($from_number, $call_Sid, $bit=""){
		
		$signalwire_credentials = get_singalwire_credentials($from_number);
		$space_url = $signalwire_credentials['space_url'];
		$project_id = $signalwire_credentials['project_id'];
		$api_token = $signalwire_credentials['api_token'];
	
		// SignalWire API endpoint for fetching call details
		$url = "https://$space_url/api/laml/2010-04-01/Accounts/$project_id/Calls/$call_Sid.json";
		$data = "";
		$response = make_curl_request("status_check", $url, 'get', $data, $signalwire_credentials);
		$ck_data = json_decode($response, true);

		// Check the call status
		if(!empty($bit)){
			if (isset($ck_data[$bit])) {
		    	return $ck_data[$bit];
		    }
		    else{
		    	return 0;
		    }
		}
		else{
			if(isset($ck_data['status'])) {
		    	return $ck_data['status'];
			}
			else {
				return ['error' => $response];
			}
		} 

	}

	function dial_new_call($from_number, $owner_number, $call_id, $callbackUrl, $callback, $first_call_sid)
	{
		$status_check = check_status($from_number, $first_call_sid);
		if($status_check == "in-progress"){
			$signalwire_credentials = get_singalwire_credentials($from_number);
			$space_url = $signalwire_credentials['space_url'];
			$project_id = $signalwire_credentials['project_id'];
			$api_token = $signalwire_credentials['api_token'];

			$raw_number = format_number($owner_number);

			// Split the input on commas
			$parts = explode(',', $raw_number);

			// The first part is the actual phone number
			$owner_number = $parts[0];

			// If there are extra parts, convert them to DTMF with "w" prefix
			$extension = '';
			if (count($parts) > 1) {
			    // Remove the first element (phone number)
			    array_shift($parts);

			    // Add "w" before each DTMF part and concatenate
			    foreach ($parts as $digit) {
			        $extension .= 'w' . $digit;
			    }
			}
			
			$gete_no = format_number($from_number); // The SignalWire phone number you're sending from
			$base_url = base_url();
			$url = "https://$space_url/api/laml/2010-04-01/Accounts/$project_id/Calls.json";
			
	        // Prepare the data to send in the request
	        if(!empty($extension)){
	        	$data = [
		            'From' => $gete_no,
		            'To' => $owner_number,
		            'SendDigits' => $extension,
		            'Url' => $callbackUrl, 
		        ];
	        }
	        else{
		        $data = [
		            'From' => $gete_no,
		            'To' => $owner_number,
		            'Url' => $callbackUrl, 
		        ];
	        }
	        $response = make_curl_request("dial_new", $url, 'post', $data, $signalwire_credentials);    
            $responseData = json_decode($response, true);
            if (isset($responseData['sid'])) {
            	return $responseData['sid'];
            }	
		}
		else{
			die();
		}
	}

	function check_call_status($from_number, $callSID){
		$signalwire_credentials = get_singalwire_credentials($from_number);
		$spaceUrl = $signalwire_credentials['space_url'];
		$projectID = $signalwire_credentials['project_id'];
		$authToken = $signalwire_credentials['api_token'];
		// The Call SID for the call you want to check
		$headers = [
		    'Content-Type: application/x-www-form-urlencoded',
		];
		$data = "";
		$url = "https://$spaceUrl/api/laml/2010-04-01/Accounts/$projectID/Calls/$callSID.json";
		$response = make_curl_request("status_check", $url, "get", $data, $signalwire_credentials, $headers);
		
	    $result = json_decode($response, true);
	    if(isset($result['status'])) {
	    	return $result['status'];
	    } else {
	        echo "Unable to fetch call status.";
	    }
	}

	function check_caller_digit($key_type, $to_number, $property_id, $digit){
	
		$check = 0;
		$phone_number = caller_id_format($to_number);

		$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'cidcode' => $digit, 'property_id' => $property_id, 'key_mode' => 'uses', 'uses >' => 0]);

		$status = "Active";
		if(isset($visitor['id'])){
			$number_of_uses = $visitor['uses'] - 1;
			if($number_of_uses == 0){
				$status = "Expired";
			}
			updateTable('visitors', 
                [
                    'uses' => $number_of_uses,
                    'status' => $status,
                ], 
                'id = :id', 
                ['id' => $visitor['id']]
            );
			// update_table_data("visitors", $visitor['id'], 'uses', $number_of_uses);
			return 1;
		}
		else{
			$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'cidcode' => $digit, 'property_id' => $property_id, 'key_mode' => 'uses', 'uses >' => 0]);
			if(isset($vendor['id'])){
				$number_of_uses = $vendor['uses'] - 1;
				if($number_of_uses == 0){
					$status = "Expired";
				}
				updateTable('vendors', 
	                [
	                    'uses' => $number_of_uses,
	                    'status' => $status,
	                ], 
	                'id = :id', 
	                ['id' => $vendor['id']]
	            );
				// 		update_table_data("vendors", $vendor['id'], 'uses', $number_of_uses);
				return 1;
			}		
		}

		$today_date = date('Y-m-d');
		$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'cidcode' => $digit, 'property_id' => $property_id, 'key_mode' => 'date', 'start_date <=' => $today_date, 'end_date >=' => $today_date]);
		if(isset($visitor['id'])){
			return 1;
		}
		else{
			$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'cidcode' => $digit, 'property_id' => $property_id, 'key_mode' => 'date', 'start_date <=' => $today_date, 'end_date >=' => $today_date]);
			if(isset($vendor['id'])){
				return 1;
			}
		}

		$current_time = date('H:i:s');
		$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'cidcode' => $digit, 'property_id' => $property_id, 'key_mode' => 'time', 'start_time <=' => $current_time, 'end_time >=' => $current_time]);
		if(isset($visitor['id'])){
			return 1;
		}
		else{
			$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'cidcode' => $digit, 'property_id' => $property_id, 'key_mode' => 'time', 'start_time <=' => $current_time, 'end_time >=' => $current_time]);
			if(isset($vendor['id'])){
				return 1;
			}
		}
		
		$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'cidcode' => $digit, 'property_id' => $property_id, 'key_mode' => 'date_time', 'start_date <=' => $today_date, 'end_date >=' => $today_date, 'start_time <=' => $current_time, 'end_time >=' => $current_time]);
		if(isset($visitor['id'])){
			return 1;
		}
		else{
			$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'cidcode' => $digit, 'property_id' => $property_id, 'key_mode' => 'date_time', 'start_date <=' => $today_date, 'end_date >=' => $today_date, 'start_time <=' => $current_time, 'end_time >=' => $current_time]);
			if(isset($vendor['id'])){
				return 1;
			}
		}

		$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'cidcode' => $digit, 'property_id' => $property_id, 'key_mode' => 'schedule']);

		if(isset($visitor['id'])){
			$resp = check_schedule_access($visitor['schedule'], $current_time);
			return $resp;
		}
		else{
			$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'cidcode' => $digit, 'property_id' => $property_id, 'key_mode' => 'schedule']);
			if(isset($vendor['id'])){
				$resp = check_schedule_access($vendor['schedule'], $current_time);
				return $resp;
			}
		}

		// After checking other key modes, add this:
		// $visitor = fetchDataByOperator('visitors', [
		//     'key_type' => $key_type,
		//     'phone' => $phone_number, // or 'cidphone' for callerid+code
		//     'property_id' => $property_id,
		//     'key_mode' => 'schedule'
		// ]);

		// if (isset($visitor['id']) && isset($visitor['schedule'])) {
		// 	$schedule_id = $visitor['schedule'];
		
		// 	// Fetch all periods for this schedule
		// 	$periods = fetchData('schedule_periods', ['schedule_id' => $schedule_id]);
		// 	$now = new DateTime();
		// 	$today = strtolower($now->format('D')); // e.g., 'mon', 'tue', etc.
		
		// 	foreach ($periods as $period) {
		// 		// For each period, check if today is active
		// 		$days = fetchData('schedule_period_days', [
		// 			'period_id' => $period['id'],
		// 			'day' => $today,
		// 			'is_active' => 1
		// 		]);
		
		// 		foreach ($days as $day) {
		// 			// Handle start and end dates
		// 			$startDate = !empty($period['start_date']) ? $period['start_date'] : $now->format('Y-m-d');
		
		// 			// If end_date is empty, set it to 7 days from now
		// 			if (!empty($period['end_date'])) {
		// 				$endDate = $period['end_date'];
		// 			} else {
		// 				$endDate = (clone $now)->modify('+7 days')->format('Y-m-d');
		// 			}
		
		// 			// Build start and end datetime for today
		// 			$startDateTime = new DateTime($startDate . ' ' . $day['startTime']);
		// 			$endDateTime = new DateTime($endDate . ' ' . $day['endTime']);
		
		// 			if ($now >= $startDateTime && $now <= $endDateTime) {
		// 				// Access granted!
		// 				return 1;
		// 			}
		// 		}
		// 	}
		
		// 	// If no period matches, access denied
		// 	return 0;
		// }

		return $check;
	}

	function check_digit($call_id, $key_type, $to_number, $property_id, $digit=""){
		$check = 0;
		if($key_type == "key_code"){
			$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'key_code' => $digit, 'property_id' => $property_id, 'key_mode' => 'uses', 'uses >' => 0]);
			$status = "Active";
			if(isset($visitor['id'])){
				$number_of_uses = $visitor['uses'] - 1;
				if($number_of_uses == 0){
					$status = "Expired";
				}
				$released_by = "";
				if($visitor['creator_type'] == "admin"){
					$release = fetchDataSingle('users', ['id' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "user"){
					$release = fetchDataSingle('property_users_data', ['property_user' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "multi"){
					$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				updateTable('visitors', 
	                [
	                    'uses' => $number_of_uses,
	                    'status' => $status,
	                ], 
	                'id = :id', 
	                ['id' => $visitor['id']]
	            );

	            updateTable('call_histories', 
	                [
	                    'door_id' => $visitor['door_id'],
	                    'released_by' => $released_by,
	                ], 
	                'id = :id', 
	                ['id' => $call_id]
	            );
				// update_table_data("visitors", $visitor['id'], 'uses', $number_of_uses);
				return 1;
			}
			else{
				$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'key_code' => $digit, 'property_id' => $property_id, 'key_mode' => 'uses', 'uses >' => 0]);
				if(isset($vendor['id'])){
					$number_of_uses = $vendor['uses'] - 1;
					if($number_of_uses == 0){
						$status = "Expired";
					}
					$released_by = "";
					if($vendor['creator_type'] == "admin"){
						$release = fetchDataSingle('users', ['id' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "user"){
						$release = fetchDataSingle('property_users_data', ['property_user' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "multi"){
						$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					updateTable('vendors', 
		                [
		                    'uses' => $number_of_uses,
		                    'status' => $status,
		                ], 
		                'id = :id', 
		                ['id' => $vendor['id']]
		            );
		            updateTable('call_histories', 
		                [
		                    'door_id' => $vendor['door_id'],
		                    'released_by' => $released_by,
		                ], 
		                'id = :id', 
		                ['id' => $call_id]
	            	);
					// 		update_table_data("vendors", $vendor['id'], 'uses', $number_of_uses);
					return 1;
				}		
			}

			$today_date = date('Y-m-d');
			$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'key_code' => $digit, 'property_id' => $property_id, 'key_mode' => 'date', 'start_date <=' => $today_date, 'end_date >=' => $today_date]);
			
			if(isset($visitor['id'])){
				$released_by = "";
				if($visitor['creator_type'] == "admin"){
					$release = fetchDataSingle('users', ['id' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "user"){
					$release = fetchDataSingle('property_users_data', ['property_user' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "multi"){
					$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				updateTable('call_histories', 
	                [
	                    'door_id' => $visitor['door_id'],
	                    'released_by' => $released_by,
	                ], 
	                'id = :id', 
	                ['id' => $call_id]
            	);
				return 1;
			}
			else{
				$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'key_code' => $digit, 'property_id' => $property_id, 'key_mode' => 'date', 'start_date <=' => $today_date, 'end_date >=' => $today_date]);
				if(isset($vendor['id'])){
					$released_by = "";
					if($vendor['creator_type'] == "admin"){
						$release = fetchDataSingle('users', ['id' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "user"){
						$release = fetchDataSingle('property_users_data', ['property_user' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "multi"){
						$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					updateTable('call_histories', 
		                [
		                    'door_id' => $vendor['door_id'],
		                    'released_by' => $released_by,
		                ], 
		                'id = :id', 
		                ['id' => $call_id]
	            	);
					return 1;
				}
			}

			$current_time = date('H:i:s');
			$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'key_code' => $digit, 'property_id' => $property_id, 'key_mode' => 'time', 'start_time <=' => $current_time, 'end_time >=' => $current_time]);
			if(isset($visitor['id'])){
				$released_by = "";
				if($visitor['creator_type'] == "admin"){
					$release = fetchDataSingle('users', ['id' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "user"){
					$release = fetchDataSingle('property_users_data', ['property_user' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "multi"){
					$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				updateTable('call_histories', 
	                [
	                    'door_id' => $visitor['door_id'],
	                    'released_by' => $released_by,
	                ], 
	                'id = :id', 
	                ['id' => $call_id]
            	);
				return 1;
			}
			else{
				$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'key_code' => $digit, 'property_id' => $property_id, 'key_mode' => 'time', 'start_time <=' => $current_time, 'end_time >=' => $current_time]);
				if(isset($vendor['id'])){
					$released_by = "";
					if($vendor['creator_type'] == "admin"){
						$release = fetchDataSingle('users', ['id' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "user"){
						$release = fetchDataSingle('property_users_data', ['property_user' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "multi"){
						$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					updateTable('call_histories', 
		                [
		                    'door_id' => $vendor['door_id'],
		                    'released_by' => $released_by,
		                ], 
		                'id = :id', 
		                ['id' => $call_id]
	            	);
					return 1;
				}
			}

			$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'key_code' => $digit, 'property_id' => $property_id, 'key_mode' => 'date_time', 'start_date <=' => $today_date, 'end_date >=' => $today_date, 'start_time <=' => $current_time, 'end_time >=' => $current_time]);
			if(isset($visitor['id'])){
				$released_by = "";
				if($visitor['creator_type'] == "admin"){
					$release = fetchDataSingle('users', ['id' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "user"){
					$release = fetchDataSingle('property_users_data', ['property_user' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "multi"){
					$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				updateTable('call_histories', 
	                [
	                    'door_id' => $visitor['door_id'],
	                    'released_by' => $released_by,
	                ], 
	                'id = :id', 
	                ['id' => $call_id]
            	);
				return 1;
			}
			else{
				$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'key_code' => $digit, 'property_id' => $property_id, 'key_mode' => 'date_time', 'start_date <=' => $today_date, 'end_date >=' => $today_date, 'start_time <=' => $current_time, 'end_time >=' => $current_time]);
				if(isset($vendor['id'])){
					$released_by = "";
					if($vendor['creator_type'] == "admin"){
						$release = fetchDataSingle('users', ['id' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "user"){
						$release = fetchDataSingle('property_users_data', ['property_user' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "multi"){
						$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					updateTable('call_histories', 
		                [
		                    'door_id' => $vendor['door_id'],
		                    'released_by' => $released_by,
		                ], 
		                'id = :id', 
		                ['id' => $call_id]
	            	);
					return 1;
				}
			}

			$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'key_code' => $digit, 'property_id' => $property_id, 'key_mode' => 'schedule']);
			if(isset($visitor['id'])){
				$resp = check_schedule_access($visitor['schedule'], $current_time);
				return $resp;
			}
			else{
				$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'key_code' => $digit, 'property_id' => $property_id, 'key_mode' => 'schedule']);
				if(isset($vendor['id'])){
					$resp = check_schedule_access($vendor['schedule'], $current_time);
					return $resp;
				}	
			}
		
		}
		else if($key_type == "CallerID"){
			$phone_number = caller_id_format($digit);
			$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'phone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'uses', 'uses >' => 0]);
			if(isset($visitor['id'])){
				$number_of_uses = $visitor['uses'] - 1;
				$status = $visitor['status'];
				if($number_of_uses == 0){
					$status = "Expired";
				}
				$released_by = "";
				if($visitor['creator_type'] == "admin"){
					$release = fetchDataSingle('users', ['id' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "user"){
					$release = fetchDataSingle('property_users_data', ['property_user' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "multi"){
					$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				updateTable('visitors', 
	                [
	                    'uses' => $number_of_uses,
	                    'status' => $status,
	                ], 
	                'id = :id', 
	                ['id' => $visitor['id']]
	            );
	            updateTable('call_histories', 
	                [
	                    'door_id' => $visitor['door_id'],
	                    'released_by' => $released_by,
	                ], 
	                'id = :id', 
	                ['id' => $call_id]
            	);

				return 1;
			}
			else{
				$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'phone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'uses', 'uses >' => 0]);
				if(isset($vendor['id'])){
					$number_of_uses = $vendor['uses'] - 1;
					$status = $vendor['status'];
					if($number_of_uses == 0){
						$status = "Expired";
					}
					$released_by = "";
					if($vendor['creator_type'] == "admin"){
						$release = fetchDataSingle('users', ['id' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "user"){
						$release = fetchDataSingle('property_users_data', ['property_user' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "multi"){
						$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					updateTable('vendors', 
		                [
		                    'uses' => $number_of_uses,
		                    'status' => $status,
		                ], 
		                'id = :id', 
		                ['id' => $vendor['id']]
		            );
		            updateTable('call_histories', 
		                [
		                    'door_id' => $vendor['door_id'],
		                    'released_by' => $released_by,
		                ], 
		                'id = :id', 
		                ['id' => $call_id]
	            	);
					return 1;
				}	
			}

			$today_date = date('Y-m-d');
			$current_time = date('H:i:s');

			$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'phone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'date', 'start_date <=' => $today_date, 'end_date >=' => $today_date]);
			if(isset($visitor['id'])){
				$released_by = "";
				if($visitor['creator_type'] == "admin"){
					$release = fetchDataSingle('users', ['id' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "user"){
					$release = fetchDataSingle('property_users_data', ['property_user' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "multi"){
					$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				updateTable('call_histories', 
	                [
	                    'door_id' => $visitor['door_id'],
	                    'released_by' => $released_by,
	                ], 
	                'id = :id', 
	                ['id' => $call_id]
            	);
				return 1;
			}
			else{
				$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'phone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'date', 'start_date <=' => $today_date, 'end_date >=' => $today_date]);
				if(isset($vendor['id'])){
					$released_by = "";
					if($vendor['creator_type'] == "admin"){
						$release = fetchDataSingle('users', ['id' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "user"){
						$release = fetchDataSingle('property_users_data', ['property_user' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "multi"){
						$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					updateTable('call_histories', 
		                [
		                    'door_id' => $vendor['door_id'],
		                    'released_by' => $released_by,
		                ], 
		                'id = :id', 
		                ['id' => $call_id]
	            	);
					return 1;
				}
			}

			$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'phone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'time', 'start_time <=' => $current_time, 'end_time >=' => $current_time]);
			if(isset($visitor['id'])){
				$released_by = "";
				if($visitor['creator_type'] == "admin"){
					$release = fetchDataSingle('users', ['id' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "user"){
					$release = fetchDataSingle('property_users_data', ['property_user' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "multi"){
					$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				updateTable('call_histories', 
	                [
	                    'door_id' => $visitor['door_id'],
	                    'released_by' => $released_by,
	                ], 
	                'id = :id', 
	                ['id' => $call_id]
            	);
				return 1;
			}
			else{
				$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'phone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'time', 'start_time <=' => $current_time, 'end_time >=' => $current_time]);
				if(isset($vendor['id'])){
					$released_by = "";
					if($vendor['creator_type'] == "admin"){
						$release = fetchDataSingle('users', ['id' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "user"){
						$release = fetchDataSingle('property_users_data', ['property_user' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "multi"){
						$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					updateTable('call_histories', 
		                [
		                    'door_id' => $vendor['door_id'],
		                    'released_by' => $released_by,
		                ], 
		                'id = :id', 
		                ['id' => $call_id]
	            	);
					return 1;
				}
			}
			
			$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'phone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'date_time', 'start_date <=' => $today_date, 'end_date >=' => $today_date, 'start_time <=' => $current_time, 'end_time >=' => $current_time]);
			if(isset($visitor['id'])){
				$released_by = "";
				if($visitor['creator_type'] == "admin"){
					$release = fetchDataSingle('users', ['id' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "user"){
					$release = fetchDataSingle('property_users_data', ['property_user' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "multi"){
					$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				updateTable('call_histories', 
	                [
	                    'door_id' => $visitor['door_id'],
	                    'released_by' => $released_by,
	                ], 
	                'id = :id', 
	                ['id' => $call_id]
            	);
				return 1;
			}
			else{
				$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'phone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'date_time', 'start_date <=' => $today_date, 'end_date >=' => $today_date, 'start_time <=' => $current_time, 'end_time >=' => $current_time]);
				if(isset($vendor['id'])){
					$released_by = "";
					if($vendor['creator_type'] == "admin"){
						$release = fetchDataSingle('users', ['id' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "user"){
						$release = fetchDataSingle('property_users_data', ['property_user' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "multi"){
						$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					updateTable('call_histories', 
		                [
		                    'door_id' => $vendor['door_id'],
		                    'released_by' => $released_by,
		                ], 
		                'id = :id', 
		                ['id' => $call_id]
	            	);
					return 1;
				}
			}

			$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'phone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'schedule']);

			if(isset($visitor['id'])){
				$resp = check_schedule_access($visitor['schedule'], $current_time);
				return $resp;
			}
			else{
				$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'phone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'schedule']);

				if(isset($vendor['id'])){
					$resp = check_schedule_access($vendor['schedule'], $current_time);
					return $resp;
				}
			}
		}
		else if($key_type == "CallerID+Code"){
			$today_date = date('Y-m-d');
			$current_time = date('H:i:s');
			$phone_number = caller_id_format($digit);
			$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'uses', 'uses >' => 0]);

			if(isset($visitor['id'])){
				$released_by = "";
				if($visitor['creator_type'] == "admin"){
					$release = fetchDataSingle('users', ['id' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "user"){
					$release = fetchDataSingle('property_users_data', ['property_user' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "multi"){
					$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}	
				updateTable('call_histories', 
	                [
	                    'door_id' => $visitor['door_id'],
	                    'released_by' => $released_by,
	                ], 
	                'id = :id', 
	                ['id' => $call_id]
            	);
				return 1;
			}
			else{
				$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'uses', 'uses >' => 0]);
				if(isset($vendor['id'])){	
					$released_by = "";
					if($vendor['creator_type'] == "admin"){
						$release = fetchDataSingle('users', ['id' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "user"){
						$release = fetchDataSingle('property_users_data', ['property_user' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "multi"){
						$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					updateTable('call_histories', 
		                [
		                    'door_id' => $vendor['door_id'],
		                    'released_by' => $released_by,
		                ], 
		                'id = :id', 
		                ['id' => $call_id]
	            	);
					return 1;
				}
			}
			$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'date', 'start_date <=' => $today_date, 'end_date >=' => $today_date]);
			if(isset($visitor['id'])){
				$released_by = "";
				if($visitor['creator_type'] == "admin"){
					$release = fetchDataSingle('users', ['id' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "user"){
					$release = fetchDataSingle('property_users_data', ['property_user' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "multi"){
					$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				updateTable('call_histories', 
	                [
	                    'door_id' => $visitor['door_id'],
	                    'released_by' => $released_by,
	                ], 
	                'id = :id', 
	                ['id' => $call_id]
            	);
				return 1;
			}
			else{
				$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'date', 'start_date <=' => $today_date, 'end_date >=' => $today_date]);
				if(isset($vendor['id'])){
					$released_by = "";
					if($vendor['creator_type'] == "admin"){
						$release = fetchDataSingle('users', ['id' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "user"){
						$release = fetchDataSingle('property_users_data', ['property_user' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "multi"){
						$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					updateTable('call_histories', 
		                [
		                    'door_id' => $vendor['door_id'],
		                    'released_by' => $released_by,
		                ], 
		                'id = :id', 
		                ['id' => $call_id]
	            	);
					return 1;
				}
			}
			
			$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'time', 'start_time <=' => $current_time, 'end_time >=' => $current_time]);
			if(isset($visitor['id'])){
				$released_by = "";
				if($visitor['creator_type'] == "admin"){
					$release = fetchDataSingle('users', ['id' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "user"){
					$release = fetchDataSingle('property_users_data', ['property_user' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "multi"){
					$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				updateTable('call_histories', 
	                [
	                    'door_id' => $visitor['door_id'],
	                    'released_by' => $released_by,
	                ], 
	                'id = :id', 
	                ['id' => $call_id]
            	);
				return 1;
			}
			else{
				$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'time', 'start_time <=' => $current_time, 'end_time >=' => $current_time]);
				if(isset($vendor['id'])){
					$released_by = "";
					if($vendor['creator_type'] == "admin"){
						$release = fetchDataSingle('users', ['id' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "user"){
						$release = fetchDataSingle('property_users_data', ['property_user' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "multi"){
						$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					updateTable('call_histories', 
		                [
		                    'door_id' => $vendor['door_id'],
		                    'released_by' => $released_by,
		                ], 
		                'id = :id', 
		                ['id' => $call_id]
	            	);
					return 1;
				}
			}

			$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'date_time', 'start_date <=' => $today_date, 'end_date >=' => $today_date, 'start_time <=' => $current_time, 'end_time >=' => $current_time]);
			if(isset($visitor['id'])){
				$released_by = "";
				if($visitor['creator_type'] == "admin"){
					$release = fetchDataSingle('users', ['id' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "user"){
					$release = fetchDataSingle('property_users_data', ['property_user' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				else if($visitor['creator_type'] == "multi"){
					$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $visitor['user_assoc']]);
					if(!empty($release)){
						$released_by = $release['firstname'] . " " . $release['lastname'];
					}
				}
				updateTable('call_histories', 
	                [
	                    'door_id' => $visitor['door_id'],
	                    'released_by' => $released_by,
	                ], 
	                'id = :id', 
	                ['id' => $call_id]
            	);
				return 1;
			}
			else{
				$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'date_time', 'start_date <=' => $today_date, 'end_date >=' => $today_date, 'start_time <=' => $current_time, 'end_time >=' => $current_time]);
				if(isset($vendor['id'])){
					$released_by = "";
					if($vendor['creator_type'] == "admin"){
						$release = fetchDataSingle('users', ['id' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "user"){
						$release = fetchDataSingle('property_users_data', ['property_user' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					else if($vendor['creator_type'] == "multi"){
						$release = fetchDataSingle('multi_prop_users', ['user_assoc' => $vendor['user_assoc']]);
						if(!empty($release)){
							$released_by = $release['firstname'] . " " . $release['lastname'];
						}
					}
					updateTable('call_histories', 
		                [
		                    'door_id' => $vendor['door_id'],
		                    'released_by' => $released_by,
		                ], 
		                'id = :id', 
		                ['id' => $call_id]
	            	);
					return 1;
				}
			}	

			$visitor = fetchDataByOperator('visitors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'schedule']);
			if(isset($visitor['id'])){
				$resp = check_schedule_access($visitor['schedule'], $current_time);
				return $resp;
			}	
			else{
				$vendor = fetchDataByOperator('vendors', ['key_type' => $key_type, 'cidphone' => $phone_number, 'property_id' => $property_id, 'key_mode' => 'schedule']);
				if(isset($vendor['id'])){
					$resp = check_schedule_access($vendor['schedule'], $current_time);
					return $resp;
				}
			}
		}

		return $check;
	
	}

	function check_schedule_access($schedule_id, $current_time){
		$act = 0;
		$start_date = gmdate("Y-m-d\T00:00:00.000\Z");
		$sql = "SELECT sp.*, spd.day, spd.is_active, spd.startTime, spd.endTime FROM schedule_periods sp LEFT JOIN schedule_period_days spd ON sp.id = spd.period_id WHERE sp.schedule_id = :s_id AND sp.start_date <= :start_date AND sp.end_date >= :end_date AND spd.is_active = 1";
	    $params = [':s_id' => $schedule_id, 'start_date' => $start_date, ':end_date' => $start_date];
	    $periods = fetchDataWithJoins($sql, $params);

	    if(!empty($periods)){
	    	foreach ($periods as $period) {
	    		if((strtolower(date("D")) == strtolower($period['day'])) && (($period['startTime'] <= $current_time) &&  ($period['endTime'] >= $current_time)) ){
	    			return 1;
	    		}
	    	}
	    }
	    return $act;
	}

	function request_open_door($call_id, $open_type, $door_data, $door_key, $to_number, $flag_bit=""){
		$sg_data = get_singalwire_credentials($to_number);
		$signalwire_id = "";
		if(isset($sg_data['id']) && !empty($sg_data['id'])){
			$signalwire_id = $sg_data['id'];
		}
		$door_id = $door_data['id'];
		$base_url = base_url();
		$url = $base_url . "/include/property_builder/doors/open_door.php";
		// Initialize cURL
		$data = [
		    		'door_id' => $door_id,
		    		'signalwire_id' => $signalwire_id,
		    		'open_type' => $open_type,
		    		'call_id' => $call_id,
				];
		$response = make_curl_request("req_open_door", $url, "post", $data);
		return $response;
		// Process the response
	}

	function get_door($to_number){
		$door = fetchDataSingle('gate_doors', ['iiNumber' => $to_number, 'is_primary' => 1]);
		if(isset($door['id'])){
			return $door;
		}
		else{
			return 0;
		}
	}

	function get_call_status($from, $owner_number, $call_id, $url, $callback, $first_call_sid){
		$calll_sid = dial_new_call($from, $owner_number, $call_id, $url, $callback, $first_call_sid);
        if(!empty($calll_sid)){
            update_call($call_id, 'count_participants', 5);
        }
		for($i= 1; $i<=30; $i++){
            sleep(5);
            $status_chk = check_status($from, $calll_sid);
            if (is_array($status_chk) && isset($status_chk['error'])) {
	            // Log and/or safely show the error if needed
	            error_log("Call status fetch error: " . $status_chk['error']);
	            // You may return a general error message here if needed
	            return "error";
	        }

            if($status_chk == "failed"){
                return "failed";
            }
            else if($status_chk == "busy"){
            	return "busy";
            }
            else if($status_chk == "no-answer"){
            	return "no-answer";
            }
            else if($status_chk == "answered"){
                return "answered";
            }
            
        }
	}

	function get_number_disturb($to_number, $count_number, $call_id, $number_disturb){
		$call_flow = get_call_flow($to_number);
		if(isset($call_flow['id']) && !empty($call_flow['id'])){
			$number = "";
			$number_disturb_chk = $number_disturb . "_disturb";
			$property_id = $call_flow['property_id'];
			if((!empty($call_flow[$number_disturb])) && ($call_flow[$number_disturb_chk] == 0) ){
				$check_user_data = fetchDataSingle('property_users_data', ['mobile_number' => $call_flow[$number_disturb], 'property_id' => $property_id, 'deleted_at' => null]);
				$check_home_number = fetchDataSingle('property_users_data', ['home_number' => $call_flow[$number_disturb], 'property_id' => $property_id, 'deleted_at' => null]);
				if(isset($check_user_data['id']) && !empty($check_user_data['id'])){
					$check_disturb = fetchDataSingle('don_not_disturb', ['user_id' => $check_user_data['property_user'], 'isDontDisturb' => 1, 'property_id' => $property_id]);

					if(isset($check_disturb['id']) && !empty($check_disturb['id'])){
				 		$number = "";
				  	}
				 	else{
				 		$released_by = $check_user_data['firstname'] . " " . $check_user_data['lastname'];
				 		updateTable('call_histories', 
			                [
			                    'released_by' => $released_by,
			                ], 
			                'id = :id', 
			                ['id' => $call_id]
			            );
				 		$number = format_number($call_flow[$number_disturb]);
				 	}
				}
				else if(isset($check_home_number['id']) && !empty($check_home_number['id'])){
					$check_disturb = fetchDataSingle('don_not_disturb', ['user_id' => $check_home_number['property_user'], 'isDontDisturb' => 1, 'property_id' => $property_id]);

					if(isset($check_disturb['id']) && !empty($check_disturb['id'])){
				 		$number = "";
				  	}
				 	else{
				 		$released_by = $check_home_number['firstname'] . " " . $check_home_number['lastname'];
				 		updateTable('call_histories', 
			                [
			                    'released_by' => $released_by,
			                ], 
			                'id = :id', 
			                ['id' => $call_id]
			            );
				 		$number = format_number($call_flow[$number_disturb]);
				 	}	
				}
				else{
				  	$check_user_data_multi = fetchDataSingle('multi_prop_users', ['mobile_number' => $call_flow[$number_disturb], 'property_id' => $property_id, 'deleted_at' => null]);
				  	$check_user_data_multi_home = fetchDataSingle('multi_prop_users', ['home_number' => $call_flow[$number_disturb], 'property_id' => $property_id, 'deleted_at' => null]);
				 	if(isset($check_user_data_multi['id']) && !empty($check_user_data_multi['id'])){
						
				 		$check_disturb = fetchDataSingle('don_not_disturb', ['user_id' => $check_user_data_multi['user_assoc'], 'isDontDisturb' => 1, 'property_id' => $property_id]);

						if(isset($check_disturb['id']) && !empty($check_disturb['id'])){
					 		$number = "";
					  	}
					 	else{
					 		$released_by = $check_user_data_multi['firstname'] . " " . $check_user_data_multi['lastname'];
					 		updateTable('call_histories', 
				                [
				                    'released_by' => $released_by,
				                ], 
				                'id = :id', 
				                ['id' => $call_id]
				            );
					 		$number = format_number($call_flow[$number_disturb]);
					 	}
					}
					else if(isset($check_user_data_multi_home['id']) && !empty($check_user_data_multi_home['id'])){
					 	$check_disturb = fetchDataSingle('don_not_disturb', ['user_id' => $check_user_data_multi_home['user_assoc'], 'isDontDisturb' => 1, 'property_id' => $property_id]);

						if(isset($check_disturb['id']) && !empty($check_disturb['id'])){
					 		$number = "";
					  	}
					 	else{
					 		$released_by = $check_user_data_multi_home['firstname'] . " " . $check_user_data_multi_home['lastname'];
					 		updateTable('call_histories', 
				                [
				                    'released_by' => $released_by,
				                ], 
				                'id = :id', 
				                ['id' => $call_id]
				            );
					 		$number = format_number($call_flow[$number_disturb]);
					 	}
				 	}
				}
	        } 
	        return $number;	
		}
		
	}

	function get_cname($from_number, $to_number){
		$signalwire_credentials = get_singalwire_credentials($to_number);
		$spaceUrl = $signalwire_credentials['space_url'];
		$projectID = $signalwire_credentials['project_id'];
		$authToken = $signalwire_credentials['api_token'];

		// API URL
		$url = "https://$spaceUrl/api/relay/rest/lookup/phone_number/$from_number?include=cnam";

		$curl = curl_init();
		curl_setopt_array($curl, [
		    CURLOPT_URL => $url,
		    CURLOPT_RETURNTRANSFER => true,
		    CURLOPT_HTTPHEADER => [
		        'Authorization: Basic ' . base64_encode("$projectID:$authToken"),
		        'Content-Type: application/json',
		    ],
		]);

		$response = curl_exec($curl);

		$error = curl_error($curl);
		curl_close($curl);

		if ($error) {
		    echo "Error: $error";
		} else {
		    $result = json_decode($response, true);
		    if (isset($result['cnam']['caller_id'])) {
		        $callerId = $result['cnam']['caller_id'];
		        return $callerId;
		    } else {
		        echo "Caller ID not found in the response.";
		    }
		}
	}

	function remove_participant_from_conference($to_number, $conferenceSid, $callSid){

		// $signalwire_credentials = get_singalwire_credentials($to_number);
		// $spaceUrl = $signalwire_credentials['space_url'];
		// $accountSid = $signalwire_credentials['project_id'];
		// $authToken = $signalwire_credentials['api_token'];

		// // API endpoint
		// $url = "https://$spaceUrl/api/laml/2010-04-01/Accounts/$accountSid/Conferences/$conferenceSid/Participants/$callSid";
		// $data = "";
		// $response = make_curl_request("remove_participant", $url, "get", $data, $signalwire_credentials);

		$signalwire_credentials = get_singalwire_credentials($to_number);
		$spaceUrl = $signalwire_credentials['space_url'];
		$accountSid = $signalwire_credentials['project_id'];
		$authToken = $signalwire_credentials['api_token'];

		// API endpoint
		$url = "https://$spaceUrl/api/laml/2010-04-01/Accounts/$accountSid/Conferences/$conferenceSid/Participants/$callSid";

		// Initialize cURL
		$ch = curl_init($url);

		// Set cURL options
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_USERPWD, "$accountSid:$authToken");

		// Execute the request
		$response = curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

		// Check for errors
		if (curl_errno($ch)) {
		    echo "cURL Error: " . curl_error($ch);
		} else {
		    if ($httpCode == 204) {
		        
		    } else {
		        
		    }
		}

		// Close cURL
		curl_close($ch);
	}

	function get_end_call_time($end_time){
		$end_call_time = 0;
		$date = strtotime(date('Y-m-d H:i:s'));
		$end_call_flow_time = strtotime($end_time);
		if ($end_call_flow_time > $date) {
		    $end_call_time = $end_call_flow_time - $date;
		}
		return $end_call_time;
	}

	function block_active_number($from_number, $to_number, $body, $number){
		$get_property = fetchDataSingle('my_numbers', ['phone_number' => $to_number, 'deleted_at' => null]);
		if(isset($get_property['property_id']) && !empty($get_property['property_id'])){
			$check_number = fetchDataSingle('block_numbers', ['property_id' => $get_property['property_id'], 'formatted_number' => $from_number]);
			
			if(!isset($check_number['id']) && empty($check_number['id']) && strtoupper($body) == "STOP"){
				$tab_name = "block_numbers";
		        $tab_data = [
		        	'property_id' => $get_property['property_id'],
		            'number' => $number,
		            'formatted_number' => $from_number,
		            'type' => 'sms',
		        ];
		        insertData($tab_name, $tab_data);	
			}
		
			else if(isset($check_number['id']) && !empty($check_number['id']) && strtoupper($body) == "ACTIVE"){
				deleteData('block_numbers', 'id', $check_number['id']);
			}

			
		}
	}

	function check_block_number($from_number, $to_number){
		$property = fetchDataSingle('my_numbers', ['phone_number' => $to_number, 'deleted_at' => null]);
		if(isset($property['id']) && !empty($property['property_id'])){
			$check_balance = fetchDataSingle('property_balances', ['property_id' => $property['property_id']]);
			if((isset($check_balance['balance'])) && ($check_balance['balance'] > 0)){
				$check_toll_free = caller_id_format($from_number);
				$get_first_digits = substr($check_toll_free, 0, 3);		
				
				if(($get_first_digits != "800") && ($get_first_digits != "888") && ($get_first_digits != "877") && ($get_first_digits != "866") && ($get_first_digits != "855") && ($get_first_digits != "844") && ($get_first_digits != "833")){
					$check_number = fetchDataSingle('block_numbers', ['property_id' => $property['property_id'], 'formatted_number' => $from_number, 'type' => 'call']);
					if(isset($check_number['id']) && !empty($check_number['id'])){
						return 1;
					}
					else{
						return 0;
					}
						
				}
				else{
					return 1;
				}
			}
			else{
				return 1;
			}
		}
		else{
			return 1;
		}
	}

	function send_device_meessage($from, $to, $body){
		$data = [
		    'From' => $from,  // New TwiML URL
			'To' => $to,
			'Body' => $body
		];
		// $url = "https://invisible-87fd8abb908d.herokuapp.com/api/handle_incoming_sms";
		
		// $url = "http://135.148.121.143:3003/api/handle_incoming_sms";
		$stream_data = fetchDataSingle('stream_url');
        $sc_url = "";
        if(isset($stream_data['id']) && !empty($stream_data['stream_url'])){
            $sc_url = $stream_data['stream_url'] . "/api/handle_incoming_sms";
        }
        if(!empty($sc_url)){

			$ch = curl_init($sc_url);
			
			// Set the URL and other appropriate options
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_HTTPHEADER, [
			    'Content-Type: application/json',
			    'Accept: application/json'
			]);
			curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

			// Execute the cURL session
			$response = curl_exec($ch);
			// Check for errors
			if (curl_errno($ch)) {
				return 0;
			} else {
			
			}

			// Close the cURL session
			curl_close($ch);
        }

	}

	function check_user_call_status($call_history){
		$status = check_call_status($call_history['to_number'], $call_history['second_person_call_sid']);
		$base_url = base_url();
		if($status == "completed"){
			$sps = $call_history['call_sid'];
            $cnf_sid = $call_history['conference_sid'];
            $url = $base_url . "/signalwire_call/conference_action.php?call_id=". urlencode($call_history['id']);
            call_socket_url($sps, $url, $call_history['to_number']);
		}
		else{
			sleep(5);
			if($call_history['again_join'] == 0){
				check_user_call_status($call_history);
			}
		}
	}

	function deduct_call_cost($call_id, $property_id, $total_price){
		$total_price = (float)$total_price * 2;
		update_call($call_id, 'call_cost', $total_price);
		$get_balance = fetchDataSingle('property_balances', ['property_id' => $property_id]);
		if(isset($get_balance['id']) && !empty($get_balance['id'])){
			$remaining_balance = (float)$get_balance['balance'] - (float)$total_price;
			$update_data = [
	            'balance' => $remaining_balance,
	        ];
	        $where = 'id = :id';
	        $params = ['id' => $get_balance['id']];
	        updateTable('property_balances', $update_data, $where, $params);
		}
	}

	function deduct_message_cost($property_id, $price){
		$total_price = (float)$price * 2;
		$get_balance = fetchDataSingle('property_balances', ['property_id' => $property_id]);
		if(isset($get_balance['id']) && !empty($get_balance['id'])){
			$remaining_balance = (float)$get_balance['balance'] - (float)$total_price;
			$update_data = [
	            'balance' => $remaining_balance,
	        ];
	        $where = 'id = :id';
	        $params = ['id' => $get_balance['id']];
	        updateTable('property_balances', $update_data, $where, $params);
		}
	}

	// function check_second_person_conference(){

	// }
?>