<?php

namespace App\Http\Controllers;

use App\Http\Resources\ServiceListResource;
use App\Http\Resources\ServiceTypeResource;
use App\Models\ServiceType;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Str;
use phpDocumentor\Reflection\Types\True_;

class ServiceTypeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return AnonymousResourceCollection
     */
    public function index(): AnonymousResourceCollection
    {
        return ServiceTypeResource::collection(ServiceType::all());
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return JsonResponse
     */
    public function show(int $id): JsonResponse
    {
        $serviceType = ServiceType::findOrFail($id);
        $serviceType->photo = $serviceType->photo != null? url('Image/Service').'/'.$serviceType->photo : null;
        return response()->json($serviceType);
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return JsonResponse
     */
    public function get_service_data(int $id): JsonResponse
    {
        $serviceType = ServiceType::findOrFail($id);
        $serviceType->photo = $serviceType->photo != null? url('Image/Service').'/'.$serviceType->photo : null;
        return response()->json($serviceType);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param ServiceType $serviceType
     * @return JsonResponse
     */
    public function update(Request $request, int $id)
    {
        $service = ServiceType::findOrFail($id);
        $data = $request->except('photo');
        if ($request->photo){
            $path = '/Image/Service/';
            $name = Str::slug($service->service_name, '-') ;
            $file = $request->photo;
            $data['photo']=ImageUploadController::uploadImage($name, $path, $file);
        }else{
            $data['photo'] = $service->photo;
        }
        $service->update($data);
        return response()->json(['msg'=>'Service Updated Successfully']);
    }

    /**
     * @return JsonResponse
     */
    public function service_list(): JsonResponse
    {
        $services = ServiceType::select('service_name as label', 'id as value')->get();
        return response()->json($services);
    }

    /**
     * @return AnonymousResourceCollection
     */
    public function service_list_details(): AnonymousResourceCollection
    {
        $services = ServiceType::get();
        return ServiceListResource::collection($services);
    }

}
