<?php

require_once('View.php');

class SearchView extends View {
	
	function fetch(){
		$keyword = $this->request->get('keyword', 'string');
		
		$this->db->query('SELECT * FROM __categories
	                    WHERE name LIKE "%'.mysql_real_escape_string($keyword).'%" AND visible=1 ORDER BY name');
		$cats = $this->db->results();
		$cats = $cats ? $this->_setHeader($cats, 'Разделы') : array();
		foreach($cats as $product) if(isset($product->url)) $product->url = '/catalog/' . $product->url . '/';
		
		
		$products = $this->products->get_products(array('keyword'=>$keyword));
		$products = $products ? $this->_setHeader($products, 'Товары') : array();
		foreach($products as $product) if(isset($product->url)) $product->url = '/products/' . $product->url . '/';
		
		$articles = $this->articles->get_articles(array('keyword'=>$keyword));
		$articles = $articles ? $this->_setHeader($articles, 'Выполненные работы') : array();
		foreach($articles as $article) if(isset($article->url)) $article->url = '/article/' . $article->url . '/';
		
		$pages = $this->pages->get_pages(array('keyword'=>$keyword, 'menu_id'=>3));
		$pages = $pages ? $this->_setHeader($pages, 'Услуги') : array();
		foreach($pages as $page) if(isset($page->url)) $page->url = $page->parentUrl . $page->url . '/';
		
		$items = array_merge($pages, $cats, $products, $articles);
		
		foreach($items as $item){
			if(!isset($item->name)) continue;
			$item->name = $this->_highlight($item->name, $keyword);
			$item->annotation = !empty($item->annotation) ? $this->_highlight($item->annotation, $keyword) : $this->_highlight($item->name, $keyword);
		}
		
		$no_results = count($items) ? '' : 'По вашему запросу ничего не найдено.';
		
		$this->design->assign('items', $items);
		$this->design->assign('no_results', $no_results);
		
		$this->design->assign('meta_title', 'Поиск по сайту');
		$this->design->assign('meta_keywords', 'Для быстрого перехода, предлагаем воспользоваться поиском по сайту atomicgarage.1gb.ru.');
		$this->design->assign('meta_description', 'поиск, по сайту, найти, товар, atomicgarage.1gb.ru');
		
		return $this->design->fetch('search.tpl');
	}
	
	function _setHeader($items, $header){
		if($items) array_unshift($items,   (object)array('_header' => $header) );
		return $items;
	}
	
	function _highlight($text, $key){
		$keys = explode(' ', $key);
		foreach($keys as $word){
			if(mb_strlen($word, 'utf-8') > 1){
				$text = str_ireplace($word, '<span style="background:#595611">' . $word . '</span>', $text);
			}
		}  
		return $text;
	}
}