<?php

namespace Sargilla\FlatLab\Controllers;

use Artdarek\Toastr\Facades\Toastr;
use Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Session;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Yajra\Datatables\Datatables;

class RolesController extends Controller
{
    public function __construct() {
        $this->middleware(['auth', 'isAdmin']);
    }

    public function index() {

        return view('flatlab::roles.index');

    }

    public function create() {

        $permissions = Permission::all();

        return view('flatlab::roles.create', ['permissions'=>$permissions]);

    }

    public function store() {

        $this->validate(request(), ['name'=>'required|unique:roles|max:25']);

        $rol = Role::create(['name' => request()->name]); 

        $rol->permissions()->sync(request()->permisos);

        Toastr::success('Rol Creado!')->push();
        
        return redirect()->route('roles.index'); 
    }


    public function show($id) {

        return redirect('flatlab::roles');

    }


    public function edit(Role $role) {
      
        $permissions = Permission::all();

        return view('flatlab::roles.edit', compact('role', 'permissions'));

    }

    public function update(Role $role) {

        $this->validate(request(), ['name'=>'required|max:25|unique:roles,name,'.$role->id]);

        $role->update(request()->except(['permisos']));
      
        $role->permissions()->sync(request()->permisos);
      
        Toastr::success('Rol Actualizado!')->push();

        return redirect()->route('roles.index');

    }

    public function destroy(Role $role)
    {
        if ($role->name == "Administrador") {
            return response()->json('No puedes borrar este rol!', 401);
        } 

        $role->delete();

        return response()->json(['Rol Borrado!']);

    }

    public function getRoles()
    {
        if (!request()->ajax()) {
            return redirect()->route('roles.index');
        }

        return Datatables::of(Role::all())
            ->addColumn('permisos', function($query){
                return  str_replace(array('[',']','"'),'', $query->permissions()->pluck('name'));
            })
            ->addColumn('acciones', function($query){
                return "<div class='acciones' data-id='$query->id' >                  
                    <button class='btn btn-xs btn-primary' 
                        data-action='editar' title='Editar'><i class='fa fa-pencil'></i></button>
                    <button class='btn btn-xs btn-danger btn-xs'
                        data-action='borrar' title='Borrar'><i class='fa fa-times'></i></button>
                </div>";
            })
            ->rawColumns(['acciones'])
            ->make(true);    
    }
    
}
