<?php
	require_once "pageBase.php";
	require_once "dal/log_errorDAL.php";
	require_once "dal/memberDAL.php";
	class _member_login extends pageBase {
		public function load() {
			if ($this->registry->isCustomer == 0) {
				header("Location: /404.php");
				exit();
			}

			if (isset($_SESSION["member_id"]) && $_SESSION["member_id"] != "") {
				$this->locationHref = "member1.html";
			} else {
				parent::isPostBack() ? $this->saveData() : $this->loadData();
			}
			
			parent::loadTemplateFile("templates/{$this->registry->webTemplates}/member_login.html");
			parent::load();
		}
		
		public function loadData() {
			// 橫幅廣告
			$this->picturetype = "130";
			
			parent::loadData();
		}

		private function saveData() {
			/* 宣告 */
			$dal = new memberDAL();
			$dalL = new log_errorDAL();

			/* 參數 */
			$login = parent::getPost("login");
			$pass = parent::getPost("pass");
			$pass2 = hash("sha256", $pass);
			$ip = parent::getIP();
			/* 檢查 */
			$dalL->LogIP = $ip;
			if ($dalL->stop_check()) {
				$this->alertMsg = "登入錯誤次數過多!";
				$this->goBack = "Y";
				return;
			}

			// 嘗試進行登入
			$memberData = $this->attemptLogin($dal, $login, $passHash);
			if ($memberData === null) {
				$dalL->login_error();
				$this->alertMsg = "帳號密碼錯誤!";
				$this->goBack = "Y";
				return;
			}

			// 檢查會員帳號狀態
			$status = (int)$memberData["Status"];
			if ($status < -2) {
				$this->alertMsg = "帳號已停用!如有疑問請和客服人員聯絡!";
				$this->goBack = "Y";
				return;
			} elseif ($status < 1) {
				$this->alertMsg = "帳號尚未驗證，請先驗證後再登入!";
				$this->locationHref = "check_member.html";
				return;
			}
		
			// 登入成功
			if ($this->loginSuccess($dal, $dalL, $memberData, $ip)) {
				$_SESSION["member_id"] = $memberData["MemberID"];
				$this->locationHref = "member1.html";
			} else {
				$this->alertMsg = "登入失敗!請重新整理頁面再試一次!或和客服人員聯絡!";
				$this->goBack = "Y";
			}
		}

		private function attemptLogin($dal, $login, $passHash) {
			$intoAry = array(
				parent::addArray(":loginName", $login, "str", 200),
				parent::addArray(":loginPass", $passHash, "str", 200)
			);
		
			$filter = "a.`LoginName`=:loginName AND a.`LoginPass`=:loginPass";
			$orderExp = "a.`MemberID`";
		
			$data = $dal->executeRecordset($intoAry, $filter, $orderExp, 0, 1);
			return count($data) == 1 ? $data[0] : null;
		}

		private function loginSuccess($dal, $dalL, $memberData, $ip) {
			$dal->MemberID = $memberData["MemberID"];
			$dal->LastLoginIP = $ip;
			if ($dal->loginRecord()) {
				$dalL->login_success();
				return true;
			}
			return false;
		}
	}

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