<?php
require_once __DIR__ . '/config.php';

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

$stmt = $pdo->query("
    SELECT title, slug, short_description, content, published_at, image_main 
    FROM news 
    WHERE is_published = 1 
    ORDER BY published_at DESC 
    LIMIT 50
");
$news = $stmt->fetchAll();

$xml = '<?xml version="1.0" encoding="UTF-8"?>';
$xml .= '<rss version="2.0" xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru">';
$xml .= '<channel>';
$xml .= '<title>' . SITE_NAME . '</title>';
$xml .= '<link>' . SITE_URL . '</link>';
$xml .= '<description>' . SITE_DESCRIPTION . '</description>';
$xml .= '<language>ru</language>';

foreach ($news as $item) {
    $xml .= '<item>';
    $xml .= '<title>' . htmlspecialchars($item['title']) . '</title>';
    $xml .= '<link>' . SITE_URL . '/' . $item['slug'] . '</link>';
    $xml .= '<description>' . htmlspecialchars(mb_substr(strip_tags($item['short_description'] ?: $item['content']), 0, 300)) . '</description>';
    $xml .= '<pubDate>' . date('r', strtotime($item['published_at'])) . '</pubDate>';
    
    if ($item['image_main']) {
        $xml .= '<enclosure url="' . UPLOAD_URL . $item['image_main'] . '" type="image/jpeg"/>';
    }
    
    $xml .= '<yandex:full-text>' . htmlspecialchars(strip_tags($item['content'])) . '</yandex:full-text>';
    $xml .= '</item>';
}

$xml .= '</channel>';
$xml .= '</rss>';

echo $xml;