<?php

namespace App\Http\Controllers\Frontend;

use App\Enums\BannerType;
use App\Http\Controllers\Controller;
use App\Models\Banner;
use App\Models\Category;
use App\Models\GalleryItem;
use App\Models\Product;
use App\Models\Review;
use Illuminate\View\View;

class HomeController extends Controller
{
    public function index(): View
    {
        // Every banner type meant for the homepage hero, fetched as one
        // collection — not one narrowly-typed variable per type (two of
        // which used ->first(), silently dropping anything past the first
        // match). That pattern is exactly why a real admin-uploaded
        // "Discount" banner never appeared anywhere: nothing ever queried
        // for that type. Popup and Category Banner are excluded — they're
        // genuinely different placements (a modal, and category pages),
        // not hero content.
        $heroBanners = Banner::whereIn('type', [
            BannerType::HeroSlider,
            BannerType::NewArrival,
            BannerType::Sale,
            BannerType::Discount,
            BannerType::Promotional,
        ])->currentlyRunning()->get();

        $categories = Category::active()->root()->orderBy('sort_order')->take(6)->get();

        $productEagerLoads = ['primaryImage', 'category'];

        $featuredProducts = Product::active()->featured()->withRatings()->with($productEagerLoads)->latest()->take(8)->get();
        $trendingProducts = Product::active()->trending()->withRatings()->with($productEagerLoads)->latest()->take(8)->get();
        $flashSaleProducts = Product::active()->flashSale()->withRatings()->with($productEagerLoads)->take(8)->get();

        $bestSellers = Product::active()
            ->has('orderItems')
            ->withCount('orderItems')
            ->withRatings()
            ->with($productEagerLoads)
            ->orderByDesc('order_items_count')
            ->take(8)
            ->get();

        $flashSaleEndsAt = $flashSaleProducts->pluck('flash_sale_ends_at')->filter()->sort()->first();

        $reviews = Review::approved()->with(['user', 'product'])->latest()->take(6)->get();
        $galleryItems = GalleryItem::active()->take(8)->get();

        return view('frontend.home', compact(
            'heroBanners',
            'categories', 'featuredProducts', 'trendingProducts', 'flashSaleProducts', 'flashSaleEndsAt',
            'bestSellers', 'reviews', 'galleryItems',
        ));
    }
}
