<?php

class menu extends cData {

	public $pluginName, $pluginMenuTitle, $tables, $joins, $rights, $order, 
		$perPage, $insertText, $urlLink, $moduleType, $childClass;

	function __construct($oDb, $oUrl, $oSession, $action) {
		$this->pluginName = "Menu on website";
		$this->pluginMenuTitle = "Menu";
		$this->tables = Array (
			Array(
				"name" => "menu"
			)
		);
		$this->joins = Array();
		$this->order = "id_parent ASC, position ASC";
		$this->perPage = 30;
		$this->insertText = "Add menu item";
		$this->urlLink = "menu";
		$this->moduleType = "class";
		$this->childClass = __CLASS__;
		parent::__construct($oDb, $oUrl, $oSession, $action);
	}
	
	final function validateData($array) {
		try { 
		} catch (Exception $e) {
			$this->errorMsg($e->getMessage());
			return FALSE;
		}
		parent::validateData($array);
		return TRUE;	
	}
	
	final function beforeSubmit($postData) {
		if ($postData['id'] > 0)
			$postData['depth'] = $this->treeDepth($postData['id']);
		else {
			$res = $this->oDb->obtain("SELECT depth FROM menu WHERE id_menu = '{$postData['id_parent']}'");
			$postData['depth'] = $res['depth'] + 1;
		}
		return parent::beforeSubmit($postData);
	}
	
	final function printList() {
		$ret = "";
		$ret .= $this->tableHead("Menu item",Array(
			"Parent","Title","Pos","Module"
		));
		
		while ($menuR = $this->oDb->get($this->query)) {
			$ID = $this->pp($menuR,$this->primaryKey);
			$ret .= $this->inTable(Array(
				$this->getMenuTitle($this->pp($menuR,"id_parent")),
				$this->pp($menuR,"menu_title"),
				$this->printReorder($ID, $this->pp($menuR,"position")),
				$this->pp($menuR,"module_type"),
			),$ID);
		}
		$ret .= $this->tableEnd();
		return parent::printList($ret);
	}
	
	final function printForm($action, $id) {
		$ret = '<script type="text/javascript">
function changeModule() {
	var module = document.getElementById("module_name");
	var uri = document.getElementById("uri");
	if (module.value == "")
		module.value = uri.value;
}
</script>';
		$ret .= $this->oForm->inputBox("Title", "title", 128, $this->pp($this->row, "title"));
		$ret .= $this->oForm->inputBox("Menu title", "menu_title", 96, $this->pp($this->row, "menu_title"));
		$ret .= $this->menuParent($this->pp($this->row, "id_parent"));
		$ret .= $this->oForm->inputBox("URI", "uri", 32, $this->pp($this->row, "uri"), 'onchange="javascript:changeModule();"');
		$ret .= $this->oForm->selectBox("Site type", "module_type", Array (
			Array (
				"name" => "Webpage template",
				"value" => "tmpl"
			),
			Array (
				"name" => "Class",
				"value" => "class"
			),
			Array (
				"name" => "Template",
				"value" => "page"
			),
			Array (
				"name" => "System core",
				"value" => "core"
			),
			Array (
				"name" => "Redirect",
				"value" => "redir"
			),
			Array (
				"name" => "Javascript action",
				"value" => "js"
			)
		), $this->pp($this->row, "module_type"));
		$ret .= $this->oForm->inputBox("Module name", "module_name", 255, $this->pp($this->row, "module_name"));	
		$ret .= $this->oForm->optionBox("Visibility", "show_menu", Array (
			Array (
				"name" => "Yes",
				"value" => 1
			),
			Array (
				"name" => "No",
				"value" => 0
			)
		), $this->pp($this->row, "show_menu"));
		$ret .= $this->oForm->inputBox("Position", "position", 4, $this->pp($this->row, "position"));
		$ret .= $this->oForm->optionBox("Protocol", "module_protocol", Array (
			Array (
				"name" => "HTTP",
				"value" => "http"
			),
			Array (
				"name" => "HTTPS (SSL)",
				"value" => "https"
			),
			Array (
				"name" => "FTP",
				"value" => "ftp"
			)
		), $this->pp($this->row, "module_protocol"));
		if (!$id)
		$ret .= $this->oForm->selectBox("Permission creation", "perms_type", Array (
			Array (
				"name" => "Public",
				"value" => "public"
			),
			Array (
				"name" => "Administration rule",
				"value" => "admins"
			),
			Array (
				"name" => "User read only",
				"value" => "users"
			),
			Array (
				"name" => "User read/write",
				"value" => "users_write"
			)
		), $this->pp($this->row, "owner_type"));
		return parent::printForm($action, $id, $ret);
	}
	
	final function getMenuTitle($ID) {
		if ($ID == 0) return "";
		
		return $this->getKey("menu_title",$ID);
	}
	
	private function getKey($key, $ID) {
		$mT = $this->oDb->obtain("SELECT `".$key."` FROM menu WHERE id_menu = '".$ID."'");
		if (is_array($mT) && array_key_exists($key,$mT))
			return $mT[$key];
		showErrorTemplate("menu");
	}
	
	private function treeDepth($ID, $depth=1) {
		
		$res = $this->oDb->obtain("SELECT id_parent FROM menu WHERE id_menu = '{$ID}'");
		if ($res['id_parent'] > 0)
			return $this->treeDepth($res['id_parent'], $depth+1);
		return $depth;
	}
	
	private function menuParent($default) {
		
		$pole = $this->poleGenerator(0, 1);
		return $this->oForm->selectBox("Parent", "id_parent", $pole, $default);
	}
	
	private function poleGenerator($idParent, $depth) {
		$pole = Array();
		if ($depth == 1)
			$pole = Array(Array(
				"name" => "Root",
				"value" => 0
			));
		//$q = $this->oDb->query("SELECT id_menu,`title` FROM menu WHERE id_parent = '{$idParent}'");
		$q = $this->oDb->queryWithBids("SELECT id_menu,`title` FROM menu WHERE id_parent = ?", Array($idParent));
		while ($res = $this->oDb->get($q)) {
			$length = count($pole);
			$prefix = "";
			for ($j=0;$j<$depth;$j++)
				$prefix .= "&raquo; ";
			$pole[$length]['name'] = $prefix . $res['title'];
			$pole[$length]['value'] = $res['id_menu'];
			if ($depth < 3) {
				$pole = array_merge($pole, $this->poleGenerator($res['id_menu'],$depth+1));
			}
		}
		return $pole;
	}
	
	final function getDb($id = 0) {
		if (array_key_exists("position",$_POST))
			$this->oDb->query("UPDATE menu SET position = '".$_POST['position']."'
				WHERE id_menu = '".$_POST['id']."'");
				
			/*$this->oDb->queryWithBids("UPDATE menu SET position = ?
				WHERE id_menu = ?", Array($_POST['position'],$_POST['id'] ));*/
		parent::getDB($id);
	}
	
	final function printReorder($ID, $pos) {
		$buttons = "";
		$buttons .= '<div class="buttons">'."\n";
		$buttons .= '	<form method="post" action="'.$this->oUrl->fullHref().'" enctype="multipart/form-data"><input type="hidden" name="position" value="'.($pos-1).'" /><input type="hidden" name="id" value="'.$ID.'" /><input type="submit" value="&uarr;" title="'.($pos-1).'" class="submit" name="form_submit" /></form>'."\n";
		$buttons .= '	<form method="post" action="'.$this->oUrl->fullHref().'" enctype="multipart/form-data"><input type="hidden" name="position" value="'.($pos+1).'" /><input type="hidden" name="id" value="'.$ID.'" /><input type="submit" value="&darr;" title="'.($pos+1).'" class="submit" name="form_submit" /></form>'."\n";
		$buttons .= ' '.$pos;
		$buttons .= '</div>'."\n";
		return $buttons;
	}
	
	final function dbInsert() {
		//echo 'dbinsert';
		$postData = $_POST;
		if (!$this->validateData($postData)) return;
		parent::dbInsert();
		if (!$this->aKe($postData,"perms_type"))
			$postData['perms_type'] = "public";
		switch ($postData['perms_type']) {
		case "public":
			$r = Array(1,0,0,0,0);
			$oType = "public";
			$oID = 0;
			$this->insertMenuRights($oID, $oType, $r);
		case "admins":
			$r = Array(1,1,1,1,1);
			$oType = "group";
			$oID = 1;
			$this->insertMenuRights($oID, $oType, $r);
			break;
		case "admins":
		case "users":
			$r = Array(1,0,0,0,0);
			$oType = "group";
			$oID = 2;
			$this->insertMenuRights($oID, $oType, $r);
			break;
		case "admins":
		case "users_write":
			$r = Array(1,1,1,1,1);
			$oType = "group";
			$oID = 2;
			$this->insertMenuRights($oID, $oType, $r);
			break;
		}
	}
	
	private function insertMenuRights($oID, $oType, $r) {
		$sqlR = "INSERT INTO perms 
			(id_menu,id_element,id_namespace,id_owner,owner_type,can_read,can_write,can_grant,can_comment)
			VALUES
			(?,?,?,?,?,?,?,?,?)";
		//$this->oDb->query($sqlR);
		
		$this->oDb->queryWithBids($sqlR, array($this->workingID, 0, 0, $oID,$oType, $r[0] , $r[1], $r[3], $r[4] ));
		/*
		$sqlR = "INSERT INTO perms_init
			(id_menu,id_namespace,id_owner,owner_type,can_read,can_write,can_insert,can_grant,can_comment)
			VALUES
			('".$this->workingID."','0','".$oID."','".$oType."','{$r[0]}','{$r[1]}','{$r[2]}','{$r[3]}','{$r[4]}')";
		$this->oDb->query($sqlR);
		*/
	}
	
	public function dbDelete($id) {
		$this->oDb->query("DELETE FROM perms WHERE id_menu = '{$id}'");
		//$this->oDb->queryWithBids("DELETE FROM perms WHERE id_menu = '?", array($id));
		
		$this->oDb->query("DELETE FROM perms_init WHERE id_menu = '{$id}'");
		//$this->oDb->queryWithBids("DELETE FROM perms_init WHERE id_menu = ?", array($id));
		parent::dbDelete($id);
	}
	
}

?>