<?php

class mfMenuController implements Iterator {
	private $db;
	private $items;
	private $Iindex;
	private $user;
	
	
	// override mfBaseController's constructor
	public function __construct() {
		if(!defined("MFMENUTABLE")) define("MFMENUTABLE","mfMenu");
		// load logging facility
		$this->log = mfLoghandler::singleton();
		$this->db=new FronkDB();
		$this->user=mfUser::Singleton();
		$this->items=$this->loadMenu();
		
	}
	
	private function loadMenu() {
		$permgroup="";
		if($this->user->id>0) {
			$permgroup=$this->user->Permgroup;
		}	
		$menu=array();
		$res=$this->db->select(MFMENUTABLE,"*","Menuitem_Parent=0 AND Menuitem_Permgroup >= $permgroup ORDER BY Menuitem_Order");
		if($this->db->num_rows($res)) {
			while($data=$this->db->fetch_object($res)) {
				$item=new mfMenu($data);
				
				$subres=$this->db->select(MFMENUTABLE,"*","Menuitem_Parent=".$data->Menuitem_id." AND Menuitem_Permgroup >= $permgroup ORDER BY Menuitem_Order");
				if($this->db->num_rows($subres)) {
					while($subdata=$this->db->fetch_object($subres)) {
						$item->addChild(new mfMenu($subdata));
					}
				}
				$menu[]=$item;
			}		
		}
		
		return $menu;
	}
	
	// produces url for generating links
	public static function getUrl($mod,$action) {
		if(!$mod) {
			return "";
		}
		$url="?action=$mod";
		if($action) {
			$url.="_$action";
		}
		
		return $url;
	}
	
	// Iterator functions
	public function rewind() {
        $this->Iindex = 0;
    }

    public function current() {
        $k = array_keys($this->items);
        $var = $this->items[$k[$this->Iindex]];
        return $var;
    }

    public function key() {
        $k = array_keys($this->items);
        $var = $k[$this->Iindex];
        return $var;
    }

    public function next() {
        $k = array_keys($this->items);
        if (isset($k[++$this->Iindex])) {
            $var = $this->items[$k[$this->Iindex]];
            return $var;
        } else {
            return false;
        }
    }

    public function valid() {
        $k = array_keys($this->items);
        $var = isset($k[$this->Iindex]);
        return $var;
    }
}