<?php
	require_once "pageBase.php";
	require_once "../dal/autokeywordDAL.php";
	require_once "../dal/autokeywordlinkDAL.php";
	require_once "../bin/system/conver.php";

	class _autokeywordAdd extends pageBase{
		//覆蓋父類load()方法
		public function load(){
			if(!parent::chkUserLimit('58')){
				parent::alert2('您沒有使用此頁面的權限!如有疑問請洽主管理者!','index.php');
				exit;
			}

			$this->loadData();
			parent::load();
		}
		public function loadData(){
			$dal = new autokeywordDAL();
			$dalL = new autokeywordlinkDAL();
			$action = conver::toDbString(trim($_POST["action"]));
			if($action == "key"){
				$keywordTitle = conver::toDbString(trim($_POST["KeywordTitle"]));
				if($keywordTitle == ""){
					parent::alert("請輸入關鍵字");
				}else{
					if($dal->countRecordset("a.`KeywordTitle`='".$keywordTitle."'") > 0){
						parent::alert("此關鍵字已經存在");
					}else{
						$data = $dal->executeRecordset("","a.`OrderNO` DESC",0,1);
						if(count($data) == 0){
							$orderNO = 1;
						}else{
							$orderNO = (int)$data[0]["OrderNO"] + 1;
						}
						$dal->KeywordTitle = $keywordTitle;
						$dal->Visible = "1";
						$dal->OrderNO = "".$orderNO;
						$dal->Important = "0";
						$saved = false;
						$saved = $dal->insertRecord();
						if($saved === false){
							parent::alert("儲存時發生錯誤!");
						}else{
							parent::redirect("autokeywordList.php");
						}
					}
				}
			}else if($action == "link"){
				$keywordID = conver::toDbString(trim($_POST["KeywordID"]));
				$linkURL = conver::toDbString(trim($_POST["LinkURL"]));
				if($keywordID == "0" || $keywordID == ""){
					parent::alert("請選擇關鍵字");
				}else if($linkURL == ""){
					parent::alert("請輸入超連結");
				}else{
					if(!preg_match("/http[s]?:\/\//i",$linkURL)){
						$linkURL = "http://".$linkURL;
					}
					if($dalL->countRecordset("a.`KeywordID`='".$keywordID."' AND a.`LinkURL`='".$linkURL."'") > 0){
						parent::alert("此關鍵字已經建立相同超連結");
					}else{
						$dataL = $dalL->executeRecordset("a.`KeywordID`='".$keywordID."'","a.`OrderNO` DESC",0,1);
						if(count($dataL) == 0){
							$orderNO = 1;
						}else{
							$orderNO = (int)$dataL[0]["OrderNO"] + 1;
						}
						$dalL->KeywordID = $keywordID;
						$dalL->LinkURL = $linkURL;
						$dalL->Visible = "1";
						$dalL->OrderNO = "".$orderNO;
						$saved = false;
						$saved = $dalL->insertRecord();
						if($saved === false){
							parent::alert("儲存時發生錯誤!");
						}else{
							parent::redirect("autokeywordList.php");
						}
					}
				}
			}else{
				parent::alert("系統異常!請重新整理頁面再試一次!");
			}
		}
	}

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