<?php
	require_once "../dal/scoreDAL.php";
	require_once "../pageBase.php";
	
	class _gs extends pageBase {
		private $dal;
		private array $aryJ;
		private string $regex;

		public function __construct() {
			$this->dal = new scoreDAL();
			$this->regex = "/^\d+$/";
			$this->aryJ = ["err" => "0", "msg" => ""];
		}

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

			$action = parent::getPost("do");
			switch ($action) {
				case "add":
					$this->addItem();
					break;
				default:
					$this->handleError("操作異常！請重新整理頁面再試一次！");
			}
		
			$this->aryJ["msg"] = urlencode($this->aryJ["msg"]);
			echo urldecode(json_encode($this->aryJ));
		}

		private function addItem(): void {
			/* 參數 */
			$key = parent::getPost("key");
			$code = parent::getPost("code");
			$num = parent::getPost("num");
			$comment = parent::getPost("cmt", "", 4);
			
			/* 檢查 */
			$se_scoreArr = $_SESSION["scoreAry"][$key];
			if (!preg_match("/^\d+$/", $key) || !preg_match("/^[A-Z]{10}$/", $code) || !preg_match("/^[1-5]$/", $num)) {
				$this->handleError("參數異常!!可能是網頁放置過久，請重新整理頁面再試一次!");
				return;
			}
			if (!isset($_SESSION["member_id"]) || !preg_match("/^[1-9]\d*$/", $_SESSION["member_id"])) {
				$this->handleError("網頁放置過久，請重新整理頁面再試一次!");
				return;
			}
			if (!isset($se_scoreArr) || !is_array($se_scoreArr)) {
				$this->handleError("網頁放置過久，請重新整理頁面再試一次!!");
				return;
			}
			if ($se_scoreArr["code"] != $code || !preg_match("/^[1-9]\d*$/", $se_scoreArr["type"]) || !preg_match("/^[1-9]\d*$/", $se_scoreArr["id"])) {
				$this->handleError("參數異常!可能是網頁放置過久，請重新整理頁面再試一次!");
				return;
			}

			$targetType = $se_scoreArr["type"];
			$targetID = $se_scoreArr["id"];
			
			$intoAry = [
				parent::addArray(":memberID", $_SESSION["member_id"], "int"),
				parent::addArray(":targetType", $targetType, "int"),
				parent::addArray(":targetID", $targetID, "int")
			];
			$filter = "a.`MemberID`=:memberID AND a.`TargetType`=:targetType AND a.`TargetID`=:targetID";
			if ($this->dal->countRecordset($intoAry, $filter) > 0) {
				$this->handleError("您已經評分過本頁，無法重複評分，歡迎前往其他頁面評分，謝謝!");
				return;
			}
			
			/* 新增評分 */
			$this->dal->MemberID = $_SESSION["member_id"];
			$this->dal->TargetType = $targetType;
			$this->dal->TargetID = $targetID;
			$this->dal->Score = $num;
			$this->dal->Comment = $comment;
			$this->dal->ReMessage = "";
			$this->dal->CreatedIP = parent::getIP();

			if (!$this->dal->insertRecord()) $this->handleError("評分失敗!請重新整理頁面再試一次!");
		}

		private function handleError(string $errorMessage): void {
			$this->aryJ["err"] = "1";
			$this->aryJ["msg"] = $errorMessage;
		}
	}
	$page = new _gs();
	$page->load();
?>