<?php
/*--------------------------------------------------------- 
 * File:authority.php
 * Author:Tomix
 * Description: 身份驗證核心類
 * Created:2009
 * -------------------------------------------------------
 * Modified history:2023/08/23
 * Copyright © 2023 蘋果世界股份有限公司 版權所有
 * -------------------------------------------------------
 */
require_once dirname(__FILE__)."/bllBase.php";
require_once dirname(__FILE__)."/../bin/system/utility.php";
require_once dirname(__FILE__)."/../modules/sessionKeys.php";

class authority extends bllBase {
	/* 用戶登錄
	 * @param		string		$logMode		0，使用LoginName登錄；1，使用Email地址登錄
	 * @return		string						1，用户不存在；2密碼錯誤；登錄成功返回用戶信息對象
	 */
	static public function login($account, $password, $logMode = 0) {
        require_once dirname(__FILE__) . "/../dal/userDAL.php";
        $user = new userDAL();
		
        if ($logMode === 0) {
            $user->LoginName = $account;
        } else if ($logMode === 1) {
            $user->Email = $account;
        }
		$user->loadRecord();

        if (!isset($user->UserID) || $user->UserID === "" || $user->UserID === 0 || ($user->Flags & 1) > 0) {
            return -1; // 1表示用戶不存在
        } else if (!utility::checkEncrypt($password, $user->Password)) {
            return -2; // 2表示密碼錯誤
        } else if (($user->Flags & 1) === 1) {
            return -3; // 3表示帳號已經被鎖定
        } else {
            // 更新用戶登錄信息
            $user->LoginTimes++;
            $user->LastLoginTime = date("Y-m-d H:i:s");
            $user->LastLoginIp = $_SERVER["REMOTE_ADDR"];
            $user->updateRecord();

            // 保存用戶對象到session(userid,email)
            session_start();

            $_SESSION[sessionKeys::USER_ID] = $user->UserID;
            $_SESSION[sessionKeys::USER_EMAIL] = $user->Email;

            return true;
		}
	}

    static public function logout() {
        session_start();
        $_SESSION[sessionKeys::USER_ID] = null;
    }
}
?>
