<?php
	require_once "pageBase.php";
	require_once "../bin/system/guid.php";
	require_once "../bin/web/repeater.php";
	require_once "../dal/categoryDAL.php";
	require_once "../dal/productDAL.php";
	require_once "../function/function.php";

	class _productEdit extends pageBase {
		private string $id;
		private string $pUrl;
		private $dal;
		private $dalC;
		
		public function load() {
			$this->dal = new productDAL();
			$this->dalC = new categoryDAL();
			$this->id = parent::getInput("id","0");
			$this->pUrl = urldecode(parent::getInput("pUrl","productList.php"));
			
			$this->limitID = "29";
			if (!parent::chkUserLimit()) {
				$this->alertMsg = "您沒有使用此頁面的權限!如有疑問請洽主管理者!";
				$this->locationHref = "index.php";
			} else {
				parent::isPostBack() ? $this->saveData() : $this->loadData();
			}
			parent::loadTemplateFile(dirname(__FILE__) . "/templates/productEdit.html");
			parent::load();
		}

		public function loadData() {
			$aryC = [];
			$dataC1 = $this->dalC->executeRecordset([], "a.`ParentID`=0 AND a.`Disable`=0");
			foreach ($dataC1 as $rows1) {
				$rows1["data"] = " data-action=\"lv1\"";
				$intoAry = [parent::addArray(":parentID", $rows1["CategoryID"], "int")];
				$dataC2 = $this->dalC->executeRecordset($intoAry, "a.`ParentID`=:parentID AND a.`Disable`=0");
				$rows1["disabled"] = (count($dataC2) > 0) ? " disabled='disabled'" : "";
				$aryC[] = $rows1;
				
				foreach ($dataC2 as $rows2) {
					$rows2["data"] = " data-action=\"lv2\"";
					$into2Ary = [parent::addArray(":parentID", $rows2["CategoryID"], "int")];
					$dataC3 = $this->dalC->executeRecordset($into2Ary, "a.`ParentID`=:parentID AND a.`Disable`=0");
					$rows2["disabled"] = (count($dataC3) > 0) ? " disabled='disabled'" : "";
					$aryC[] = $rows2;
					
					foreach ($dataC3 as $rows3) {
						$rows3["data"] = " data-action=\"lv3\"";
						$rows3["disabled"] = "";
						$aryC[] = $rows3;
					}
				}
			}
			$listC = new repeater();
			$listC->id = "listC";
			$listC->dataSource = $aryC;
			parent::addControl($listC);

			$delTxt = "";
			$aryPI = [];
			if (!empty($this->id) && $this->id != 0) {
				$this->dal->ProductID = $this->id;
				$this->dal->loadRecord();

				if (parent::getCurrentUserID() > "1" && $this->dal->Disable == "1") {
					$this->alertMsg = "產品已經被刪除了!如有疑問請洽主管理者!";
					$this->locationHref = "productList.php";
				} else {
					$aryPI = $this->dal->ProductImageArray;

					$this->addParametersFromProduct($this->dal);
					
					$bestRating = $this->dal->BestRating;
					$ratingValue = $this->dal->RatingValue;
					$ratingCount = $this->dal->RatingCount;
					$reviewCount = $this->dal->ReviewCount;
					$isShowJason = $this->dal->IsShowJason;
					$isShowStars = $this->dal->IsShowStars;
					$BannerImage = $this->dal->BannerImage;
					$BannerTitle = $this->dal->BannerTitle;
					$BannerLink = $this->dal->BannerLink;
					$BannerColor = $this->dal->BannerColor;
					$BannerDesc = $this->dal->BannerDesc;
					$OGTitle = $this->dal->OGTitle;
					$OGDescription = $this->dal->OGDescription;
					$OGImage = $this->dal->OGImage;
					$WebTitle = $this->dal->WebTitle;
					$WebKeyword = $this->dal->WebKeyword;
					$WebDescription = $this->dal->WebDescription;
					$editTitle = "修改";

					$delTxt = $this->getDeleteText($this->dal);
				}
			} else {
				$dataO = $this->dal->executeRecordset([], "", "a.`OrderNO` DESC", 0, 1);
				$orderNO = (count($dataO) == 0) ? 10 : ((int)$dataO[0]["OrderNO"] + 10);
				$defaultParameters = [
					"CategoryID" => "0",
					"ViewCount" => "0",
					"IsIndex" => "1",
					"Visible" => "1",
					"OrderNO" => $orderNO,
				];
				foreach ($defaultParameters as $paramName => $paramValue) {
					parent::addParameter($paramName, $paramValue);
				}
				
				$ratingValue = rand(40, 49) / 10;
				$reviewCount = rand(10, 99);
				$ratingCount = round($ratingValue * $reviewCount);
				$editTitle = "新增";
			}
			$listPI = new repeater();
			$listPI->id = "listPI";
			$listPI->dataSource = $aryPI;
			parent::addControl($listPI);
			
			$aryT = [];
			$aryH = [];
			//Banner設定
			$aryT[] = ["id" => "banset", "name" => "Banner設定"];
			$aryH[] = ["html_box" => parent::BannerSetHtml(($BannerTitle ?? ''), ($BannerLink ?? ''), ($BannerColor ?? ''), ($BannerImage ?? ''), ($BannerDesc ?? ''), "Product")];
			//社群分享設定
			$aryT[] = ["id" =>"ogset", "name" => "社群分享設定"];
			$aryH[] = ["html_box" => parent::MetaogSetHtml(($OGTitle ?? ''), ($OGImage ?? ''), ($OGDescription ?? ''), "Product")];
			//結構化資料
			if(parent::getCurrentUserID() == 1){
				$aryT[] = ["id" => "boxgseo", "name" => "結構化資料設定"];
				$aryH[] = ["html_box" => parent::GoogleSearchHtml(($bestRating ?? 5), $ratingValue, $reviewCount, $ratingCount, ($isShowJason ?? 0), ($isShowStars ?? 0))];
			}
			//SEO設定
			$aryT[] = ["id" => "seoset", "name" => "SEO設定"];
			$aryH[] = ["html_box" => parent::SeoSetHtml(($WebTitle ?? ''), ($WebKeyword ?? ''), ($WebDescription ?? ''))];
			
			$listT = new repeater();
			$listT->id = "listT";
			$listT->dataSource = $aryT;
			parent::addControl($listT);
			$listH = new repeater();
			$listH->id = "listH";
			$listH->dataSource = $aryH;
			parent::addControl($listH);

			parent::addParameter("id", $this->id);
			parent::addParameter("pUrl", $this->pUrl);
			parent::addParameter("editTitle", $editTitle);
			parent::addParameter("delTxt", $delTxt);
			parent::loadData();
		}

		public function saveData() {
			if (!empty($this->id) && $this->id != 0) {
				$this->dal->ProductID = $this->id;
				$this->dal->loadRecord();
			} else {
				$this->dal->PathName = guid::newGuid()->toString();
				$this->dal->ViewCount = "0";
				$this->dal->CreatedUserID = parent::getCurrentUserID();
				$this->dal->CreatedIP = parent::getIP();
			}
			
			$this->dal->CategoryID = parent::getPost("CategoryID", "0");
			if (!preg_match("/^\d+$/", $this->dal->CategoryID)) {
				$this->alertMsg = "產品分類選擇錯誤!請重新選擇!";
				$this->goBack = "Y";
				return false;
			}
			$this->dal->ProductName = parent::getPost("ProductName");
			if ($this->dal->ProductName === "") {
				$this->alertMsg = "請輸入產品名稱!";
				$this->goBack = "Y";
				return false;
			}
			$twPathName = parent::getPost("TwPathName", $this->dal->ProductName);
			$twPathName = parent::generateTwPathName($twPathName);
			if ($this->dal->checkTwPathNameExists($twPathName) && $this->dal->TwPathName !== $twPathName) {
				$this->alertMsg = "中文路徑名稱「" . $twPathName . "」已經存在!";
				$this->goBack = "Y";
				return false;
			}
			$this->dal->TwPathName = $twPathName;
			$this->dal->ProductNO = parent::getPost("ProductNO");
			$this->dal->OldPrice = parent::getPost("OldPrice", "0");
			$this->dal->Price = parent::getPost("Price", "0");
			$this->dal->IconImage = parent::getPost("IconImage");
			$this->dal->BannerImage = parent::getPost("BannerImage");
			$this->dal->BannerTitle = parent::getPost("BannerTitle");
			$this->dal->BannerLink = parent::getPost("BannerLink");
			$this->dal->BannerColor = parent::getPost("BannerColor");
			$this->dal->BannerDesc = parent::getPost("BannerDesc");
			$this->dal->Introduction = preg_replace("/\s+/", " ", parent::getPost("Introduction"));
			$this->dal->Specification = parent::getPost("Specification", "", 2);
			$this->dal->Title1 = parent::getPost("Title1");
			$this->dal->Title2 = parent::getPost("Title2");
			$this->dal->Title3 = parent::getPost("Title3");
			$this->dal->Description1 = parent::getPost("Description1", "", 2);
			$this->dal->Description2 = parent::getPost("Description2", "", 2);
			$this->dal->Description3 = parent::getPost("Description3", "", 2);
			$this->dal->OGTitle = parent::getPost("OGTitle");
			$this->dal->OGDescription = preg_replace("/\s+/", " ", parent::getPost("OGDescription"));
			$this->dal->OGImage = parent::getPost("OGImage");
			$this->dal->IsIndex = parent::getPost("IsIndex", "0");
			$this->dal->Visible = parent::getPost("Visible", "0");
			$this->dal->OrderNO = parent::getPost("OrderNO", "0");

			$this->dal->WebTitle = preg_replace("/\s+/", " ", parent::getPost("WebTitle"));
			if (empty($this->dal->WebTitle)) $this->dal->WebTitle = $this->dal->ProductName . "-" . parent::getRegistryValue("webTitle");
			$this->dal->WebKeyword = preg_replace("/\s+/", " ", parent::getPost("WebKeyword"));
			if (empty($this->dal->WebKeyword)) {
				$this->dalC->CategoryID = $this->dal->CategoryID;
				$this->dalC->loadRecord();
				$this->dal->WebKeyword = $this->dal->ProductName . "," . $this->dalC->CategoryName;
				if ($this->dalC->ParentName !== "") $this->dal->WebKeyword .= "," . $this->dalC->ParentName;
				if ($this->dalC->GrandName !== "") $this->dal->WebKeyword .= "," . $this->dalC->GrandName;
			}
			$this->dal->WebDescription = preg_replace("/\s+/", " ", parent::getPost("WebDescription"));
			if (empty($this->dal->WebDescription)) $this->dal->WebDescription = mb_substr($this->dal->Introduction, 0, 150, "utf-8");
			
			$this->dal->ModifiedUserID = parent::getCurrentUserID();
			$this->dal->ModifiedIP = parent::getIP();
    
			$this->dal->BestRating = parent::getPost("BestRating", "5");
			$this->dal->RatingValue = parent::getPost("RatingValue", "0");
			$this->dal->RatingCount = parent::getPost("RatingCount", "0");
			$this->dal->ReviewCount = parent::getPost("ReviewCount", "0");
			$this->dal->IsShowJason = parent::getPost("IsShowJason", "0");
			$this->dal->IsShowStars = parent::getPost("IsShowStars", "0");
			
			$this->dal->ProductImageArray = [];
			$ImageArray = parent::getPostArray("Image");
			$TitleArray = parent::getPostArray("Title");
			$DescriptionArray = parent::getPostArray("Description");
			for ($i = 0; $i < count($ImageArray); $i++) {
				if (!empty($ImageArray[$i])) {
					$aryI = ["Image" => $ImageArray[$i]];
					if (count($ImageArray) === count($TitleArray)) $aryI["Title"] = $TitleArray[$i];
					if (count($ImageArray) === count($DescriptionArray)) $aryI["Description"] = $DescriptionArray[$i];
					
					$this->dal->ProductImageArray[] = $aryI;
				}
			}
			
			$saved = ($this->id !== "" && $this->id !== "0") ? $this->dal->updateRecord() : $this->dal->insertRecord();
			if ($saved === false) {
				$this->alertMsg = "儲存時發生錯誤!";
				$this->goBack = "Y";
			} else {
				$this->locationHref = $this->pUrl;
			}
		}

		/* 取得產品資訊 */
		private function addParametersFromProduct($product) {
			$parameters = [
				"CategoryID" => $product->CategoryID,
				"ProductName" => $product->ProductName,
				"PathName" => $product->PathName,
				"TwPathName" => $product->TwPathName,
				"ProductNO" => $product->ProductNO,
				"OldPrice" => $product->OldPrice,
				"Price" => $product->Price,
				"IconImage" => $product->IconImage,
				"Introduction" => $product->Introduction,
				"Specification" => $product->Specification,
				"Title1" => $product->Title1,
				"Title2" => $product->Title2,
				"Title3" => $product->Title3,
				"Description1" => $product->Description1,
				"Description2" => $product->Description2,
				"Description3" => $product->Description3,
				"ViewCount" => $product->ViewCount,
				"IsIndex" => $product->IsIndex,
				"Visible" => $product->Visible,
				"OrderNO" => $product->OrderNO,
			];
			foreach ($parameters as $name => $value) {
				parent::addParameter($name, $value);
			}
		}

		/* 獲取刪除文本 */
		private function getDeleteText($product) {
			return $product->Disable == "1" ? "<p class=\"mt_3 h4 txt_danger card_body\">注意:【".$product->ProductName."】產品已經被刪除，不會顯示在前台列表頁。</p>" : "";
		}
	}

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