<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ProductController extends Controller
{
    public function index(Request $request): View
    {
        $query = Product::query()->where('is_active', true)
            ->with(['category', 'images', 'activeVariants'])
            ->withCount('productRatings')
            ->withAvg('productRatings', 'rating');

        if ($request->filled('category_id')) {
            $query->where('category_id', $request->category_id);
        }
        if ($request->filled('search')) {
            $query->where('name', 'like', '%' . $request->search . '%');
        }
        if ($request->boolean('featured')) {
            $query->where('is_featured', true);
        }

        $sort = $request->get('sort', 'default');
        if ($sort === 'price_asc') {
            $query->orderBy('base_price');
        } elseif ($sort === 'price_desc') {
            $query->orderByDesc('base_price');
        } elseif ($sort === 'rating') {
            $query->orderByDesc('product_ratings_avg_rating');
        } else {
            $query->orderBy('sort_order');
        }

        $products = $query->paginate(24)->withQueryString();

        return view('store.products.index', compact('products'));
    }

    public function show(Request $request, Product $product): View
    {
        if (! $product->is_active) {
            abort(404);
        }

        $product->load([
            'category',
            'images',
            'variants',
            'productRatings' => fn ($q) => $q->with(['order' => fn ($o) => $o->with('user:id,name,email')])
                ->orderByDesc('created_at')
                ->limit(50),
        ]);
        $product->loadCount('productRatings');
        $product->loadAvg('productRatings', 'rating');

        $related = Product::where('category_id', $product->category_id)
            ->where('id', '!=', $product->id)
            ->where('is_active', true)
            ->with(['images'])
            ->withCount('productRatings')
            ->withAvg('productRatings', 'rating')
            ->orderBy('sort_order')
            ->limit(8)
            ->get();

        return view('store.products.show', compact('product', 'related'));
    }
}
