<?php

class CategoriesController extends AppController {

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

	public function admin_index($cat_id = null){
		$this->index($cat_id);
	}

	public function admin_add(){
		if($this->request->is('post')){
			$this->Category->create();
			if($this->Category->save($this->request->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, 0);
		$this->set(compact('categories'));
	}

	public function admin_edit($category_id = null){
		if( is_null($category_id) || !(int)$category_id ){
			throw new NotFoundException('Такой страницы нет...');
		}
		$category = $this->Category->findById($category_id);
		if( !$category ){
			throw new NotFoundException('Такой странцы нет...');	
		}
		
		if($this->request->is(array('post', 'put'))){
			$this->Category->id = $category_id;
			if($this->request->data['Category']['parent_id'] != $category_id){
				// если выбрана категория из списка
				if($this->Category->save($this->request->data)){
					$this->Session->setFlash('Сохранено', 'default', array('class' => 'ok'));
					return $this->redirect($this->referer());
				}
			}else{
				// если изменилось только название
				if($this->Category->saveField('title', $this->request->data['Category']['title'], true)){
					$this->Session->setFlash('Сохранено', 'default', array('class' => 'ok'));
					return $this->redirect($this->referer());
				}
			}
			$this->Session->setFlash('Ошибка', 'default', array('class' => 'error'));
		}

		$this->request->data = $category;
		$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_delete($category_id){
		if ($this->request->is('get')) {
			throw new MethodNotAllowedException();
		}
		if( is_null($category_id) || !(int)$category_id ){
			throw new NotFoundException('Такой страницы нет...');
		}
		
		$cats = $this->Category->find('first', array(
			'conditions' => array('parent_id' => $category_id)
		));
		if($cats){
			$this->Session->setFlash('Ошибка! Нельзя удалить категорию в которой есть подкатегории', 'default', array('class' => 'error'));
			return $this->redirect($this->referer());
		}

		$products = $this->Product->find('first', array(
			'conditions' => array('category_id' => $category_id)
		));
		if($products){
			$this->Session->setFlash('Ошибка! Нельзя удалить категорию в которой есть товары', 'default', array('class' => 'error'));
			return $this->redirect($this->referer());
		}

		if($this->Category->delete($category_id)){
			$this->Session->setFlash('Категория удалена', 'default', array('class' => 'ok'));
			return $this->redirect('/admin/');
		}else{
			$this->Session->setFlash('Ошибка', 'default', array('class' => 'error'));
		}
	}

	public function index($cat_id = null){
		if( is_null($cat_id) ){
			// все товары категории
			$this->Paginator->settings = array(
				'fields' => array('id', 'title', 'price', 'img'),
				'recursive' => -1,
				'limit' => 3
			);
			$products = $this->Paginator->paginate('Product');
			// получаем корневые категории
			$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] = 'Каталог';
			return $this->set(compact('products', 'cats_menu_sidebar', 'cat_id'));
		}
		if( !(int)$cat_id || !$this->Category->exists($cat_id) ){
			// 404
			throw new NotFoundException('Такой страницы нет...');
		}

		$cats = $this->Category->find('all');
		$ids = $this->_catsIds($cats, $cat_id);
		$ids = !$ids ? $cat_id : $ids . $cat_id;
		$ids = explode(",", $ids);
		$this->Paginator->settings = array(
			'conditions' => array("Product.category_id" => $ids),
			'fields' => array('id', 'title', 'price', 'img'),
			'recursive' => -1,
			'limit' => 3
		);
		$products = $this->Paginator->paginate('Product');
		// получаем 1 уровень дочерних категорий
		$cats_menu_sidebar = $this->_catsMenuSidebar($cats, $cat_id);
		return $this->set(compact('products', 'cats_menu_sidebar', 'cat_id'));
	}

	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;
	}

	protected function _catsIds($cats, $cat_id){
		$data = '';
		foreach($cats as $item){
			if($item['Category']['parent_id'] == $cat_id){
				$data .= $item['Category']['id'] . ',';
				$data .= $this->_catsIds($cats, $item['Category']['id']);
			}
		}
		return $data;
	}

	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();
	}

}