<?php

namespace App\Http\Controllers\Admin;

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

class NivelSalarialController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth', 'role:admin']);
    }
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $niveis = NivelSalarial::paginate(20);

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.niveis-salariais.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, [
            'nome' => 'required|max:50|unique:niveis_salariais,nome',
            'salario_base' => 'nullable',
        ]);

        $nivel = new NivelSalarial($request->all());
        $nivel->save();

        return redirect()
                ->route('admin.niveis-salariais.index')
                ->with('status', 'Nivel incluído com sucesso!');
    }

    public function edit(NivelSalarial $nivel)
    {
        return view('admin.niveis-salariais.edit', ['nivel' => $nivel]);
    }

    public function update(Request $request, NivelSalarial $nivel)
    {
        $this->validate($request, [
            'nome' => ['required', 'max:50', Rule::unique('niveis_salariais')->ignore($nivel)],
            'salario_base' => 'nullable',
        ]);

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

        return redirect()
            ->route('admin.niveis-salariais.index')
            ->with('status', 'Nivel editado com sucesso!');
    }

    public function destroy(NivelSalarial $nivel)
    {
        $nivel->delete();

        return redirect()
            ->route('admin.niveis-salariais.index')
            ->with('status', 'Nivel excluído com sucesso!');
    }
}
