<?php

namespace Yajny\Controller;

use App\Http\Controllers\Controller;
use DB;
use Spatie\Searchable\ModelSearchAspect;
use Spatie\Searchable\Search;

class SearchCtrl extends Controller
{

    public static function doSearch($keyword,$search_for)
    {


        $search =  (new Search());

        if($search_for=='all' || $search_for =='store_cat' )
            $search->registerModel(\Yajny\Models\Category::class, function(ModelSearchAspect $modelSearchAspect) {
                $modelSearchAspect
                    ->addSearchableAttribute('name')
                    ->addExactSearchableAttribute('name');
            });

        if($search_for=='all' || $search_for =='store' )
            $search->registerModel(\Yajny\Models\Store::class, function(ModelSearchAspect $modelSearchAspect) {
                $modelSearchAspect
                    ->addSearchableAttribute('name')
                    ->addExactSearchableAttribute('name');

                if (request('region') and request('region')!="global") {
                    $regionCode = request('region');
                    $modelSearchAspect->whereJsonContains('region_code', $regionCode);
                }
            });

        if($search_for=='all' || $search_for =='brand' )
            $search->registerModel(\Yajny\Models\Brand::class, function(ModelSearchAspect $modelSearchAspect) {
                $modelSearchAspect
                    ->addSearchableAttribute('name')
                    ->addExactSearchableAttribute('name');
            });

        if($search_for=='all' || $search_for =='tag' )
            $search->registerModel(\Yajny\Models\Tag::class, function(ModelSearchAspect $modelSearchAspect) {
                $modelSearchAspect
                    ->addSearchableAttribute('name')
                    ->addExactSearchableAttribute('name');
            });

        if($search_for=='all' || $search_for =='coupon' )
            $search->registerModel(\Yajny\Models\Coupon::class, function(ModelSearchAspect $modelSearchAspect) {
                $modelSearchAspect
                    ->addSearchableAttribute('title')
                    ->addExactSearchableAttribute('title');

                if (request('region') and request('region')!="global") {
                    $regionCode = request('region');
                    $modelSearchAspect->whereJsonContains('region_code', $regionCode);
                }
            });

        if($search_for=='all' || $search_for =='cat' )
            $search->registerModel(\Yajny\Models\CategoryCoupon::class, function(ModelSearchAspect $modelSearchAspect) {
                $modelSearchAspect
                    ->addSearchableAttribute('name')
                    ->addExactSearchableAttribute('name');
            });

        return $search->search($keyword);
    }
}



