<?php

namespace App\Http\Controllers;

use App\Models\Post;
use App\Models\Setting;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\URL;

class FeedController extends Controller
{
    public function index()
    {
        // 1. Fetch Site Settings for the Channel Header
        $settings = Setting::where('group', 'seo')->pluck('value', 'key');
        
        $siteTitle = $settings['site_name'] ?? config('app.name');
        $siteDescription = $settings['meta_description'] ?? 'Latest news and updates.';
        $siteEmail = $settings['contact_email'] ?? 'admin@example.com'; // Optional

        // 2. Fetch Latest Published Posts
        $posts = Post::where('status', 'published')
            ->with(['user', 'category'])
            ->latest()
            ->take(50) // Limit feed to last 50 posts
            ->get();

        // 3. Render the View with XML Content Type
        return response()->view('rss-feed', [
            'posts' => $posts,
            'siteTitle' => $siteTitle,
            'siteDescription' => $siteDescription,
            'siteEmail' => $siteEmail,
            'lastBuildDate' => $posts->first()?->created_at ?? now(),
        ])->header('Content-Type', 'text/xml');
    }
}