<?php
namespace carabi_cms;

/**
 * Модуль для работы со страницами сайта в CMS.
 * Список Action-ов:
 * index
 * getPagesList
 * edit
 * create
 * reparent
 *
 * @author sasha
 */
include_once CARABI_DIR . '/classes/wave_editor/class.WaveEditorUtils.php';

class pagehandler_pages extends \SimplePagehandler {
	
	var $pagesColModel = '[
	{ name: "WEB_PAGE_TITLE", label: "Заголовок", sortable: false},
	{ name: "WEB_PAGE_ID", hidden: true},
	{ name: "PARENT_PAGE_ID", hidden:true},
	{ name: "WEB_PAGE_PAGE_TYPE_OLD", label: "Тип", sortable: false, width: 24, fixed: true},
	{ name: "WEB_PAGE_ICONS", label: "&nbsp;", sortable: false, width: 64, fixed: true},
	{ name: "WEB_PAGE_LINK", label: "ID", sortable: false, width: 64, fixed: true},
]';

	public function process() {
		if (\lib_cms::hasPermission($this->user(), \lib_cms::PERMISSION_PAGES)) {
			$this->executeAction();
		} else {
			header("Location: " . \lib_cms::loginPage());
		}
	}
	
	/**
	 * action для открытия главной страницы
	 */
	protected function index() {
		$tpl = $this->renderer()->createTemplate("carabi_cms/content.pages.tpl");
		$pagesList = $this->selectPagesList(true);
		$tpl->assign('colModel', $this->pagesColModel);
		$tpl->assign('size', count($pagesList));
		$tpl->assign("pagehandler", $this);
		$tpl->display();
	}
	
	/**
	 * action для выдачи содержимого jqGrid
	 */
	protected function getPagesList() {
		$pagesList = $this->selectPagesList();
		foreach ($pagesList as &$page) {
			$webPageID = $page["WEB_PAGE_ID"];
			$page["WEB_PAGE_LINK"] = "<a href='" . $this->baseUrl() . "/edit/$webPageID' style='text-decoration:underline'>$webPageID</a>";
		}
		$pagesTree = \utls::listToTree($pagesList, "WEB_PAGE_ID", "PARENT_PAGE_ID");
		$orderedPagesList = \utls::treeToOrderedList($pagesTree);
		$size = count($orderedPagesList);
		$rows = json_encode($orderedPagesList);
		echo '{"page": "1", "total": "1", "records": "'.$size.'",
			"rows":' . $rows . '
		}';
	}
	
	protected function search() {
		$q = get("q");
		if (empty($q)) {
			return $this->index();
		}
		
		$tpl = $this->renderer()->createTemplate("carabi_cms/content.pages.tpl");
		
		$sql = "APPL_CARABI_TABLE2.GET_CURSOR('WEB_PAGE',
			APPL_WEB_PAGE.FIND_PAGES_BY_TEXT('$q'," . \lib_cms::WEBSITE_ID . ")
		)";
		$pagesList = ora_cursor($sql);
		$this->initPagesIcons($pagesList);
		$_SESSION["pagehandler_pages"]["pagesList"] = $pagesList;
		$tpl->assign("colModel", $this->pagesColModel);
		$tpl->assign("size", count($pagesList));
		$tpl->assign("search", true);
		$tpl->assign("pagehandler", $this);
		$tpl->display();
	}
	
	/**
	 * Выборка списка страниц -- из БД или из кеша в сессии
	 * @param type $forceUpdate 
	 */
	private function selectPagesList($forceUpdate = false) {
		if ($forceUpdate || empty($_SESSION["pagehandler_pages"]["pagesList"])) {
			$pagesList = ora_cursor("APPL_WEB_TABLE.GET_WEB_PAGE_TABLE(" . \lib_cms::WEBSITE_ID . ")", 5000);
			$this->initPagesIcons($pagesList);
			$_SESSION["pagehandler_pages"]["pagesList"] = $pagesList;
		} else {
			$pagesList = $_SESSION["pagehandler_pages"]["pagesList"];
		}
		return $pagesList;
	}
	
	/**
	 * Формирование значения поля WEB_PAGE_ICONS с HTML-кодом картинок
	 * в зависимости от значений других полей
	 * @param array $pagesList 
	 */
	private function initPagesIcons(&$pagesList) {
		foreach ($pagesList as &$page) {
			$page["WEB_PAGE_ICONS"] = "";
			if ($page["WEB_PAGE_AUTH"] == "Да") {
				$page["WEB_PAGE_ICONS"] .= '<img src="' . IMAGES_URL . '/icon_lock.png"/>';
			}
			if ($page["WEB_PAGE_VISIBLE"] == "Да") {
				$page["WEB_PAGE_ICONS"] .= '<img src="' . IMAGES_URL . '/icon_eye.png"/>';
			}
		}
	}

	/**
	 * action для редактирования страницы -- открывает DocumentEditor
	 */
	protected function edit($parameters) {
		$pageID = $parameters["url"][1];
		if (empty($pageID)) {
			throw new \NotFoundException("Page id is empty");
		}
		$this->user()->actAsSelf();
		$tpl = DocumentEditor::editDocument($pageID, "carabi_cms/editor.pages.tpl");
		$pageName = \WaveEditorUtils::getSimpleField($pageID, "WEB_PAGE", "TITLE");
		$this->user()->actAsCommonUser();
		$tpl->assign("pageName", $pageName);
		$tpl->assign("pagehandler", $this);
		$tpl->display();
	}
	
	/**
	 * action для создания страницы -- создаёт пустой документ и редиректит на редактор
	 */
	protected function create() {
		$parent = get("parent");
		if ($parent) {
			$parentKind = ora_func("get_dockind_name($parent)");
			if ($parentKind != "WEB_PAGE") {
				throw new Exception("Parent $parent has wrong type: $parentKind");
			}
		}
		$this->user()->actAsSelf();
		$pageID = DocumentEditor::createNewDocument("WEB_PAGE");
		//Старый ID (пока от него не отказались) для новых страниц дублируем новым
		\WaveEditorUtils::updateSimpleField($pageID, "WEB_PAGE", "PAGE_ID", $pageID);
		\WaveEditorUtils::updateSimpleField($pageID, "WEB_PAGE", "WEBSITE_ID", \lib_cms::WEBSITE_ID);
		if ($parent) {
			\WaveEditorUtils::addReference($parent, "WEB_PAGE", "WEB_PAGE-REF-WEB_PAGE", $pageID);
		}
		$this->user()->actAsCommonUser();
		header("Location: " . $this->baseUrl() . "/edit/$pageID");
	}
	
	/**
	 * action для замены родителя страницы (перемещения в дереве)
	 */
	protected function reparent() {
		$reparentPage = get("reparentPage");
		if (empty($reparentPage)) {
			throw new Exception("reparentPageID is not set");
		}
		$this->user()->actAsSelf();
		$parentID = \WaveEditorUtils::getReference($reparentPage, "WEB_PAGE", "WEB_PAGE-BREF-WEB_PAGE");
		\WaveEditorUtils::reparentDocument($reparentPage, $parentID, get("newParent"), "WEB_PAGE", "WEB_PAGE-REF-WEB_PAGE");
		$this->user()->actAsCommonUser();
		header("Location: " . $this->baseUrl());
	}
	
	/**
	 * action для удаления страницы, детей привязываем к родителю
	 */
	protected function delete() {
		$page = get("page");
		if (empty($page)) {
			throw new Exception("page for delete is not set");
		}
		$parentID = \WaveEditorUtils::getReference($page, 'WEB_PAGE', 'WEB_PAGE-BREF-WEB_PAGE');
		\WaveEditorUtils::reparentChildren($page, 'WEB_PAGE', 'WEB_PAGE-REF-WEB_PAGE', $parentID);
		DocumentEditor::deleteDocument($page);
		header("Location: " . $this->baseUrl());
	}
}
?>
