<?php
header('Content-Type: application/xml; charset=UTF-8');
require_once __DIR__ . '/includes/functions.php';

$base = rtrim(SITE_URL, '/');
$today = date('Y-m-d');

$static_pages = [
    ['loc' => '/',                        'priority' => '1.0', 'changefreq' => 'weekly'],
    ['loc' => '/servizi.php',             'priority' => '0.9', 'changefreq' => 'monthly'],
    ['loc' => '/caf.php',                 'priority' => '0.8', 'changefreq' => 'monthly'],
    ['loc' => '/patronato.php',           'priority' => '0.8', 'changefreq' => 'monthly'],
    ['loc' => '/chi-siamo.php',           'priority' => '0.7', 'changefreq' => 'monthly'],
    ['loc' => '/contatti.php',            'priority' => '0.7', 'changefreq' => 'monthly'],
    ['loc' => '/news.php',                'priority' => '0.8', 'changefreq' => 'weekly'],
    ['loc' => '/prenota-appuntamento.php','priority' => '0.9', 'changefreq' => 'monthly'],
];

$news_articles = read_json('news');

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

foreach ($static_pages as $page) {
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($base . $page['loc'], ENT_XML1, 'UTF-8') . "</loc>\n";
    echo "    <lastmod>{$today}</lastmod>\n";
    echo "    <changefreq>{$page['changefreq']}</changefreq>\n";
    echo "    <priority>{$page['priority']}</priority>\n";
    echo "  </url>\n";
}

foreach ($news_articles as $article) {
    if (!($article['published'] ?? false)) continue;
    $slug = $article['slug'] ?? '';
    if (!$slug) continue;
    $lastmod = $article['date'] ?? $today;
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($base . '/news-single.php?slug=' . urlencode($slug), ENT_XML1, 'UTF-8') . "</loc>\n";
    echo "    <lastmod>" . htmlspecialchars($lastmod, ENT_XML1, 'UTF-8') . "</lastmod>\n";
    echo "    <changefreq>never</changefreq>\n";
    echo "    <priority>0.6</priority>\n";
    echo "  </url>\n";
}

echo '</urlset>' . "\n";
