<?php
// app/Http\Controllers\Api\Admin\CategoryController.php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Traits\ApiResponse;
use App\Models\Category;
use App\Http\Requests\Api\Admin\CategoryRequest;
use App\Http\Resources\Api\CategoryResource;
use App\Http\Resources\Api\CategoryCollection;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    use ApiResponse;

    /**
     * Get all categories
     */
    public function index(Request $request)
    {
        try {
            $query = Category::withCount('menus')
                ->when($request->search, function ($q, $search) {
                    $q->where('name', 'like', "%{$search}%")
                      ->orWhere('description', 'like', "%{$search}%");
                })
                ->when($request->is_active !== null, function ($q) use ($request) {
                    $q->where('is_active', $request->is_active);
                })
                ->orderBy('created_at', 'desc');

            $perPage = $request->per_page ?? 20;
            $categories = $query->paginate($perPage);

            return $this->successResponse(
                new CategoryCollection($categories),
                'Categories retrieved successfully'
            );
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to retrieve categories', 500, $e->getMessage());
        }
    }

    /**
     * Get single category
     */
    public function show($id)
    {
        try {
            $category = Category::with('menus')->find($id);

            if (!$category) {
                return $this->errorResponse('Category not found', 404);
            }

            return $this->successResponse(
                new CategoryResource($category),
                'Category retrieved successfully'
            );
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to retrieve category', 500, $e->getMessage());
        }
    }

    /**
     * Create new category
     */
    public function store(CategoryRequest $request)
    {
        try {
            $category = Category::create($request->validated());

            return $this->successResponse(
                new CategoryResource($category),
                'Category created successfully',
                201
            );
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to create category', 500, $e->getMessage());
        }
    }

    /**
     * Update category
     */
    public function update(CategoryRequest $request, $id)
    {
        try {
            $category = Category::find($id);

            if (!$category) {
                return $this->errorResponse('Category not found', 404);
            }

            $category->update($request->validated());

            return $this->successResponse(
                new CategoryResource($category->fresh()),
                'Category updated successfully'
            );
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to update category', 500, $e->getMessage());
        }
    }

    /**
     * Delete category
     */
    public function destroy($id)
    {
        try {
            $category = Category::find($id);

            if (!$category) {
                return $this->errorResponse('Category not found', 404);
            }

            // Check if category has menus
            if ($category->menus()->exists()) {
                return $this->errorResponse(
                    'Cannot delete category because it has associated menus',
                    400
                );
            }

            $category->delete();

            return $this->successResponse(
                null,
                'Category deleted successfully'
            );
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to delete category', 500, $e->getMessage());
        }
    }

    /**
     * Toggle category status
     */
    public function toggleStatus($id)
    {
        try {
            $category = Category::find($id);

            if (!$category) {
                return $this->errorResponse('Category not found', 404);
            }

            $category->update(['is_active' => !$category->is_active]);

            return $this->successResponse(
                new CategoryResource($category),
                'Category status updated successfully'
            );
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to update category status', 500, $e->getMessage());
        }
    }
}