<?php
	require_once "pageBase.php";
	require_once "bin/web/tables/sends.php";
	require_once "dal/memberDAL.php";
	class _forget_password extends pageBase {
		private $dal;
	
		public function load() {
			if ($this->registry->isCustomer == 0) {
				header("Location: /404.php");
				exit();
			}
		
			$this->dal = new memberDAL();
    
			if (isset($_SESSION["member_id"]) && $_SESSION["member_id"] != "") {
				$this->dal->MemberID = $_SESSION["member_id"];
				$this->dal->loadRecord();

				if ((int)$this->dal->Status > 0) {
					$this->alertMsg = "您已經登入!";
					$this->locationHref = "/";
				} elseif ((int)$this->dal->Status < -2) {
					unset($_SESSION["member_id"]);
					$this->alertMsg = "您已遭停權，如有疑問請和客服人員聯絡!";
					$this->locationHref = "/";
				} else {
					unset($_SESSION["member_id"]);
					$this->alertMsg = "您尚未通過驗證，請先完成驗證再登入一次!";
					$this->locationHref = "check_member.html";
				}
			} else {
				parent::isPostBack() ? $this->saveData() : $this->loadData();
			}
			
			parent::loadTemplateFile("templates/{$this->registry->webTemplates}/forget_password.html");
			parent::load();
		}
		
		public function loadData() {
			// 橫幅廣告
			$this->picturetype = "130";
			
			parent::loadData();
		}

		private function saveData() {
			/* 參數 */
			$login = parent::getPost("login");
			$checknum = parent::getPost("Checknum");

			// 驗證驗證碼
			if (!$this->validateChecknum($checknum)) {
				return;
			}

			// 取得會員資料
			$memberData = $this->getMemberData($login);
			if ($memberData === null) {
				$this->alertMsg = "找不到會員帳號資料!";
				$this->goBack = "Y";
				return;
			}

			// 生成新密碼
			$newPassword = $this->generateNewPassword($memberData);

			// 更新密碼
			if ($this->updatePassword($memberData, $newPassword)) {
				// 發送通知信
				$this->sendNotificationEmail($memberData, $newPassword);
				$this->locationHref = "member_login.html";
			} else {
				$this->alertMsg = "密碼變更失敗!";
				$this->goBack = "Y";
			}
		}

		private function validateChecknum($checknum) {
			if ($checknum != $_SESSION["dd_ckstr"] || !isset($_SESSION["dd_ckstr"]) || $_SESSION["dd_ckstr"] == '') {
				$this->alertMsg = "驗證碼輸入錯誤喔";
				$this->locationHref = "forget_password.html";
				return false;
			}
			return true;
		}

		private function getMemberData($login) {
			$intoAry = [parent::addArray(":loginName", $login, "str", 200)];
			$filter = "a.`LoginName`=:loginName AND a.`Status`>-3";
			return $this->dal->executeRecordset($intoAry, $filter)[0] ?? null;
		}

		private function generateNewPassword($memberData) {
			$aryP = array_merge(range(0, 9), range('A', 'Z'));
			do {
				$newPassword = implode('', array_rand(array_flip($aryP), 8));
				$hashedPassword = hash("sha256", $newPassword);
			} while ($hashedPassword == $memberData["LoginPass"]);
			return $newPassword;
		}

		private function updatePassword($memberData, $newPassword) {
			$this->dal->MemberID = $memberData["MemberID"];
			$this->dal->LoginPass = hash("sha256", $newPassword);
			$this->dal->ModifiedIP = parent::getIP();
			$this->dal->ModifiedUserID = "0";
			return $this->dal->changePassRecord();
		}

		private function sendNotificationEmail($memberData, $newPassword) {
			$sends = new sends();
			// 通知信
			$mbody = '<!doctype html>'.PHP_EOL;
			$mbody .= '<html lang="zh-tw">'.PHP_EOL;
			$mbody .= '<head>'.PHP_EOL;
			$mbody .= '<meta charset="utf-8" />'.PHP_EOL;
			$mbody .= '</head>'.PHP_EOL;
			$mbody .= '<body>'.PHP_EOL;
			$mbody .= '<p>會員遺忘密碼通知信</p>'.PHP_EOL;
			$mbody .= '<p>新密碼：'.$pass.'</p>'.PHP_EOL;
			$mbody .= '<p>請盡快登入後，變更會員密碼!</p>'.PHP_EOL;
			$mbody .= '<p>系統信件請勿直接回覆!</p>'.PHP_EOL;
			$mbody .= '</body>'.PHP_EOL;
			$mbody .= '</html>';
			$subject = "[" . $this->registry->webName . "][" . $_SERVER['HTTP_HOST'] . "]會員遺忘密碼通知信";

			if (empty($this->registry->sendMailType)) {
				$sends->sendemail($this->registry->webName, $memberData["MemberEmail"], $subject, $mbody, $memberData["MemberEmail"]);
			} else {
				$toAry = [$memberData["MemberEmail"]];
				$sends->sendsmtpmail($subject, $mbody, $toAry);
			}
		}
	}

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