<?php
	function get_calls_data($property_id, $start_date, $end_date, $page_size, $page_token, $type){
		$sg_credentials = fetchDataSingle('signalwire_settings', ['user_id' => $property_id, 'is_property' => 1]);
		if(isset($sg_credentials['id'])){ 
			$projectID = $sg_credentials['project_id'];
			$apiToken = $sg_credentials['api_token'];
			$spaceURL = $sg_credentials['space_url'];

			// Date range 
			$startDate = $start_date . 'T00:00:00Z'; // Start time in ISO 8601 format 
			$endDate = $end_date . 'T23:59:59Z'; 
			if($type == "call"){
				$apiUrl = "https://$spaceURL/api/laml/2010-04-01/Accounts/$projectID/Calls.json";
			}
			else{
				$apiUrl = "https://$spaceURL/api/laml/2010-04-01/Accounts/$projectID/Messages.json";
			}
			// SignalWire API endpoint for fetching calls 
			 

			// Prepare cURL 
			$ch = curl_init(); 
			curl_setopt($ch, CURLOPT_URL, $apiUrl); 
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
			curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
			curl_setopt($ch, CURLOPT_USERPWD, "{$projectID}:{$apiToken}"); 
			curl_setopt($ch, CURLOPT_HTTPGET, true); 

			// Add date filters 
			if(!empty($page_token)){
				if($type == "call"){
					$filters = http_build_query([ 
					    'StartTime>' => $startDate, 
					    'StartTime<' => $endDate, 
					    'Page' => $page_size,
					    'PageToken' => $page_token,
					]);	
				}
				else if($type == "message"){
					$filters = http_build_query([ 
					    'DateSent>' => $startDate, 
					    'DateSent<' => $endDate, 
					    'Page' => $page_size,
					    'PageToken' => $page_token,
					]);
				}
			}
			else{
				if($type == "call"){
					$filters = http_build_query([ 
					    'StartTime>' => $startDate, 
					    'StartTime<' => $endDate, 
					    'Page' => $page_size,
					]);	
				}
				else if($type == "message"){
					$filters = http_build_query([ 
					    'DateSent>' => $startDate, 
					    'DateSent<' => $endDate, 
					    'Page' => $page_size,
					]);
				}
			}

			curl_setopt($ch, CURLOPT_URL, $apiUrl . '?' . $filters); 

			// Execute cURL 
			$response = curl_exec($ch); 

			$httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); 

			// Check for cURL errors 
			if (curl_errno($ch)) { 
			    echo "cURL Error: " . curl_error($ch) . "\n"; 
			    curl_close($ch); 
			    exit; 
			} 

			// Close cURL handle 
			curl_close($ch); 

			// Process response 
			if ($httpStatus == 200) { 
			    $data = json_decode($response, true);
			    if(isset($data['calls']) && !empty($data['calls'])){
			    	$caller_number = "";
			    	$caller_cnam = "";
			    	$is_ban = 0;
			    	$ban_id = "";
				    foreach ($data['calls'] as &$d) {
						$check_cnam = fetchDataSingle('visitor_call_data', ['call_sid' => $d['sid']]);
						if($caller_number != $d['from']){
							$caller_check = fetchDataSingle('visitor_call_data', ['visitor_number' => $d['from']]);
							if(isset($caller_check['id']) && !empty($caller_check['id'])){
								$caller_cnam = $caller_check['cnam'];
							}
							else{
								$caller_cnam = "";	
							}
							$check_ban = fetchDataSingle('block_numbers', ['formatted_number' => $d['from'], 'type' => 'call']);
							if(isset($check_ban['id']) && !empty($check_ban['id'])){
								$is_ban = 1;
								$ban_id = $check_ban['id'];
							}
							else{
								$is_ban = 0;
								$ban_id = 0;	
							}
							
						}
						$d['is_ban'] = $is_ban;
						$d['ban_id'] = $ban_id;
						$d['caller_cnam'] = $caller_cnam;
						if(isset($check_cnam['id']) && !empty($check_cnam['id'])){
							$d['cnam'] = 1;
						}
						else{
							$d['cnam'] = 0;
						}		    	
				    }
				    unset($d);
			    }
			    else if(isset($data['messages']) && !empty($data['messages'])){
			    	$caller_number = "";
			    	$caller_cnam = "";
			    	$is_ban = 0;
			    	$ban_id = "";
				    foreach ($data['messages'] as &$d) {
						if($caller_number != $d['from']){
							$caller_check = fetchDataSingle('visitor_call_data', ['visitor_number' => $d['from']]);
							if(isset($caller_check['id']) && !empty($caller_check['id'])){
								$caller_cnam = $caller_check['cnam'];
							}
							else{
								$caller_cnam = "";	
							}
							$check_ban = fetchDataSingle('block_numbers', ['formatted_number' => $d['from'], 'type' => 'sms']);
							if(isset($check_ban['id']) && !empty($check_ban['id'])){
								$is_ban = 1;
								$ban_id = $check_ban['id'];
							}
							else{
								$is_ban = 0;
								$ban_id = 0;	
							}
						}
						$d['is_ban'] = $is_ban;
						$d['ban_id'] = $ban_id;
						$d['caller_cnam'] = $caller_cnam;	    	
				    }
			    }
			    return $data;
			} else { 
			    echo "Error: Received HTTP status code {$httpStatus}\n"; 
			    echo "Response: {$response}\n"; 
			} 
		}

	}

	function save_block($property_id, $type, $name, $number, $formatted_number){
		$tab_name = "block_numbers";
		$user_id = $_SESSION['userid'];
        $tab_data = [
            'property_id' => $property_id,
            'name' => $name,
            'number' => $number,
            'formatted_number' => $formatted_number,
            'created_by' => $user_id,
            'type' => $type,
        ];
        insertData($tab_name, $tab_data);
        return 1;
	}

	function get_block_data($type){
		$sql = "SELECT bn.*, u.firstname, u.lastname, p.name as property_name FROM block_numbers bn LEFT JOIN users u ON bn.created_by = u.id LEFT JOIN properties p ON bn.property_id = p.id WHERE bn.type = :type";
        $params = [':type' => $type];
        $block_numbers = fetchDataWithJoins($sql, $params);
        return $block_numbers;
	}

	function remove_block_number($type, $number_id){
		$delete_number = deleteData('block_numbers', 'id', $number_id);
		if($delete_number){
			return 1;
		}
		else{
			return 0;
		}
	}

	function get_snapshot_data($property_id){
		$sql = "SELECT hs.*, c.from_number, c.to_number, c.cnam, c.released_by FROM hardwares_settings_events hs LEFT JOIN call_histories c ON hs.call_id = c.id WHERE hs.property_id = :property_id";
        $params = [':property_id' => $property_id];
        $snap_data = fetchDataWithJoins($sql, $params);
		return array_reverse($snap_data);
	}


?>