<?php
	require_once "pageBase.php";
	require_once "dal/memberDAL.php";
	class _change_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) {
					parent::isPostBack() ? $this->saveData() : $this->loadData();
				} 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 {
				$this->alertMsg = "您尚未登入! 請先登入!";
				$this->locationHref = "member_login.html";
			}
			
			parent::loadTemplateFile("templates/{$this->registry->webTemplates}/change_password.html");
			parent::load();
		}
		
		public function loadData() {
			// 橫幅廣告
			$this->picturetype = "130";
			
			parent::loadData();
		}

		private function saveData() {
			/* 參數 */
			$oldpass = parent::getPost("old", "");
			$newpass1 = parent::getPost("new1", "");
			$newpass2 = parent::getPost("new2", "");

			// 檢查舊密碼是否正確
			if (!$this->isOldPasswordCorrect($oldpass)) {
				$this->alertMsg = "舊密碼錯誤!";
				$this->goBack = "Y";
				return false;
			}

			// 檢查新密碼是否有效
			if (!$this->isNewPasswordValid($newpass1, $newpass2)) return false;

			// 更新密碼並保存
			$newhash = hash("sha256", $newpass1);
			$this->dal->LoginPass = $newhash;
			$this->dal->ModifiedIP = parent::getIP();
			$this->dal->ModifiedUserID = "0";
			$saved = $this->dal->changePassRecord();

			if (!$saved) {
				$this->alertMsg = "密碼變更失敗!";
				$this->goBack = "Y";
			} else {
				$this->alertMsg = "密碼變更完成!";
				$this->locationHref = "member1.html";
			}
		}
		
		private function isOldPasswordCorrect($oldpass) {
			if (empty($oldpass) || !preg_match("/^\S{5,20}$/", $oldpass)) return false;

			$oldhash = hash("sha256", $oldpass);
			return $this->dal->LoginPass === $oldhash;
		}

		private function isNewPasswordValid($newpass1, $newpass2) {
			if (empty($newpass1) || !preg_match("/^\S{5,20}$/", $newpass1)) {
				$this->alertMsg = "新密碼錯誤!";
				$this->goBack = "Y";
				return false;
			}
			if ($newpass1 === $oldpass) {
				$this->alertMsg = "新舊密碼輸入相同!";
				$this->goBack = "Y";
				return false;
			}
			if ($newpass1 !== $newpass2) {
				$this->alertMsg = "兩次輸入的密碼不同!";
				$this->goBack = "Y";
				return false;
			}

			return true;
		}
	}

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