<?php
	require_once('call_flow_functions.php');
	header('Content-Type: application/xml; charset=UTF-8');
	
	// Sanitize user inputs
	$call_id = htmlspecialchars($_REQUEST['call_id'] ?? '', ENT_QUOTES, 'UTF-8');
	$digit = htmlspecialchars($_REQUEST['Digits'] ?? '', ENT_QUOTES, 'UTF-8');

	// Fetch data from the database
	$call_history = fetch_table_data('call_histories', 'id', $call_id);
	$to_number = htmlspecialchars(format_number($call_history['to_number'] ?? ''), ENT_QUOTES, 'UTF-8');
	$call_flow = get_call_flow($to_number);

	// Base URL sanitization
	$base_url = htmlspecialchars(base_url(), ENT_QUOTES, 'UTF-8');
	// $get_door = get_door($to_number);
	$get_door = fetchDataSingle('gate_doors', ['iiNumber' => $to_number, 'door_key' => $digit]);
	
	$is_door_key = 0;
    if (isset($get_door['id'])) {
    	$is_door_key = 1;
        // $door_key = htmlspecialchars($get_door['door_key'], ENT_QUOTES, 'UTF-8');
    }
	// Start the response
	echo '<?xml version="1.0" encoding="UTF-8"?>';

	// Update the call history with the received digit
	// Handle the "*" digit case
	if ($digit === '*') {
		echo "<Response>
			<Redirect>check_stream.php?call_id=$call_id</Redirect>
		</Response>";
	}
	else if($is_door_key == 0){
		echo "<Response>
			<Say>Your door key is wrong</Say>
			<Redirect>check_stream.php?call_id=$call_id</Redirect>
		</Response>";
	}
	else {
		update_call($call_id, 'stream_digit', $digit);
		update_call($call_id, 'door_id', $get_door['id']);
		// Fetch and sanitize call history details
		$pressed_digit = $call_history['pressed_digit'] ?? 0;

		$end_call_time = htmlspecialchars($call_flow['end_call_time'] ?? '60', ENT_QUOTES, 'UTF-8');

		// Update the call history
		update_call($call_id, 'stream_digit', 1);
		update_call($call_id, 'pressed_digit', 1);

		$check_status = check_call_status($call_history['to_number'], $call_history['call_sid']);
		if($check_status == "completed"){
			$message_say = $base_url . "/signalwire_call/message_say.php?call_id=". urlencode($call_id);
			echo "<Response>
                    <Redirect>$message_say</Redirect>
            	</Response>";
		}
		else{
			// Secure the conference name
			$conference_name = 'MyConference_' . preg_replace('/[^a-zA-Z0-9_\-]/', '', $call_id); // Strip any non-alphanumeric characters

			// Output the TwiML response with sanitized data
			echo "<Response>
				<Dial timeLimit='$end_call_time'>
					<Conference maxParticipants='4' startConferenceOnEnter='true'
						endConferenceOnExit='false' beep='false'
						statusCallback='" . htmlspecialchars($base_url . '/signalwire_call/conference_connect.php?call_id=' . $call_id, ENT_QUOTES, 'UTF-8') . "'
						statusCallbackEvent='start end join leave'>
						$conference_name
					</Conference>
				</Dial>
			</Response>";
		}
	}
?>
	