<?php

use MtcPharmacy\Multisite\Classes\MultisiteConstants;
use MtcPharmacy\Multisite\Classes\MultisiteManager;

$path = '../../';
include_once($path . 'core/includes/header.inc.php');

$term = str_replace(' ', '%', $_REQUEST['term']);
$search_terms = [trim(str_replace(['-', '/'], ' ', $_REQUEST['term']))];

$categories = \Mtc\Shop\Category::query()
    ->active()
    ->where('hide', 0)
    ->where('deleted', 0)
    ->where('name', 'like', "%{$term}%")->take(10)
    ->get()
    ->map(function ($category) {
        $category->url = $category->is_online_doctor ? $category->getDoctorLink() :  browse_url($category->id);
        return $category;
    });

$brands = \Mtc\Shop\Brand::query()
    ->active()
    ->where('hide', 0)
    ->where('deleted', 0)
    ->where('name', 'like', "%{$term}%")->take(10)
    ->get()
    ->map(function ($brand) {
        $brand->url = browse_url(0, $brand->id);
        return $brand;
    });

$products_query = \Mtc\Shop\Item::query()
    ->where('hidden', 0)
    ->where('deleted', 0)
    ->where(function ($query) use ($term) {
        $query
            ->where('name', 'like', "% {$term}%")
            ->orWhere('name', 'like', "{$term}%");
    })
    ->with(['images', 'sizes'])
    ->orderBy('num_sold', 'desc')
    ->take(10)
    ->selectRaw('items.*')
;

MultisiteManager::decorateQueryBaseOnly($products_query, MultisiteConstants::ENTITY_TYPE_SHOP_ITEM);

$products = $products_query
    ->get()
    ->map(function ($item) {
        $temp_item = new Item();
        $temp_item->Get_Item($item->id, true, true);
        $item->url = $temp_item->url;
        $default_image = $item->images->where('default', 1)->first();
        $item->image = THEME_URL . '/images/placeholders/no-image.jpg';

        if ($default_image) {
            $item_image = '/uploads/images/products/smallthumbs/' . $default_image->name;
            if (file_exists(SITE_PATH . $item_image)) {
                $item->image = $item_image;
            }
        }


        $size = $item->sizes->first();
        if ($size) {
            $item->rating = $size->trustpilot_average_rating;
            $item->stars = floor($size->trustpilot_average_rating);
        }

        $item->price = $item->from_price;


        //Use last category
        $last_category_name = '';
        $last_category = $item->categories->toArray();

        if(!empty($last_category)) {
            $last_category = $last_category[count($last_category) - 1];

            if(!empty($last_category['name'])) {
                $last_category_name = $last_category['name'];
            }
        }

        $item->category_name = $last_category_name;

        $item->setVisible([
            'price',
            'name',
            'id',
            'url',
            'image',
            'no_sizes',
            'rating',
            'stars',
            'category_name'
        ]);

        return $item;
    });

$search_lister = Search::newInstance()
    ->setLimit(10)                      // set number of articles (pages) per one pagination page
    ->setSearchTerm($term)
    ->setCurrentPage(1)     // pass page number (its safe to pass unset vars)
    ->run();                            // before getting anything - one needs to "run()" this whole setup

$search_lister->getListing();

$pages = collect($search_lister->list);

$pages = $pages->reject(function($page){

    return $page->template == 'faqs_question.twig';

});

/*
 * FAQS
*/


$faqs = \App\SearchHelper::getFAQPagesByTerm($term);


if(!empty($_REQUEST['faqs_only'])) {

    $response = [
        'status'     => 'ok',
        'faqs'       => $faqs,
        'browse_url' => (new ProductFilter())->generateURL(['search_add' => $search_terms])
    ];

}else{

    $response = [
        'status'     => 'ok',
        'categories' => $categories,
        'products'   => $products,
        'pages'      => $pages,
        'brands'     => $brands,
        'faqs'       => $faqs,
        'browse_url' => (new ProductFilter())->generateURL(['search_add' => $search_terms])
    ];

}

header('Content-Type: application/json');
echo json_encode($response);
die();
