<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    /**
     * Display category page with products
     */
    public function show($slug)
    {
        $category = Category::where('slug', $slug)
            ->where('is_active', true)
            ->with('children')
            ->firstOrFail();

        // Get products in this category and its subcategories
        $categoryIds = [$category->id];
        $categoryIds = array_merge($categoryIds, $category->children->pluck('id')->toArray());
        
        $query = Product::whereIn('category_id', $categoryIds)
            ->where('is_active', true);

        // Filtering
        $brand = request('brand');
        if ($brand) {
            $query->where('brand', $brand);
        }

        // Sorting
        $sort = request('sort', 'default');
        switch ($sort) {
            case 'price_asc':
                $query->orderBy('price', 'asc');
                break;
            case 'price_desc':
                $query->orderBy('price', 'desc');
                break;
            case 'name_asc':
                $query->orderBy('name', 'asc');
                break;
            case 'name_desc':
                $query->orderBy('name', 'desc');
                break;
            case 'stock':
                $query->where('in_stock', true)->orderBy('stock_quantity', 'desc');
                break;
            default:
                $query->orderBy('order', 'asc')->orderBy('name', 'asc');
        }

        $products = $query->paginate(24);
        
        // Get unique brands for filter
        $brands = Product::whereIn('category_id', $categoryIds)
            ->where('is_active', true)
            ->whereNotNull('brand')
            ->distinct()
            ->pluck('brand')
            ->sort()
            ->values();

        return view('category.show', compact('category', 'products', 'brands'));
    }
}
