<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\CategoryResource;
use App\Http\Resources\ProductResource;
use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\Request;

class CategoryApiController extends Controller
{
    /**
     * Display listing of active categories.
     */
    public function index()
    {
        $categories = Category::where('status', 'active')->withCount('products')->get();
        return CategoryResource::collection($categories);
    }

    /**
     * Display category products.
     */
    public function products($id)
    {
        $category = Category::where('id', $id)->orWhere('slug', $id)->first();
        if (!$category) {
            return response()->json(['message' => 'Category not found.'], 404);
        }

        $products = Product::with(['category', 'images'])
            ->where('category_id', $category->id)
            ->where('status', 'active')
            ->get();

        return ProductResource::collection($products);
    }
}
