<?php
/**
 * Oct8ne Doofinder Search
 *
 * @author Oct8ne
 * @version 1.0.0
 */

require_once ("basesearch.php");

class DoofinderSearchOct8ne extends Oct8neBaseSearch {

    public function getEngineName() {
        return "Doofinder";
    }

    public function search() {
        $result = array();
        $result["results"] = [];
        $filterInfo = array();
        $filterInfo["applied"] = array();
        $filterInfo["available"] = array();

        $search = isset($_GET["search"]) ? $_GET["search"] : "";
        $locale = isset($_GET["locale"]) ? $_GET["locale"] : "en"; // Default to English if not set
        $orderby = isset($_GET["orderby"]) ? $_GET["orderby"] : "relevance";
        $dir = isset($_GET["dir"]) ? $_GET["dir"] : "ASC";
        $page = isset($_GET["page"]) ? intval($_GET["page"]) : 1;
        $pageSize = isset($_GET["pageSize"]) ? intval($_GET["pageSize"]) : 10;

        if (empty($search)) {
            return $result;
        }

        $doofinderResult = $this->executeDoofinderSearchQuery($search, $orderby, $dir, $page, $pageSize, $locale);
        
        if (isset($doofinderResult['result']) && is_array($doofinderResult['result'])) {
            $connector = new Oct8neConnector();
            foreach ($doofinderResult['result'] as $item) {
                if (isset($item['id_product'])) {
                    $product_id = intval($item['id_product']);
                    $productData = $connector->getProductData($product_id, $locale);
                    if ($productData) {
                        $result["results"][] = $productData;
                    }
                }
            }
            $result["total"] = isset($doofinderResult['total']) ? intval($doofinderResult['total']) : 0;
        } else {
            $result["total"] = 0;
        }

        $result["filters"] = $filterInfo;            

        if(isset($doofinderResult['error'])){
            $result["error"] = $doofinderResult['error'];
        }

        return $result;
    }

    private function executeDoofinderSearchQuery($searchTerm, $searchOrder, $searchDir, $page, $pageSize, $locale) {
        $lang_code = substr($locale, 0, 2);
        $get_lang_option = function($name) use ($lang_code) {
            $val = get_option($name . '_' . $lang_code);
            return !empty($val) ? $val : get_option($name);
        };
        $hashId = $get_lang_option('oct8ne_doofinder_hash_id');
        $apiKey         = $get_lang_option('oct8ne_doofinder_api_key');
        $searchZone     = $get_lang_option('oct8ne_doofinder_search_zone');
        if(empty($searchZone)) $searchZone = 'eu1';

        $queryName      = $get_lang_option('oct8ne_doofinder_query_name');
        if(empty($queryName)) $queryName = 'match_and';

        $indices        = $get_lang_option('oct8ne_doofinder_indices');
        
        $idPropertyConf = $get_lang_option('oct8ne_doofinder_productid_property');
        if(empty($idPropertyConf)) $idPropertyConf = 'id';

        if(!isset($hashId) || !isset($apiKey) || $hashId == "" || $apiKey == ""){
            return array('total' => 0, 'result' => array(), 'error' => 'HashId or ApiKey not set for lang ' . $lang_code);
        }            

        $url = "https://{$searchZone}-search.doofinder.com/6/{$hashId}/_search";
        $host = str_replace("##zone##", $searchZone, $url);

        $sortLabel = "_score";
        $queryParams = array(
            'rpp' => $pageSize,
            'page' => $page,
            'query' => $searchTerm,
        );

        if ($sortLabel != "_score") {
            $queryParams['sort[' . $sortLabel . ']'] = $searchDir;
        } elseif ($sortLabel == "_score" && $searchDir == "desc") {
            $queryParams['sort[' . $sortLabel . ']'] = 'desc';
        }

        if ($queryName != "none") {
            $queryParams['query_name'] = $queryName;
        }

        if ($indices && !is_null($indices) && $indices != "") {
            $multipleIndices = explode(",", $indices);
            foreach ($multipleIndices as $pos => $index) {
                $queryParams['indices[' . $pos . ']'] = $index;
            }
        }

        $query = $host . '?' . http_build_query($queryParams);
        $request = curl_init($query);

        curl_setopt($request, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($request, CURLOPT_RETURNTRANSFER, 1);

        $headers = array(
            'Authorization: Token ' . $apiKey,
            'Content-Type: application/json',
            'Expect:',
        );

        curl_setopt($request, CURLOPT_HTTPHEADER, $headers);

        $response = curl_exec($request);
        $err = curl_error($request);
        $result = null;
        if (is_null($err) || $err == "") {
            $result = json_decode($response, true);
            if (is_null($result)) {
                curl_close($request);
                return array('total' => 0, 'result' => array());
            }
        } else {
            curl_close($request);
            return array('total' => 0, 'result' => array());
        }
        curl_close($request);
        if (!is_null($result) && isset($result["results"])) {
            $products = array();
            foreach ($result["results"] as $item) {
                $idProperty = explode(",", $idPropertyConf);
                foreach ($idProperty as $value) {
                    $value = trim($value);
                    if (isset($item[$value]) && $item[$value] != "") {
                        $products[] = array('id_product' => $item[$value]);
                        break;
                    }
                }
            }
            return array('total' => $result["total"], 'result' => $products);
        }
        return array('total' => 0, 'result' => array());
    }
}
?>