<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\ContentType;
use Illuminate\Support\Facades\DB;

class SectionsController extends Controller
{
    public function index()
    {
        // Load all content types with full category tree (roots + children)
        $contentTypes = ContentType::with([
            'rootCategories' => function ($q) {
                $q->active()
                  ->withCount(['artworks as artwork_count'])
                  ->orderBy('sort_order')
                  ->orderBy('name');
            },
            'rootCategories.children' => function ($q) {
                $q->active()
                  ->withCount(['artworks as artwork_count'])
                  ->orderBy('sort_order')
                  ->orderBy('name');
            },
        ])->ordered()->get();

        // Total artwork counts per content type via a single aggregation query
        $artworkCountsByType = DB::table('artworks')
            ->join('artwork_category', 'artworks.id', '=', 'artwork_category.artwork_id')
            ->join('categories', 'artwork_category.category_id', '=', 'categories.id')
            ->where('artworks.is_approved', true)
            ->where('artworks.is_public', true)
            ->whereNull('artworks.deleted_at')
            ->select('categories.content_type_id', DB::raw('COUNT(DISTINCT artworks.id) as total'))
            ->groupBy('categories.content_type_id')
            ->pluck('total', 'content_type_id');

        return view('web.sections', [
            'contentTypes'        => $contentTypes,
            'artworkCountsByType' => $artworkCountsByType,
            'page_title'          => 'Browse Sections',
            'page_meta_description' => 'Browse all artwork sections on Skinbase — Photography, Wallpapers, Skins and more.',
        ]);
    }
}
