<?php
	require_once dirname(__FILE__) . "/dalBase.php";
	class areaDAL extends dalBase {
		public $AreaID;
		public $CityID;
		public $ZipCode;
		public $AreaName;
		public $Visible;
		public $OrderNO;
		//外部欄位
		public $CityName;

		public function loadRecord(): bool {
			$intoAry = [];
			$sql = "SELECT a.*,b.`CityName` FROM `area` a INNER JOIN `city` b ON a.`CityID`=b.`CityID` WHERE a.`AreaID`=:areaID";
			$intoAry[] = parent::addArray(":areaID", $this->AreaID, "int");
			$reader = $this->data->executeReader($sql, $intoAry);

			if (!empty($reader)) {
				$this->AreaID = $reader["AreaID"];
				$this->CityID = $reader["CityID"];
				$this->ZipCode = $reader["ZipCode"];
				$this->AreaName = $reader["AreaName"];
				$this->Visible = $reader["Visible"];
				$this->OrderNO = $reader["OrderNO"];
				$this->CityName = $reader["CityName"];
				return true;
			} else {
				return false;
			}
		}
		public function insertRecord(): bool|int {
			$intoAry = [
				parent::addArray(":cityID", $this->CityID, "int"),
				parent::addArray(":zipCode", $this->ZipCode, "str", 10),
				parent::addArray(":areaName", $this->AreaName, "str", 10),
				parent::addArray(":visible", $this->Visible, "int"),
				parent::addArray(":orderNO", $this->OrderNO, "int")
			];
			$sql = "INSERT INTO `area` (`CityID`, `ZipCode`, `AreaName`, `Visible`, `OrderNO`) VALUES (:cityID, :zipCode, :areaName, :visible, :orderNO)";
			$this->data->executeNonQuery($sql, $intoAry, true);
			return (!$this->data->error) ? $this->data->getInsertID() : false;
		}
		public function updateRecord(): bool {
			$intoAry = [
				parent::addArray(":areaID", $this->AreaID, "int"),
				parent::addArray(":zipCode", $this->ZipCode, "str", 10),
				parent::addArray(":areaName", $this->AreaName, "str", 10),
				parent::addArray(":visible", $this->Visible, "int"),
				parent::addArray(":orderNO", $this->OrderNO, "int")
			];
			$sql = "UPDATE `area` SET ".
				"`ZipCode`=:zipCode".
				",`AreaName`=:areaName".
				",`Visible`=:visible".
				",`OrderNO`=:orderNO".
				" WHERE `AreaID`=:areaID";
			$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.*,b.`CityName` FROM `area` a INNER JOIN `city` b ON a.`CityID`=b.`CityID`";
			if ($filter !== "") $sql .= " WHERE $filter";
			$sql .= (!isset($order) || $order === "") ? " ORDER BY a.`OrderNO`" : " 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 `area` a INNER JOIN `city` b ON a.`CityID`=b.`CityID`";
			if ($filter !== "") $sql .= " WHERE $filter";
			return $this->data->executeScalar($sql, $intoAry);
		}
	}
?>