<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    // Maps frontend URL slugs to DB slugs
    private array $slugAliases = [
        'womens-clothing'  => 'womens',
        'mens-clothing'    => 'mens',
        'kids-clothing'    => 'kids',
        'home-accessories' => 'home',
    ];

    private function resolveSlug(string $slug): string
    {
        return $this->slugAliases[$slug] ?? $slug;
    }

    public function index()
    {
        $cats = Category::active()->parents()->withCount('products')->with('children')->orderBy('sort_order')->get();
        return response()->json(['success' => true, 'data' => $cats]);
    }

    public function show(string $slug)
    {
        $slug = $this->resolveSlug($slug);
        $cat  = Category::active()->where('slug', $slug)->with('children')->withCount('products')->firstOrFail();
        return response()->json(['success' => true, 'data' => $cat]);
    }

    public function products(string $slug, Request $request)
    {
        $slug = $this->resolveSlug($slug);
        $cat  = Category::active()->where('slug', $slug)->firstOrFail();

        $query = Product::with('category')->active()->inStock()
            ->where('category_id', $cat->id);

        if ($request->min_price) $query->where('price', '>=', $request->min_price);
        if ($request->max_price) $query->where('price', '<=', $request->max_price);
        if ($request->sub)       $query->where('sub_category', $request->sub);

        match($request->sort ?? 'popular') {
            'price_asc'  => $query->orderBy('price'),
            'price_desc' => $query->orderByDesc('price'),
            'newest'     => $query->latest(),
            'rating'     => $query->withAvg('reviews', 'rating')->orderByDesc('reviews_avg_rating'),
            default      => $query->orderByDesc('id'),
        };

        $products = $query->paginate($request->per_page ?? 16);
        return response()->json(['success' => true, 'data' => $products]);
    }
}
