<?php

namespace App\Http\Controllers;

use App\Http\Requests\Category\CategoryRequest;
use App\Http\Resources\CategoriesProductsResource;
use App\Models\Category;
use App\Http\Resources\CategoryResource;

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $categories = Category::get();
        return \SuccessData(__('public.Show'), $categories);
    }
    /**
     * Display a listing of the resource with a random, limited number of products per category.
     */
    public function all()
    {
        $limit = 5;
        $categories = Category::with(['products' => function ($query) use ($limit) {
            $query->inRandomOrder()
                ->limit($limit);
        }])->get();
        return \SuccessData(__('public.Show'), CategoriesProductsResource::collection($categories));
    }


    /**
     * Store a newly created resource in storage.
     */
    public function store(CategoryRequest $request)
    {
        Category::create($request->validated());
        return \Success(__('public.Store'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(CategoryRequest $request, Category $category)
    {
        $category->update($request->validated());
        return \SuccessData(__('public.category_updated'), new CategoryResource($category->load('products')));
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Category $category)
    {
        $category->delete();
        return \SuccessData(__('public.category_deleted'), null);
    }
}
