<?php
  
  namespace Api\Controllers\Auth;
  
  use Api\Core\Controller;
  use PDO;
  
  class GameSessionController extends Controller
  {
	  public function check()
	  {
		  validate([
			  'username' => 'required',
			  'ip' => 'required|ip',
			  'useragent' => 'required'
		  ]);
			
			$username = input('username');
		  
		  if (!validate_username($username)) {
			  response()->json([
				  'status' => 'INVALID_USERNAME',
			  ]);
		  }
		  
		  $user = db()->prepare("SELECT id, realname FROM Accounts WHERE username = ?");
		  $user->execute([$username]);
		  $user = $user->fetch(PDO::FETCH_ASSOC);
		  
		  if (!$user) {
			  response()->json([
				  'status' => 'ACCOUNT_NOT_FOUND',
			  ]);
		  }
			
			if ($user["realname"] !== $username) {
				response()->json([
					'status' => 'INVALID_USERNAME',
				]);
			}
		  
		  $session = db()->prepare("SELECT loginToken, isTfaVerified FROM AccountSessions WHERE accountID = ? AND creationIP = ? AND expiryDate > ? AND useragent = ?");
		  $session->execute([$user['id'], input('ip'), date('Y-m-d H:i:s'), input('useragent')]);
		  $session = $session->fetch(PDO::FETCH_ASSOC);
		  
		  if (!$session) {
			  response()->json([
				  'status' => 'LOGIN_REQUIRED',
			  ]);
		  }
			
			if (!moduleIsDisabled('tfa') && $session['isTfaVerified'] == '0') {
			  response()->json([
				  'status' => 'TFA_REQUIRED',
				  'token' => $session['loginToken'],
			  ]);
		  }
		  
		  response()->json([
			  'status' => 'HAS_SESSION',
			  'token' => $session['loginToken'],
		  ]);
	  }
  }