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

		public function __construct() {
			$this->dal = new articleDAL();
			$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;
				case "vis":
					$this->changeVisible(1);
					break;
				case "unvis":
					$this->changeVisible(0);
					break;
				case "ono":
					$this->orderNO();
					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() {
			$id = parent::getPost("id");
			$ids = parent::getPost("ids");
			$type = parent::getPost("type");
			$this->aryJ["type"] = $type;
		
			if (($id && $id !== "0") || ($ids && $ids !== "0")) {
				$success = false;
				if ($id) {
					$success = $this->dal->deleteRecord($id, $type);
				} else if ($ids) {
					$success = $this->dal->batDelete($ids, $type);
				}
				if (!$success) $this->handleError("刪除失敗!");
			} else {
				$this->handleError("找不到要刪除的文章!");
			}
		}
		
		private function changeVisible($visible) {
			$ids = parent::getPost("ids");
			if ($ids && $ids !== "0") {
				$success = $this->dal->batUpdateVisible($ids, $visible);
				if (!$success) $this->handleError("變更狀態失敗!");
			} else {
				$this->handleError("找不到要變更狀態的文章!");
			}
		}

		private function orderNO() {
			$ids = parent::getPost("ids");
			$ono = parent::getPost("ono");
			$ary1 = explode(",", $ids);
			$ary2 = explode(",", $ono);
		
			if (count($ary1) !== count($ary2)) {
				$this->handleError("參數異常!排序不可輸入數字以外的字元!請重新整理頁面再試一次!");
				return false;
			}
		
			foreach ($ary1 as $index => $articleID) {
				$this->dal->ArticleID = $articleID;
				$this->dal->loadRecord();
				if ($this->dal->ArticleID === $articleID) {
					$this->dal->OrderNO = $ary2[$index];
					$this->dal->ModifiedUserID = parent::getCurrentUserID();
					$this->dal->ModifiedIP = parent::getIP();
					$this->dal->updateRecord();
				} else {
					$this->handleError("找不到指定的文章!變更排序已中斷!請重新整理頁面再試一次!");
					return false;
				}
			}
		}
		
		private function handleError(string $errorMessage): void {
			$this->aryJ["error"] = "1";
			$this->aryJ["msg"] = $errorMessage;
		}
	}

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