<?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() {
			$this->login();
			parent::loadTemplateFile(dirname(__FILE__) . "/templates/loginGmail.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);
			}
			/* 錯誤鎖定 */
			
			$http_reffer = preg_replace("/login\/facebookOauth\.php\?\w.*/", '', $_SERVER['HTTP_REFERER']);
			$apiWhiteListServers = file_get_contents('./line/srever.json');
			$apiWhiteListServers = json_decode($apiWhiteListServers, true);
			$r = array_search($http_reffer, $apiWhiteListServers);

			if ($r !== false) {
				$fbAccount = $this->getPost('FbAccount');
				$dalU = new userDAL();
				$dalU->FbAccount = $fbAccount;
				$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($fbAccount);
					$this->alertMsg = "用戶不存在,請聯繫管理員!";
					$this->locationHref = "login.php";
				} else if ($dalU->Visible != "1") {
					$this->loginError($fbAccount);
					$this->alertMsg = "管理帳號已被停權!";
					$this->locationHref = "login.php";
				} else {
					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->alertMsg = "系統錯誤";
				$this->locationHref = "login.php";
			}
		}

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

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