<?php
	
	namespace Main\Services;
	
	use PDO;
	
	class AvatarService
	{
		const AVATARS_PATH = "/assets/core/images/avatars";
		const DEFAULT_AVATAR = self::AVATARS_PATH . "/default.png";
		
		public static function get($id, $username): string
		{
			// Shows only minecraft avatars
			if (settings('gameType') == 'minecraft' && settings('allowCustomAvatars') == 0) {
				return self::getMinecraftAvatar($username);
			}
			
			$avatar = db()->prepare("SELECT * FROM Avatars WHERE accountID = ?");
			$avatar->execute([$id]);
			$avatar = $avatar->fetch(PDO::FETCH_ASSOC);
			if (!$avatar) {
				return self::DEFAULT_AVATAR;
			}
			
			return self::AVATARS_PATH . "/" . $avatar['imageID'] . "." . $avatar['imageType'];
		}
		
		public static function getMinecraftAvatar($username, $size = 128): string
		{
			$avatarAPI = settings('avatarAPI');
			
			// Remove geysermc prefix
			$username = str_replace(['.', '*'], ['', ''], $username);
			
			if ($avatarAPI == 1) {
				return "https://minotar.net/helm/$username/$size.png";
			}
			if ($avatarAPI == 2) {
				return "https://cravatar.eu/helmavatar/$username/$size.png";
			}
			
			return "https://minotar.net/helm/$username/$size.png";
		}
	}