<?php

namespace App\Http\Controllers\News;

use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
use cPad\Plugins\News\Models\NewsArticle;

class NewsRssController extends Controller
{
    /**
     * Generate RSS 2.0 feed for published news articles.
     * Endpoint: GET /rss/news
     */
    public function feed(): Response
    {
        $ttl = max(60, (int) config('news.rss_cache_ttl', 300));

        $xml = Cache::remember('news.rss.feed', $ttl, function (): string {
            $articles = NewsArticle::with('author', 'category')
                ->published()
                ->orderByDesc('published_at')
                ->limit(config('news.rss_limit', 25))
                ->get();

            return $this->buildRss($articles);
        });

        return response($xml, 200, [
            'Content-Type' => 'application/rss+xml; charset=UTF-8',
        ]);
    }

    private function buildRss($articles): string
    {
        $siteUrl     = config('app.url');
        $title       = e(config('news.rss_title', 'News'));
        $description = e(config('news.rss_description', 'Latest news.'));
        $now         = now()->toRfc2822String();

        $items = '';
        foreach ($articles as $article) {
            $link         = e(url('/news/' . $article->slug));
            $pubDate      = $article->published_at?->toRfc2822String() ?? $now;
            $articleTitle = e($article->title);
            $excerpt      = e(strip_tags((string) ($article->excerpt ?? '')));
            $category     = e((string) ($article->category?->name ?? ''));
            $author       = e((string) ($article->author?->name ?? ''));

            $items .= <<<ITEM
        <item>
            <title><![CDATA[{$articleTitle}]]></title>
            <link>{$link}</link>
            <guid isPermaLink="true">{$link}</guid>
            <description><![CDATA[{$excerpt}]]></description>
            <pubDate>{$pubDate}</pubDate>
            <author>{$author}</author>
            <category>{$category}</category>
        </item>

ITEM;
        }

        return <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>{$title}</title>
        <link>{$siteUrl}/news</link>
        <description>{$description}</description>
        <language>en-us</language>
        <lastBuildDate>{$now}</lastBuildDate>
        <atom:link href="{$siteUrl}/rss/news" rel="self" type="application/rss+xml"/>
{$items}    </channel>
</rss>
XML;
    }
}
