<?php
	namespace Dashboard\Middlewares;
	
	use Dashboard\Core\Auth;
	use Dashboard\Services\AvatarService;
	use PDO;
  use Pecee\Http\Middleware\IMiddleware;
	use Pecee\Http\Request;
	
	class AuthMiddleware implements IMiddleware {
		
		public function handle(Request $request): void
		{
			global $readAdmin;

      $isAdmin = false;

			if (isset($_COOKIE["rememberMe"]) || isset($_SESSION["login"])) {
				$loginToken = ((isset($_COOKIE["rememberMe"])) ? $_COOKIE["rememberMe"] : ((isset($_SESSION["login"])) ? $_SESSION["login"] : null));
				$admin = db()->prepare("SELECT A.*, ASe.loginToken, ASe.isTfaVerified, ANI.lastReadDate FROM Accounts A LEFT JOIN AccountNoticationInfo ANI ON A.id = ANI.accountID INNER JOIN AccountSessions ASe ON A.id = ASe.accountID WHERE ASe.loginToken = ? AND ASe.expiryDate > ?");
				$admin->execute(array($loginToken, date("Y-m-d H:i:s")));
				$readAdmin = $admin->fetch(PDO::FETCH_ASSOC);
				if ($admin->rowCount() > 0) {
					unset($readAdmin["password"]);
					
					if (!moduleIsDisabled('tfa') && $readAdmin["isTfaVerified"] === '0') {
						redirect("/tfa");
					}
					
					$siteBannedStatus = db()->prepare("SELECT id FROM BannedAccounts WHERE accountID = ? AND categoryID = ? AND (expiryDate > ? OR expiryDate = ?)");
					$siteBannedStatus->execute(array($readAdmin["id"], 1, date("Y-m-d H:i:s"), '1000-01-01 00:00:00'));
					if ($siteBannedStatus->rowCount() == 0) {
						$readAdmin["permissions"] = getPermissions($readAdmin["id"]);
						$readAdmin["roles"] = getRoles($readAdmin["id"]);
						$readAdmin["supportPermissions"] = getSupportPermissions($readAdmin["id"]);
						
						if (checkStaff($readAdmin)) {
							$loginToken = $readAdmin["loginToken"];
              $isAdmin = true;
							
							// Get Avatar
							$readAdmin["avatar"] = AvatarService::get($readAdmin["id"], $readAdmin["realname"]);
							
							$_SESSION["user"] = $readAdmin;
							$_SESSION["login"] = $loginToken;
							
							if (!isset($_COOKIE["rememberMe"])) {
								$updateAccountsSessions = db()->prepare("UPDATE AccountSessions SET expiryDate = ? WHERE accountID = ? AND loginToken = ?");
								$updateAccountsSessions->execute(array(createDuration(0.01666666666), $readAdmin["id"], $loginToken));
							}
							$onlineAccountsHistory = db()->prepare("SELECT * FROM OnlineAccountsHistory WHERE accountID = ?");
							$onlineAccountsHistory->execute(array($readAdmin["id"]));
							if ($onlineAccountsHistory->rowCount() > 0) {
								$updateOnlineAccountsHistory = db()->prepare("UPDATE OnlineAccountsHistory SET expiryDate = ?, creationDate = ? WHERE accountID = ?");
								$updateOnlineAccountsHistory->execute(array(createDuration(0.00347222222), date("Y-m-d H:i:s"), $readAdmin["id"]));
							}
							else {
								$insertOnlineAccountsHistory = db()->prepare("INSERT INTO OnlineAccountsHistory (accountID, type, expiryDate, creationDate) VALUES (?, ?, ?, ?)");
								$insertOnlineAccountsHistory->execute(array($readAdmin["id"], 1, createDuration(0.00347222222), date("Y-m-d H:i:s")));
							}
						}
					}
				}
			}
			
			// If authentication failed, redirect request to user-login page.
			if ($isAdmin === false) {
				Auth::logout();
				redirect("/login");
			}
		}
	}