<?php
/**
 * Oct8ne
 *
 * @author      Oct8ne
 * @version     1.2.6
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

require_once ("basesearch.php");

class FiboSearchOct8ne extends Oct8neBaseSearch
{
    public function getEngineName()
    {
        return "FiboSearch";
    }

    public function search(){

        $result = array();
        $result["results"] = [];
        $args = array();
        
        $filterInfo = array();
        $filterInfo["applied"] = array();
        $filterInfo["available"] = array();

        $search = isset($_GET["search"]) ? sanitize_text_field($_GET["search"]) : '';
        $locale = isset($_GET["locale"]) ? sanitize_text_field($_GET["locale"]) : '';

        if (!isset($search) || empty($search)) return $result;
        $orderby = isset($_GET["orderby"]) ? sanitize_text_field($_GET["orderby"]) : '';
        switch ($orderby) {
            case "relevance":
                $args["orderby"] = "relevance";
                break;
            case "name":
                $args["orderby"] = "title";
                break;
            case "price":
                $args["orderby"] = "meta_value_num";
                $args["meta_key"] = "_price"; 
                break;
            default:
                $args["orderby"] = "relevance";
                break;
        }
        $page = isset($_GET["page"]) ? absint($_GET["page"]) : 1;
        $pagesize = isset($_GET["pageSize"]) ? absint($_GET["pageSize"]) : 10;
        
        $args["per_page"] = $pagesize;
        $args["page"] = $page;
        $args["post_type"] = "product";
        $args["fields"] = "ids";  
        try {
            $lang_code = !empty($locale) ? explode("-", $locale)[0] : '';
            if ($lang_code) {
                $args['_wpml_lang'] = $lang_code; 
                $args['lang'] = $lang_code;       
            }
        } catch(Exception $e) {}         
        if (strpos($search, '#') === 0) { 
             $sku = preg_replace('/#/', '', $search, 1);
             $id = $this->get_product_by_sku($sku);
             if ( $id ) {
                $connector = new Oct8neConnector();
                $result["results"][] =  $connector->getProductData($id, $locale);
                $result["total"] = 1;
                $result["filters"] = $filterInfo;
            }

        } else { 
            
            if ( is_null( $this->search ) ) {
                $this->search = new \DgoraWcas\Search();
            }

            $myposts =  $this->search->searchPosts( $search, $args );

            if ( empty($myposts["results"]) || $myposts["total"] === 0 ) {
                
                $sku_id = $this->get_product_by_sku($search);

                if ($sku_id && $sku_id > 0) {
                    $hide_stock_global = get_option( 'woocommerce_hide_out_of_stock_items', 'no' );
                    $product_stock_status = get_post_meta($sku_id, '_stock_status', true);

                    if ( !($hide_stock_global === 'yes' && $product_stock_status === 'outofstock') ) {
                        $myposts["results"][] = $sku_id;
                        $myposts["total"] = 1;
                    }
                }
            }
            // -------------------------------------------

            $count = isset($myposts["total"]) ? $myposts["total"] : 0;
            $result["total"] = $count;

            $connector = new Oct8neConnector();
            
            if (!empty($myposts["results"])) {
                foreach ($myposts["results"] as $post) {
                    $result["results"][] = $connector->getProductData($post, $locale);          
                }
            }

            $result["filters"] = $filterInfo;
        }
        return $result;
    }
    
    public function get_product_by_sku ($sku) {
        if ( function_exists( 'wc_get_product_id_by_sku' ) ) {
            return wc_get_product_id_by_sku( $sku );
        }
        return 0;  
    }
}