<?php
	
	namespace Main\Services;
	
	use PDO;
	use SitemapPHP\Sitemap;
	
	class SitemapService
	{
		public static function generate()
		{
			$pages = [
				[
					'url' => url('home'),
				],
				[
					'url' => url('auth.login'),
				],
				[
					'url' => url('auth.register'),
				],
				[
					'url' => url('auth.forgot-password'),
				],
				[
					'url' => url('download.index'),
					'module' => 'download',
				],
				[
					'url' => url('blog.posts.index'),
					'module' => 'blog',
				],
				[
					'url' => url('store.index'),
					'module' => 'store',
				],
				[
					'url' => url('leaderboards.index'),
					'module' => 'leaderboards',
				],
				[
					'url' => url('games.index'),
					'module' => 'games',
				],
				[
					'url' => url('help.index'),
					'module' => 'help',
				],
				[
					'url' => url('gaming-night.index'),
					'module' => 'gaming_night',
				],
				[
					'url' => url('forum.index'),
					'module' => 'forum',
				],
				[
					'url' => url('punishments.index'),
					'module' => 'punishments',
				],
				[
					'url' => url('punishments.bans'),
					'module' => 'punishments',
				],
				[
					'url' => url('punishments.kicks'),
					'module' => 'punishments',
				],
				[
					'url' => url('punishments.warnings'),
					'module' => 'punishments',
				],
				[
					'url' => url('punishments.mutes'),
					'module' => 'punishments',
				],
				[
					'url' => url('suggestions.index'),
					'module' => 'suggestions',
				],
				[
					'url' => url('play'),
				],
				[
					'url' => url('staff'),
					'module' => 'staff',
				],
				[
					'url' => url('vote'),
					'module' => 'vote',
				],
				[
					'url' => url('changelog.index'),
					'module' => 'changelog',
				],
			];
			
			// Check modules for pages
			$pages = array_filter($pages, function ($page) {
				return !(isset($page['module']) && !modules($page['module'])->isActive());
			});
			
			
			// Custom Pages
			$customPages = db()->query("SELECT slug FROM Pages")->fetchAll(PDO::FETCH_ASSOC);
			foreach ($customPages as $customPage) {
				$pages[] = [
					'url' => url('pages.show', ['slug' => $customPage["slug"]]),
				];
			}
			
			// Store Categories
			if (modules('store')->isActive()) {
				$categories = db()->query("SELECT name, slug, imageID, imageType FROM ProductCategories")->fetchAll(PDO::FETCH_ASSOC);
				foreach ($categories as $category) {
					$pages[] = [
						'url' => url('store.categories.show', ['slug' => $category["slug"]]),
						'image' => [
							'url' => "/assets/core/images/store/products/" . $category["imageID"] . "." . $category["imageType"],
							'title' => $category["name"],
						],
					];
				}
			}
			
			// Blog
			if (modules('blog')->isActive()) {
				$posts = db()->query("SELECT title, slug, imageID, imageType FROM News")->fetchAll(PDO::FETCH_ASSOC);
				foreach ($posts as $post) {
					$pages[] = [
						'url' => url('blog.posts.show', ['slug' => $post["slug"]]),
						'image' => [
							'url' => "/assets/core/images/blog/posts/" . $post["imageID"] . "." . $post["imageType"],
							'title' => $post["title"],
						],
					];
				}
				
				$categories = db()->query("SELECT slug FROM NewsCategories")->fetchAll(PDO::FETCH_ASSOC);
				foreach ($categories as $category) {
					$pages[] = [
						'url' => url('blog.categories.show', ['slug' => $category["slug"]]),
					];
				}
			}
			
			// Download
			if (modules('download')->isActive()) {
				$downloads = db()->query("SELECT id, slug FROM Downloads")->fetchAll(PDO::FETCH_ASSOC);
				foreach ($downloads as $download) {
					$pages[] = [
						'url' => url('download.show', ['id' => $download["id"], 'slug' => $download["slug"]]),
					];
				}
			}
			
			// Leaderboards
			if (modules('leaderboards')->isActive()) {
				$leaderboards = db()->query("SELECT serverSlug FROM Leaderboards")->fetchAll(PDO::FETCH_ASSOC);
				foreach ($leaderboards as $leaderboard) {
					$pages[] = [
						'url' => url('leaderboards.show', ['slug' => $leaderboard["serverSlug"]]),
					];
				}
			}
			
			// Games
			if (modules('games')->isActive()) {
				$games = db()->query("SELECT slug FROM Games")->fetchAll(PDO::FETCH_ASSOC);
				foreach ($games as $game) {
					$pages[] = [
						'url' => url('games.show', ['slug' => $game["slug"]]),
					];
				}
			}
			
			// Help
			if (modules('help')->isActive()) {
				$topics = db()->query("SELECT slug FROM HelpTopics")->fetchAll(PDO::FETCH_ASSOC);
				foreach ($topics as $topic) {
					$pages[] = [
						'url' => url('help.topics.show', ['slug' => $topic["slug"]]),
					];
				}
				
				$articles = db()->query("SELECT id, slug FROM HelpArticles")->fetchAll(PDO::FETCH_ASSOC);
				foreach ($articles as $article) {
					$pages[] = [
						'url' => url('help.articles.show', ['id' => $article["id"], 'slug' => $article["slug"]]),
					];
				}
			}
			
			// Forum
			if (modules('forum')->isActive()) {
				$categories = db()->query("SELECT id, slug FROM ForumCategories")->fetchAll(PDO::FETCH_ASSOC);
				foreach ($categories as $category) {
					$pages[] = [
						'url' => url('forum.categories.show', ['id' => $category["id"], 'slug' => $category["slug"]]),
					];
				}
			}
			
			// Suggestions
			if (modules('suggestions')->isActive()) {
				$categories = db()->query("SELECT slug FROM SuggestionCategories")->fetchAll(PDO::FETCH_ASSOC);
				foreach ($categories as $category) {
					$pages[] = [
						'url' => url('suggestions.categories.show', ['slug' => $category["slug"]]),
					];
				}
			}
			
			// Download
			if (modules('changelog')->isActive()) {
				$changelogs = db()->query("SELECT id FROM Changelogs")->fetchAll(PDO::FETCH_ASSOC);
				foreach ($changelogs as $changelog) {
					$pages[] = [
						'url' => url('changelog.show', ['id' => $changelog["id"]]),
					];
				}
			}
			
			$urls_per_sitemap = 500;
			$sitemap_index = [];
			$total_urls = count($pages);
			$num_sitemaps = ceil($total_urls / $urls_per_sitemap);
			
			for ($i = 0; $i < $num_sitemaps; $i++) {
				$sitemap_file = "sitemap-$i.xml";
				
				$pages_chunk = array_slice($pages, $i * $urls_per_sitemap, $urls_per_sitemap);
				
				$sitemap_xml = '<?xml version="1.0" encoding="UTF-8"?>';
				$sitemap_xml .= '<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd http://www.google.com/schemas/sitemap-image/1.1 http://www.google.com/schemas/sitemap-image/1.1/sitemap-image.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
				
				foreach ($pages_chunk as $page) {
					$sitemap_xml .= '<url>';
					$sitemap_xml .= '<loc>' . htmlspecialchars(website_url($page["url"])) . '</loc>';
					$sitemap_xml .= '<lastmod>' . date('Y-m-d') . '</lastmod>';
					if (isset($page["image"])) {
						$sitemap_xml .= '<image:image>';
						$sitemap_xml .= '<image:loc>' . htmlspecialchars(website_url($page["image"]["url"])) . '</image:loc>';
						$sitemap_xml .= '<image:title>' . $page["image"]["title"] . '</image:title>';
						$sitemap_xml .= '</image:image>';
					}
					$sitemap_xml .= '</url>';
				}
				
				$sitemap_xml .= '</urlset>';
				
				file_put_contents("sitemaps/$sitemap_file", $sitemap_xml);
				
				$sitemap_index[] = $sitemap_file;
			}

			// create sitemap-index.xml
			$sitemap_index_xml = '<?xml version="1.0" encoding="UTF-8"?>';
			$sitemap_index_xml .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
			
			foreach ($sitemap_index as $sitemap_file) {
				$sitemap_index_xml .= '<sitemap>';
				$sitemap_index_xml .= '<loc>' . htmlspecialchars(website_url("/sitemaps/$sitemap_file")) . '</loc>';
				$sitemap_index_xml .= '<lastmod>' . date('Y-m-d') . '</lastmod>';
				$sitemap_index_xml .= '</sitemap>';
			}
			
			$sitemap_index_xml .= '</sitemapindex>';

			file_put_contents('sitemaps/sitemap-index.xml', $sitemap_index_xml);
			
			return true;
		}
	}