<?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 {
		public function load() {
			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();
			$lineUID = parent::getPost("lineUID");
			$pictureUrl = parent::getPost("pictureUrl");
			$displayName = parent::getPost("displayName");

			$dalU = new userDAL();
			$dalU->LineUID = $lineUID;
			$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($lineUID);
				$this->alertMsg = "用戶不存在,請聯繫管理員!";
				$this->locationHref = "login.php";
			} else if ($dalU->Visible != "1") {
				$this->loginError($lineUID);
				$this->alertMsg = "管理帳號已被停權!";
				$this->locationHref = "login.php";
			} else {
				if (file_exists("loginerror.txt")) unlink('loginerror.txt');
				
				if($dalU->LineName == ""){
					$dalU->LineName = $displayName;
					$dalU->LinePicture = $pictureUrl;
					$dalU->updateRecord();
				}
	
				$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;
			}
		}

		// 錯誤鎖定
		private function loginError($loginName) {
			$aryErr[] = [
				"Time" => date("Y-m-d H:i:s"),
				"IP" => $this->getIP(),
				"LineUID" => $loginName !== null ? urlencode($loginName) : null,
			];
			$newlog = json_encode($aryErr);
			file_put_contents("loginerror.txt", $newlog);
		}
	}

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