<?php
	require_once "pageBase.php";
	require_once "../../dal/articleDAL.php";
	require_once "../../dal/article_categoryDAL.php";
	require_once "../../dal/bookDAL.php";
	require_once "../../dal/book_categoryDAL.php";
	require_once "../../dal/categoryDAL.php";
	require_once "../../dal/faqDAL.php";
	require_once "../../dal/faq_categoryDAL.php";
	require_once "../../dal/htaccessDAL.php";
	require_once "../../dal/newsDAL.php";
	require_once "../../dal/news_categoryDAL.php";
	require_once "../../dal/productDAL.php";
	require_once "../../dal/registryDAL.php";
	require_once "../../dal/webmenuDAL.php";
	class _webmenu extends pageBase {
		private array $aryJ;

		public function __construct() {
			$this->dal = new bookDAL();
			$this->aryJ = ["err" => "0", "msg" => ""];
		}

		public function load(): void {
			$this->aryJ["msg"] = "";

			$action = parent::getPost("do");
			switch ($action) {
				case "slt":
					$this->select();
					break;
				case "del":
					$this->delete();
					break;
				default:
					$this->handleError("參數異常!請重新整理頁面再試一次!");
			}
		
			if ($this->aryJ["msg"] !== "") $this->aryJ["msg"] = urlencode($this->aryJ["msg"]);
			echo urldecode(json_encode($this->aryJ));
			parent::load();
		}
		
		private function select(){
			$dal = new htaccessDAL();
			$kw = parent::getPost("kw");
			$typ = parent::getPost("typ");
			$webLinkType = registryDAL::getRegistryValue("webLinkType");
			$host = preg_replace("/^www\./", "", $_SERVER['HTTP_HOST']);
			$link = preg_replace("/^(https?:)?\/\/(www\.)?".$host."\//", "/", $kw);
			if(preg_match("/^\//", $link)){
				switch($typ){
					case "2":
						$this->handleLinkType($webLinkType, 1, $link);
						break;
					case "3":
						$this->handleLinkType($webLinkType, 4, $link);
						break;
					case "4":
						$this->handleLinkType($webLinkType, 2, $link);
						break;
					case "5":
						$this->handleLinkType($webLinkType, 3, $link);
						break;
					case "6":
						$this->handleLinkType($webLinkType, 5, $link);
						break;
				}
			}else{
				$this->handleError("找不到對應的資料!請重新確認網址!");
			}
		}

		private function delete() {
			$dal = new webmenuDAL();
			$id = parent::getPost("id");
			if(!$dal->deleteRecord($id)){
				$this->handleError("刪除失敗!請重新整理頁面再試一次!");
			}else{
				$dal->delete2Record($id);
			}
		}

		// 建立網址正則式模板
		private function matchWebLinkPattern($webLinkType, $patternType, $htmlName, $actionName = "") {
			if ($webLinkType === "2") {
				switch ($patternType) {
					case 'default':
						return "/^\/" . preg_quote($htmlName, '/') . "\/(page\/\d+\/)?$/";
					case 'category':
						return "/^\/" . preg_quote($htmlName, '/') . "\/cate\/([^\/]+)\/(page\/\d+\/)?$/";
					case 'detail':
						return "/^\/" . preg_quote($htmlName, '/') . "\/([^\/]+)\/$/";
				}
			} else {
				switch ($patternType) {
					case 'default':
						return "/^\/" . preg_quote($htmlName, '/') . "(_\d+)?\.html$/";
					case 'category':
						return "/^\/" . preg_quote($htmlName, '/') . "(\d+)(_\d+)?\.html$/";
					case 'detail':
						if ($webLinkType === "3" || $actionName === "article") {
							return "/^\/" . preg_quote($htmlName, '/') . "-([a-zA-Z0-9\-_]+)\.html$/";
						} else {
							return "/^\/" . preg_quote($htmlName, '/') . "-(\d+)\.html$/";
						}
				}
			}
		}

		// 建立網址檢查模板
		private function handleLinkType($webLinkType, $typ, $v) {
			$linkMethods = [
				"1" => ["article_categoryDAL", "articleDAL", "ArticleID"],
				"2" => ["news_categoryDAL", "newsDAL", "NewsID"],
				"3" => ["faq_categoryDAL", "faqDAL", "FaqID"],
				"4" => ["categoryDAL", "productDAL", "ProductID"],
				"5" => ["book_categoryDAL", "bookDAL", "BookID"]
			];

			if (isset($linkMethods[$typ])) {
				[$categoryMethod, $detailMethod, $detailID] = $linkMethods[$typ];
			}

			$dal = new htaccessDAL();
			$dal->ID = $typ;
			$dal->loadRecord();
			$defaultPattern = $this->matchWebLinkPattern($webLinkType, 'default', $dal->HtmlName, $dal->ActionName);
			$categoryPattern = $this->matchWebLinkPattern($webLinkType, 'category', $dal->HtmlName, $dal->ActionName);
			$detailPattern = $this->matchWebLinkPattern($webLinkType, 'detail', $dal->HtmlName, $dal->ActionName);
		
			$category = new $categoryMethod();
			$detail = new $detailMethod();
			
			if (preg_match($defaultPattern, $v)) {
				$this->aryJ["typ"] = "1";
				$this->aryJ["id"] = "0";
			} else if (preg_match($categoryPattern, $v, $ary1)) {
				if ($webLinkType === "2") {
					$category->TwPathName = urldecode($ary1[1]);
				} else {
					$category->CategoryID = $ary1[1];
				}
				$category->loadRecord();
				
				if (($typ === "4" || $typ === "5") && 
					($category->Visible=== 1 || $category->Disable === "0") && 
					($category->ParentID === "0" || $category->ParentVisible=== 1 || $category->ParentDisable === "0") && 
					($category->ParentID === "0" || $category->GrandID === "0" || $category->GrandVisible=== 1|| $category->GrandDisable === "0")) {
					$this->aryJ["typ"] = "1";
					$this->aryJ["id"] = $category->CategoryID;
				} else if ($category->Visible=== 1 || $category->Disable === "0") {
					$this->aryJ["typ"] = "1";
					$this->aryJ["id"] = $category->CategoryID;
				} else {
					$this->handleError("指定的網址無法開啟!請選擇其它網址!");
				}
			} else if (preg_match($detailPattern, $v, $ary1)) {
				if ($typ=== 1) {
					$detailIDKey = $webLinkType === "2" ? "TwPathName" : "PathName";
				} else {
					$detailIDKey = $webLinkType === "2" ? "TwPathName" : ($webLinkType === "3" ? "PathName" : $detailID);
				}
				$detail->$detailIDKey = ($webLinkType === "2") ? urldecode($ary1[1]) : $ary1[1];
				$detail->loadRecord();
				
				if (($typ === "4" || $typ === "5") &&
					($detail->Visible=== 1 || $detail->Disable === "0") && 
					($detail->CategoryVisible=== 1 || $detail->CategoryDisable) && 
					($detail->ParentID === "0" || $detail->ParentVisible=== 1 || $detail->ParentDisable === "0") && 
					($detail->ParentID === "0" || $detail->GrandID === "0" || $detail->GrandVisible=== 1 || $detail->GrandDisable === "0")) {
					$this->aryJ["typ"] = "2";
					$this->aryJ["id"] = $detail->$detailID;
				} else if (($detail->Visible=== 1 || $detail->Disable === "0") && ($detail->CategoryVisible=== 1 || $detail->CategoryDisable === "0")) {
					$this->aryJ["typ"] = "2";
					$this->aryJ["id"] = $detail->$detailID;
				} else {
					$this->handleError("指定的網址無法開啟!請選擇其它網址!");
				}
			} else {
				$this->handleError("找不到對應的資料!請重新確認網址!");
			}
		}
		
		private function handleError(string $errorMessage): void {
			$this->aryJ["err"] = "1";
			$this->aryJ["msg"] = $errorMessage;
		}
	}

	$page = new _webmenu();
	$page->load();
?>