<?php

declare(strict_types=1);


namespace App\Blog\Controllers;

use App\Models\Post;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;

class FeedController extends Controller
{
    public function rss()
    {
        $posts = Post::query()
            ->published()
            ->latest('published_at')
            ->limit((int) blog_setting('rss_num', config('blog.rss_num')))
            ->with('category', 'author', 'tags')
            ->get();

        $content = view('feed.rss', [
            'posts' => $posts,
            'siteName' => blog_setting('site_name', config('blog.name')),
            'siteDescription' => blog_setting('site_description', config('blog.description')),
            'xmlDeclaration' => '<?xml version="1.0" encoding="UTF-8"?>',
        ])->render();

        return response($content)->header('Content-Type', 'application/rss+xml; charset=utf-8');
    }

    public function sitemap()
    {
        $posts = Post::query()
            ->published()
            ->latest('published_at')
            ->get(['id', 'slug', 'updated_at']);

        $content = view('feed.sitemap', [
            'posts' => $posts,
            'xmlDeclaration' => '<?xml version="1.0" encoding="UTF-8"?>',
        ])->render();

        return response($content)->header('Content-Type', 'application/xml; charset=utf-8');
    }

    public function robots(): Response
    {
        $disallow = array_merge(config('robots.disallow'), (array) blog_setting('seo_robots_disallow', []));
        $sitemap = config('robots.sitemap');

        $lines = ['User-agent: *'];
        foreach ($disallow as $path) {
            $lines[] = "Disallow: {$path}";
        }
        $lines[] = "Sitemap: ".url($sitemap);

        return response(implode("\n", $lines)."\n")->header('Content-Type', 'text/plain; charset=utf-8');
    }
}
