<?php
$loader = $this->registry->get('load');
$loader->controller('product/productDefault');

class ControllerProductSearch extends ControllerProductDefault {

    public function index($setting = null) {

		$this->language->load('product/search');

		parent::index();

		$this->loadscripts();

		$filterData = parent::setFilterData();

		if (isset($filterData['search']) && (!empty($filterData['search']))) {
            //seta os cookies para o historico da pesquisa e grava a contagem

            if (isset($_COOKIE['search_terms'])) {
                $search_terms = json_decode(urldecode($_COOKIE['search_terms']));
            } else {
                $search_terms = array();
            }

            if((!in_array($filterData['search'], $search_terms))){
                $this->load->dmodel('catalog/searchterms');
                $this->dmodel_catalog_searchterms->addSearchTerm(array('term' => $filterData['search']));
            }

			$data = array($filterData['search']);
			if (isset($_COOKIE['search_terms'])) {
                array_unshift($search_terms, $filterData['search']);
				$data = array_slice(array_unique(array_merge(array_filter($search_terms))),0,5);
			}

			ftr_geral::setCookie('search_terms', $data);
    }

		if (isset($filterData['search']) && (!empty($filterData['search']))) {
			$this->document->setTitle($filterData['search']);
		} elseif(isset($filterData['tag']) && ($filterData['tag']!='')) {
			$this->document->setTitle($filterData['tag']);
		}else{
			$this->document->setTitle($this->language->get('heading_title'));
		}

		$this->document->addScript(array(
			'catalog/view/theme/vista/js/page.search.js'
		));

		$this->document->addScript('catalog/view/javascript/jquery/jquery.total-storage.min.js');

		$this->data['wg24_seo_fer_facebook_status'] = $this->config->get('wg24_seo_fer_facebook_status');
		$this->data['wg24_seo_fer_facebook_pixel'] = $this->config->get('wg24_seo_fer_facebook_pixel');

		$this->data['text_critea'] = $this->language->get('text_critea');
		$this->data['entry_search'] = $this->language->get('entry_search');
		$this->data['text_category'] = $this->language->get('text_category');
		$this->data['button_search'] = $this->language->get('button_search');
		$this->data['text_search'] = $this->language->get('text_search');
		$this->data['text_empty'] = $this->language->get('text_empty');

		$this->data['t_result']   = $this->language->get('t_result');
		$this->data['t_results']   = $this->language->get('t_results');
		$this->data['t_order_by']   = $this->language->get('t_order_by');
		$this->data['t_result_not_found']   = $this->language->get('t_result_not_found');

		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home','','NONSSL','false'),
			'separator' => false
		);

		$this->breadcrumbs->setbreadcumbs($this->data['breadcrumbs']);

		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('product/search', parent::getUrlParameters(['search' => ($filterData['search'])])),
			'separator' => $this->language->get('text_separator')
		);

		$this->breadcrumbs->setbreadcumbs($this->data['breadcrumbs']);

		if (isset($filterData['search'])) {
			$this->data['heading_title'] = $filterData['search'];
		} else {
			$this->data['heading_title'] = $this->language->get('heading_title');
		}

		$this->data['categories'] = array();

		$categories_1 = $this->model_catalog_category->getCategories(0);

		foreach ($categories_1 as $category_1) {
			$level_2_data = array();

			$categories_2 = $this->model_catalog_category->getCategories($category_1['category_id']);

			foreach ($categories_2 as $category_2) {
				$level_3_data = array();

				$categories_3 = $this->model_catalog_category->getCategories($category_2['category_id']);

				foreach ($categories_3 as $category_3) {
					$level_3_data[] = array(
						'category_id' => $category_3['category_id'],
						'name'        => $category_3['name'],
					);
				}

				$level_2_data[] = array(
					'category_id' => $category_2['category_id'],
					'name'        => $category_2['name'],
					'children'    => $level_3_data
				);
			}

			$this->data['categories'][] = array(
				'category_id' => $category_1['category_id'],
				'name'        => $category_1['name'],
				'children'    => $level_2_data
			);
		}

		$dataPagination = array (
			'total' => $this->model_catalog_product->getTotalProducts(parent::getFilterData()),
			'page'	=> $filterData['page'],
			'limit'	=> $filterData['limit'],
			'text'	=> $this->language->get('text_pagination')
		);

		//validação feita para funcionar com a configuração de paginação pelo botão
		$this->data['status_aviseme'] = $this->config->get('avise_me_status');
        if(($this->config->get('config_pagination_type') && ($this->config->get('config_pagination_type') == Type_Pagination::Tp_More)) || $this->ftrgeralregistry->isApp()){
            $dataPagination['url']        = $this->url->link('product/productList/defaultList', parent::getUrlParameters(['search' => $filterData['search'], 'page'=> '{page}', 'sort'=> $filterData['sort'],'order'=> $filterData['order']]), 'NONSSL', 'true', false, false) ;
            $this->data['pagination']     = json_encode(parent::getPagination($dataPagination, true), JSON_HEX_APOS);
            $this->data['paginationajax'] = true ;

            if($this->ftrgeralregistry->isApp()){
                $this->document->addScriptApp(array('catalog/view/theme/appmobile/js/page.pagination.js'));
            }else{
                $this->document->addscript('catalog/view/theme/vista/js/page.pagination.js');
            }

        }else{
            $dataPagination['url']        = $this->url->link('product/search', parent::getUrlParameters(['search' => $filterData['search'], 'page'=> '{page}','sort'=> $filterData['sort'],'order'=> $filterData['order'] ])) ;
			$this->data['pagination']     = parent::getPagination($dataPagination);
            $this->data['paginationajax'] = false ;
        }

		$this->data['totalProduct'] = $dataPagination['total']; // Criado para o app

		$sortower = array(
		'text'  => $this->language->get('text_default'),
		'value' => 'score-DESC',
		'href'  => $this->url->link('product/search', parent::getUrlParameters([null, 'sort' => 'score', 'order' => 'DESC']))
		);

        $sortList = parent::getSortList('product/search', parent::getUrlParameters( ['search' => $filterData['search']] ));
        array_unshift($sortList, $sortower);

        $this->data['sorts']        = $sortList;
		$this->data['limits']       = parent::getLimits('product/search', ['page'=> '{page}']);
		$this->data['search']       = $filterData['search'] ;
		$this->data['category_id']  = $filterData['category_id'];
		$this->data['sort'] 	    = parent::getSort();
		$this->data['order']        = parent::getOrder();
		$this->data['sortorder']    = parent::getSort() . '-' . parent::getOrder(); // esta sendo usado no app
		$this->data['limit']   		= $filterData['limit'];

		$this->template = parent::getTemplate('product/search.tpl');

		if (!empty($this->request->get['search']) || !empty($this->request->get['tag']) || (!empty($this->request->get['category_id']) && $this->request->get['category_id'] > 0)) {
	  	    $this->children = parent::getChildren('product/productList/defaultList');
		}else{
			$this->children = parent::getChildren();
			$this->data['defaultList']    = '';
			$this->data['error_criterio'] = 'Adicione um critério de busca';
		}

		$url= '';

		if(isset($this->request->get['route'])){
			$url .= 'route2=' . $this->request->get['route'] ;
		}

		if(isset($this->request->get['search'])){
			$url .= '&search=' . $this->request->get['search'] ;
		}

		$this->data['url'] = $url;//'route2=' . $this->request->get['route'] . '&search=' . $this->request->get['search'];

		$this->response->setOutput($this->render('product/search'));

	}





	public function getSearchSuggestion() {

		$json = array();

		if (isset($this->request->get['search'])) {
			$search = $this->request->get['search'];
		} else {
			$json['error']['search'] = 'Pesquisa invalida';
		}

		if (!$json) {

			$this->load->model('catalog/product');
			$this->load->dmodel('tool/image');

			$products = array();

			$data = array(
				'filter_name' => $search,
				'sort'				=> 'score',
				'order'				=> 'DESC',
				'start'				=> 0,
        'limit' 			=> 5,
        'filter_content'=> (ftr_geral::isIsset($this->config->get('config_setting_search_name'))) ? $this->config->get('config_setting_search_name') : Type_FilterContent::Tp_Default
			);

			$results = $this->model_catalog_product->getProducts($data);

			foreach ($results as $key => $result) {
				$image = '';
				if ($result['image']) {
					$image = $this->dmodel_tool_image->resize($result['image'], 50, 50);
					$image .= '?version='.md5($image);
				} else {
					$image = $this->dmodel_tool_image->resize('data/sem-imagem.png', 50, 50);
				}

				$products[] = array(
					'name'  => $result['name'],
					'href'  =>  $this->url->link('product/product', '&product_id='.$result['product_id'] , 'SSL'),
					'image' => $image
				);
			}

			$json['products'] = $products;

		}

		$this->response->setOutputJson($json);

	}





	public function getSortList($url, $urlParam = null){
    $result[] = array(
      'text'  => $this->language->get('text_default'),
      'value' => 'score-DESC',
      'href'  => $this->url->link($url, $this->getUrlParameters([$urlParam, 'sort' => 'score', 'order' => 'DESC']))
    );

    $result[] = array(
      'text'  => $this->language->get('text_price_asc'),
      'value' => 'p.price-ASC',
      'href'  => $this->url->link($url, $this->getUrlParameters([$urlParam, 'sort' => 'p.price', 'order' => 'ASC']))
    );

    $result[] = array(
      'text'  => $this->language->get('text_price_desc'),
      'value' => 'p.price-DESC',
      'href'  => $this->url->link($url, $this->getUrlParameters([$urlParam, 'sort' => 'p.price', 'order' => 'DESC']))
    );

    return $result;
  }

	public function loadscripts() {
		$this->document->addScript('catalog/view/theme/vista/js/filter.js');
	}
}
