<?php
/**
 * RadioWebSystem - Automatický Sitemap Generátor
 */
header("Content-Type: application/xml; charset=utf-8");
require_once __DIR__ . '/JsonDB.php';

$pagesDb = new JsonDB('pages');
$modsDb = new JsonDB('moderators');
$settingsDb = new JsonDB('settings');

$activeLangs = ['cs'];
foreach ($settingsDb->getAll() as $row) {
    if (isset($row['key']) && $row['key'] === 'active_langs' && is_array($row['value'])) { $activeLangs = $row['value']; break; }
}

// Získání base URL
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') ? "https" : "http";
$host = $_SERVER['HTTP_HOST'];
$baseUrl = $protocol . "://" . $host;

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

$urls = [
    '/',
    '/porady',
    '/hitparada',
    '/historie',
    '/moderatori',
    '/podcasty',
    '/objednavka'
];

foreach ($activeLangs as $lang) {
    $lParam = "?lang=" . $lang;
    foreach ($urls as $u) {
        echo "  <url>\n";
        echo "    <loc>" . htmlspecialchars($baseUrl . $u . $lParam) . "</loc>\n";
        echo "    <changefreq>daily</changefreq>\n";
        echo "    <priority>0.8</priority>\n";
        echo "  </url>\n";
    }

    foreach ($pagesDb->getAll() as $p) {
        if (!is_array($p) || empty($p['slug']) || !empty($p['is_home'])) continue;
        echo "  <url>\n";
        echo "    <loc>" . htmlspecialchars($baseUrl . '/clanek/' . $p['slug'] . $lParam) . "</loc>\n";
        echo "    <changefreq>weekly</changefreq>\n";
        echo "    <priority>0.6</priority>\n";
        echo "  </url>\n";
    }

    foreach ($modsDb->getAll() as $m) {
        if (!is_array($m) || empty($m['active'])) continue;
        echo "  <url>\n";
        echo "    <loc>" . htmlspecialchars($baseUrl . '/moderator/' . $m['id'] . $lParam) . "</loc>\n";
        echo "    <changefreq>monthly</changefreq>\n";
        echo "    <priority>0.5</priority>\n";
        echo "  </url>\n";
    }
}

echo '</urlset>';