<?php
namespace App\Http\Controllers;

use App\Models\Post;
use App\Models\Category;
use App\Models\Country;
use App\Models\Continent;
use Illuminate\Http\Response;

class SitemapController extends Controller
{
    private function fe(string $path): string
    {
        return rtrim(env('FRONTEND_URL', 'http://localhost:3000'), '/') . $path;
    }

    public function index(): Response
    {
        $urls = collect();

        $urls->push(['loc' => $this->fe('/'), 'changefreq' => 'hourly', 'priority' => '1.0', 'lastmod' => now()->toAtomString()]);

        Category::all()->each(fn($cat) =>
            $urls->push(['loc' => $this->fe("/category/{$cat->slug}"), 'changefreq' => 'hourly', 'priority' => '0.8'])
        );

        Continent::all()->each(fn($c) =>
            $urls->push(['loc' => $this->fe("/{$c->slug}"), 'changefreq' => 'hourly', 'priority' => '0.7'])
        );

        Country::with('continent')->active()->each(fn($c) =>
            $urls->push(['loc' => $this->fe("/{$c->continent->slug}/{$c->slug}"), 'changefreq' => 'daily', 'priority' => '0.6'])
        );

        Post::published()
            ->with(['continent', 'country', 'category'])
            ->select('slug', 'updated_at', 'published_at', 'continent_id', 'country_id', 'category_id')
            ->orderByDesc('published_at')
            ->chunk(500, function ($posts) use ($urls) {
                $posts->each(fn($p) =>
                    $urls->push([
                        'loc'        => $this->fe("/{$p->continent->slug}/{$p->country->slug}/{$p->category->slug}/{$p->slug}"),
                        'lastmod'    => $p->updated_at->toAtomString(),
                        'changefreq' => 'weekly',
                        'priority'   => '0.9',
                    ])
                );
            });

        return response(view('sitemap', ['urls' => $urls])->render(), 200)
            ->header('Content-Type', 'application/xml');
    }

    public function news(): Response
    {
        $posts = Post::published()
            ->with(['category', 'continent', 'country'])
            ->where('published_at', '>=', now()->subDays(2))
            ->select('title', 'slug', 'published_at', 'category_id', 'continent_id', 'country_id')
            ->orderByDesc('published_at')
            ->limit(1000)
            ->get();

        return response(view('sitemap-news', ['posts' => $posts])->render(), 200)
            ->header('Content-Type', 'application/xml');
    }
}
