<?php

declare(strict_types=1);


namespace App\Blog\Controllers;

use App\Models\Post;
use Spatie\Tags\Tag;

class TagController extends Controller
{
    public function index()
    {
        $counts = \Illuminate\Support\Facades\DB::table('taggables')
            ->selectRaw('tag_id, COUNT(*) as total')
            ->where('taggable_type', Post::class)
            ->groupBy('tag_id')
            ->pluck('total', 'tag_id');

        $tags = Tag::query()
            ->where('type', 'post')
            ->get()
            ->map(fn (Tag $tag) => $tag->setAttribute('posts_count', (int) ($counts[$tag->id] ?? 0)))
            ->sortByDesc('posts_count')
            ->values();

        return theme_view('tags', compact('tags'));
    }

    public function show(string $slug)
    {
        $tag = Tag::findFromString($slug, 'post');

        abort_unless($tag, 404);

        $posts = Post::query()
            ->whereHas('tags', fn ($q) => $q->where('tags.id', $tag->id))
            ->published()
            ->latest('published_at')
            ->paginate((int) blog_setting('per_page', config('blog.per_page')));

        return theme_view('tag', compact('tag', 'posts'));
    }
}
