<?php
// Set default timezone to Asia/Kolkata (+05:30)
date_default_timezone_set('Asia/Kolkata');

header('Content-Type: application/rss+xml; charset=utf-8');

function getDbConnection() {
    try {
        $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
        $pdo = new PDO($dsn, DB_USER, DB_PASS);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo;
    } catch (PDOException $e) {
        return null;
    }
}

function escapeXml($str) {
    return htmlspecialchars($str ?? '', ENT_QUOTES, 'UTF-8');
}

$pdo = getDbConnection();
$items = [];

if ($pdo) {
    $stmt = $pdo->query("SELECT id, type, title, excerpt, full_description, image_url, date 
                         FROM news_updates 
                         ORDER BY date DESC 
                         LIMIT 50");
    $items = $stmt->fetchAll();
}

$siteUrl = "https://developer.khogendrarupini.com";
$currentDate = date('D, d M Y H:i:s O');

echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
<channel>
    <title>Nexus Update Hub - Official Updates & Announcements</title>
    <link><?php echo $siteUrl; ?>/updates.php</link>
    <description>Stay updated with the latest Nexus platform updates, new features, and important announcements.</description>
    <language>en-us</language>
    <lastBuildDate><?php echo $currentDate; ?></lastBuildDate>
    <atom:link href="<?php echo $siteUrl; ?>/rss.xml" rel="self" type="application/rss+xml" />
    <generator>Nexus CMS</generator>
    
    <?php foreach ($items as $item): ?>
    <item>
        <title><?php echo escapeXml($item['title']); ?></title>
        <link><?php echo $siteUrl; ?>/update.php?id=<?php echo $item['id']; ?></link>
        <guid isPermaLink="true"><?php echo $siteUrl; ?>/update.php?id=<?php echo $item['id']; ?></guid>
        <pubDate><?php 
            $dateObj = new DateTime($item['date']);
            $dateObj->setTimezone(new DateTimeZone('Asia/Kolkata'));
            echo $dateObj->format('D, d M Y H:i:s O');
        ?></pubDate>
        <description><![CDATA[<?php echo strip_tags($item['excerpt']); ?>]]></description>
        <content:encoded><![CDATA[
            <?php if (!empty($item['image_url'])): ?>
            <img src="<?php echo escapeXml($item['image_url']); ?>" alt="<?php echo escapeXml($item['title']); ?>" style="max-width:100%;">
            <?php endif; ?>
            <?php echo nl2br(escapeXml($item['full_description'])); ?>
        ]]></content:encoded>
        <category><?php echo ucfirst($item['type']); ?></category>
    </item>
    <?php endforeach; ?>
    
</channel>
</rss>