<?php


const ZENSERP_KEY = 'df2de800-cc3e-11f0-b9ec-8b29b34f37e2';
const RESULTS_HASH_KEY = "rsoc_search_results";
const SERP_HOST = '127.0.0.1';
const SERP_PORT = '22135';

function getZenSerpResult($query, $start = 0, $num = 10, $page = 1) {
    
    $redis = new Redis();
    if ($redis->pconnect( SERP_HOST, SERP_PORT )){
        $zenserpStart = ($page) * $num;
        $key = 'q='.urlencode($query).'&page='.$zenserpStart;
        $response = $redis->hget(RESULTS_HASH_KEY, $key);
        if ($response)
            $data = json_decode($response, true);
        if (empty($data)) {
            $query = urlencode($query);
            $url = "https://app.zenserp.com/api/v2/search?apikey=".ZENSERP_KEY."&q=$query&start=$start&num=$num";
            $curl = curl_init();
        
            // Set cURL options
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
            if (defined('CURLOPT_TCP_FASTOPEN')) {
                curl_setopt($curl, CURLOPT_TCP_FASTOPEN, 1);  // Only set this option if it is defined
            }            
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_ENCODING, '');
            curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
            curl_setopt($curl, CURLOPT_TIMEOUT, 0);
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
        
            // Execute the request and fetch response
            $response = curl_exec($curl);
            curl_close($curl);
            // Check for errors
            if ($response === false)
            return ["size" => 0, "data" => []];
            else 
            $redis->hset(RESULTS_HASH_KEY, $key, $response);
        }
    }

    $data = json_decode($response, true);

    $organic = $data["organic"];
            
    $result = [];
    $result["size"] = $data["number_of_results"];
    $result["data"] = [];
    foreach($organic as $item) {
        if(isset($item["title"]) && isset($item["url"]) && isset($item["description"]))
            $result["data"][] = ["title" => $item["title"], "url" => $item["url"], "description" => $item["description"]];
    }
    return $result;
}