<?php
declare(strict_types=1);

$baseUrl = 'https://supertoolsx.com';

$languages = [
    ''   => 'en',
];

$pages = [
    '',
    'about',
    'age-calculator',
    'base64',
    'bmi-calculator',
    'canvas',
    'case',
    'contact',
    'cookies',
    'counter',
    'gpa-calculator',
    'image-compressor',
    'json',
    'loan',
    'merge-pdf',
    'percentage',
    'policies',
    'password',
    'privacy',
    'qr',
    'security',
    'terms'
];

function pageFilePath(string $root, string $prefix, string $slug): ?string
{
    if ($slug === '') {
        $candidates = ($prefix === '')
            ? [$root . '/index.html']
            : [$root . '/' . $prefix . '/index.html'];
    } else {
        $relative = ($prefix !== '' ? '/' . $prefix : '') . '/' . $slug;
        $candidates = [
            $root . $relative . '.html',
            $root . $relative . '/index.html'
        ];
    }

    foreach ($candidates as $candidate) {
        if (is_file($candidate)) {
            return $candidate;
        }
    }

    return null;
}

function publicUrl(string $baseUrl, string $prefix, string $slug): string
{
    $path = '';

    if ($prefix !== '') {
        $path .= '/' . $prefix;
    }

    if ($slug !== '') {
        $path .= '/' . $slug;
    }

    if ($path === '') {
        $path = '/';
    } elseif ($slug === '' && $prefix !== '') {
        $path .= '/';
    }

    return $baseUrl . $path;
}

function xmlEscape(string $value): string
{
    return htmlspecialchars($value, ENT_XML1 | ENT_COMPAT, 'UTF-8');
}

$available = [];
$lastModified = [];

foreach ($languages as $prefix => $hreflang) {
    foreach ($pages as $slug) {
        $file = pageFilePath(__DIR__, $prefix, $slug);
        if ($file === null) {
            continue;
        }

        $key = $slug;
        $available[$prefix][$key] = publicUrl($baseUrl, $prefix, $slug);

        $mtime = filemtime($file);
        if ($mtime !== false) {
            $lastModified[$prefix][$key] = gmdate('Y-m-d', $mtime);
        }
    }
}

$generatedMaps = [];
$mapLastModified = [];

foreach ($languages as $prefix => $hreflang) {
    $entries = $available[$prefix] ?? [];

    if (empty($entries)) {
        continue;
    }

    $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">' . "\n";

    $latestMod = '1970-01-01';

    foreach ($entries as $slug => $loc) {
        $xml .= "  <url>\n";
        $xml .= '    <loc>' . xmlEscape($loc) . "</loc>\n";

        $lastmod = $lastModified[$prefix][$slug] ?? null;
        if ($lastmod !== null) {
            $xml .= '    <lastmod>' . xmlEscape($lastmod) . "</lastmod>\n";
            if ($lastmod > $latestMod) {
                $latestMod = $lastmod;
            }
        }

        foreach ($languages as $alternatePrefix => $alternateLang) {
            if (isset($available[$alternatePrefix][$slug])) {
                $altUrl = $available[$alternatePrefix][$slug];
                $xml .= '    <xhtml:link rel="alternate" hreflang="' . xmlEscape($alternateLang) . '" href="' . xmlEscape($altUrl) . '" />' . "\n";
            }
        }

        if (isset($available[''][$slug])) {
            $xml .= '    <xhtml:link rel="alternate" hreflang="x-default" href="' . xmlEscape($available[''][$slug]) . '" />' . "\n";
        }

        $xml .= "  </url>\n";
    }

    $xml .= "</urlset>\n";

    $filename = ($prefix === '') ? 'sitemap-en.xml' : 'sitemap-' . $prefix . '.xml';
    $written = file_put_contents(__DIR__ . '/' . $filename, $xml, LOCK_EX);

    if ($written === false) {
        http_response_code(500);
        exit('Could not write ' . htmlspecialchars($filename, ENT_QUOTES, 'UTF-8'));
    }

    $generatedMaps[] = $filename;
    $mapLastModified[$filename] = ($latestMod !== '1970-01-01') ? $latestMod : gmdate('Y-m-d');
}

$index = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$index .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

foreach ($generatedMaps as $filename) {
    $index .= "  <sitemap>\n";
    $index .= '    <loc>' . xmlEscape($baseUrl . '/' . $filename) . "</loc>\n";
    if (isset($mapLastModified[$filename])) {
        $index .= '    <lastmod>' . xmlEscape($mapLastModified[$filename]) . "</lastmod>\n";
    }
    $index .= "  </sitemap>\n";
}

$index .= "</sitemapindex>\n";

if (file_put_contents(__DIR__ . '/sitemap.xml', $index, LOCK_EX) === false) {
    http_response_code(500);
    exit('Could not write sitemap.xml');
}

header('Content-Type: text/plain; charset=UTF-8');
echo "Done.\n";