 <?php
/**
 * RadioWebSystem - RSS Feed
 */
header("Content-Type: application/rss+xml; charset=utf-8");
require_once __DIR__ . '/JsonDB.php';

$pagesDb = new JsonDB('pages');
$podcastsDb = new JsonDB('podcasts');

$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 '<rss version="2.0">' . "\n";
echo "<channel>\n";
echo "  <title>RadioWebSystem - RSS Feed</title>\n";
echo "  <link>" . htmlspecialchars($baseUrl) . "</link>\n";
echo "  <description>Nejnovější články a podcasty z vysílání.</description>\n";

$items = [];
foreach ($pagesDb->getAll() as $p) {
    if (!is_array($p) || empty($p['slug']) || !empty($p['is_home'])) continue;
    $items[] = ['title' => $p['title'] ?? '', 'link' => $baseUrl . '/clanek/' . $p['slug'], 'desc' => strip_tags($p['content'] ?? ''), 'date' => $p['created_at'] ?? '', 'image' => $p['image'] ?? ''];
}
foreach ($podcastsDb->getAll() as $p) {
    if (!is_array($p)) continue;
    $items[] = ['title' => 'Podcast: ' . ($p['title'] ?? ''), 'link' => $baseUrl . '/podcasty', 'desc' => strip_tags($p['description'] ?? ''), 'date' => $p['created_at'] ?? '', 'image' => $p['image'] ?? ''];
}

usort($items, function($a, $b) { return strtotime($b['date']) <=> strtotime($a['date']); });

foreach (array_slice($items, 0, 30) as $item) {
    echo "  <item>\n";
    echo "    <title>" . htmlspecialchars($item['title']) . "</title>\n";
    echo "    <link>" . htmlspecialchars($item['link']) . "</link>\n";
    echo "    <description>" . htmlspecialchars(substr($item['desc'], 0, 300)) . "...</description>\n";
    if (!empty($item['image'])) {
        $imgPath = __DIR__ . '/' . $item['image'];
        $imgUrl = $baseUrl . '/' . $item['image'];
        $imgSize = file_exists($imgPath) ? filesize($imgPath) : 0;
        $imgExt = strtolower(pathinfo($item['image'], PATHINFO_EXTENSION));
        $mime = 'image/jpeg'; if ($imgExt === 'png') $mime = 'image/png'; elseif ($imgExt === 'webp') $mime = 'image/webp'; elseif ($imgExt === 'gif') $mime = 'image/gif';
        echo "    <enclosure url=\"" . htmlspecialchars($imgUrl) . "\" length=\"" . $imgSize . "\" type=\"$mime\" />\n";
    }
    if (!empty($item['date'])) echo "    <pubDate>" . date(DATE_RSS, strtotime($item['date'])) . "</pubDate>\n";
    echo "  </item>\n";
}

echo "</channel>\n</rss>";