<?php
	require_once dirname(dirname(__FILE__))."/bin/web/repeater.php";
	require_once dirname(dirname(__FILE__))."/dal/pictureDAL.php";
	require_once dirname(dirname(__FILE__))."/dal/extrainfoDAL.php";
	require_once dirname(dirname(__FILE__))."/dal/customDAL.php";

	class _sidePage2 extends webPartBase {
		public $product;
		public int $picturetype = 30;
		public function load() : void {
			$this->product = new product();
			$this->loadData();
			parent::loadTemplateFile(dirname(__FILE__)."/../templates/webParts/".$this->registry->webTemplates."/sidePage2.html");
			parent::load();
		}

		public function loadData() : void {
			$dalC = new categoryDAL();
			$dal = new productDAL();
			$dalOP = new productDAL();
			$dalC2 = new categoryDAL();
			$dalC3 = new categoryDAL();
			$dalP = new pictureDAL();
			$dalE = new extrainfoDAL();
			$dalCU = new customDAL();
			
			/*==================== 網站資訊 ====================*/
			// 網站SEO
			$seoParams = [ "webH1", "webMarquee", "webTitle", "webKeyword" , "webTemplates" ];
			foreach ($seoParams as $paramName) {
				parent::addParameter($paramName, $this->registry->$paramName);
			}
			// Line 連結開啟方式
			$LinkTarget = (parent::generateIosDevice()) ? " target=\"_blank\"" : "";
			parent::addParameter("LinkTarget" , $LinkTarget);
			$isShow = false;
			$webInfoStyle = " style=\"display:none;\"";
			$fields = [
				"webEmail" => ["webEmailisShow", "webEmailStyle", "", ""],
				"webAddress" => ["webAddressisShow", "webAddressStyle", "webAddressLink", ""],
				"webPhone" => ["webPhoneisShow", "webPhoneStyle", "", ""],
				"webMobile" => ["webMobileShow", "webMobileStyle", "", ""],
				"webFax" => ["webFaxisShow", "webFaxStyle", "", ""],
				"LineOpen" => ["lineTitleShow", "QRstyle", "lineQRCode", "lineTitle"]
			];
			foreach ($fields as $field => $properties) {
				[$isShowProperty, $styleProperty, $linkProperty] = $properties;
    
				$$styleProperty = " style=\"display:none;\"";
				$$linkProperty = "javascript:void(0);";
				
				if ($this->registry->$field !== "" && $this->registry->$isShowProperty=== 1) {
					$isShow = true;
					$$field = $this->registry->$field;
					$$styleProperty = "";
				
					if ($field === "webAddress") {
						$$linkProperty = !empty($this->registry->$field) ? "https://maps.google.com/maps?ll=23.016519,120.21529&z=15&t=m&hl=zh-TW&gl=US&mapclient=embed&q=" . urlencode($this->registry->$field) : "javascript:void(0);";
					}
				}
				parent::addParameter($field, $$field ?? "");
				parent::addParameter($styleProperty, $$styleProperty);
				parent::addParameter($linkProperty, $$linkProperty);
			}
			if ($isShow) $webInfoStyle = "";
			parent::addParameter("webInfoStyle", $webInfoStyle);
			
			/*================= 網站資訊是否顯示 =================*/
			$arySN = explode(",", $this->registry->sideNavShow);
			$sideNavStyle = in_array($this->picturetype, $arySN) ? "" : " style=\"display:none;\"";
			parent::addParameter("sideNavStyle", $sideNavStyle);

			/*=================== 商品分類列表 ===================*/
			$aryCSPS = explode(",", $this->registry->categorySidePageShow);
			$sideCategoryStyle = in_array($this->picturetype, $aryCSPS) ? "" : " style='display:none;'";
			if ($sideCategoryStyle === "") {
				$dataC = $dalC->executeRecordset([], "a.`ParentID`=0 AND a.`Visible`=1 AND a.`Disable`=0");
				$dataC = $this->formatCategory($dataC);
				$listC = new repeater();
				$listC->id = "listC";
				$listC->dataSource = $dataC;
				parent::addControl($listC);
			} else {
				$dataC = [];
			}
			parent::addParameter("sideCategoryStyle", $sideCategoryStyle);
			
			/*===================== Fb 相關 =====================*/
			$aryPS = explode(",", $this->registry->fbFansSidePageShow);
			$fbFans = "";
			if(in_array($this->picturetype, $aryPS) && !empty($this->registry->fbFansURL)){
				switch($this->registry->fbFansSidePageType){
					case "1":
						$fbFans = "<div class=\"fb-fans\"><a href=\"{$this->registry->fbFansURL}\" target=\"_blank\"><img src=\"/images/fb-fans.jpg\" style=\"width:100%;\"></a></div>";
						break;
					case "2":
						$fbFansLOGO = (empty($this->registry->fbFansLOGO) || !parent::image_exists($this->registry->fbFansLOGO)) ? "/images/fb-fans.jpg" : $this->registry->fbFansLOGO;
						$fbFans = "<div class=\"fb-fans\"><a href=\"{$this->registry->fbFansURL}\" target=\"_blank\"><img src=\"{$fbFansLOGO}\"></a></div>";
						break;
					case "3":
						$facepile = ($this->registry->fbFansFriendFace === '0') ? 'false' : 'true';
						$hidecover = ($this->registry->fbFansCoverPhoto === '1') ? 'false' : 'true';
						$showpost = ($this->registry->fbFansPagePost === '0') ? 'false' : 'true';
						$fbFans = "<div class=\"fb-page\" data-href=\"{$this->registry->fbFansURL}\" data-width=\"1200\" data-adapt-container-width=\"true\" data-hide-cover=\"{$hidecover}\" data-show-facepile=\"{$facepile}\" data-show-posts=\"{$showpost}\"><div class=\"fb-xfbml-parse-ignore\"><blockquote cite=\"{$this->registry->fbFansURL}\"><a href=\"{$this->registry->fbFansURL}\">Facebook</a></blockquote></div></div>";
						break;
					default:
						$fbFans = "";
						break;
				}
			}
			parent::addParameter("fbFans",$fbFans);
			
			/*=================== Google Map ===================*/
			$aryGMSPS = explode(",", $this->registry->googlemapSidePageShow);
			$googlemapStyle = in_array($this->picturetype, $aryGMSPS) && !empty($this->registry->googlemapAddress) ? "" : " style=\"display:none;\"";
			$googlemapAddress = $googlemapStyle === "" ? urlencode($this->registry->googlemapAddress) : "";
			parent::addParameter("googlemapStyle", $googlemapStyle);
			parent::addParameter("googlemapAddress", $googlemapAddress);

			/*==================== Youbtube ====================*/
			$aryYSPS = explode(",", $this->registry->youtubeSidePageShow);
			$youtubeHTML = "";
			$youtubeStyle = "";
			$youtubeImg = $this->NoPicImage;
			$youtubeURL = "javascript:void(0);";
			if ($this->registry->youtubeIndex == "1" || (in_array($this->picturetype, $aryYSPS) && !empty($this->registry->youtubeURL))) {
				if (!empty($this->registry->youtubeURL)) {
					$youtubeURL = str_replace("//youtu.be/", "//www.youtube.com/embed/", $this->registry->youtubeURL);
					$youtubeImg = "https://img.youtube.com/vi/" . substr($youtubeURL, -11) . "/maxresdefault.jpg";
					$playList = preg_replace("/^embed\//", "", stristr($youtubeURL, "embed/"));
					$youtubeURL .= joinQueryParameters([
						["rel", $this->registry->youtubeRel === "0"],
						["autoplay", $this->registry->youtubeAutoPlay=== 1],
						["mute", $this->registry->youtubeMute=== 1],
						["loop", $this->registry->youtubeLoop=== 1, "playlist" => $playList]
					]);
					$youtubeHTML .= "<a id=\"playYoutu\" href=\"" . $youtubeURL . "\" data-fancybox title=\"" . $this->registry->indexAboutTitle1 . "\"><i class=\"fa fa-play\"></i></a>";
				}
			} else {
				$youtubeStyle = " style=\"display:none;\"";
			}
			parent::addParameter("youtubeHTML",$youtubeHTML);
			parent::addParameter("youtubeStyle",$youtubeStyle);
			parent::addParameter("youtubeImg",$youtubeImg);
			parent::addParameter("youtubeURL",$youtubeURL);
			
			/*===================== 額外資訊 ======================*/
			$dataE = $dalE->executeRecordset([], "a.`Visible`=1");
			$dataE = parent::formatExtra($dataE);
			$listE = new repeater();
			$listE->id = "listE";
			$listE->dataSource = $dataE;
			parent::addControl($listE);
			$sideExtraStyle = (count($dataE) > 0) ? "" : " style=\"display:none;\"";
			parent::addParameter("sideExtraStyle", $sideExtraStyle);
			
			/*===================== 自訂欄位 ======================*/
			$arrCU = [];
			$dataCU = $dalCU->executeRecordset(
				intoAry: [],
				filter: "a.`Visible`=1 AND a.`Disable`=0"
			);
			foreach ($dataCU as $key => $item) {
				$item["NO"] = $key;
				$item["CustomContent"] = str_replace(PHP_EOL, "<br />", $item["CustomContent"]);
				$item["imageStyle"] = "";
				if ($item["CustomImage"] == "" || !parent::image_exists($item["CustomImage"])) {
					$item["CustomImage"] = $this->NoPicImage;
					$item["imageStyle"] = " style='display: none;'";
				}
				if ($item["CustomLink"] == "") $item["CustomLink"] = "javascript:void(0);";
				$arrCU[] = $item;
			}
			$listCU = new repeater();
			$listCU->id = "listCU";
			$listCU->dataSource = $arrCU;
			parent::addControl($listCU);
			
			/*=================== 小廣告設置 ===================*/
			$arySP = explode(",", $this->registry->smallPictureShow);
			$smallPictureStyle = in_array($this->picturetype, $arySP) ? "" : " style=\"display:none;\"";
			parent::addParameter("smallPictureStyle", $smallPictureStyle);
			
			/*==================== 相關產品 ====================*/
			$aryOP = [];
			$dataOP = $dalOP->executeRecordset([],"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)", "RAND()", 0, 4);
			foreach ($dataOP as &$item) {
				$item["link"] = $this->product->linkProductDetail($item["ProductID"]);
				$item["linkC"] = $this->product->linkProductList($item["CategoryID"]);
				if (empty($item["IconImage"]) || !parent::image_exists($item["IconImage"])) $item["IconImage"] = $this->NoPicImage;
				$aryOP[] = $item;
			}
			$listOP = new repeater();
			$listOP->id = "listOP";
			$listOP->dataSource = $dataOP;
			parent::addControl($listOP);
			
			/*====================== 小廣告 =======================*/
			$aryP = [];
			$dataP = $dalP->executeRecordset([], "a.`PictureType`=20", "a.`TypeOrderNO`");
			foreach ($dataP as $item) {
				if (!empty($item["Image"]) && parent::image_exists($item["Image"])) {
					$ary = [
						"Image" => $item["Image"],
						"Title" => $item["Title"],
						"Link" => (!empty($item["Link"]) ? $item["Link"] : "javascript:void(0);"),
						"NO" => $item["TypeOrderNO"],
						"NO2" => str_pad($item["TypeOrderNO"], 2, '0', STR_PAD_LEFT)
					];
					$aryP[] = $ary;
				}
			}
			$listP = new repeater();
			$listP->id = "listP";
			$listP->dataSource = $aryP;
			parent::addControl($listP);
			parent::addParameter("countsPicture", count($aryP));
			parent::addParameter("countsPicture2", str_pad(count($aryP), 2, '0', STR_PAD_LEFT));
		}

		private function formatCategory($data = []): array {
			$dal = new categoryDAL();
			$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>";
			
			foreach ($data as &$category) {
				$category["link"] = $this->product->linkProductList($category["CategoryID"]);
				$category["iLabel"] = "";
				$category["SubList"] = "";
				$category["className"] = "";
		
				$intoAry = [ parent::addArray(":parentID", $category["CategoryID"], "int") ];
				$dataS = $dal->executeRecordset($intoAry, "a.`ParentID`=:parentID AND a.`Visible`=1 AND a.`Disable`=0");
				if (count($dataS) > 0) {
					$category["iLabel"] = $iLabel;
					$category["SubList"] = "<ul class=\"subUL\" style=\"display:none;\">";
					foreach ($dataS as $subCategory) {
						$into2Ary = [ parent::addArray(":parentID", $subCategory["CategoryID"], "int") ];
						$dataS2 = $dal->executeRecordset($into2Ary, "a.`ParentID`=:parentID AND a.`Visible`=1 AND a.`Disable`=0");
						$category["SubList"] .= "<li><div class=\"subULHead\"><p><a href=\"" . $this->product->linkProductList($subCategory["CategoryID"]) . "\">" . $subCategory["CategoryName"] . "</a></p>";
						if (count($dataS2) > 0) {
							$category["SubList"] .= $iLabel;
							$category["SubList"] .= "<ul class=\"sub2UL\" style=\"display:none;\">";
							foreach ($dataS2 as $subCategory2) {
								$category["SubList"] .= "<li><div class=\"sub2ULHead\"><p><a href=\"" . $this->product->linkProductList($subCategory2["CategoryID"]) . "\">" . $subCategory2["CategoryName"] . "</a></p></div></li>";
							}
							$category["SubList"] .= "</ul>";
						} else {
							$category["SubList"] .= "</div>";
						}
						$category["SubList"] .= "</li>";
					}
					$category["SubList"] .= "</ul>";
				}
			}
			return $data;
		}
	}
?>