<?php

namespace App\Http\Controllers\Api\Dashboard\Admin\WorkoutCategory;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\Dashboard\Admin\WorkoutCategory\WorkoutCategoryRequest;
use App\Http\Resources\Api\Dashboard\Admin\WorkoutCategory\{WorkoutCategoryResource};
use App\Models\{WorkoutCategory};
use Illuminate\Http\Request;

class WorkoutCategoryController extends Controller
{

    public function indexWithoutPagination()
    {
        $categories = WorkoutCategory::latest()->get();
        return WorkoutCategoryResource::collection($categories)->additional(['status' => 'success', 'message' => '']);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $categories = WorkoutCategory::when($request->keyword, function ($q) use ($request) {
            $q->whereTranslationLike('title', '%' . $request->keyword . '%');
        })->latest()->paginate($request->per_page ?? 25);
        return WorkoutCategoryResource::collection($categories)->additional(['status' => 'success', 'message' => '']);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(WorkoutCategoryRequest $request)
    {
        $category = WorkoutCategory::create($request->validated());
        return WorkoutCategoryResource::make($category)->additional(['status' => 'success', 'message' => trans('Created successfully')]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $category = WorkoutCategory::findOrFail($id);
        return WorkoutCategoryResource::make($category)->additional(['status' => 'success', 'message' => '']);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(WorkoutCategoryRequest $request, $id)
    {
        $category = WorkoutCategory::findOrFail($id);
        $category->update($request->validated());
        return WorkoutCategoryResource::make($category)->additional(['status' => 'success', 'message' => trans('Updated successfully')]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $category = WorkoutCategory::findOrFail($id);
        if ($category->delete()) {
            return response()->json(['status' => 'success', 'data' => null, 'message' => trans('Deleted successfully')]);
        }
        return response()->json(['status' => 'fail', 'data' => null, 'message' => trans('Something went wrong, please try again')], 422);
    }
}
