<?php


class Search
{

    private $CI;


    public function __construct($params = [])
    {
        $this->CI = &get_instance();
    }

    public function searchByPostTitle($postTitle, $limit, $exception = [], $activeQ = false)
    {
        $titleSegments = [];
        foreach (explode(' ', $postTitle) as $k => $t) {
            if (mb_strlen($t, 'utf-8') > ($activeQ ? 1 : 3)) array_push($titleSegments, $this->clean($t));
        }
        $this->CI->db
            ->join('cm_post_tag t', 'p.postID=t.postID', 'left')
            ->from('cm_post p');
        foreach ($titleSegments as $k => $t) {
            !$k ? $this->CI->db->like('postTitle', $t) : $this->CI->db->or_like('postTitle', $t);
            $this->CI->db->or_like('tag', $t);
        }
        if ($activeQ) {
            return $this->CI->db;
        } else {
            $rows = $this->CI->db->limit($limit + count($exception))
                ->get()->result();
            return array_filter($rows, function ($row) use ($exception) {
                if ($exception && count($exception)) {
                    $duplicated = false;
                    foreach ($exception as $ex) {
                        $duplicated = $row->postID == $ex;
                    }
                    return !$duplicated;
                }
                return true;
            });
        }
    }

    private function clean($string)
    {
        return trim(preg_replace('/[^\x{1100}-\x{11FF}\x{3130}-\x{318F}\x{AC00}-\x{D7AF}0-9a-zA-Z\s]/u', "", $string));
    }
}