<?php

declare(strict_types=1);


namespace App\Blog\View\Composers;

use App\Models\Category;
use App\Models\Link;
use App\Models\Post;
use Illuminate\Support\Facades\Cache;
use Illuminate\View\View;
use Spatie\Tags\Tag;

class SidebarComposer
{
    public function compose(View $view): void
    {
        $view->with('categories', Cache::remember('blog.sidebar.categories', now()->addHour(), function () {
            return Category::query()->orderBy('display_order')->orderBy('name')->get();
        }));

        $view->with('recentPosts', Cache::remember('blog.sidebar.recent_posts', now()->addHour(), function () {
            return Post::published()->latest('published_at')->limit(10)->get(['id', 'title', 'slug']);
        }));

        $view->with('recentComments', Cache::remember('blog.sidebar.recent_comments', now()->addHour(), function () {
            return \App\Models\Comment::query()
                ->where('status', 'published')
                ->latest('created_at')
                ->limit(10)
                ->with('post:id,title,slug')
                ->get();
        }));

        $view->with('hotTags', Cache::remember('blog.sidebar.hot_tags', now()->addHour(), function () {
            $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');

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

        $view->with('links', Cache::remember('blog.sidebar.links', now()->addHour(), function () {
            return Link::query()->where('visible', true)->orderBy('display_order')->orderBy('name')->get();
        }));

        $view->with('blogStats', Cache::remember('blog.sidebar.stats', now()->addHour(), function () {
            return [
                'posts' => Post::published()->count(),
                'comments' => \App\Models\Comment::query()->where('status', 'published')->count(),
                'categories' => Category::query()->count(),
                'tags' => Tag::query()->count(),
            ];
        }));

        $view->with('siteName', blog_setting('site_name', config('blog.name')));
        $view->with('siteDescription', blog_setting('site_description', config('blog.description')));
        $view->with('siteIcp', blog_setting('site_icp', config('blog.icp')));
    }
}
