<?php

namespace App\Http\Controllers\API\V1;

use App\Http\Controllers\Controller;
use App\Http\Resources\CategoryResource;
use App\Http\Resources\HomeProductResource;
use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class CategoryController extends Controller
{
    public function index(): AnonymousResourceCollection
    {
        $query = Category::query()
            ->with(['parent', 'children'])
            ->withCount('children');

        // Filter by parent_id (null for root categories)
        if (request()->has('parent_id')) {
            $parentId = request()->query('parent_id');
            if ($parentId === 'null' || $parentId === '') {
                $query->whereNull('parent_id');
            } else {
                $query->where('parent_id', $parentId);
            }
        }

        // Include only root categories when specified
        if (request()->query('only_parents') === 'true') {
            $query->whereNull('parent_id');
        }

        if (request()->has('per_page')) {
            $perPage = request()->query('per_page');
            $categories = $query->paginate($perPage);
        } else {
            $categories = $query->get();
        }

        return CategoryResource::collection($categories);
    }

    public function show(Category $category): CategoryResource
    {
        $category->load(['parent', 'children']);
        $category->loadCount('children');

        return new CategoryResource($category);
    }

    /**
     * Get products from all subcategories of a parent category.
     *
     * @param  Category  $category  The parent category
     */
    public function subcategoriesProducts(Category $category): JsonResponse
    {
        // Get all child category IDs
        $childCategoryIds = $category->children()->where('status', 'active')->pluck('id')->toArray();

        // Add parent category ID to include products from parent too
        $allCategoryIds = array_merge([$category->id], $childCategoryIds);

        // Build query for products
        $query = Product::query()->whereIn('category_id', $allCategoryIds);

        // Apply search filter if provided
        if (request()->has('search')) {
            $search = request()->query('search');
            $query->where(function ($q) use ($search) {
                $q->where('name_en', 'like', "%{$search}%")
                    ->orWhere('name_ar', 'like', "%{$search}%")
                    ->orWhere('description_en', 'like', "%{$search}%")
                    ->orWhere('description_ar', 'like', "%{$search}%");
            });
        }

        // Apply source filter if provided
        if (request()->has('source')) {
            $query->where('source', request()->query('source'));
        }

        // Order by latest
        $query->orderBy('created_at', 'desc');

        // Handle pagination
        $perPage = request()->query('per_page', 15);
        $products = $query->paginate($perPage);

        return response()->json([
            'data' => HomeProductResource::collection($products),
            'meta' => [
                'current_page' => $products->currentPage(),
                'per_page' => $products->perPage(),
                'total' => $products->total(),
                'last_page' => $products->lastPage(),
                'from' => $products->firstItem(),
                'to' => $products->lastItem(),
            ],
        ]);
    }
}
