<?php

abstract class SearchModelAbstract extends CI_Model
{

    /**
     * 
     * @return SearchItem[]
     */
    abstract public function find($search = '');
    
    /**
     * Find text in title for autocomplate
     * @param string $term
     * @return array
     */
    public function findInTitles($term = '')
    {
        return array();
    }

    /**
     * Find string in content
     * @param array $strs
     * @param string $content
     * @return boolean|int
     */
    public function isStrsInContent($strs = array(), $content = '')
    {
        if (!is_array($strs)) {

            return FALSE;
        }

        $findData = array();
        $el = 0;
        foreach ($strs as $str) {
            if (empty($str)) {
                continue;
            }
            $el++;
            $find = mb_strpos($content, mb_strtolower($str));
            if ($find !== FALSE) {
                $findData[] = $find;
            }
        }
        
        return ($el == count($findData)) ? $findData : FALSE;
    }

    /**
     * Clearing string
     * @param string $str
     * @return string
     */
    public function clearString($str = '')
    {
        return trim(mb_strtolower(preg_replace('/\s+/S', " ", strip_tags(preg_replace('#<style(.*?)>(.*?)</style>#is', '', preg_replace('#<script(.*?)>(.*?)</script>#is', '', $str))))));
    }

    public function createOneSearchItem($searchArray = array(), $href = '', $title = '', $description = '')
    {
        $content = $this->clearString($description);
        $find = $this->isStrsInContent($searchArray, $content);
        if (!empty($find)) {
            // Prepare content
            $content = '... ' . mb_substr($content, $find[0], 255) . ' ...';
            
            // Set bold to words
            foreach ($searchArray as $v) {
                $v = mb_strtolower($v);
                $content = str_replace($v, '<b>' . $v . '</b>', $content);
            }
            
            $item = new SearchItem();
            $item
                    ->setHref($href)
                    ->setTitle(mb_substr(trim(strip_tags($title)), 0, 64))
                    ->setDescription($content);

            return $item;
        }

        return FALSE;
    }

}
