<?php
	require_once "pageBase.php";
	require_once "../../dal/message_typeDAL.php";
	class _message_type extends pageBase {
		private $dal;
		private array $aryJ;

		public function __construct() {
			$this->dal = new message_typeDAL();
			$this->aryJ = ["error" => "0", "msg" => ""];
		}

		public function load(): void {
			$this->aryJ["msg"] = "";

			$action = parent::getPost("do");
			switch ($action) {
				case "del":
					$this->deleteType();
					break;
				default:
					$this->handleError("操作異常！請重新整理頁面再試一次！");
			}
		
			if ($this->aryJ["msg"] !== "") $this->aryJ["msg"] = urlencode($this->aryJ["msg"]);
			echo urldecode(json_encode($this->aryJ));
			parent::load();
		}
		
		private function deleteType() {
			$id = parent::getPost("id");
		
			if (!preg_match("/^[1-9]\d*$/", $id)) {
				$this->handleError("參數異常!");
				return;
			}
			
			/* 檢查類型資料是否存在 */
			$intoAry = [ parent::addArray(":typeID", $id, "int") ];
			$filter = "a.`TypeID`=:typeID";
			if ($this->dal->countRecordset($intoAry, $filter) === 0) {
				$this->handleError("找不到指定刪除的訊息類型!請重新整理頁面再試一次!");
				return;
			}

			/* 刪除 */
			if (!$this->dal->deleteRecord($id)) $this->handleError("刪除失敗!");
		}
		
		private function handleError(string $errorMessage): void {
			$this->aryJ["error"] = "1";
			$this->aryJ["msg"] = $errorMessage;
		}
	}

	$page = new _message_type();
	$page->load();
?>