<?php

Class Search extends Listing {

    protected $search_term = "";

    public static function newInstance($container_id = 0) {
        return new Search($container_id);
    }

    /**
     * Search::setSearchTerm()
     *
     * Must be called after and other set... functions
     *
     * @param string search_term
     * @return Search this
     *
     */
    public function setSearchTerm($search_term) {
        // stemm
        $search_term_tmp = PorterStemmer::multi_stem(clean_page($search_term, true, true));
        if (is_array($search_term_tmp)) {
            $this->search_term = implode(' ', $search_term_tmp);

            $this->filter[] = " `searchable` = 1 ";
            $this->filter[] = "AND (";
            $this->filter[] = "MATCH(`search_title`, `search_content`) AGAINST(:search_term_against)";
            $this->filter[] = "OR";
            $this->filter[] = "`search_title` LIKE :search_term_like";
            $this->filter[] = "OR";
            $this->filter[] = "`search_content` LIKE :search_term_like";
            $this->filter[] = ")";
            $this->order[] = "`relevance` DESC"	;
            $this->select[] = "MATCH(`search_title`,`search_content`) AGAINST(:search_term_against_as_relevance) AS `relevance`";

            $this->params[":search_term_against"] = $this->search_term;
            $this->params[":search_term_like"] = "%".$this->search_term."%";
            $this->params[":search_term_against_as_relevance"] = ($_GET['filter'] ?? null);
        }
        return $this;
    }
}
