<?php
	require_once "pageBase.php";
	require_once "../bin/system/guid.php";
	require_once "../bin/web/repeater.php";
	require_once "../dal/menuDAL.php";
	require_once "../function/function.php";

	class _menuEdit extends pageBase {
		private string $id;
		private string $pUrl;
		private $dal;
		
		public function load() {
			$this->dal = new menuDAL();
			$this->id = parent::getInput("id","0");
			$this->pUrl = urldecode(parent::getInput("pUrl","menuList.php"));
			
			$this->limitID = "74";
			if (!parent::chkUserLimit()) {
				$this->alertMsg = "您沒有使用此頁面的權限!如有疑問請洽主管理者!";
				$this->locationHref = "index.php";
			} else {
				parent::isPostBack() ? $this->saveData() : $this->loadData();
			}
			parent::loadTemplateFile(dirname(__FILE__) . "/templates/menuEdit.html");
			parent::load();
		}

		public function loadData() {
			// 上層
			$dataP = $this->dal->executeRecordset([], "a.`ParentID`=0 AND a.`Visible`=1", "a.`OrderNO`");
			$listP = new repeater();
			$listP->id = "listP";
			$listP->dataSource = $dataP;
			parent::addControl($listP);

			//
			if (!empty($this->id) && $this->id != 0) {
				$this->dal->MenuID = $this->id;
				$this->dal->loadRecord();
				
				$parameters = [
					"ParentID" => $this->dal->ParentID,
					"MenuName" => $this->dal->MenuName,
					"MenuIcon" => $this->dal->MenuIcon,
					"MenuLink" => $this->dal->MenuLink,
					"LinkTarget" => $this->dal->LinkTarget,
					"Visible" => $this->dal->Visible,
					"OrderNO" => $this->dal->OrderNO,
					"IsOA" => $this->dal->IsOA,
					"editTitle" => "修改功能項目",
				];
			}else{
				$parameters = [
					"ParentID" => "0",
					"LinkTarget" => "_self",
					"Visible" => "1",
					"IsOA" => "0",
					"editTitle" => "新增功能項目",
				];
			}
			foreach ($parameters as $name => $value) {
				parent::addParameter($name, $value);
			}

			parent::addParameter("id", $this->id);
			parent::addParameter("pUrl", $this->pUrl);
			parent::loadData();
		}
		public function saveData(){
			if (!empty($this->id) && $this->id != 0) {
				$this->dal->MenuID = $this->id;
				$this->dal->loadRecord();
			}
			$this->dal->ParentID = (int) parent::getPost("ParentID", "0");
			$this->dal->MenuName = parent::getPost("MenuName");
			$this->dal->MenuLink = parent::getPost("MenuLink");
			$this->dal->LinkTarget = parent::getPost("LinkTarget");
			$this->dal->Visible = (int) parent::getPost("Visible", "0");
			$this->dal->OrderNO = (int) parent::getPost("OrderNO", "0");
			$this->dal->IsOA = (int) parent::getPost("IsOA", "1");
			
			$saved = ($this->id !== "" && $this->id !== "0") ? $this->dal->updateRecord() : $this->dal->insertRecord();
			if ($saved === false) {
				$this->alertMsg = "儲存時發生錯誤!";
				$this->goBack = "Y";
			} else {
				$this->locationHref = $this->pUrl;
			}
		}
	}

	$page = new _menuEdit();
	$page->load();
	$page->render();
?>