<?php
	require_once('call_flow_functions.php');
	header('Content-Type: application/xml; charset=UTF-8');
	$message_url = "/shared/serve_audios.php?path=";
	echo '<?xml version="1.0" encoding="UTF-8"?>';

	// Sanitize input
	$call_id = htmlspecialchars($_REQUEST['call_id'] ?? '', ENT_QUOTES, 'UTF-8');
	$call_id_safe = preg_replace('/[^a-zA-Z0-9_\-]/', '', $call_id);

	$call_history = fetch_table_data('call_histories', 'id', $call_id_safe);
	$to_number = format_number($call_history['to_number']) ?? '';
	$from_number = format_number($call_history['from_number']) ?? '';
	$base_url = htmlspecialchars(base_url(), ENT_QUOTES, 'UTF-8');

	$call_flow = get_call_flow($to_number);
	$connected_message = "";

	if (($call_history['is_access_granted'] ?? 0) == 0) {
		$connected_message = defalt_voice_message("access_denied.wav");

		if (($call_flow['id'] ?? false) && ($call_flow['is_connected_hangeup_default_message'] == 0)) {
			if ($call_flow['is_connected_hangeup_message'] == 1) {
				$connected_hang_up_message = $call_flow['is_connected_hangeup_textto_speech'];
				if ($connected_hang_up_message == 0) {
					$connected_hang_message = $message_url . $call_flow['connected_hangeup_audio_file'];
					$connected_hang_message = urlencode($connected_hang_message);
					$connected_message = "<Play>$connected_hang_message</Play>";
				} else {
					$connected_hang_text = htmlspecialchars($call_flow['connected_hangeup_text'], ENT_QUOTES, 'UTF-8');
					$connected_hangup_vocie_select = htmlspecialchars($call_flow['connected_hangup_vocie_select'], ENT_QUOTES, 'UTF-8');
					$connected_message = "<Say voice='" . $connected_hangup_vocie_select . "'>$connected_hang_text</Say>";
				}
			} else {
				$connected_message = "";
			}
		}
	}

	echo "<Response>
		$connected_message
		<Hangup/>
	</Response>";

	if(empty($call_history['call_cost']) || $call_history['call_cost'] == 0){
		
		$first_call_sid = $call_history['call_sid'];
		$secons_call_sid = $call_history['second_person_call_sid'];
		$first_sip_sid = $call_history['first_sip_sid'];
		$second_sip_sid = $call_history['second_sip_sid'];

		$price1 = 0;
		$price2 = 0;
		$price3 = 0;
		$price4 = 0;
		if(!empty($first_call_sid)){
			$price1 = check_status($to_number, $first_call_sid, 'price');
		}
		if(!empty($secons_call_sid)){
			$price2 = check_status($to_number, $secons_call_sid, 'price');
		}
		if(!empty($first_sip_sid)){
			$price3 = check_status($to_number, $first_sip_sid, 'price');
		}
		if(!empty($second_sip_sid)){
			$price4 = check_status($to_number, $second_sip_sid, 'price');
		}

		$total_price = (float)$price1 + (float)$price2 + (float)$price3 + (float)$price4;

		$deduct_cost = deduct_call_cost($call_id_safe, $call_history['property_id'], $total_price);
	}

?>
