<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

use Illuminate\Routing\Controller;

class RoleController extends Controller
{

    public function __construct() {
        $this->middleware('can:role.index')->only('index','show');
        $this->middleware('can:role.create')->only('create','store');
        $this->middleware('can:role.edit')->only('edit','update');
        $this->middleware('can:role.destroy')->only('destroy');
    }
    public function index()
    {
        $roles = Role::all();
        return view('role.index',compact('roles'));
    }

    public function create()
    {
        $permissions = Permission::all();
        return view('role.create',compact('permissions'));
    }


    public function store(Request $request)
    {
        $request->validate([
            'name'=>'required'
        ]);

        $role = Role::create($request->all());

        $role->permissions()->sync($request->permissions);

        return redirect()->route('role.edit',$role)->with('info','El rol se creo correctamente');
    }


    public function show(Role $role)
    {
        return view('role.show',compact('role'));
    }


    public function edit(Role $role)
    {
        $permissions = Permission::all();
        return view('role.edit',compact('role','permissions'));
    }


    public function update(Request $request, Role $role)
    {
        $request->validate([
            'name'=>'required'
        ]);

        $role->update($request->all());

        $role->permissions()->sync($request->permissions);

        return redirect()->route('role.edit',$role)->with('info','El rol se actualizo correctamente');
    }


    public function destroy(Role $role)
    {
        $role->delete();
        session()->flash('swal',[
            'icon'=>'success',
            'title'=>'Eliminado!',
            'text'=>'Se ha eliminado el registro correctamente'
        ]);
        return redirect()->route('role.index');
    }
}
