<?php
	require_once "pageBase.php";
	require_once "../bin/system/conver.php";
	require_once "../dal/bookDAL.php";
	require_once "../dal/photoDAL.php";

	class _photoMulti extends pageBase {
		private string $bookID;
		private string $pUrl2;
		private $dal;
		
		public function load() {
			$this->dal = new photoDAL();
			$this->bookID = parent::getInput("bookID","0");
			$this->pUrl2 = parent::getInput("pUrl2","bookList.php");
			
			$this->limitID = "26";
			if (!parent::chkUserLimit()) {
				$this->alertMsg = "您沒有使用此頁面的權限!如有疑問請洽主管理者!";
				$this->locationHref = "index.php";
			} else {
				parent::isPostBack() ? $this->saveData() : $this->loadData();
			}
			parent::load();
		}

		public function loadData() {
			$dalB = new bookDAL();
			$dalB->BookID = $this->bookID;
			$dalB->loadRecord();

			$intoAryO = [parent::addArray(":bookID", $this->bookID, "int")];
			$dataO = $this->dal->executeRecordset($intoAryO, "a.`BookID`=:bookID", "a.`OrderNO` DESC", 0, 1);
			$orderNO = (count($dataO) == 0) ? 10 : ((int)$dataO[0]["OrderNO"] + 10);
			
			parent::addParameter("OrderNO", $orderNO);
			parent::addParameter("PhotoName", $PhotoName);
			parent::addParameter("BookName", $dalB->BookName);

			parent::addParameter("bookID", $this->bookID);
			parent::addParameter("pUrl2", $this->pUrl2);
			
			parent::loadTemplateFile(dirname(__FILE__) . "/templates/photoMulti.html");
			parent::loadData();
		}

		public function saveData() {
			$images = parent::getPostArray("Image");
			$orderNumbers = parent::getPostArray("OrderNO");
			$photoNames = parent::getPostArray("PhotoName");
			if (count($images) === count($orderNumbers)) {
				foreach ($images as $index => $image) {
					$this->dal->BookID = $this->bookID;
					$this->dal->PhotoType = "1";
					$this->dal->Image = $image;
					$this->dal->Visible = "1";
					$this->dal->PhotoName = $photoNames[$index];
					$this->dal->OrderNO = is_numeric($orderNumbers[$index]) ? $orderNumbers[$index] : 0;
					$this->dal->insertRecord();
				}
			}
			parent::redirect($this->pUrl2);
		}
	}

	$page = new _photoMulti();
	$page->load();
	$page->render();
?>