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

}