<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

/**
 * Description of resmng_search
 *
 * @author Igor Ratsun
 */
class resmng_search extends SearchModelAbstract
{

    public function __construct()
    {
        parent::__construct();
        
        $this->load->model('ciext/core_model');
        $this->load->driver('cache', $this->config->item('cache_init_config'));
        $this->load->config('search/resmng_search_config');
    }

    public function find($search = '')
    {
        $pages = $this->getPagesList();
        if (empty($pages)) {

            return FALSE;
        }

        $items = array();
        foreach ($pages as $page) {
            
            $href = $this->core_model->create_page_url($page['alias']);
            if (rtrim($href, '/') == base_url($this->uri->uri_string())) {
                continue;
            }
            
            // Ignored page
            if (in_array(str_replace(base_url(), '/', $href), $this->config->item('ignored_pages'))) {
                continue;
            }
            
            // Load content from DB or cache
            $content = $this->loadPageContent($page['alias']);
            $title = !empty($page['seo_title']) ? $page['seo_title'] : $href;
            $tmpItem = $this->createOneSearchItem(explode(' ', $search), $href, $title, $content);
            if (!empty($tmpItem)) {
                $items[] = $tmpItem;
            }
        }

        return $items;
    }
    
    public function findInTitles($term = '')
    {
        $pages = $this->getPagesList();
        $data = array();
        foreach ($pages as $page) {
            if ($this->isStrsInContent(explode(' ', $term), mb_strtolower($page['seo_title']))) {
                $data[] = $page['seo_title'];
            }
        }
        
        return $data;
    }

    protected function getPagesList()
    {
        $this->load->library('db_lang_lib');
        $id_lan = $this->db_lang_lib->get_current_lang_id();

        $pages = $this->db
                        ->select('r.alias, rt.seo_title, rt.seo_description')
                        ->join('resource_type_page_data rt', 'rt.id_resource_type_page=r.id_resource_type_page', 'left')
                        ->where('r.active', TRUE)
                        ->where('rt.id_lan', $id_lan)
                        ->get('resource_type_page r')->result_array();

        return $pages;
    }

    protected function loadPageContent($alias = '')
    {
        $cache_key = 'search_' . url_title($alias, 'dash', TRUE);
        if (!$content = $this->cache->get($cache_key)) {
            $content = $this->clearString($this->core_model->get_page($alias));
            $this->cache->save($cache_key, $content, $this->config->item('cache_life_time'));
        }

        return $content;
    }
    
}
