<?php

namespace App\Providers;

use App\Models\BlogCategory;
use App\Models\BlogPost;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ThemeServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        //
    }



    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        $theme = setting('site_theme', 'default');
        $themePath = resource_path("themes/{$theme}/views");
        
        $this->loadViewsFrom($themePath, 'theme');
        
        // Also add the path to the main view finder so we can override standard views if needed
        View::addLocation($themePath);

        // Dynamic Blog Widgets
        View::composer('theme::partials.blog.widgets.categories', function ($view) {
            $categories = BlogCategory::withCount(['posts' => function($q) {
                    $q->where('status', 'published');
                }])
                ->having('posts_count', '>', 0)
                ->orderBy('posts_count', 'desc')
                ->take(setting('blog.categories_widget_count', 5))
                ->get();
            $view->with('categories', $categories);
        });

        View::composer('theme::partials.blog.widgets.popular-posts', function ($view) {
            $popular_posts = BlogPost::where('status', 'published')
                ->withCount('comments')
                ->orderBy('comments_count', 'desc')
                ->take(3)
                ->get();
            $view->with('popular_posts', $popular_posts);
        });
    }
}
