<?php

namespace App\Http\Controllers\API\V1;

use App\Http\Controllers\Controller;
use App\Http\Resources\CategoryResource;
use App\Models\Category;
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);
    }
}
