<?php
require __DIR__ . '/../app/bootstrap.php';
header('Content-Type: application/xml; charset=utf-8');
$scheme = 'https';
$host = $_SERVER['HTTP_HOST'] ?? 'hymic.com';
$base = $scheme . '://' . $host;
function sitemap_loc(string $url): string { return htmlspecialchars($url, ENT_XML1 | ENT_QUOTES, 'UTF-8'); }
function sitemap_path(string $path): string {
    $parts = parse_url($path);
    $rawPath = $parts['path'] ?? '/';
    $encodedPath = implode('/', array_map('rawurlencode', explode('/', $rawPath)));
    if (str_starts_with($rawPath, '/') && !str_starts_with($encodedPath, '/')) $encodedPath = '/' . $encodedPath;
    if (!empty($parts['query'])) { parse_str($parts['query'], $query); $encodedPath .= '?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986); }
    return $encodedPath;
}
$urls = ['/', '/products.php', '/news.php', '/faq.php', '/certificates.php'];
foreach (db()->query('SELECT * FROM products ORDER BY id') as $r) $urls[] = product_url($r);
foreach (db()->query("SELECT c.* FROM categories c WHERE EXISTS (SELECT 1 FROM products p WHERE ('|' || p.category_ids || '|') LIKE '%|' || c.id || '|%') ORDER BY c.id") as $r) $urls[] = category_url($r);
foreach (db()->query('SELECT slug FROM pages ORDER BY id') as $r) $urls[] = page_url($r['slug']);
foreach (db()->query('SELECT * FROM news ORDER BY id') as $r) $urls[] = news_url($r);
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
foreach (array_unique($urls) as $path) echo "  <url><loc>" . sitemap_loc($base . sitemap_path($path)) . "</loc></url>\n";
echo "</urlset>\n";
