<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ServicoAtendimento;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class ServicoAtendimentoController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth', 'role:admin']);
    }
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $servicos = ServicoAtendimento::orderBy('descricao')->get();

        return view('admin.servicos-atendimentos.index', ['servicos' => $servicos]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.servicos-atendimentos.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'descricao' => 'required|max:50|unique:servicos_atendimento,descricao',
        ], [], ['descricao' => 'descrição']);

        $servico = new ServicoAtendimento($request->all());
        $servico->save();

        return redirect()
                ->route('admin.servicos-atendimentos.index')
                ->with('status', 'Serviço incluído com sucesso!');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\ServicoAtendimento  $servico
     * @return \Illuminate\Http\Response
     */
    public function edit(ServicoAtendimento $servico)
    {
        return view('admin.servicos-atendimentos.edit', ['servico' => $servico]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\ServicoAtendimento  $servico
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, ServicoAtendimento $servico)
    {
        $this->validate($request, [
            'descricao' => ['required', 'max:50', Rule::unique('servicos_atendimento')->ignore($servico)],
        ], [], ['descricao' => 'descrição']);

        $servico->fill($request->all());
        $servico->save();

        return redirect()
            ->route('admin.servicos-atendimentos.index')
            ->with('status', 'Serviço editado com sucesso!');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\ServicoAtendimento  $servico
     * @return \Illuminate\Http\Response
     */
    public function destroy(ServicoAtendimento $servico)
    {
        $servico->delete();

        return redirect()
            ->route('admin.servicos-atendimentos.index')
            ->with('status', 'Serviço excluído com sucesso!');
    }
}
