<?php

namespace App\Http\Controllers;

use App\Http\Requests\ProcedureRequest;
use App\Models\Procedure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class ProcedureController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return response()->json(['procedures' => Procedure::select('id', 'name','description')->get()]);
    }


    /**
     * Store a newly created resource in storage.
     */
    public function store(ProcedureRequest $request)
    {
        $procedure = Procedure::create($request->all());
        return response()->json(['message' => __('messages.procedure_created'), 'procedure' => $procedure]);
    }

    /**
     * Display the specified resource.
     */
    public function show(Procedure $procedure)
    {
        return response()->json(['procedure' => $procedure]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(ProcedureRequest $request,Procedure $procedure)
    {
        $procedure->update($request->all());

        return response()->json(['message' => __('messages.procedure_updated'), 'type' => $procedure]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Procedure $procedure)
    {
        $hasReports = $procedure->reports()->exists();

        if ($hasReports) {
            return response()->json([
                'message' => __('messages.report_type_in_use')
            ], Response::HTTP_CONFLICT); // 409 Conflict
        }

        $procedure->delete();

        return response()->json(['message' => __('messages.report_type_deleted')]);
    }
}
