<?php
/**
 * Dynamická sitemap.xml – generuje všechny URL webu včetně blogových článků
 */
require_once __DIR__ . '/admin/config.php';

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

$domain = 'https://evakapralova.cz';

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

// Hlavní stránka
echo "  <url>\n    <loc>{$domain}/</loc>\n    <lastmod>" . date('Y-m-d') . "</lastmod>\n    <changefreq>weekly</changefreq>\n    <priority>1.0</priority>\n  </url>\n";

// Blogové články
$posts = [];
if (file_exists(BLOG_DATA_PATH)) {
    $json = file_get_contents(BLOG_DATA_PATH);
    $posts = json_decode($json, true) ?? [];
}

foreach ($posts as $post) {
    $url = $domain . '/clanek.php?id=' . $post['id'];
    $date = date('Y-m-d', strtotime($post['datum']));
    echo "  <url>\n";
    echo "    <loc>{$url}</loc>\n";
    echo "    <lastmod>{$date}</lastmod>\n";
    echo "    <changefreq>monthly</changefreq>\n";
    echo "    <priority>0.8</priority>\n";
    // Obrázky článku – Google má rád image záznamy v sitemap
    $obrazky = $post['obrazky'] ?? [];
    if (!empty($obrazky) && is_array($obrazky)) {
        foreach ($obrazky as $img) {
            if (empty($img)) continue;
            echo "    <image:image>\n";
            echo "      <image:loc>{$domain}/" . ltrim($img, '/') . "</image:loc>\n";
            echo "      <image:title>" . htmlspecialchars($post['nadpis']) . "</image:title>\n";
            echo "    </image:image>\n";
        }
    }
    echo "  </url>\n";
}

echo '</urlset>';