<?php
	namespace Api\Services;
	
	use Curl\Curl;
	use DateTime;
	use DateTimeZone;
	
	class DiscordBotService
	{
		public static function isBotReady(): bool
		{
			return !moduleIsDisabled('discord_bot') && moduleSettings('discord_bot', 'botLinkToken') != '' && moduleSettings('discord_bot', 'guildID') != '';
		}
		public static function linkUser($discordUserID, $nickname, $roles): void
		{
			if (!self::isBotReady()) return;
			
			$roles = self::formatRoles($roles);
			
			$curl = new Curl();
			$curl->post("https://discord-bot-api.leaderos.net/link-user", [
				"token" => moduleSettings('discord_bot', 'botLinkToken'),
				"userID" => $discordUserID,
				"nickname" => $nickname,
				"roles" => $roles
			]);
		}
		
		public static function unlinkUser($discordUserID, $roles): void
		{
			if (!self::isBotReady()) return;
			
			$roles = self::formatRoles($roles);
			
			$curl = new Curl();
			$curl->post("https://discord-bot-api.leaderos.net/unlink-user", [
				"token" => moduleSettings('discord_bot', 'botLinkToken'),
				"userID" => $discordUserID,
				"roles" => $roles
			]);
		}
		
		public static function addRoles($discordUserID, $roles): void
		{
			if (!self::isBotReady()) return;
			if (!is_array($roles) || count($roles) === 0) return;
			
			$roles = self::formatRoles($roles);
			
			$curl = new Curl();
			$curl->post("https://discord-bot-api.leaderos.net/add-roles", [
				"token" => moduleSettings('discord_bot', 'botLinkToken'),
				"userID" => $discordUserID,
				"roles" => $roles
			]);
		}
		
		private static function formatRoles($roles)
		{
			return array_map(function ($role) {
				if (isset($role['expiryDate']) && $role['expiryDate'] !== '1000-01-01 00:00:00') {
					$role['expiryDate'] = self::formatExpiryDate($role['expiryDate']);
				}
				return $role;
			}, $roles);
		}
		
		private static function formatExpiryDate($expiryDate)
		{
			try {
				$timezone = (settings('timezone') == '' || settings('timezone') == null) ? 'UTC' : settings('timezone');
				$expiryDateObj = new DateTime($expiryDate, new DateTimeZone($timezone));
				return $expiryDateObj->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s');
			} catch (\Exception $e) {
				return $expiryDate; // Return original date in case of error
			}
		}
	}