<?php
/**
 * RSS 2.0 feed for the EduTrack blog.
 */

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/db.php';

$conn  = blog_db();
$posts = $conn->query(
    'SELECT title, slug, meta_description, excerpt, category, published_at
     FROM blog_posts WHERE status = "published"
     ORDER BY published_at DESC LIMIT 20'
);

header('Content-Type: application/rss+xml; charset=utf-8');

$last_build = date('D, d M Y H:i:s +0000');

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">' . "\n";
echo '<channel>' . "\n";
echo '  <title>' . htmlspecialchars(BLOG_SITE_NAME) . '</title>' . "\n";
echo '  <link>' . BLOG_BASE_URL . '/index.php</link>' . "\n";
echo '  <description>' . htmlspecialchars(BLOG_DESCRIPTION) . '</description>' . "\n";
echo '  <language>' . BLOG_LANG . '</language>' . "\n";
echo '  <lastBuildDate>' . $last_build . '</lastBuildDate>' . "\n";
echo '  <atom:link href="' . BLOG_BASE_URL . '/rss.php" rel="self" type="application/rss+xml"/>' . "\n";
echo '  <managingEditor>info@oricnetwork.com (' . BLOG_AUTHOR . ')</managingEditor>' . "\n";
echo '  <copyright>Copyright ' . date('Y') . ' ORIC Network Limited</copyright>' . "\n";
echo '  <ttl>1440</ttl>' . "\n";

if ($posts) {
    while ($p = $posts->fetch_assoc()) {
        $url     = BLOG_BASE_URL . '/post.php?slug=' . urlencode($p['slug']);
        $pub     = $p['published_at'] ? date('D, d M Y H:i:s +0000', strtotime($p['published_at'])) : $last_build;
        $desc    = htmlspecialchars($p['meta_description'] ?: $p['excerpt'] ?? '');
        echo '  <item>' . "\n";
        echo '    <title>' . htmlspecialchars($p['title']) . '</title>' . "\n";
        echo '    <link>' . $url . '</link>' . "\n";
        echo '    <guid isPermaLink="true">' . $url . '</guid>' . "\n";
        echo '    <description>' . $desc . '</description>' . "\n";
        echo '    <pubDate>' . $pub . '</pubDate>' . "\n";
        if ($p['category']) {
            echo '    <category>' . htmlspecialchars($p['category']) . '</category>' . "\n";
        }
        echo '  </item>' . "\n";
    }
}

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