<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

class menu_level_main extends ModuleTools
{
	public function __construct($level=null)
	{
		self::_setTpl('menu');
		//значение по умолчанию
		if (!config::get('menu_level')) config::set('menu_level', 1);
		
		$parent=array_key_exists((config::get('menu_level')-1), LabCMS::i()->parents)
			?LabCMS::i()->parents[(config::get('menu_level')-1)]
			:$parent=LabCMS::i()->id;
		
		if (LabCMS::i()->is_cached(self::_getTpl(), -1, LabCMS::i()->id)) return;
		
		$menu = Db::i()->select(
			"-- CACHE: 24h
			SELECT name,t.tree_id, path, external, symlink
			FROM ?_tree t
			WHERE parent_id=? AND menu=1
			ORDER BY pos", $parent
		);

		foreach ($menu as $key=>$m) {
			if (isset(LabCMS::i()->parents[config::get('menu_level')])
				&& $m["tree_id"] == LabCMS::i()->parents[config::get('menu_level')])
			$menu[$key]["active"]=1;
		}
		
		$this->_checkLinks($menu);
		
		self::_assign('menu', $menu);
	}
	
	protected function _checkLinks(&$data)
	{
		$symlynks=array();
		foreach ($data as $key=>$val) {
			if ($val['symlink']) $symlynks[]=$val['symlink'];
		}

		if (count($symlynks)) {
			$result = Db::i()->select(
				"SELECT t.tree_id AS ARRAY_KEY, path, external, symlink
				FROM ?_tree t
				WHERE tree_id IN (?a)", $symlynks
			);
			
			foreach ($data as $key=>$val) {
				if ($val['symlink'] && $result[$val['symlink']]) {
					$tgt=$result[$val['symlink']];
					$data[$key]['symlink']=$tgt['symlink'];
					$data[$key]['path']=$tgt['path'];
					$data[$key]['external']=$tgt['external'];
				} elseif ($val['symlink']) {
					$data[$key]['symlink']=0;
				}
			}
			$this->_checkLinks($data);
		}
	}
}