<?php
// RSS Feed for Archive Posts
// URL: /feed/archive.xml

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

// Set content type to RSS
header('Content-Type: application/rss+xml; charset=UTF-8');

// Get recent published posts for RSS
$posts = getPublishedPosts(1, 20); // Latest 20 posts

// Build RSS XML
$rss = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$rss .= '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">' . "\n";
$rss .= '<channel>' . "\n";
$rss .= '  <title>' . escape(SITE_NAME) . ' - Archive</title>' . "\n";
$rss .= '  <link>' . SITE_URL . '/archive.php</link>' . "\n";
$rss .= '  <description>Local blog archive: drafts, legacy posts, and jm13.io-specific content</description>' . "\n";
$rss .= '  <language>en-us</language>' . "\n";
$rss .= '  <lastBuildDate>' . date(DATE_RSS) . '</lastBuildDate>' . "\n";
$rss .= '  <atom:link href="' . SITE_URL . '/feed/archive.xml" rel="self" type="application/rss+xml" />' . "\n";

foreach ($posts as $post) {
    $postUrl = postUrl($post['slug']);
    $pubDate = date(DATE_RSS, strtotime($post['published_at']));
    
    $rss .= '  <item>' . "\n";
    $rss .= '    <title>' . escape($post['title']) . '</title>' . "\n";
    $rss .= '    <link>' . $postUrl . '</link>' . "\n";
    $rss .= '    <description>' . escape($post['excerpt'] ?: getExcerpt($post['content'], 200)) . '</description>' . "\n";
    $rss .= '    <pubDate>' . $pubDate . '</pubDate>' . "\n";
    $rss .= '    <guid isPermaLink="true">' . $postUrl . '</guid>' . "\n";
    
    // Add enclosure if there's a featured image
    if (!empty($post['featured_image'])) {
        $rss .= '    <enclosure url="' . escape($post['featured_image']) . '" type="image/jpeg" />' . "\n";
    }
    
    $rss .= '  </item>' . "\n";
}

$rss .= '</channel>' . "\n";
$rss .= '</rss>';

echo $rss;
