<?php

namespace App\Http\Controllers;

use App\Models\Post;
use App\Models\Category;
use App\Models\User;
use App\Models\Page;
use Illuminate\Http\Response;

class SitemapController extends Controller
{
    /**
     * The Main Index: Lists all other sitemaps.
     */
    public function index()
    {
        $postLatest = Post::where('status', 'published')->latest('updated_at')->first();
        $catLatest  = Category::latest('updated_at')->first();
        $userLatest = User::latest('updated_at')->first();
        $pageLatest = Page::where('status', 'published')->latest('updated_at')->first();

        return response()->view('sitemap.index', [
            'sitemaps' =>[
                'posts-sitemap.xml'      => $postLatest?->updated_at ?? now(),
                'categories-sitemap.xml' => $catLatest?->updated_at ?? now(),
                'users-sitemap.xml'      => $userLatest?->updated_at ?? now(),
                'pages-sitemap.xml'      => $pageLatest?->updated_at ?? now(),
                'tags-sitemap.xml'       => now(),
            ]
        ])->header('Content-Type', 'text/xml');
    }

    /**
     * Sub-Sitemap: Posts
     */
    public function posts()
    {
        $items = Post::where('status', 'published')
            ->latest()
            ->get()
            ->map(function ($post) {
                return[
                    'loc' => $post->route_url, 
                    'lastmod' => $post->updated_at->toAtomString(),
                    'freq' => 'monthly',
                    'priority' => '0.8'
                ];
            });

        return $this->renderSitemap($items);
    }

    /**
     * Sub-Sitemap: Categories
     */
    public function categories()
    {
        $items = Category::all()->map(function ($cat) {
            return[
                'loc' => route('category.show', $cat->slug),
                'lastmod' => $cat->updated_at->toAtomString(),
                'freq' => 'weekly',
                'priority' => '0.6'
            ];
        });

        return $this->renderSitemap($items);
    }

    /**
     * Sub-Sitemap: Users (Authors)
     */
    public function users()
    {
        // Only include users who have published posts
        $items = User::whereHas('posts', function ($q) {
                $q->where('status', 'published');
            })
            ->get()
            ->map(function ($user) {
                return[
                    'loc' => route('author.show', $user->username),
                    'lastmod' => $user->updated_at->toAtomString(),
                    'freq' => 'weekly',
                    'priority' => '0.5'
                ];
            });

        return $this->renderSitemap($items);
    }

    /**
     * Sub-Sitemap: Static Pages
     */
    public function pages()
    {
        $items = Page::where('status', 'published')->get()->map(function ($page) {
            return[
                'loc' => route('page.show', $page->slug),
                'lastmod' => $page->updated_at->toAtomString(),
                'freq' => 'yearly',
                'priority' => '0.4'
            ];
        });

        return $this->renderSitemap($items);
    }

    /**
     * Sub-Sitemap: Tags (Extracted from JSON)
     */
    public function tags()
    {
        $rawTags = Post::where('status', 'published')
            ->whereNotNull('tags')
            ->pluck('tags');

        $uniqueTags = collect($rawTags)
            ->flatten()
            ->unique()
            ->values();

        $items = $uniqueTags->map(function ($tag) {
            return[
                'loc' => route('tag.show', urlencode($tag)),
                'lastmod' => now()->startOfDay()->toAtomString(),
                'freq' => 'weekly',
                'priority' => '0.4'
            ];
        });

        return $this->renderSitemap($items);
    }

    /**
     * Helper to render the common view
     */
    private function renderSitemap($items)
    {
        return response()->view('sitemap.urlset', [
            'items' => $items
        ])->header('Content-Type', 'text/xml');
    }
}