<?php

namespace App\Model;

use Str;

trait Searchable
{
    public function scopeSearch($query, $q)
    {
        // ignore 2 chars words, otherwise search doesn't work (due mysql full search word length)
        $q_words = collect(explode(' ', $q))->filter(function ($item) {
            return strlen($item) > 2;
        });

        if ($q_words->count()) {
            $q = $q_words->implode(' ');
        }

        $q = '+' . Str::slug($q, ' +'); // we can have str_repeat()
//        dump($q);
        return $query
            ->selectRaw("MATCH(search) AGAINST(? IN BOOLEAN MODE) AS relevance, articles.*", array($q))
//            ->whereRaw("MATCH(search) AGAINST(? IN BOOLEAN MODE) >= 0.001", array($q))
            ->whereRaw("MATCH(search) AGAINST(? IN BOOLEAN MODE) >= 0.05", array($q))
            ->orderByDesc('relevance');

        return $query->whereRaw("MATCH(search) AGAINST(? IN BOOLEAN MODE)", array($q));
    }

    public function scopeSearchOld($query, $q)
    {
        $q = '+' . Str::slug($q, ' +'); // we can have str_repeat()
        $query->whereRaw("MATCH(search) AGAINST(? IN BOOLEAN MODE)", array($q));
    }
}
