<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Category\StoreCategoryRequest;
use App\Http\Requests\Category\UpdateCategoryRequest;
use App\Http\Resources\CategoryResource;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Str;

class CategoryController extends ApiController
{
    public function index(Request $request): AnonymousResourceCollection
    {
        $companyId = $this->currentCompanyId($request);
        $search = $request->string('search')->toString();

        $categories = Category::query()
            ->with(['parent'])
            ->withCount('children')
            ->where('company_id', $companyId)
            ->when($search !== '', function ($query) use ($search) {
                $query->where('name', 'like', "%{$search}%");
            })
            ->when($request->boolean('only_parents'), function ($query) {
                $query->whereNull('parent_id');
            })
            ->orderBy('sort_order')
            ->orderBy('name')
            ->paginate((int) $request->integer('per_page', 15));

        return CategoryResource::collection($categories);
    }

    public function store(StoreCategoryRequest $request): CategoryResource
    {
        $companyId = $this->currentCompanyId($request);
        $data = $request->validated();
        
        if (empty($data['slug'])) {
            $data['slug'] = Str::slug($data['name']);
        }

        $category = Category::create([
            ...$data,
            'company_id' => $companyId,
        ]);

        return new CategoryResource($category->load(['parent']));
    }

    public function show(Request $request, Category $category): CategoryResource
    {
        $this->ensureCompanyScoped($category, $this->currentCompanyId($request));
        
        return new CategoryResource($category->load(['parent', 'children']));
    }

    public function update(UpdateCategoryRequest $request, Category $category): CategoryResource
    {
        $this->ensureCompanyScoped($category, $this->currentCompanyId($request));
        
        $data = $request->validated();
        if (isset($data['name']) && empty($data['slug'])) {
            $data['slug'] = Str::slug($data['name']);
        }

        $category->update($data);

        return new CategoryResource($category->load(['parent']));
    }

    public function destroy(Request $request, Category $category): \Illuminate\Http\JsonResponse
    {
        $this->ensureCompanyScoped($category, $this->currentCompanyId($request));
        
        $category->delete();

        return response()->json(['message' => 'Category deleted successfully']);
    }
}
