<?php
header('Content-Type: text/html; charset=UTF-8');

$filename = $_GET['feed'] ?? '';
if (empty($filename)) {
    die('Feed filename required');
}

// Security: only allow alphanumeric, dash, underscore, and dot
if (!preg_match('/^[a-zA-Z0-9._-]+$/', $filename)) {
    die('Invalid feed filename');
}

$feedPath = __DIR__ . '/' . $filename;
if (!file_exists($feedPath)) {
    die('Feed not found');
}

$xml = simplexml_load_file($feedPath);
if ($xml === false) {
    die('Failed to parse feed');
}

// Register namespaces
$xml->registerXPathNamespace('content', 'http://purl.org/rss/1.0/modules/content/');
?>
<!DOCTYPE html>
<html lang="pl">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($xml->channel->title); ?></title>
    <link rel="stylesheet" href="/styles.css" />
</head>

<body>
    <div class="container">
        <h1><?php echo htmlspecialchars($xml->channel->title); ?></h1>
        <?php foreach ($xml->channel->item as $item): ?>
            <div class="item">
                <div class="item-title">
                    <a href="<?php echo htmlspecialchars($item->link); ?>">
                        <?php echo htmlspecialchars($item->title); ?>
                    </a>
                </div>
                <div class="item-date"><?php echo htmlspecialchars($item->pubDate); ?></div>

                <details>
                    <summary>Pokaż treść</summary>
                    <div class="item-content">
                        <?php
                        $content = $item->children('http://purl.org/rss/1.0/modules/content/');
                        if (!empty($content->encoded)) {
                            echo (string) $content->encoded;
                        } else {
                            if (isset($item->description->HTML)) {
                                echo (string) $item->description->HTML;
                            } else {
                                echo (string) $item->description;
                            }
                        }
                        ?>
                    </div>
                </details>

            </div>
        <?php endforeach; ?>
    </div>
</body>

</html>
