<?php
require __DIR__ . '/includes/functions.php';

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

$stateSlug = $_GET['state'] ?? '';
$citySlug = $_GET['city'] ?? '';
$city = get_city($stateSlug, $citySlug);

if (!$city || ($city['status'] ?? '') !== 'live') {
    http_response_code(404);
    echo '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>';
    exit;
}

// URL list (with lastmod) built by the shared helper in includes/functions.php — the exact same
// helper ping-search-engines.php uses, so the sitemap and the IndexNow pings never disagree.
$urls = d108_build_city_sitemap_urls($city);

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
foreach ($urls as $u) {
    echo "  <url>\n    <loc>" . htmlspecialchars($u['loc']) . "</loc>\n";
    // lastmod comes from the real mtime of the data file backing this URL — see
    // d108_build_city_sitemap_urls() — so it's only emitted when we actually know it.
    if (!empty($u['lastmod'])) {
        echo "    <lastmod>" . d108_iso8601($u['lastmod']) . "</lastmod>\n";
    }
    echo "    <priority>" . $u['priority'] . "</priority>\n  </url>\n";
}
echo '</urlset>';
