<?php

class Search extends Controller {

	function Search()
	{
		parent::Controller();
		$this->load->helper('url');
		$this->load->model('Functions');
		$this->load->model('Dbmysql');
		$this->config->load('katalog_config');
		$this->data = $this->config->item('data');
		$this->data['itemsPerPage'] = 10;
		$this->data['controller'] = 'search';
		$this->output->cache((24-date("H"))*60 -(60-date("i")));
	}

	function AsciiToHex($ascii)
	{
		$hex = '';
		for($i = 0; $i < strlen($ascii); $i++)
			$hex .= str_pad(base_convert(ord($ascii[$i]), 10, 16), 2, '0', STR_PAD_LEFT);
	return $hex;
	}

	function HexToAscii($hex)
	{
		$ascii = '';
		if (strlen($hex) % 2 == 1)
			$hex = '0'.$hex;
		for($i = 0; $i < strlen($hex); $i += 2)
			$ascii .= chr(base_convert(substr($hex, $i, 2), 16, 10));
		return $ascii;
	}

	function index()
	{
		$uriQ = $this->uri->segment(2);
		$this->data['aktPage'] = (int)$this->uri->segment(3);
		$od = ($this->data['aktPage'] * $this->data['itemsPerPage']);
		if(!empty($_POST['q']))
		{
			$_POST = $this->Functions->htmlarrayspecialchars($_POST);
			header('HTTP/1.0 301 Moved Permanently');
			header('Location: /'.$this->data['controller'].'/'.$this->Functions->MakeCool($_POST['q']).'-'.$this->AsciiToHex($_POST['q']).'/');
			exit;
		}
		elseif(!empty($uriQ))
		{
			$tmpQ = explode("-", $uriQ);
			$qString = $this->Dbmysql->escape_string($this->HexToAscii($tmpQ[count($tmpQ)-1]));
			$this->data['description'] = $qString;
			$this->data['title'] = $qString;
			$this->data['h1'] = '<span class="normal">'.$this->data['words'][32].':</span> "'.$qString.'"';
			$this->data['keywords'] = $qString;
			$query = $this->Dbmysql->db->query("SELECT SQL_CALC_FOUND_ROWS(firma.id), firma.* FROM firma WHERE 
			  status = 1 AND
				MATCH(nazev) AGAINST ('".$qString."' IN BOOLEAN MODE)
				OR MATCH(popis) AGAINST ('".$qString."' IN BOOLEAN MODE)
				OR MATCH(obec) AGAINST ('".$qString."' IN BOOLEAN MODE)
				OR MATCH(ico) AGAINST ('".$qString."' IN BOOLEAN MODE)
				ORDER BY MATCH(nazev) AGAINST ('".$qString."' IN BOOLEAN MODE) DESC
				LIMIT ".$od.", ".$this->data['itemsPerPage']);
			$this->data['result'] = $query->result();
			$query = $this->Dbmysql->db->query('SELECT FOUND_ROWS() as pocet');
			$this->data['pocet'] = $query->result_array();
			$this->data['celkPocet'] = $this->data['pocet'][0]['pocet'];
			$this->data['start'] = $this->data['aktPage'] - 5;
			if($this->data['start'] < 0)$this->data['start'] = 0;
			$this->data['pocetStranok'] = ceil($this->data['celkPocet'] / $this->data['itemsPerPage']);
			$this->data['do'] = $this->data['itemsPerPage'] + $this->data['start'];
			if($this->data['do'] > $this->data['pocetStranok'])$this->data['do'] = $this->data['pocetStranok'];
		}
		$this->load->view('search', $this->data);
	}

}
?>
