<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Role;
use App\Models\User;

class PerfisUsuarioController extends Controller
{
    public function __construct()
    {
        $this->middleware(['role:admin']);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(User $usuario)
    {
        $perfis = $usuario->roles()->where('name', '!=', 'superuser')->get();
        return view('admin.usuarios.perfis.index', ['perfis' => $perfis, 'usuario' => $usuario]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(User $usuario)
    {
        $perfis = Role::assignable()->get();
        return view('admin.usuarios.perfis.create', ['perfis' => $perfis, 'usuario' => $usuario]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, User $usuario)
    {
        $this->validate($request, [
            'perfil' => 'required'
        ]);

        $usuario->assignRole($request->perfil);

        return redirect()
            ->route('admin.usuarios.perfis.index', ['usuario' => $usuario])
            ->with('status', 'Perfil concedido com sucesso!');
    }

    public function destroy(User $usuario, Role $perfil)
    {
        $usuario->removeRole($perfil);

        return redirect()
            ->route('admin.usuarios.perfis.index', ['usuario' => $usuario])
            ->with('status', 'Perfil removido do usuário com sucesso!');
    }
}
