<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\View\View;

class CategoryController extends Controller
{
    /**
     * Get categories with subcategories and product counts
     */
    protected function getCategoriesWithCounts($selectedCategoryIds = [])
    {
        $rootCategories = Category::active()
            ->root()
            ->orderBy('sort_order')
            ->with(['children' => function ($query) {
                $query->active()->orderBy('sort_order');
            }])
            ->get();

        // Calculate product counts for each category
        foreach ($rootCategories as $category) {
            // Get all category IDs including subcategories
            $categoryIds = [$category->id];
            foreach ($category->children as $child) {
                $categoryIds[] = $child->id;
            }

            // Count products for this category and its children
            $category->product_count = Product::whereIn('category_id', $categoryIds)->active()->count();

            // Count products for each subcategory
            foreach ($category->children as $child) {
                $child->product_count = Product::where('category_id', $child->id)->active()->count();
            }
        }

        return $rootCategories;
    }

    public function show(string $slug, Request $request): View
    {
        $category = Category::where('slug', $slug)
            ->active()
            ->firstOrFail();

        $query = $category->products()
            ->with('category')
            ->active();

        // Handle multiple category filtering from checkboxes (subcategory filtering)
        $selectedCategoryIds = $request->has('categories') && is_array($request->categories) 
            ? $request->categories 
            : [];

        if (!empty($selectedCategoryIds)) {
            // Filter by selected subcategories if any are selected
            $allCategoryIds = [];
            foreach ($selectedCategoryIds as $catId) {
                $selectedCat = Category::find($catId);
                if ($selectedCat && ($selectedCat->parent_id == $category->id || $selectedCat->id == $category->id)) {
                    $allCategoryIds[] = $selectedCat->id;
                }
            }
            if (!empty($allCategoryIds)) {
                $query->whereIn('category_id', $allCategoryIds);
            }
        } else {
            // If no subcategory filters, include subcategories by default
            $categoryIds = [$category->id];
            $subcategories = Category::where('parent_id', $category->id)->active()->pluck('id');
            $categoryIds = array_merge($categoryIds, $subcategories->toArray());
            $query->whereIn('category_id', $categoryIds);
        }

        $products = $query->paginate(12)->withQueryString();

        // Get categories with subcategories and counts for sidebar
        $categoriesWithCounts = $this->getCategoriesWithCounts($selectedCategoryIds);

        return view('category.show', compact('category', 'products', 'categoriesWithCounts', 'selectedCategoryIds'));
    }
}
