<?php
	require_once "pageBase.php";
	require_once "../dal/userDAL.php";
	require_once "../dal/line_gearingDAL.php";
	require_once "../bin/system/utility.php";
	require_once "../bin/web/tables/sends.php";

	class _login extends pageBase {
		//覆蓋父類load()方法
		public function load() {
			// 顯示驗證碼
			parent::addParameter("checknum_html", $this->CheckNumHtml($this->registry->loginType));
			
			// 其他登入方式
			$loginMethods = [];
			if ($this->registry->isGoogleLogin == 1) $loginMethods[] = ["Name" => "Google登入", "Link" => "gmailLoginSend.php", "Icon" => "icon-google.svg"];
			if ($this->registry->isFbLogin == 1) $loginMethods[] = ["Name" => "Facebook登入", "Link" => "fbLoginSend.php", "Icon" => "icon-facebook.svg"];
			if ($this->registry->isLineLogin == 1) $loginMethods[] = ["Name" => "Line登入", "Link" => "lineLoginSend.php", "Icon" => "icon-line.svg"];

			$login_html = "";
			if (!empty($loginMethods)) {
				$login_html .= "<p class=\"mb_2 txt_g_300 talign_center\">使用其他帳號登入</p>";
				$login_html .= "<div class=\"talign_center btns\">";
				foreach ($loginMethods as $method) {
					$login_html .= "<a class=\"mr_2 ml_2 d_inblock\" href=\"{$method["Link"]}\" title=\"{$method["Name"]}\"><img src=\"images/svgs/{$method["Icon"]}\"></a>";
				}
				$login_html .= "</div>";
			}
			parent::addParameter("login_html", $login_html);
			
			if (parent::isPostBack()) {
				$this->login();
			} else if (parent::getGet("do") == "logout") {
				session_unset();
				header("Location: login.php");
			}
	
			parent::loadTemplateFile(dirname(__FILE__) . "/templates/login.html");
			parent::load();
		}

		// 登入
		private function login() {
			/* 錯誤鎖定 */
			$aryErr = [];
			if (file_exists("loginerror.txt")) {
				$errlog = file_get_contents("loginerror.txt");
				if (!empty($errlog)) $aryErr = json_decode($errlog, true);
			}
			/* 錯誤鎖定 */

			$myip = $this->getIP();
			$loginName = parent::getPost("login", "", 3);
			$password = parent::getPost("pass", "", 3);
			$checknum = parent::getPost("checknum");
			
			$dalU = new userDAL();
			$dalU->LoginName = $loginName;
			$dalU->loadRecord();
			
			if (!isset($dalU->UserID) || $dalU->UserID === "" || $dalU->UserID === 0 || ($dalU->Flags & 1) > 0 || (($dalU->UserType & userType::ADMIN) === 0 && ($dalU->UserType & userType::ADMINISTRATOR) === 0)) {
				$this->loginError($dalU->UserID, $loginName, $password, $checknum);
				$this->alertMsg = "用戶不存在,請聯繫管理員!";
				$this->locationHref = "login.php";
			} else if ($password !== $dalU->Password) {
				$this->loginError($dalU->UserID, $loginName, $password, $checknum);
				$this->alertMsg = "密碼錯誤,請聯繫管理員!";
				$this->locationHref = "login.php";
			} else if ($dalU->Visible != "1") {
				$this->loginError($dalU->UserID, $loginName, $password, $checknum);
				$this->alertMsg = "管理帳號已被停權!";
				$this->locationHref = "login.php";
			} else {
				if ($checknum === $_SESSION["dd_ckstr"] && isset($_SESSION["dd_ckstr"]) && $_SESSION["dd_ckstr"] !== "") {
					if (file_exists("loginerror.txt")) unlink('loginerror.txt');
	
					$info = new userInfo();
					$info->userID = $dalU->UserID;
					$info->loginName = $dalU->LoginName;
					$info->userName = $dalU->UserName;
					$info->userType = $dalU->UserType;
	
					$_SESSION[sessionKeys::ADMIN_USER_ID] = $dalU->UserID;
					$_SESSION[sessionKeys::USER_INFO] = $info;
	
					$dalU->LoginTimes = time();
					$dalU->LastLoginIp = $myip;
					$dalU->LastLoginTime = date("Y-m-d H:i:s");
					$dalU->updateRecord();
	
					$returnUrl = urldecode(isset($_GET["returnUrl"]) ? urldecode($_GET["returnUrl"]) : "/iweb/");
					$this->locationHref = $returnUrl;
				} else {
					$this->loginError($dalU->UserID, $loginName, $password, $checknum);
					$this->alertMsg = "驗證碼輸入錯誤!";
					$this->locationHref = "login.php";
				}
			}
		}
		// 錯誤鎖定
		private function loginError($userid, $loginName, $password, $checknum) {
			$dal = new userDAL();
			$dal->UserID = $userid;
			$dal->loadRecord();
			
			$sends = new sends();
			if ($userid > 1) {
				// line通知
				$dalL = new line_gearingDAL();
				$data = $dalL->executeRecordset([], "a.`LGID`!=0");
				$text = '網站後台登入錯誤，請盡快去后台查看!' . "\n" . '網站後台:' . $_SERVER['HTTP_HOST'] . '/iweb' . "\n" . '登入帳號:' . $loginName;
				for ($i = 0; $i < count($data); $i++) {
					$data[$i]["name"] = ($data[$i]["TargetType"] == "1") ? $data[$i]["Target"] . '您好:' . "\n" : '';
					$sends->linemessage($data[$i]["name"] . $text, $data[$i]["AccessToken"]);
				}
				
				// 系統信件內容
				$mtxt = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
				$mtxt .= '<html xmlns="https://www.w3.org/1999/xhtml">';
				$mtxt .= '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>';
				$mtxt .= '<body>';
				$mtxt .= '<p>您好：<br />網站後台登入錯誤，請盡快去後台查看!</p><br />';
				$mtxt .= '<p>網站後台：<a href="' . parent::getProtocol() . "://" . $_SERVER["HTTP_HOST"] . '/iweb">' . parent::getProtocol() . "://" . $_SERVER["HTTP_HOST"] . '/iweb</a></p>';
				$mtxt .= '<p>登入帳號：' . $loginName . '</p><br />';
				$mtxt .= '<p>為了確保資料安全，建議您登入後台重新更改密碼。</p>';
				$mtxt .= '<p>若無法登入請洽客服人員。</p><br />';
				$mtxt .= '<p style="color:#f00; font-weight:bolder;">此信件為系統自動發送!請勿直接回覆!</p>';
				$mtxt .= '</body>';
				$mtxt .= '</html>';

				$subject = "[" . $this->registry->webName . " " . $_SERVER['HTTP_HOST'] . "] [網站後台登入通知]";
	
				if ($dal->Email !== "") {
					if ($this->registry->sendMailType === "") {
						$sends->sendemail($this->registry->webName, $dal->Email, $subject, $mtxt, $dal->Email);
					} else {
						$toAry = [ $dal->Email ];
						$sends->sendsmtpmail($subject, $mtxt, $toAry);
					}
				}
			}

			$aryErr[] = [
				"Time" => date("Y-m-d H:i:s"),
				"IP" => $this->getIP(),
				"LoginName" => $loginName !== null ? urlencode($loginName) : null,
				"Password" => $password !== null ? urlencode($password) : null,
				"Checknum" => $checknum !== null ? urlencode($checknum) : null,
			];
			$newlog = json_encode($aryErr);
			file_put_contents("loginerror.txt", $newlog);
		}

		private function CheckNumHtml($loginType = "1") {
			if ($loginType === 1) {
				return <<<HTML
				<div class="mb_8" id="check_box">
					<label class="mb_1">登入驗證碼</label>
					<font class="in_group"><input type="text" id="checknum" name="checknum"><span class="group"><a class="btn btn_secondary" id="getCode" href="javascript:void(0);">取得驗證碼</a></span></font>
				</div>
			HTML;
			} else {
				return <<<HTML
				<div class="mb_8" id="check_box">
					<label class="mb_1">驗證碼</label>
					<font class="d_flex f_justify_center f_aitems_center">
						<input type="text" id="checknum" name="checknum" onKeyUp="this.value=this.value.toUpperCase();" autocomplete="off" maxlength="4" />
						<img class="ml_3" src="/vdimgck.php" id="rand-img" alt="看不清楚？ 點圖更換新圖片" align="absmiddle" style="cursor:pointer; border:none; width:auto;">
					</font>
				</div>
			HTML;
			}
		}
	}

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