<?php
class Development_Plugin_CatMultiLevelMenu_Generator extends appRain_Base_Objects{

	const ROOTID = 0;
	private $gdata = "";

	public function getRecursive()
	{
		if(!$this->getType()) return "";

		$this->createList(self::ROOTID);

		echo $this->gdata;
	}

	private function createList($id)
	{
		$cats = App::CategorySet($this->getType())->findAll("parent_id={$id} ORDER BY generic ASC");
		$Html = App::Helper('Html');

		if(!empty($cats['data']))
		{
			if($id === 0)$this->gdata .= $Html->getTag('ul',array("class"=>"dropdown","id"=>"dropdown-demo"));
			else $this->gdata .= $Html->getTag('ul');
			foreach($cats['data'] as $cat)
			{
				$this->gdata .= $Html->getTag('li');
				$this->addLink($cat);
				$this->createList($cat['id']);
				$this->gdata .= $Html->getTag('/li');
			}
			$this->gdata .= $Html->getTag('/ul');
		}
		else return ;
	}

	private function addLink($cat=null)
	{
		$attribute = ($this->getSelected() == $cat['id']) ? Array("class"=>$this->getSelectedCSSClass()): Array();

		if($url = $this->getUrlPattern())
		{
			$Html = App::Helper('Html');

			if(!$this->hasChild($cat['id']) || $this->getLinkToParent())
			{
				$url = str_replace('[id]',$cat['id'],$url);
				$url = str_replace('[title]',App::Helper('Utility')->text2Normalize($cat['title']),$url);
				$this->gdata .= $Html->linkTag($url,$cat['title'],$attribute);
			}
			else
			{
				$this->gdata .= $Html->linkTag("javascript:void(0)",$cat['title'],$attribute);
			}
		}
		else
		{
			$this->gdata .= $cat['title'];
		}
	}

	private function hasChild($id=null)
	{
		$data = App::CategorySet($this->getType())->findByParent_id($id);
		return !empty($data);
	}
}
