<?php
namespace carabi_cms;

/**
 * Работа с Web-меню
 *
 * @author sasha
 */
include_once CARABI_DIR . '/classes/wave_editor/class.WaveEditorUtils.php';

class pagehandler_navigate extends \SimplePagehandler {
	
	var $menuColModel = '[
	{ name: "WEB_MENU_LINK_CAPTION", label: "Заголовок", sortable: false},
	//{ name: "WEB_MENU_LINK_DESCRIPTION", label: "Описание", sortable: false},
	{ name: "WEB_MENU_LINK_URL", label: "Адрес", sortable: false, },
	{ name: "WEB_MENU_LINK_VISIBLE", label: "Показывать", sortable: false, width: 64, fixed: true},
	{ name: "WEB_MENU_LINK_ORDERBY", label: "Порядковый номер", sortable: false, width: 64, fixed: true},
	{ name: "WEB_MENU_EDITOR", label: "ID", sortable: false, width: 64, fixed: true}
]';
	
	public function process() {
		if (\lib_cms::hasPermission($this->user(), \lib_cms::PERMISSION_NAVIGATION)) {
			$this->executeAction();
		} else {
			header("Location: " . \lib_cms::loginPage());
		}
	}
	
	public function index() {
		$navigateElements = $this->selectWebMenu(true);
		$tpl = $this->renderer()->createTemplate("carabi_cms/content.navigate.tpl");
		$tpl->assign('colModel', $this->menuColModel);
		$tpl->assign('size', count($navigateElements));
		$tpl->assign("pagehandler", $this);
		$tpl->display();
		
	}
	
	public function getJqgridData() {
		$navigateElements = $this->selectWebMenu();
		usort($navigateElements, function ($l1, $l2){return $l1["WEB_MENU_LINK_ORDERBY"] - $l2["WEB_MENU_LINK_ORDERBY"];});
		$navigateElements = \utls::treeToOrderedList(\utls::listToTree($navigateElements, "ID", "PARENT"));
		$size = count($navigateElements);
		$rows = json_encode($navigateElements);
		echo '{"page": "1", "total": "1", "records": "'.$size.'",
			"rows":' . $rows . '
		}';
	}
	
	/**
	 * Выборка меню и его ссылок
	 * Из БД или кеша в сессии
	 */
	private function selectWebMenu($forceUpdate = false) {
		if ($forceUpdate || empty($_SESSION["pagehandler_navigate"]["navigate_elements"])) {
			$menu = ora_cursor("APPL_WEB_TABLE.GET_WEB_MENU_TABLE(". \lib_cms::WEBSITE_ID .")");
			$links = ora_cursor("APPL_WEB_TABLE.GET_WEB_MENU_LINKS_TABLE(". \lib_cms::WEBSITE_ID .")");
			//Меню и ссылки надо свести в один массив для построения дерева.
			//Меню -- корни, у ссылок родителями могут быть как меню, так и вышележащие ссылки.
			$navigateElements = array();
			foreach ($menu as $node) {
				$node["ID"] = $node["WEB_MENU_ID"]; unset($node["WEB_MENU_ID"]);
				$node["PARENT"] = "";
				$node["WEB_MENU_LINK_CAPTION"] = $node["WEB_MENU_MENU_NAME"];
				$node["WEB_MENU_EDITOR"] = "<a href='" . $this->baseUrl() . "/edit/{$node["ID"]}' style='text-decoration:underline'>{$node["ID"]}</a>";
				$navigateElements[] = $node;
			}
			foreach ($links as $link) {
				$link["ID"] = $link["WEB_MENU_LINK_ID"]; unset($link["WEB_MENU_LINK_ID"]);
				if (!empty($link["WEB_MENU_ID"])) {
					$link["PARENT"] = $link["WEB_MENU_ID"]; 
				} else if (!empty($link["PARENT_LINK_ID"])) {
					$link["PARENT"] = $link["PARENT_LINK_ID"]; 
				}
				unset($link["WEB_MENU_ID"]);
				unset($link["PARENT_LINK_ID"]);
				$link["WEB_MENU_EDITOR"] = "<a href='" . $this->baseUrl() . "/edit/{$link["ID"]}' style='text-decoration:underline'>{$link["ID"]}</a>";
				$navigateElements[] = $link;
			}
			$_SESSION["pagehandler_navigate"]["navigate_elements"] = $navigateElements;
		} else {
			$navigateElements = $_SESSION["pagehandler_navigate"]["navigate_elements"];
		}
		return $navigateElements;
	}

	/**
	 * action для редактирования элемента навигации-- открывает DocumentEditor
	 * Может применяться к ссылкам и меню
	 */
	protected function edit($parameters) {
		$nodeID = $parameters["url"][1];
		if (empty($nodeID)) {
			throw new \NotFoundException("Node id is empty");
		}
		$nodeKind = ora_func("get_dockind_name($nodeID)");
		if (!in_array($nodeKind, array("WEB_MENU", "WEB_MENU_LINK"))) {
			throw new \Exception("Document with ID $nodeID has wrong type: $nodeKind");
		}
		$this->user()->actAsSelf();
		$tpl = DocumentEditor::editDocument($nodeID, "carabi_cms/editor.navigate.tpl");
		if ($nodeKind == "WEB_MENU") {
			$nodeName = \WaveEditorUtils::getSimpleField($nodeID, "WEB_MENU", "MENU_NAME");
		} else {
			$nodeName = \WaveEditorUtils::getSimpleField($nodeID, "WEB_MENU_LINK", "CAPTION");
		}
		$this->user()->actAsCommonUser();
		$tpl->assign("nodeKind", $nodeKind);
		$tpl->assign("nodeName", $nodeName);
		$tpl->assign("pagehandler", $this);
		$tpl->display();
	}
	
	/**
	 * action для создания ссылки, в меню или под другой ссылкой
	 */
	public function createLink() {
		$parent = get("parent");
		if (empty($parent)) {
			throw new \Exception("Can not create a link without parent");
		}
		$parentKind = ora_func("get_dockind_name($parent)");
		if (!in_array($parentKind, array("WEB_MENU", "WEB_MENU_LINK"))) {
			throw new \Exception("Parent $parent has wrong type: $parentKind");
		}
		$this->user()->actAsSelf();
		$linkID = DocumentEditor::createNewDocument("WEB_MENU_LINK");
		\WaveEditorUtils::addReference($parent, $parentKind, "$parentKind-REF-WEB_MENU_LINK", $linkID);
		$this->user()->actAsCommonUser();
		header("Location: " . $this->baseUrl() . "/edit/$linkID");
	}

	/**
	 * action для замены родителя ссылки (перемещения в дереве)
	 */
	protected function reparentLink() {
		$reparentLink = get("reparentLink");
		if (empty($reparentLink)) {
			throw new \Exception("reparentLinkID is not set");
		}
		$this->user()->actAsSelf();
		$parent = $this->getLinkParent($reparentLink);
		$newParent = get("newParent");
		if (!empty($newParent)) {
			$newParentKind = ora_func("get_dockind_name($newParent)");
		}
		\WaveEditorUtils::reparentDocument($reparentLink, $parent["id"], $newParent, $parent["kind"], "{$parent["kind"]}-REF-WEB_MENU_LINK", $newParentKind, "$newParentKind-REF-WEB_MENU_LINK");
		$this->user()->actAsCommonUser();
		header("Location: " . $this->baseUrl());
	}
	
	/**
	 * action для удаления ссылки, детей привязываем к родителю
	 */
	protected function delete() {
		$link = get("link");
		if (empty($link)) {
			throw new Exception("link for delete is not set");
		}
		$this->user($link)->actAsSelf();
		$parent = $this->getLinkParent($link);
		\WaveEditorUtils::reparentChildren($link, "WEB_MENU_LINK", "WEB_MENU_LINK-REF-WEB_MENU_LINK", $parent["id"], $parent["kind"], "{$parent["kind"]}-REF-WEB_MENU_LINK");
		DocumentEditor::deleteDocument($link);
		$this->user()->actAsCommonUser();
		header("Location: " . $this->baseUrl());
	}
	
	/**
	 * Определение предка ссылки.
	 * Ссылка должна находиться ровно в одном предке: меню или другой ссылке
	 * @param int $linkID 
	 * @return aray массив[ID предка, тип предка]
	 */
	private function getLinkParent($linkID) {
		$parentMenu = \WaveEditorUtils::getReference($linkID, "WEB_MENU_LINK", "WEB_MENU_LINK-BREF-WEB_MENU");
		$parentLink = \WaveEditorUtils::getReference($linkID, "WEB_MENU_LINK", "WEB_MENU_LINK-BREF-WEB_MENU_LINK");
		$result = array();
		if (empty($parentMenu) && !empty($parentLink)) {
			$result["id"] = $parentLink;
			$result["kind"] = "WEB_MENU_LINK";
		} else if (!empty($parentMenu) && empty($parentLink)) {
			$result["id"] = $parentMenu;
			$result["kind"] = "WEB_MENU";
		} else {
			throw new \Exception("The $linkID link has no or more than one parent, check the database");
		}
		return $result;
	}
}
?>
