<?php
	require_once dirname(__FILE__) . "/dalBase.php";
	class limitDAL extends dalBase {
		public $ID;
		public $UserID;
		public $MenuID;

		public function insertRecord(){
			$intoAry = [
				parent::addArray(":userID", $this->UserID, "int"),
				parent::addArray(":menuID", $this->MenuID, "int")
			];
			$sql = "INSERT INTO `limit` (`UserID`, `MenuID`) VALUES (:userID, :menuID)";
			$this->data->executeNonQuery($sql, $intoAry, true);
			return (!$this->data->error) ? $this->data->getInsertID() : false;
		}
		//刪除
		public function deleteRecord(int $userID): bool {
			$intoAry = [
				parent::addArray(":userID", $userID, "int")
			];
			$sql = "DELETE FROM `limit` WHERE `UserID`=:userID";
			$this->data->executeNonQuery($sql, $intoAry, true);
			return !$this->data->error;
		}

		//查詢
		public function executeRecordset(array $intoAry = [], string $filter = "", string $order = "", int $start = 0, int $length = -1): array {
			$sql = "SELECT a.`ID`,a.`UserID`,b.* FROM `limit` a LEFT JOIN `menu` b ON a.`MenuID`=b.`MenuID`";
			if ($filter !== "") $sql .= " WHERE $filter";
			$sql .= (!isset($order) || $order === "") ? " ORDER BY a.`ID`" : " ORDER BY $order";
			$length = is_int($length) ? $length : -1;
			return $this->data->executeRecordset($sql, $intoAry, $start, $length);
		}

		//
		public function countRecordset(array $intoAry = [], string $filter = ""): int {
			$sql = "SELECT COUNT(*) FROM `limit` a LEFT JOIN `menu` b ON a.`MenuID`=b.`MenuID`";
			if ($filter !== "") $sql .= " WHERE $filter";
			return $this->data->executeScalar($sql, $intoAry);
		}

		//權限檢查
		public function checkLimit(int $uid, int $mid): bool {
			if ($uid == "1") return true;
		
			$sql = "SELECT COUNT(*) FROM `limit` WHERE `UserID`=:userID AND `MenuID`=:menuID";
			$intoAry = [
				parent::addArray(":userID", $uid, "int"),
				parent::addArray(":menuID", $mid, "int")
			];
			$count = $this->data->executeScalar($sql, $intoAry);
			return ($count == 0) ? false : true;
		}
	}
?>