<?php
	require_once "pageBase.php";
	require_once "bin/web/repeater.php";

	class _bookdetail extends pageBase {
		public $book;
		private $dalC;
	
		public function load() {
			$this->book = new book();
			$this->dalC = new book_categoryDAL();
			$this->loadData();
			parent::loadTemplateFile("templates/{$this->registry->webTemplates}/book-detail.html");
			parent::load();
		}
		
		public function loadData() {
			// 橫幅廣告
			$this->picturetype = "80";

			//宣告
			$dal = new bookDAL();
			$dalC2 = new book_categoryDAL();
			$dalC3 = new book_categoryDAL();

			switch ($this->registry->webLinkType) {
				case "2":
					$dal->TwPathName = parent::getGet("path", "", 2);
					break;
				case "3":
					$dal->PathName = parent::getGet("path", "", 2);
					break;
				default:
					$dal->BookID = parent::getGet("id");
			}
			$dal->loadRecord();
			if ($dal->Visible != "1" || $dal->CategoryVisible != "1" || 
				($dal->ParentID != "0" && $dal->ParentVisible != "1") || 
				($dal->ParentID != "0" && $dal->GrandID != "0" && $dal->GrandVisible != "1")) {
				$this->alertMsg = "找不到指定的網頁!";
				$this->locationHref = "/";
				return false;
			}
			
			if ($this->registry->isAnalyze != 0) $dal->click();

			// 內頁內容陣列
			$parameter = [
				"CategoryID" => $dal->CategoryID,
				"CategoryName" => $dal->CategoryName,
				"CategoryLink" => $this->book->linkBookList($dal->CategoryID),
				"BookID" => $dal->BookID,
				"BookName" => $dal->BookName,
				"Introduction" => str_replace("\r\n", "<br />", $dal->Introduction),
				"Description" => $dal->Description,
				"BookImage" => (!empty($dal->BookImage) && parent::image_exists($dal->BookImage)) ? $dal->BookImage : $this->NoPicImage,
				"bookImageStyle" => "",
			];

			// 資料內容檢查
			if ($parameter["BookImage"] == $this->NoPicImage) $parameter["bookImageStyle"] = " style='display:none;'";

			if (!empty($dal->OGTitle)) $parameter["ogTitle"] = $dal->OGTitle;
			if (!empty($dal->OGDescription)) $parameter["ogDescription"] = $dal->OGDescription;
			if (!empty($dal->OGImage)) $parameter["ogImage"] = parent::setPageOGImage($dal->OGImage);
			
			if (!empty($dal->WebTitle)) $parameter["webTitle"] = $dal->WebTitle;
			if (!empty($dal->WebKeyword)) $parameter["webKeyword"] = $dal->WebKeyword;
			if (!empty($dal->WebDescription)) $parameter["webDescription"] = $dal->WebDescription;
			
			if (!empty($dal->BannerImage) && parent::image_exists($dal->BannerImage)) {
				parent::setPageBanner($dal->BannerImage, $dal->BannerTitle, $dal->BannerLink, $dal->BannerColor, $dal->BannerDesc);
			} else {
				$this->dalC->CategoryID = $dal->CategoryID;
				$this->dalC->loadRecord();
				if (!empty($this->dalC->BannerImage) && parent::image_exists($this->dalC->BannerImage)) {
					parent::setPageBanner($this->dalC->BannerImage, $this->dalC->BannerTitle, $this->dalC->BannerLink, $this->dalC->BannerColor, $this->dalC->BannerDesc);
				} else {
					if ($this->dalC->ParentID != "0") {
						$dalC2->CategoryID = $this->dalC->ParentID;
						$dalC2->loadRecord();
						if (!empty($dalC2->BannerImage) && parent::image_exists($dalC2->BannerImage)) {
							parent::setPageBanner($dalC2->BannerImage, $dalC2->BannerTitle, $dalC2->BannerLink, $dalC2->BannerColor, $dalC2->BannerDesc);
						} else {
							if ($dalC2->ParentID != "0") {
								$dalC3->CategoryID = $dalC2->ParentID;
								$dalC3->loadRecord();
								if (!empty($dalC3->BannerImage) && parent::image_exists($dalC3->BannerImage)) parent::setPageBanner($dalC3->BannerImage, $dalC3->BannerTitle, $dalC3->BannerLink, $dalC3->BannerColor, $dalC3->BannerDesc);
							}
						}
					}
				}
			}
			
			foreach ($parameter as $name => $value) {
				parent::addParameter($name, $value);
			}
			
			// 相簿圖片
			$aryP = [];
			$aryP = $this->formatPhoto($dal->PhotoArray, $dal->BookName);
			$listP = new repeater();
			$listP->id = "listP";
			$listP->dataSource = $aryP;
			parent::addControl($listP);
			
			// 麵包削
			$aryR = [];
			$aryR[] = ["Name"=>$parameter["CategoryName"], "Link"=>$parameter["CategoryLink"]];
			if ($dal->ParentID != "0") {
				$aryR[] = ["Name"=>$dal->ParentName, "Link"=>$this->book->linkBookList($dal->ParentID)];
				if ($dal->GrandID != "0") $aryR[] = ["Name"=>$dal->GrandName, "Link"=> $this->book->linkBookList($dal->GrandID)];
			}
			$aryR = array_reverse($aryR);
			$listR = new repeater();
			$listR->id = "listR";
			$listR->dataSource = $aryR;
			parent::addControl($listR);

			// 相本分類列表
			$dataC = $this->dalC->executeRecordset([], "a.`ParentID`=0 AND a.`Visible`=1 AND a.`Disable`=0");
			$dataC = $this->formatCategory($dataC, $dal->CategoryID);
			$listC = new repeater();
			$listC->id = "listC";
			$listC->dataSource = $dataC;
			parent::addControl($listC);

			//同分類相本
			$intoAry = [
				parent::addArray(":categoryID", $dal->CategoryID, "int"),
				parent::addArray(":parentID", $dal->CategoryID, "int"),
				parent::addArray(":grandID", $dal->CategoryID, "int"),
			];
			$filter = "a.`Visible`=1 AND a.`Disable`=0 AND b.`Visible`=1 AND b.`Disable`=0 AND (b.`ParentID`=0 OR c.`Visible`=1 OR c.`Disable`=0) AND (b.`ParentID`=0 OR c.`ParentID`=0 OR d.`Visible`=1 OR d.`Disable`=0) AND (a.`CategoryID`=:categoryID OR b.`ParentID`=:parentID OR c.`ParentID`=:grandID)";
			$dataB = $dal->executeRecordset($intoAry, $filter);

			//上/下個相本
			$key = array_search($dal->BookID, array_column($dataB, "BookID")); // 取得上下筆的key值
			$up = ($key - 1);
			$down = ($key + 1);
			$pageParameter = [
				"pageUpName" => "-",
				"pageUpLink" => "javascript:void(0);",
				"pageUpImage" => $this->NoPicImage,
				"pageUpStyle" => " style='display:none;'",
				"pageDownName" => "-",
				"pageDownLink" => "javascript:void(0);",
				"pageDownImage" => $this->NoPicImage,
				"pageDownStyle" => " style='display:none;'",
			];
			if ($up >= 0) {
				$pageParameter["pageUpName"] = $dataB[$up]["BookName"];
				$pageParameter["pageUpLink"] = $this->book->linkBookDetail($dataB[$up]["BookID"]);
				if (!empty($dataB[$up]["BookImage"]) && parent::image_exists($dataB[$up]["BookImage"])) $pageParameter["pageUpImage"] = $dataB[$up]["BookImage"];
				$pageParameter["pageUpStyle"] = "";
			}
			if ($down < count($dataB)) {
				$pageParameter["pageDownName"] = $dataB[$down]["BookName"];
				$pageParameter["pageDownLink"] = $this->book->linkBookDetail($dataB[$down]["BookID"]);
				if (!empty($dataB[$down]["BookImage"]) && parent::image_exists($dataB[$down]["BookImage"])) $pageParameter["pageDownImage"] = $dataB[$down]["BookImage"];
				$pageParameter["pageDownStyle"] = "";
			}
			foreach ($pageParameter as $name => $value) {
				parent::addParameter($name, $value);
			}
			
			// 相關產品
			$dataB2 = $dal->executeRecordset($intoAry, $filter, "RAND()", 0, 4);
			$dataB2 = $this->formatBook($dataB2);
			$listB = new repeater();
			$listB->id = "listB";
			$listB->dataSource = $dataB2;
			parent::addControl($listB);
			
			// 結構化資料
			$GoogleSearch = $this->book->seoGoogleSearch($dal->BookID, 1);
			parent::addParameter("GoogleSearch", $GoogleSearch);

			//父類方法
			parent::loadData();
		}
		
		private function formatCategory($data = [], $id = 0) {
			$iLabel = "<b data-action='sideOpen'><i class='fa fa-plus' aria-hidden='true'></i></b>";
			$iLabel2 = "<b data-action='sideOpen'><i class='fa fa-minus' aria-hidden='true'></i></b>";
			$this->dalC->CategoryID = $id;
			$this->dalC->loadRecord();
			foreach ($data as &$category) {
				$category["link"] = $this->book->linkBookList($category["CategoryID"]);
				$category["iLabel"] = "";
				$category["SubList"] = "";
				$category["className"] = "";

				$intoAry = [parent::addArray(":parentID", $category["CategoryID"], "int")];
				$dataS = $this->dalC->executeRecordset($intoAry, "a.`ParentID`=:parentID AND a.`Visible`=1 AND a.`Disable`=0");
				if (count($dataS) > 0) {
					$categoryId = $category["CategoryID"];
					if ($categoryId == $id || $categoryId == $this->dalC->ParentID || $categoryId == $this->dalC->GrandID) {
						$category["className"] = " class='action'";
						$category["iLabel"] = $iLabel2;
					} else {
						$category["iLabel"] = $iLabel;
					}
					
					$category["SubList"] .= "<ul class='subUL'>";
					foreach ($dataS as $rows) {
						$into2Ary = [parent::addArray(":parentID", $rows["CategoryID"], "int")];
						$dataS2 = $this->dalC->executeRecordset($into2Ary, "a.`ParentID`=:parentID AND a.`Visible`=1 AND a.`Disable`=0");

						$category["SubList"] .= ($rows["CategoryID"] == $id || $rows["CategoryID"] == $this->dalC->ParentID) ? "<li class='action'>" : "<li>";
						$category["SubList"] .= "<div class='subULHead'><p><a href='".$this->book->linkBookList($rows["CategoryID"])."'>".$rows["CategoryName"]."</a></p>";
						
						if (count($dataS2) > 0) {
							if ($rows["CategoryID"] == $id || $rows["CategoryID"] == $this->dalC->ParentID) {
								$category["className"] = " class='action'";
								$category["SubList"] .= $iLabel2."</div>";
							} else {
								$category["SubList"] .= $iLabel."</div>";
							}

							$category["SubList"] .= "<ul class='sub2UL'>";
							foreach ($dataS2 as $rows2) {
								$category["SubList"] .= ($rows2["CategoryID"] == $id) ? "<li class='action'>" : "<li>";
								$category["SubList"] .= "<div class='sub2ULHead'><p><a href='".$this->book->linkBookList($rows2["CategoryID"])."'>".$rows2["CategoryName"]."</a></p></div></li>";
							}
							$category["SubList"] .= "</ul>";
						} else {
							$category["SubList"] .= "</div>";
						}
						$category["SubList"] .= "</li>";
					}
					$category["SubList"] .= "</ul>";
				} else {
					if ($category["CategoryID"] == $id) $category["className"] = " class='action'";
				}
			}
			return $data;
		}

		private function formatBook($data = []) {
			foreach ($data as &$item) {
				$item["link"] = $this->book->linkBookDetail($item["BookID"]);
				$item["linkC"] = $this->book->linkBookList($item["CategoryID"]);
				
				if (empty($item["BookImage"]) || !parent::image_exists($item["BookImage"])) $item["BookImage"] = $this->NoPicImage;
				$item["imageStyle"] = ($item["BookImage"] == $this->NoPicImage) ? " style='display:none;'" : "";
			}
			return $data;
		}
		
		private function formatPhoto($data = [], $name = "") {
			$formattedData = [];

			foreach ($data as $item) {
				if ($item["Visible"] != "1") continue;

				$item["Title"] = $item["Title"] ?: $name;

				if ($item["PhotoType"] == "2") {
					$item["attr"] = "><a class=\"popup-youtube photo\"";
					$item["Image"] = "https://img.youtube.com/vi/" . $this->youtubeurl($item["Video"]) . "/maxresdefault.jpg";
					$item["Link"] = "https://www.youtube.com/embed/" . $this->youtubeurl($item["Video"]);
				} else {
					$item["attr"] = " class=\"popup-img\"><a class=\"photo\"";
					$item["Image"] = (!empty($item["Image"]) && parent::image_exists($item["Image"])) ? $item["Image"] : $this->NoPicImage;
					$item["Link"] = ($item["Image"] != $this->NoPicImage) ? $item["Image"] : "javascript:void(0);";
				}

				$formattedData[] = $item;
			}
			return $formattedData;
		}

		public function youtubeurl($url="") {
			$urlarr = parse_url($url);
			parse_str($urlarr["query"], $parr);
		
			if (isset($parr["v"])) {
				$vid = $parr["v"];
			} else {
				$vid = end(preg_split("/\//", reset(preg_split("/\?/",$url))));
			}
		
			return $vid;
		}
	}

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