<?php

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

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

    public function findInTitles($term = '')
    {
        $items = $this->db->
                        select('p.name')->
                        join('resource_type_page rp', 'rp.id_resource_type_page=p.id_resource_type_page', 'left')->
                        where('rp.active', true)->
                        like('p.name', $term)->
                        get('product p')->result_array();

        return array_column($items, 'name');
    }

    public function find($search = '')
    {
        if (empty($search)) {

            return FALSE;
        }

        $likes = explode(' ', $search);

        if (empty($likes)) {

            return FALSE;
        }
        
        $like = '';
        foreach ($likes as $v) {
            $like .= ' OR LOWER(p.name) LIKE ' . $this->db->escape('%' . mb_strtolower($v) . '%');
        }
        $like = '(' . ltrim($like, ' OR ') . ')';

        $q = $this->db->
                        select('rp.alias, p.name, p.description')->
                        join('resource_type_page rp', 'rp.id_resource_type_page=p.id_resource_type_page', 'left')->
                        where('rp.active', true)->
                        where($like)->
                        get('product p')->result_array();

        $items = array();
        foreach ($q as $page) {
            $tmpItem = $this->createOneSearchItem($likes, $this->core_model->create_page_url($page['alias']), $page['name'], $page['description'] . $page['name']);
            if (!empty($tmpItem)) {
                $items[] = $tmpItem;
            }
        }
     
        if (!empty($items)) {
            $this->set_ignored_page_for_resmng();
        }

        return $items;
    }
    
    protected function set_ignored_page_for_resmng()
    {
        $items = $this->db->
                        select('CONCAT("/", rp.alias) as alias', false)->
                        join('resource_type_page rp', 'rp.id_resource_type_page=p.id_resource_type_page', 'left')->
                        where('rp.active', true)->
                        get('product p')->result_array();
        
        $this->config->load('search/resmng_search_config');
        $this->config->set_item('ignored_pages', array_merge($this->config->item('ignored_pages'), array_column($items, 'alias')));
        
        return $this;
    }

}
