<?php
/**
 * GameCMS RSS Feed 生成
 */
define('GAMECMS_ROOT', dirname(__DIR__));
$config = require GAMECMS_ROOT.'/config.php';

$dsn = sprintf('mysql:host=%s;port=%s;dbname=%s;charset=%s',
    $config['db']['host'], $config['db']['port'], $config['db']['database'], $config['db']['charset']);
$db = new PDO($dsn, $config['db']['username'], $config['db']['password'], [PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
$prefix = $config['db']['prefix'] ?? 'gc_';

$siteUrl = $config['site']['url'] ?? 'https://'.($_SERVER['HTTP_HOST']??'localhost');
$siteName = $config['site']['name'] ?? 'GameCMS';
$siteDesc = $config['site']['description'] ?? '';

$articles = $db->query("SELECT id,title,slug,content,author,published_at FROM {$prefix}articles WHERE status='published' AND is_deleted=0 AND published_at<=NOW() ORDER BY published_at DESC LIMIT 20")->fetchAll(PDO::FETCH_ASSOC);

// 构建文章URL：优先使用 /article/{slug}，确保与 canonical 一致
$articleUrl = function($a) use ($siteUrl) {
    if (!empty($a['slug'])) {
        return $siteUrl . '/article/' . urlencode($a['slug']);
    }
    return $siteUrl . '/' . $a['id'] . '.html';
};

header('Content-Type: application/rss+xml; charset=utf-8');
echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
    <title><?php echo htmlspecialchars($siteName); ?></title>
    <link><?php echo $siteUrl; ?></link>
    <description><?php echo htmlspecialchars($siteDesc); ?></description>
    <language>zh-CN</language>
    <lastBuildDate><?php echo date('r'); ?></lastBuildDate>
    <atom:link href="<?php echo $siteUrl; ?>/feed.xml" rel="self" type="application/rss+xml"/>
    <?php foreach($articles as $a):
        $link = $articleUrl($a);
    ?>
    <item>
        <title><?php echo htmlspecialchars($a['title']); ?></title>
        <link><?php echo $link; ?></link>
        <guid isPermaLink="true"><?php echo $link; ?></guid>
        <description><![CDATA[<?php echo mb_substr(strip_tags($a['content']??''),0,300,'UTF-8'); ?>...]]></description>
        <author><?php echo htmlspecialchars($a['author']??'匿名'); ?></author>
        <pubDate><?php echo date('r',strtotime($a['published_at'])); ?></pubDate>
    </item>
    <?php endforeach; ?>
</channel>
</rss>
