<?php
require_once __DIR__ . '/../app/helpers.php';

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

$pages = public_pages();
foreach ($pages as &$page) {
    $routePath = $page['route_path'] ?? $page['path'];
    $filePath = __DIR__ . $routePath;
    if ($routePath === '/') {
        $filePath = __DIR__ . '/index.php';
    } elseif (str_starts_with($routePath, '/services/')) {
        $filePath = __DIR__ . '/service-page.php';
    } else {
        $filePath = __DIR__ . $routePath . '.php';
    }
    $page['lastmod'] = file_exists($filePath)
        ? gmdate('Y-m-d', filemtime($filePath))
        : gmdate('Y-m-d');
}
unset($page);

echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
<?php foreach ($pages as $page): ?>
    <url>
        <loc><?= h(site_url($page['path'])) ?></loc>
        <xhtml:link rel="alternate" hreflang="ru" href="<?= h(site_url(localized_path($page['route_path'], 'ru'))) ?>" />
        <xhtml:link rel="alternate" hreflang="en" href="<?= h(site_url(localized_path($page['route_path'], 'en'))) ?>" />
        <lastmod><?= h($page['lastmod']) ?></lastmod>
    </url>
<?php endforeach; ?>
</urlset>
