<?php
if (session_status() == PHP_SESSION_NONE) {
	session_start();
}

// Check if the user is logged in
$username = isset($_SESSION['username']) ? $_SESSION['username'] : "";
if (!defined('_AUTO_SITEMAP')) {
	if (!$username) {
		exit('logout');
	}
}

// Include necessary files
include_once 'config.php';
include_once 'init.php';
include_once 'includes/plugin.php';

// Include Post plugin if it exists
if (file_exists(PLUGIN_PATH . 'posts/Post.php')) {
	include_once PLUGIN_PATH . 'posts/Post.php';
}

// Exit if running in demo mode
if (ADMIN_DEMO) {
	exit('ADMIN DEMO');
}

// Check for permissions and pretty URLs
if (!defined('_AUTO_SITEMAP')) {
	if (!USER_ADMIN) {
		exit('access forbidden!');
	}
}
if (!PRETTY_URL) {
	exit('Pretty URL is disabled!');
}

// Helper function to check for ampersand in URL slugs
function containsAmpersand($string) {
	return strpos($string, '&') !== false;
}

// Initialize the generated sitemap files array
$generated_sitemaps = [];

// Start the sitemap XML structure
$str = '<?xml version="1.0" encoding="UTF-8"?>
<urlset
	xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
	http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<!-- generated by CloudArcade -->';

// Add homepage URL
$str .= '
<url>
	<loc>' . DOMAIN . '</loc>
	<priority>1.00</priority>
	<changefreq>daily</changefreq>
	<lastmod>' . date('Y-m-d') . '</lastmod>
</url>';

// Get all available JSON language files
$json_file_names = [];
$directory = ABSPATH . 'locales/public/';
if (file_exists($directory)) {
	$all_files = scandir($directory);
	foreach ($all_files as $file) {
		$file_info = pathinfo($file);
		if ($file_info['extension'] === 'json') {
			$file_size_in_kb = filesize($directory . $file) / 1024;
			if ($file_size_in_kb >= 2) {
				$json_file_names[] = $file_info['filename'];
			}
		}
	}
}

// Ensure English ('en') is in the language array
if (!in_array('en', $json_file_names)) {
	if (!get_setting_value('disable_en_language') || count($json_file_names) === 0) {
		$json_file_names[] = 'en';
	}
}

// Get all categories and games
$cats = get_all_categories();
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT slug, last_modified FROM games WHERE published = 1 ORDER BY id DESC LIMIT 10000";
$st = $conn->prepare($sql);
$st->execute();
$games = $st->fetchAll();
$conn = null;

// Handle language codes in the URL
if (get_setting_value('lang_code_in_url')) {
	foreach ($json_file_names as $json_file_name) {
		$lang_code = $json_file_name;
		$_str = $str;

		// Add categories
		foreach ($cats as $cat) {
			if (!containsAmpersand($cat->slug)) {
				$_str .= '
				<url>
					<loc>' . get_permalink('category', $cat->slug) . '</loc>
					<priority>0.8</priority>
					<changefreq>weekly</changefreq>
					<lastmod>' . date('Y-m-d') . '</lastmod>
				</url>';
			}
		}

		// Add blog posts
		if (defined('POST_ACTIVE')) {
			$posts = Post::getList()['results'];
			if ($posts) {
				foreach ($posts as $post) {
					if (!containsAmpersand($post->slug)) {
						$_str .= '
						<url>
							<loc>' . get_permalink('post', $post->slug) . '</loc>
							<priority>0.6</priority>
							<changefreq>monthly</changefreq>
							<lastmod>' . date('Y-m-d') . '</lastmod>
						</url>';
					}
				}
			}
		}

		// Add games
		foreach ($games as $game) {
			if (!containsAmpersand($game['slug'])) {
				$lastmod = $game['last_modified'];
				$_str .= '
				<url>
					<loc>' . get_permalink('game', $game['slug']) . '</loc>
					<priority>0.7</priority>
					<changefreq>weekly</changefreq>';
				if ($lastmod) {
					$_str .= '<lastmod>' . date('Y-m-d', strtotime($lastmod)) . '</lastmod>';
				} else {
					$_str .= '<lastmod>' . date('Y-m-d') . '</lastmod>';
				}
				$_str .= '
				</url>';
			}
		}

		// Close the sitemap and save it
		$_str .= '</urlset>';
		$sitemap_path = dirname(__FILE__) . "/sitemap-" . $json_file_name . ".xml";
		$sitemap = fopen($sitemap_path, "w") or die("Unable to open file!");
		$generated_sitemaps[] = "sitemap-" . $json_file_name . ".xml";
		fwrite($sitemap, $_str);
		fclose($sitemap);
	}

	// Create a sitemap index to link all generated sitemaps
	$sitemap_index = '<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
	foreach ($generated_sitemaps as $file) {
		$sitemap_index .= '
		<sitemap>
			<loc>' . DOMAIN . $file . '</loc>
			<lastmod>' . date("Y-m-d", filemtime($file)) . '</lastmod>
		</sitemap>';
	}
	$sitemap_index .= '</sitemapindex>';

	// Save the sitemap index
	file_put_contents(dirname(__FILE__) . '/sitemap.xml', $sitemap_index);

	// Generate robots.txt if it doesn't exist
	if (!file_exists('robots.txt')) {
		$domain = rtrim(DOMAIN, '/');
		$robots_txt = 'User-agent: *
		Disallow: /includes/
		Disallow: /classes/
		Disallow: /admin/
		Disallow: /vendor/
		Sitemap: ' . $domain . '/sitemap.xml';
		file_put_contents(dirname(__FILE__) . '/robots.txt', $robots_txt);
	}
} else {
	// Handle case without language code in URL

	// Add categories
	foreach ($cats as $cat) {
		if (!containsAmpersand($cat->slug)) {
			$str .= '
			<url>
				<loc>' . get_permalink('category', $cat->slug) . '</loc>
				<priority>0.8</priority>
				<changefreq>weekly</changefreq>
				<lastmod>' . date('Y-m-d') . '</lastmod>
			</url>';
		}
	}

	// Add blog posts
	if (defined('POST_ACTIVE')) {
		$posts = Post::getList()['results'];
		if ($posts) {
			foreach ($posts as $post) {
				if (!containsAmpersand($post->slug)) {
					$str .= '
					<url>
						<loc>' . get_permalink('post', $post->slug) . '</loc>
						<priority>0.6</priority>
						<changefreq>monthly</changefreq>
						<lastmod>' . date('Y-m-d') . '</lastmod>
					</url>';
				}
			}
		}
	}

	// Add games
	foreach ($games as $game) {
		if (!containsAmpersand($game['slug'])) {
			$lastmod = $game['last_modified'];
			$str .= '
			<url>
				<loc>' . get_permalink('game', $game['slug']) . '</loc>
				<priority>0.7</priority>
				<changefreq>weekly</changefreq>';
			if ($lastmod) {
				$str .= '<lastmod>' . date('Y-m-d', strtotime($lastmod)) . '</lastmod>';
			} else {
				$str .= '<lastmod>' . date('Y-m-d') . '</lastmod>';
			}
			$str .= '
			</url>';
		}
	}

	// Finalize the sitemap and save it
	$str .= '</urlset>';
	$sitemap = fopen(dirname(__FILE__) . "/sitemap.xml", "w") or die("Unable to open file!");
	$generated_sitemaps[] = "sitemap.xml";
	fwrite($sitemap, $str);
	fclose($sitemap);

	// Generate robots.txt if it doesn't exist
	if (!file_exists('robots.txt')) {
		$domain = rtrim(DOMAIN, '/');
		$robots_txt = 'User-agent: *
		Disallow: /includes/
		Disallow: /classes/
		Disallow: /admin/
		Disallow: /vendor/
		Sitemap: ' . $domain . '/sitemap.xml';
		file_put_contents(dirname(__FILE__) . '/robots.txt', $robots_txt);
	}
}

// Output the generated sitemaps in JSON format if necessary
if (!empty($generated_sitemaps) && !defined('_AUTO_SITEMAP')) {
	echo json_encode($generated_sitemaps);
}
?>