<?php

/**
 * Generated: 2014-03-24 15:01:35
 * @author Rtn_Module_Tool
 */
class Bip_Controller_IndexController extends Eppe_Frontend_Controller_Action {

	public function indexAction() {
		$this->_setLayout('bip-layout');
		if($this->_getParam('id') != ':id'){
			$category = R::findOne('category', 'id = ?', [$this->_getParam('id')]);
			$pages = R::find('viewbipintems', 
				'category_id = ? AND active = ? AND current = ? AND hidden = ? ORDER BY `data` DESC' ,
				[$this->_getParam('id'), 1, 1, 0] );
		}else{
			
			$category = null;
			$pages = null;
			$this->view->showMain = true;
		}
		$this->view->category = $category;
		$this->view->pages = $pages;
	}
	
	public function showAction(){
		$this->_setLayout('bip-layout');
		$category = R::findOne('category', 'id = ?', [$this->_getParam('catid')]);
		$page = R::findOne('viewbipintems', 
			'id = ? AND active = ?',
			[$this->_getParam('id'), 1] );
		$this->view->category = $category;
		$this->view->page = $page;
	}
	
	public function searchAction(){
		$this->_setLayout('bip-layout');
		$keyword = $this->_getParam('search');
		$this->_saveSearch($keyword);
		$this->view->keyword = $keyword;
		 $results = R::find('biparticle', "`current` = 1 AND `active` = 1 AND MATCH (title,body) AGAINST ('$keyword' IN NATURAL LANGUAGE MODE ) > 0.99");
		if(count($results) == 0){
			$results = R::find('biparticle', "`current` = 1 AND `active` = 1 AND MATCH (title,body) AGAINST ('$keyword' IN BOOLEAN MODE)");
		}
		$this->view->results = $results;
	}
	
	private function _saveSearch($keyword){
		$bean = R::dispense('bipsearched');
		$bean->keyword = $keyword;
		$bean->ip = $this->_getIp();
		$bean->data = date('Y-m-d H:i:s');
		R::store($bean);
	}
	
	private function _getIp(){
		$server = $this->getRequest()->getServer();
		if (!empty($server['HTTP_CLIENT_IP'])) {
			$ip = $server['HTTP_CLIENT_IP'];
		} elseif (!empty($server['HTTP_X_FORWARDED_FOR'])) {
			$ip = $server['HTTP_X_FORWARDED_FOR'];
		} else {
			$ip = $server['REMOTE_ADDR'];
		}
		return $ip;
	}


	public function widgetSearchAction() {
                $form = new Bip_Form_Search();
                $this->view->form = $form;
        }

}
