<?php
  namespace Api\Services;
  
  use PDO;
  
  class UserService
  {
	  public static function getByID($id)
	  {
		  if ($id == null || $id == "") return false;
			
		  $account = db()->prepare("SELECT * FROM Accounts WHERE id = ?");
		  $account->execute([$id]);
		  if ($account->rowCount() === 0) return false;
		  
		  return $account->fetch(PDO::FETCH_ASSOC);
	  }
	  
	  public static function getByUsername($username)
	  {
			if ($username == null || $username == "") return false;
			
			if (settings('gameType') == 'minecraft') {
				$account = db()->prepare("SELECT * FROM Accounts WHERE realname = ?");
			} else {
				$account = db()->prepare("SELECT * FROM Accounts WHERE username = ?");
			}
			
		  $account->execute([$username]);
		  if ($account->rowCount() === 0) return false;
		  
		  return $account->fetch(PDO::FETCH_ASSOC);
	  }
		
		public static function getByParams()
	  {
			if (isset($_GET["userID"])) {
				return UserService::getByID(_get('userID'));
			}
			if (isset($_GET["username"])) {
				return UserService::getByUsername(_get('username'));
			}
			
			return false;
	  }

    public static function getByDiscordUserID($discordUserID)
    {
			if (settings('loginProvider') == 'discord') {
				$account = db()->prepare("SELECT A.* FROM Accounts A WHERE A.username = ?");
				$account->execute([$discordUserID]);
			}
			else if (DiscordBotService::isBotReady()) { // for new Discord Bot
				$account = db()->prepare('SELECT A.* FROM LinkedAccounts L INNER JOIN AccountLinkingProviders P ON P.id = L.providerID INNER JOIN Accounts A ON A.id = L.accountID WHERE P.slug = ? AND L.identifier = ?');
				$account->execute(['discord', $discordUserID]);
			}
			else if (!moduleIsDisabled('discord')) { // For legacy discord bot
				$account = db()->prepare("SELECT A.* FROM AccountDiscordData ADC INNER JOIN Accounts A ON A.id = ADC.accountID WHERE ADC.discordUserID = ?");
				$account->execute([$discordUserID]);
			}
			else {
				return false;
			}
			
	    if ($account->rowCount() === 0) return false;
	    $account = $account->fetch(PDO::FETCH_ASSOC);
	    
	    $account["avatar"] = AvatarService::get($account["id"], $account["realname"]);

      return $account;
    }
  }