<?php
	namespace Main\Middlewares;
	
	use Main\Services\DiscordBotService;
	use PDO;
	use Pecee\Http\Middleware\IMiddleware;
	use Pecee\Http\Request;
	
	class AppMiddleware implements IMiddleware {
		public function handle(Request $request): void
		{
			// Auto Installer Check
			if (settings('autoInstallation') != 'COMPLETED') {
				redirect("/auto-install");
			}
			
			// Roles
			$roles = db()->query("SELECT * FROM Roles");
			$roles = $roles->fetchAll(PDO::FETCH_ASSOC);
			
			// Broadcasts
			$announcements = null;
			if (modules('announcements')->isActive()) {
				$announcements = db()->query("SELECT * FROM Broadcast ORDER BY id DESC");
				$announcements = $announcements->fetchAll(PDO::FETCH_ASSOC);
			}
			
			// Header
			$headerJSON = json_decode(settings('header'), true);
			$header = array_map(function($headerItem) {
				if (isset($headerItem["module"]) && $headerItem["module"] != null && $headerItem["module"] != '' && !modules($headerItem["module"])->isActive()) return null;
				$headerItem['title'] = t__($headerItem['title']);
				if (isset($headerItem['children'])) {
					$headerItem['children'] = array_map(function($headerItemChildren) {
						if (isset($headerItemChildren["module"]) && $headerItemChildren["module"] != null && $headerItemChildren["module"] != '' && !modules($headerItemChildren["module"])->isActive()) return null;
						$headerItemChildren['title'] = t__($headerItemChildren['title']);
						
						return $headerItemChildren;
					}, $headerItem['children']);
					$headerItem['children'] = array_filter($headerItem['children']);
				}
				
				return $headerItem;
			}, $headerJSON);
			$header = array_filter($header);
			
			// Footer
			$footerJSON = json_decode(settings('footer'), true);
			$footer = array_map(function($footerItem) {
				if (isset($footerItem["module"]) && $footerItem["module"] != null && $footerItem["module"] != '' && !modules($footerItem["module"])->isActive()) return null;
				$footerItem['title'] = t__($footerItem['title']);
				if (isset($footerItem['children'])) {
					$footerItem['children'] = array_map(function($footerItemChildren) {
						if (isset($footerItemChildren["module"]) && $footerItemChildren["module"] != null && $footerItemChildren["module"] != '' && !modules($footerItemChildren["module"])->isActive()) return null;
						$footerItemChildren['title'] = t__($footerItemChildren['title']);
						switch ($footerItemChildren["url"]) {
							case "%discord%":
								$footerItemChildren["url"] = settings('discordUrl');
								break;
							case "%facebook%":
								$footerItemChildren["url"] = settings('facebookUrl');
								break;
							case "%instagram%":
								$footerItemChildren["url"] = settings('instagramUrl');
								break;
							case "%x%":
								$footerItemChildren["url"] = settings('xUrl');
								break;
							case "%youtube%":
								$footerItemChildren["url"] = settings('youtubeUrl');
								break;
							case "%tiktok%":
								$footerItemChildren["url"] = settings('tiktokUrl');
								break;
						}
						
						return $footerItemChildren;
					}, $footerItem['children']);
					$footerItem['children'] = array_filter($footerItem['children']);
				}
				
				return $footerItem;
			}, $footerJSON);
			$footer = array_filter($footer);
			
			// Theme Mode
			$themeModeCookieKey = theme()->id() . ':theme_mode';
			$themeMode = cookies()->get($themeModeCookieKey) ?? theme()->settings('defaultMode');
			if ($request->getInputHandler()->get('theme')) {
				cookies()->set($themeModeCookieKey, get('theme'), 365 * 3 * 24 * 60 * 60);
				$themeMode = escape(strip_tags(trim($request->getInputHandler()->get('theme')->getValue())));
			}
			
			// Game Name
			$gameNames = [
				'minecraft' => 'Minecraft',
				'fivem' => 'FiveM',
				'csgo' => 'CS:GO',
				'cs2' => 'CS2',
				'ark' => 'ARK: Survival Evolved',
				'roblox' => 'Roblox',
				'rust' => 'Rust',
				'unturned' => 'Unturned',
				'garrysmod' => 'Garry\'s Mod',
			];
			if (array_key_exists(settings('gameType'), $gameNames)) {
				$gameName = $gameNames[settings('gameType')];
			} else {
				$gameName = settings('serverName');
			}
			
			template()->addData([
				'roles' => $roles,
				'announcements' => $announcements,
				'header' => $header,
				'footer' => $footer,
				'route_type' => '',
				'theme_mode' => $themeMode,
				'game_type' => settings('gameType'),
				'login_provider' => settings('loginProvider'),
				'game_name' => $gameName,
				'show_discord_sync_btn' => settings('loginProvider') != 'discord' && (DiscordBotService::isBotReady() || modules('discord')->isActive()),
			]);
		}
	}