<?php
class Menu extends MY_Model
{
	const DB_TABLE = 'menus';
    const DB_TABLE_PK = 'menu_id';

    function LoadBySiteID($id)
	{
		$query = $this->db->query("SELECT * FROM menus WHERE site_id=? ORDER BY `name`", array($id));

		return $query->result();
	}

	public function build_tree($user)
	{
		$this->load->model("menuitem");

		$tree 				= new StdClass();
		$tree->menu_id 		= $this->menu_id;
		$tree->children 	= $this->_menu(null, 0, $user);
		return $tree;
	}

	private function _menu($parent_id, $level, $user)
	{
		$branches = array();
		$children = $this->menuitem->LoadByMenuID($this->menu_id, $parent_id, $user);

		foreach($children as $item)
		{
			if($item->url)
			{
				$url = $item->url;
			}
			else
			{
				if($item->url)
				{
					$url = $item->url;
				}
				else
				{
					$url = "page" . $item->page_id;
				}
			}

			$item->level = $level;
			// $item->children = $this->_menu($item->menu_item_id);
			$branches = array_merge($branches, array($item), $this->_menu($item->menu_item_id, ($level+1), $user));
		}

		return $branches;
	}
}
