<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * This class extends renders OSB menu tree.
 *
 * @package    lnApp
 * @subpackage Tree
 * @category   Controllers
 * @author     Deon George
 * @copyright  (c) 2010 Open Source Billing
 * @license    http://dev.osbill.net/license.html
 */
class Controller_Tree extends Controller_lnApp_Tree {
	protected $auth_required = TRUE;

	/**
	 * Draw the Tree Menu
	 *
	 * The incoming ID is either a Branch B_x or a Node N_x
	 * Where X is actually the module.
	 *
	 * @param id
	 */
	public function action_json($id=null,array $data=array()) {
		// Get the user details
		$id = (is_null($id) && isset($_REQUEST['id'])) ? substr($_REQUEST['id'],2) : $id;
		$user = Auth::instance()->get_user();

		if (! $id) {
			$modules = array();
			foreach ($user->groups() as $go)
				$modules = array_merge($modules,Module_Method::groupmodules($go->id));

			ksort($modules);

			$data = array();
			foreach ($modules as $module => $details)
				if (! $details['parent_id'])
					array_push($data,
						array('id'=>$details['id'],'name'=>$module,'state'=>'closed')
					);

		} else {
			$module = preg_replace('/^N_/','',$id);
			$methods = array();
			foreach ($user->groups() as $go)
				$methods = array_merge($methods,Module_Method::groupmethods($go->id,$module));

			ksort($methods);

			$data = array();
			foreach ($methods as $method => $details) {
				if (preg_match('/_/',$method)) {
					list($mode,$action) = explode('_',$method);
					$url = URL::site(sprintf('/%s/%s/%s',$mode,$details['module'],$action));
				} else {
					$url = URL::site(sprintf('/%s/%s',$details['module'],$method));
				}
				
				array_push($data,array(
					'id'=>sprintf('%s_%s',$module,$details['id']),
					'name'=>$method,
					'state'=>'none',
					'attr_id'=>sprintf('%s_%s',$module,$details['id']),
					'attr_href'=>(empty($details['page']) ? $url : $details['page'])
				));
			}
		}

		$this->output = array();

		foreach ($data as $branch) {
			array_push($this->output,array(
				'attr'=>array('id'=>sprintf('B_%s',$branch['id'])),
				'state'=>$branch['state'],
				'data'=>array('title'=>$branch['name']),
				'attr'=>array('id'=>sprintf('N_%s',$branch['id']),'href'=>empty($branch['attr_href']) ? URL::site(sprintf('/%s/menu',$branch['name'])) : $branch['attr_href']),
				)
			);
		}

		return parent::action_json($id,$data);
	}
}
?>