<?php
    $totalCallDuration = 0;
    $totalCallCost = 0;
    $totalSms = 0;
    $totalSmsAmount = 0;
    function get_calls($property_id, $start_date, $end_date, $page=0, $page_token=""){
    	global $totalCallDuration, $totalCallCost;
        $sg_credentials = fetchDataSingle('signalwire_settings', ['user_id' => $property_id, 'is_property' => 1]);
		$call_array = [];
		if(isset($sg_credentials['id'])){
			$space_url = $sg_credentials['space_url'];
		    $project_id = $sg_credentials['project_id'];
		    $api_token = $sg_credentials['api_token'];

	        // SignalWire API endpoint
	        $apiUrl = "https://$space_url/api/laml/2010-04-01/Accounts/$project_id/Calls.json";

	        // Add query parameters
	        $filters = [
	            'StartTime>' => $start_date,
	            'StartTime<' => $end_date,
	            'Page' => $page,
	        ];
	        if (!empty($page_token)) {
	            $filters['PageToken'] = $page_token;
	        }

	        $queryString = http_build_query($filters);

	        // Prepare cURL
	        $ch = curl_init();
	        curl_setopt($ch, CURLOPT_URL, $apiUrl . '?' . $queryString);
	        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	        curl_setopt($ch, CURLOPT_USERPWD, "{$project_id}:{$api_token}");
	        curl_setopt($ch, CURLOPT_HTTPGET, true);

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

	        curl_close($ch);

	        // Process response
	        if ($httpStatus == 200) {
	            $data = json_decode($response, true);
	            if (isset($data['calls'])) {
	                foreach ($data['calls'] as $call) {
	                	$check_cnam = fetchDataSingle('visitor_call_data', ['call_sid' => $call['sid']]);

						if(isset($check_cnam['id']) && !empty($check_cnam['id'])){	
	                    	$totalCallCost += '0.008000' ?? 0;
						}
						if(!empty($call['duration'])){
	                    	$totalCallDuration += $call['duration'] ?? 0;
						}
						if(!empty($call['price'])){
	                    	$totalCallCost += $call['price'] ?? 0;
						}
	                }
	            }

	            // Handle pagination using `next_page_uri`
	            if (isset($data['next_page_uri']) && !empty($data['next_page_uri'])) {
	                // Extract PageToken from `next_page_uri`
	                parse_str(parse_url($data['next_page_uri'], PHP_URL_QUERY), $params);
	                if (isset($params['PageToken'])) {
	                    
	                    get_calls($property_id, $start_date, $end_date, $page + 1, $params['PageToken']); // Recursive call with the next token
	                }
	            }
	            
	        } else {
	            echo "Error: Received HTTP status code {$httpStatus}\n";
	            echo "Response: {$response}\n";
	        }
	        $call_duration = 0;
	        $unit_price = 0;
	        if($totalCallDuration != 0){
	        	$call_duration = $totalCallDuration / 60 ;
	        	$unit_price = $totalCallCost / $call_duration;
        		$call_duration = round($call_duration, 3) . " Minutes";
	        }
	        
	        $call_array['call_duration'] = $call_duration;
	        $call_array['call_amount'] = round($totalCallCost, 3);
	        $call_array['call_unit_price'] = round($unit_price, 3);
	    }
	    else{
	    	$call_array['call_duration'] = 0;
	        $call_array['call_amount'] = 0;
	        $call_array['call_unit_price'] = 0;
	    }
	    return $call_array;
    }

    function get_messages($property_id, $start_date, $end_date, $page=0, $page_token=""){
    	global $totalSms, $totalSmsAmount;
        $sg_credentials = fetchDataSingle('signalwire_settings', ['user_id' => $property_id, 'is_property' => 1]);
        $message_array = [];
		if(isset($sg_credentials['id'])){
			$space_url = $sg_credentials['space_url'];
		    $project_id = $sg_credentials['project_id'];
		    $api_token = $sg_credentials['api_token'];

	        // SignalWire API endpoint
	        $apiUrl = "https://$space_url/api/laml/2010-04-01/Accounts/$project_id/Messages.json";

	        // Add query parameters

	        $filters = [
	            'DateSent>' => $start_date,
	            'DateSent<' => $end_date,
	            'Page' => $page,
	        ];
	        if (!empty($page_token)) {
	            $filters['PageToken'] = $page_token;
	        }

	        $queryString = http_build_query($filters);

	        // Prepare cURL
	        $ch = curl_init();
	        curl_setopt($ch, CURLOPT_URL, $apiUrl . '?' . $queryString);
	        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	        curl_setopt($ch, CURLOPT_USERPWD, "{$project_id}:{$api_token}");
	        curl_setopt($ch, CURLOPT_HTTPGET, true);

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

	        curl_close($ch);

	        // Process response
	        if ($httpStatus == 200) {
	            $data = json_decode($response, true);
	            if (isset($data['messages'])) {
	                foreach ($data['messages'] as $message) {
	                	$totalSms++;
	                    $totalSmsAmount += $message['price'] ?? 0;
	                }
	            }

	            // Handle pagination using `next_page_uri`
	            if (isset($data['next_page_uri']) && !empty($data['next_page_uri'])) {
	                // Extract PageToken from `next_page_uri`
	                parse_str(parse_url($data['next_page_uri'], PHP_URL_QUERY), $params);
	                if (isset($params['PageToken'])) {
	                    
	                    get_messages($property_id, $start_date, $end_date, $page + 1, $params['PageToken']); // Recursive call with the next token
	                }
	            }
	            
	        } else {
	            echo "Error: Received HTTP status code {$httpStatus}\n";
	            echo "Response: {$response}\n";
	        }

	        $msg_unit_price = 0;
	        if($totalSms != 0 && $totalSmsAmount != 0){
	        	$msg_unit_price = $totalSmsAmount / $totalSms;
	        }

	        $message_array['total_messages'] = $totalSms;
	        $message_array['messages_amount'] = round($totalSmsAmount, 3);
	        $message_array['message_unit_amount'] = round($msg_unit_price, 3);
	    }
	    else{
	    	$message_array['total_messages'] = 0;
	        $message_array['messages_amount'] = 0;
	        $message_array['message_unit_amount'] = 0;
	    }
	    return $message_array;
    }

    function get_voice_calls_amount($property_id, $start_date="", $end_date="")
    {
  		if(!empty($start_date)){
        	$start_date = $start_date . 'T00:00:00Z';
        }
        else{
        	$start_date = date('Y-m-01') . 'T00:00:00Z';
        }
        if(!empty($end_date)){
        	$end_date = $end_date . 'T23:59:59Z';
        }
        else{
        	$end_date = date("Y-m-t") . 'T23:59:59Z';
        }
  		$datares = [];
  		$calls = get_calls($property_id, $start_date, $end_date);
  		$messages = get_messages($property_id, $start_date, $end_date);
     	$datares['calls'] = $calls;
    	$datares['messages'] = $messages;
  		return $datares;
    }



?>