<?php
declare(strict_types=1);

header('Content-Type: application/xml; charset=UTF-8');

$root = __DIR__;

/**
 * Load JSON as associative array or null on failure.
 */
function loadJsonFile(string $absolutePath): ?array
{
    if (!is_file($absolutePath)) {
        return null;
    }

    $contents = file_get_contents($absolutePath);
    if ($contents === false || $contents === '') {
        return null;
    }

    $decoded = json_decode($contents, true);
    return is_array($decoded) ? $decoded : null;
}

/**
 * Compute the freshest modification date (YYYY-MM-DD) for given relative paths.
 */
function computeLastmod(array $relativePaths, ?string $fallbackDate = null): string
{
    $latestTimestamp = null;

    foreach ($relativePaths as $relativePath) {
        $relativePath = trim($relativePath);
        if ($relativePath === '') {
            continue;
        }
        $absolutePath = __DIR__ . '/' . ltrim($relativePath, '/');
        if (is_file($absolutePath)) {
            $timestamp = filemtime($absolutePath);
            if ($timestamp !== false && ($latestTimestamp === null || $timestamp > $latestTimestamp)) {
                $latestTimestamp = $timestamp;
            }
        }
    }

    if ($fallbackDate) {
        $fallbackTimestamp = strtotime($fallbackDate);
        if ($fallbackTimestamp !== false && ($latestTimestamp === null || $fallbackTimestamp > $latestTimestamp)) {
            $latestTimestamp = $fallbackTimestamp;
        }
    }

    if ($latestTimestamp === null) {
        return gmdate('Y-m-d');
    }

    return gmdate('Y-m-d', $latestTimestamp);
}

/**
 * Build absolute URL from base and relative path, handling anchors and queries.
 */
function buildAbsoluteUrl(string $baseUrl, string $path): string
{
    $path = trim($path);
    if ($path === '') {
        return rtrim($baseUrl, '/');
    }

    if (preg_match('#^https?://#i', $path)) {
        return $path;
    }

    $normalizedBase = rtrim($baseUrl, '/');
    if ($path === '/') {
        return $normalizedBase . '/';
    }

    if ($path[0] === '#') {
        return $normalizedBase . '/' . $path;
    }

    if ($path[0] !== '/') {
        $path = '/' . $path;
    }

    return $normalizedBase . $path;
}

/**
 * Whitelist changefreq values per sitemap spec.
 */
function sanitizeChangefreq(?string $value): ?string
{
    if ($value === null) {
        return null;
    }

    $normalized = strtolower(trim($value));
    $allowed = ['always', 'hourly', 'daily', 'weekly', 'monthly', 'yearly', 'never'];

    return in_array($normalized, $allowed, true) ? $normalized : null;
}

/**
 * Clamp and format priority to one decimal.
 */
function sanitizePriority($value): ?string
{
    if ($value === null) {
        return null;
    }

    if (is_string($value)) {
        $value = trim($value);
        if ($value === '') {
            return null;
        }
    }

    $priority = (float)$value;
    if (!is_finite($priority)) {
        return null;
    }

    if ($priority < 0.0) {
        $priority = 0.0;
    } elseif ($priority > 1.0) {
        $priority = 1.0;
    }

    return number_format($priority, 1, '.', '');
}

$baseUrl = 'https://gameserv.co.il';
$configData = loadJsonFile($root . '/data/config.json');

if ($configData) {
    $siteConfig = $configData['site'] ?? [];
    $configuredBase = '';

    if (is_array($siteConfig) && !empty($siteConfig['baseUrl'])) {
        $configuredBase = trim((string)$siteConfig['baseUrl']);
    } elseif (is_array($siteConfig) && !empty($siteConfig['domain'])) {
        $configuredBase = 'https://' . ltrim((string)$siteConfig['domain'], '/');
    }

    if ($configuredBase !== '') {
        $baseUrl = rtrim($configuredBase, '/');
    }
}

$staticPages = [
    [
        'path' => '/',
        'files' => ['index.php'],
        'changefreq' => 'daily',
        'priority' => 1.0,
    ],
    [
        'path' => '/game-servers.php',
        'files' => ['game-servers.php', 'data/games.json', 'data/servers.json', 'data/packages.json'],
        'changefreq' => 'daily',
        'priority' => 0.9,
    ],
    [
        'path' => '/servers.php',
        'files' => ['servers.php', 'servers.json'],
        'changefreq' => 'daily',
        'priority' => 0.85,
    ],
    [
        'path' => '/server-farm-hosting.php',
        'files' => ['server-farm-hosting.php'],
        'changefreq' => 'weekly',
        'priority' => 0.8,
    ],
    [
        'path' => '/mu-online.php',
        'files' => ['mu-online.php', 'data/mu-online-seo.json'],
        'changefreq' => 'weekly',
        'priority' => 0.85,
    ],
    [
        'path' => '/hosting.php',
        'files' => ['hosting.php'],
        'changefreq' => 'weekly',
        'priority' => 0.8,
    ],
    [
        'path' => '/web-hosting.php',
        'files' => ['web-hosting.php'],
        'changefreq' => 'weekly',
        'priority' => 0.75,
    ],
    [
        'path' => '/vps.php',
        'files' => ['vps.php'],
        'changefreq' => 'weekly',
        'priority' => 0.8,
    ],
    [
        'path' => '/dedicated.php',
        'files' => ['dedicated.php'],
        'changefreq' => 'weekly',
        'priority' => 0.8,
    ],
    [
        'path' => '/instant-launch.php',
        'files' => ['instant-launch.php'],
        'changefreq' => 'weekly',
        'priority' => 0.7,
    ],
    [
        'path' => '/demo-servers.php',
        'files' => ['demo-servers.php'],
        'changefreq' => 'weekly',
        'priority' => 0.6,
    ],
    [
        'path' => '/discord-bots.php',
        'files' => ['discord-bots.php'],
        'changefreq' => 'monthly',
        'priority' => 0.6,
    ],
    [
        'path' => '/website-development.php',
        'files' => ['website-development.php'],
        'changefreq' => 'monthly',
        'priority' => 0.6,
    ],
    [
        'path' => '/blog.php',
        'files' => ['blog.php', 'data/blog-data.json'],
        'changefreq' => 'daily',
        'priority' => 0.7,
    ],
    [
        'path' => '/knowledge-base.php',
        'files' => ['knowledge-base.php', 'data/knowledge.json'],
        'changefreq' => 'weekly',
        'priority' => 0.6,
    ],
    [
        'path' => '/support.php',
        'files' => ['support.php'],
        'changefreq' => 'weekly',
        'priority' => 0.6,
    ],
    [
        'path' => '/contact.php',
        'files' => ['contact.php'],
        'changefreq' => 'monthly',
        'priority' => 0.6,
    ],
    [
        'path' => '/status.php',
        'files' => ['status.php'],
        'changefreq' => 'hourly',
        'priority' => 0.6,
    ],
];

$urls = [];

foreach ($staticPages as $page) {
    $urls[] = [
        'loc' => buildAbsoluteUrl($baseUrl, $page['path']),
        'lastmod' => computeLastmod($page['files']),
        'changefreq' => sanitizeChangefreq($page['changefreq'] ?? null),
        'priority' => sanitizePriority($page['priority'] ?? null),
    ];
}

$gamesData = loadJsonFile($root . '/data/games.json');
$gameSourceFiles = ['game-servers.php', 'data/games.json', 'data/servers.json', 'data/packages.json'];

if ($gamesData && !empty($gamesData['games']) && is_array($gamesData['games'])) {
    foreach ($gamesData['games'] as $game) {
        if (!is_array($game)) {
            continue;
        }
        $gameId = $game['id'] ?? ($game['slug'] ?? null);
        if (!is_string($gameId) && !is_numeric($gameId)) {
            continue;
        }

        $gameId = trim((string)$gameId);
        if ($gameId === '') {
            continue;
        }

        $isHighlighted = !empty($game['featured']) || !empty($game['popular']);
        $gamePriority = $isHighlighted ? 0.8 : 0.6;

        $urls[] = [
            'loc' => buildAbsoluteUrl($baseUrl, '/game-servers.php#' . rawurlencode($gameId)),
            'lastmod' => computeLastmod($gameSourceFiles),
            'changefreq' => 'weekly',
            'priority' => sanitizePriority($gamePriority),
        ];
    }
}

$blogData = loadJsonFile($root . '/data/blog-data.json');

if ($blogData && !empty($blogData['articles']) && is_array($blogData['articles'])) {
    foreach ($blogData['articles'] as $article) {
        if (!is_array($article)) {
            continue;
        }

        $slug = $article['slug'] ?? null;
        if (!is_string($slug) && !is_numeric($slug)) {
            continue;
        }

        $slug = trim((string)$slug);
        if ($slug === '') {
            continue;
        }

        $articleDate = $article['date'] ?? ($article['lastUpdated'] ?? null);
        $urls[] = [
            'loc' => buildAbsoluteUrl($baseUrl, '/blog.php?article=' . rawurlencode($slug)),
            'lastmod' => computeLastmod(['blog.php', 'data/blog-data.json'], $articleDate ? (string)$articleDate : null),
            'changefreq' => 'monthly',
            'priority' => sanitizePriority(0.6),
        ];
    }
}

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<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">
<?php foreach ($urls as $entry): ?>
    <url>
        <loc><?= htmlspecialchars($entry['loc'], ENT_XML1 | ENT_QUOTES, 'UTF-8') ?></loc>
<?php if (!empty($entry['lastmod'])): ?>
        <lastmod><?= htmlspecialchars($entry['lastmod'], ENT_XML1 | ENT_QUOTES, 'UTF-8') ?></lastmod>
<?php endif; ?>
<?php if (!empty($entry['changefreq'])): ?>
        <changefreq><?= htmlspecialchars($entry['changefreq'], ENT_XML1 | ENT_QUOTES, 'UTF-8') ?></changefreq>
<?php endif; ?>
<?php if (!empty($entry['priority'])): ?>
        <priority><?= htmlspecialchars($entry['priority'], ENT_XML1 | ENT_QUOTES, 'UTF-8') ?></priority>
<?php endif; ?>
    </url>
<?php endforeach; ?>
</urlset>
