<?php
	require_once "pageBase.php";
	require_once "../../dal/book_categoryDAL.php";
	require_once "../../dal/bookDAL.php";
	class _book_category extends pageBase {
		private $dal;
		private array $aryJ;

		public function __construct() {
			$this->dal = new book_categoryDAL();
			$this->aryJ = ["error" => "0", "type" => "", "uid" => parent::getCurrentUserID(), "msg" => ""];
		}

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

			$action = parent::getPost("do");
			switch ($action) {
				case "del":
					$this->delete();
					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 delete() {
			$dalB = new bookDAL();
			$id = parent::getPost("id");
			$type = parent::getPost("type");
			$this->aryJ["type"] = $type;
			
			$intoAry = [ parent::addArray(":id", $id, "int") ];
			if ($this->dal->countRecordset($intoAry, "a.`ParentID`=:id AND a.`Disable`=0") > 0) {
				$this->handleError("相本分類下面還有子分類不能刪除!");
			} else if ($dalB->countRecordset($intoAry, "a.`CategoryID`=:id AND a.`Disable`=0") > 0) {
				$this->handleError("相本分類下面還有相本不能刪除!");
			} else {
				if (!$this->dal->deleteRecord($id, $type)) $this->handleError("刪除失敗!");
			}
		}
		
		private function handleError(string $errorMessage): void {
			$this->aryJ["error"] = "1";
			$this->aryJ["msg"] = $errorMessage;
		}
	}

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