<?php

class ProductsController extends AppController {

	public $uses = array('Category', 'Product');
	public $components = array('Paginator');

	public function index($product_id = null){
		if( is_null($product_id) || !(int)$product_id || !$this->Product->exists($product_id) ){
			throw new NotFoundException('Такой странцы нет...');
		}

		$product = $this->Product->find('first', array(
			'conditions' => array('Product.id' => $product_id)
		));
		$this->set(compact('product'));
	}

	public function admin_add($category_id = null){
		if($this->request->is('post')){
			// debug($this->request->data);
			$this->Product->create();
			$data = $this->request->data['Product'];
			if(!$data['img']['name']){
				unset($data['img']);
			}
			if($this->Product->save($data)){
				$this->Session->setFlash('Товар добавлен', 'default', array('class' => 'ok'));
				return $this->redirect($this->referer());
			}else{
				$this->Session->setFlash('Ошибка!', 'default', array('class' => 'error'));
			}
		}

		$cats = $this->Category->find('threaded', array(
			'fields' => array('id', 'title', 'parent_id')
		));
		$categories = $this->_catsSelect($cats, $category_id);
		$this->set(compact('categories'));
	}

	public function admin_edit($product_id = null){
		if( is_null($product_id) || !(int)$product_id ){
			throw new NotFoundException('Такой странцы нет...');
		}
		$product = $this->Product->findById($product_id);
		if( !$product ){
			throw new NotFoundException('Такой странцы нет...');	
		}
		
		if($this->request->is(array('post', 'put'))){
			$this->Product->id = $product_id;
			if($this->Product->save($this->request->data)){
				$this->Session->setFlash('Сохранено', 'default', array('class' => 'ok'));
				return $this->redirect($this->referer());
			}else{
				$this->Session->setFlash('Ошибка!', 'default', array('class' => 'error'));
			}
		}

		if(!$this->request->data){
			$this->request->data = $product;
			// $categories = $this->Product->Category->find('list');
			$cats = $this->Category->find('threaded', array(
				'fields' => array('id', 'title', 'parent_id')
			));
			$categories = $this->_catsSelect($cats, $product['Category']['id']);
		}
		$this->set(compact('product', 'categories'));
	}

	public function admin_delete($id){
		if ($this->request->is('get')) {
			throw new MethodNotAllowedException();
		}
		if($this->Product->delete($id)){
			$this->Session->setFlash('Товар удален', 'default', array('class' => 'ok'));
		}else{
			$this->Session->setFlash('Ошибка', 'default', array('class' => 'error'));
		}
		return $this->redirect($this->referer());
	}

	public function search(){
		$search = !empty($_GET['q']) ? $_GET['q'] : null;

		// получаем корневые категории
			$cats = $this->Category->find('all', array(
				'conditions' => array(
					'parent_id' => 0
				)
			));
		$cats_menu_sidebar = $this->_catsMenuSidebar($cats, $cat_id = 0);
		$cats_menu_sidebar[$cat_id][$cat_id] = 'Каталог';

		if( is_null($search) ){
			$search_res = 'Введите поисковый запрос...';
			return $this->set(compact('search_res', 'cats_menu_sidebar', 'cat_id'));
		}

		$this->Paginator->settings = array(
			'conditions' => array('Product.title LIKE' => '%' . $search . '%'),
			'fields' => array('id', 'title', 'price', 'img'),
			'recursive' => -1,
			'limit' => 3
		);
		$search_res = $this->Paginator->paginate('Product');

		$this->set(compact('search_res', 'cats_menu_sidebar', 'cat_id'));
	}

	protected function _catsSelect($cats, $category_id, $tab = ''){
		$string = '';
		foreach($cats as $item){
			$string .= $this->_catsSelectTemplate($item, $category_id, $tab);
		}
		return $string;
	}

	protected function _catsSelectTemplate($category, $category_id, $tab){
		ob_start();
		include APP . "View/Elements/cats_select_tpl.ctp";
		return ob_get_clean();
	}

	protected function _catsMenuSidebar($cats, $cat_id){
		$data = array();
		foreach($cats as $item){
			if($item['Category']['id'] == $cat_id){
				$data[$cat_id][$cat_id] = $item['Category']['title'];
			}
			if($item['Category']['parent_id'] == $cat_id){
				$data[$cat_id]['Children'][$item['Category']['id']] = $item['Category']['title'];
			}
		}
		return $data;
	}

}