<?php

class mfMenu {
	private $id;
	private $data;
	private $db;
	private $table=MFMENUTABLE;
	
	
	public function __construct($_=NULL) {
		$this->db=FronkDB::singleton();
		
		if(is_numeric($_)) {
			$this->fetch($_);
		} elseif(is_object($_)) {
			$this->load($_);
		}
	}
	
	public function load($row) {
		foreach($row as $field => $value) {
			if(preg_match('/^Menuitem_(.+)$/',$field,$m)) {
				$field=$m[1];
			}
			if($field=="Menuitem_id") continue;
			$this->data->$field=$value;
		}
		
		$this->id=$row->Menuitem_id;
		return true;
	}
	
	public function fetch($id) {
		$res=$this->db->select($this->table,"*","Menuitem_id=$id");
		if($this->db->num_rows($res)) {
			$data=$this->db->fetch_object($res);
			$this->load($data);
			return true;
		}
		return false;
	}
	
	public function save() {
		$fields=array();
		foreach($this->data as $field => $value) {
			$fields['Menuitem_'.$field]=$value;
		}
		
		if($this->id) {
			$id=$this->id;
			if($this->db->update($this->table,$fields,"id=$id")) {
				return $id;
			}
		} else {
			if($this->db->insert($this->table,$fields)) {
				$id=mysql_insert_id($this->db->link);
				$this->id=$id;
				return $id;
			}
		}
		return false;
	}
	
	public function delete() {
		if($this->id) {
			$id=$this->id;
			if($this->db->delete($this->table,"Menuitem_id=$id")) {
				$this->data=new stdClass();
				$this->id="";
				return true;
			}
		}
		return false;
	}
	
	public function addChild($child) {
		$this->data->Children[$child->id]=$child;
	}

	// generic functions for object-classes
	public function __toString() {
		return (string) $this->data->Name;
	}
	
	public function __get($name) {
		if(isset($this->data->$name)) {
			return $this->data->$name;
		} elseif(property_exists(__CLASS__, $name)) {
			return $this->$name;
		}
		return null;
	}
	
	public function __set($name,$value) {
		$this->data->$name=$value;
		return true;
	}
}