<?php
	require_once "pageBase.php";
	require_once "../dal/userDAL.php";

	class _changePassword extends pageBase {
		public function load() {
			$this->limitID = (registryDAL::getRegistryValue("isAnalyze") == 0) ? "20" : "42";
			if (!parent::chkUserLimit()) {
				$this->alertMsg = "您沒有使用此頁面的權限!如有疑問請洽主管理者!";
				$this->locationHref = "index.php";
			} else {
				parent::isPostBack() ? $this->save() : parent::loadData();
			}
			parent::loadTemplateFile(dirname(__FILE__) . "/templates/changePassword.html");
			parent::load();
		}
		
		private function save() {
			$dal = new userDAL();
			$dal->UserID = parent::getCurrentUserID();
			$dal->loadRecord();

			$password = parent::getPost("password", "", 3);
			$newPassword = parent::getPost("newpassword", "", 3);
			$passwordPattern = "/^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$/";		

			if ($password == $dal->Password) {
				if ($newPassword != "") {
					if (!preg_match($passwordPattern, $newPassword)) {
						$this->alertMsg = "密碼格式錯誤，請輸入至少8碼以上的英文加數字加符號!";
						$this->goBack = "Y";
						return;
					}

					$dal->Password = parent::auth_code($newPassword, "key");
		
					if ($dal->updateRecord()) {
						$this->alertMsg = "密碼修改成功!";
						$this->goBack = "Y";
					} else {
						$this->alertMsg = "修改密碼時發生錯誤!";
						$this->goBack = "Y";
					}
				} else {
					$this->alertMsg = "請輸入新密碼!";
					$this->goBack = "Y";
				}
			} else {
				$this->alertMsg = "請輸入正確的舊密碼!";
				$this->goBack = "Y";
			}
		}
	}

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