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

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

		public function loadData() {
			$delTxt = "";
			if (!empty($this->id) && $this->id != 0) {
				$this->dal->NewsID = $this->id;
				$this->dal->loadRecord();
				if (parent::getCurrentUserID() > "1" && $this->dal->Disable == "1") {
					$this->alertMsg = "最新消息已經被刪除了!如有疑問請洽主管理者!";
					$this->locationHref = "newsList.php";
				} else {
					$this->addParametersFromNews($this->dal);
					
					$viewCount = $this->dal->ViewCount;
					$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{
				$defaultParameters = [
					"CategoryID" => "0",
					"OnlineTime" => date("Y-m-d H:i:s"),
					"ViewCount" => "0",
					"Visible" => "1",
					"OrderNO" => 100,
				];
				foreach ($defaultParameters as $paramName => $paramValue) {
					parent::addParameter($paramName, $paramValue);
				}
				
                $viewCount = 0;
				$ratingValue = rand(40, 49) / 10;
				$reviewCount = rand(10, 99);
				$ratingCount = round($ratingValue * $reviewCount);
				$editTitle = "新增";
			}
			
			//點閱次數
			$isAnalyze = registryDAL::getRegistryValue("isAnalyze");
			$count_box = ($isAnalyze === 0) ? "" : "<div class=\"col_md_4 d_flex form_list\"><label>點閱次數</label><input type=\"text\" value=\"" . $viewCount . "\" readonly /></div>";
			$count_style = ($isAnalyze === 0) ? "col_md_6" : "col_md_4";
            parent::addParameter("count_box", $count_box);
            parent::addParameter("count_style", $count_style);

			//分類下拉
			$dataC = $this->dalC->executeRecordset([], "a.`Visible`='1' AND a.`Disable`=0");
			$listC = new repeater();
			$listC->id = "listC";
			$listC->dataSource = $dataC;
			parent::addControl($listC);
			
			$aryT = [];
			$aryH = [];
			//Banner設定
			$aryT[] = ["id" => "banset", "name" => "Banner設定"];
			$aryH[] = ["html_box" => parent::BannerSetHtml(($BannerTitle ?? ''), ($BannerLink ?? ''), ($BannerColor ?? ''), ($BannerImage ?? ''), ($BannerDesc ?? ''), "News")];
			//社群分享設定
			$aryT[] = ["id" =>"ogset", "name" => "社群分享設定"];
			$aryH[] = ["html_box" => parent::MetaogSetHtml(($OGTitle ?? ''), ($OGImage ?? ''), ($OGDescription ?? ''), "News")];
			//結構化資料
			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->NewsID = $this->id;
				$this->dal->loadRecord();
			} else {
				$this->dal->PathName = guid::newGuid()->toString();
				$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->Title = parent::getPost("Title", "");
			if ($this->dal->Title === "") {
				$this->alertMsg = "請輸入消息標題!";
				$this->goBack = "Y";
				return false;
			}
			
			$twPathName = parent::getPost("TwPathName", $this->dal->Title);
			$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->QuoteText = parent::getPost("QuoteText");
			$this->dal->QuoteLink = parent::getPost("QuoteLink");
			$this->dal->Introduction = preg_replace("/\s+/", " ", parent::getPost("Introduction"));
			$this->dal->Description = parent::getPost("Description", "", 2);
			$this->dal->Image = parent::getPost("Image");
			$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->OGTitle = parent::getPost("OGTitle");
			$this->dal->OGDescription = preg_replace("/\s+/", " ", parent::getPost("OGDescription"));
			$this->dal->OGImage = parent::getPost("OGImage");
			$onlineTime = parent::getPost("OnlineTime");
			$this->dal->OnlineTime = ($onlineTime != "") ? strtotime($onlineTime) : time();
			$this->dal->Visible = parent::getPost("Visible", "0");
			$this->dal->OrderNO = parent::getPost("OrderNO", "100");
			
			$this->dal->WebTitle = preg_replace("/\s+/", " ", parent::getPost("WebTitle"));
			if (empty($this->dal->WebTitle)) $this->dal->WebTitle = $this->dal->Title . "-" . 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->Title . "," . $this->dalC->CategoryName;
			}
			$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");
			
			$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 addParametersFromNews($news) {
			$parameters = [
				"CategoryID" => $news->CategoryID,
				"Title" => $news->Title,
				"PathName" => $news->PathName,
				"TwPathName" => $news->TwPathName,
				"QuoteText" => $news->QuoteText,
				"QuoteLink" => $news->QuoteLink,
				"Introduction" => $news->Introduction,
				"Description" => $news->Description,
				"Image" => $news->Image,
				"OnlineTime" => ((int)$news->OnlineTime > 0) ? date("Y-m-d H:i:s", $news->OnlineTime) : date("Y-m-d H:i:s"),
				"ViewCount" => $news->ViewCount,
				"Visible" => $news->Visible,
				"OrderNO" => $news->OrderNO
			];
			foreach ($parameters as $name => $value) {
				parent::addParameter($name, $value);
			}
		}

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

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