<?php

namespace Sargilla\Flatlab4\Controllers;

use Illuminate\Support\Arr;
use Yajra\DataTables\DataTables;
use Spatie\Permission\Models\Role;
use App\Http\Controllers\Controller;

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

    public function index() {
        return view('flatlab::roles.index');
    }

    public function create() {
        return view('flatlab::roles.create');
    }

    public function store() {
        request()->validate(['name'=>'required|unique:roles|max:25']);
        $rol = Role::create(['name' => request()->name]);
        $rol->permissions()->sync(Arr::pluck(request()->permisos, 'id'));
        return response("Se creó el rol $rol->name correctamente!");
    }

    public function show($id) {
        return redirect('flatlab::roles');
    }

    public function update(Role $role) {
        request()->validate(['name'=>'required|max:25|unique:roles,name,'.$role->id]);
        $role->update(request()->except(['permisos']));
        $role->permissions()->sync(Arr::pluck(request()->permisos, 'id'));
        return response("Se editó el rol $role->name correctamente!");
    }

    public function destroy(Role $role)
    {
        if ($role->name == "Administrador") {
            return response('No puedes borrar este rol!', 401);
        }
        $role->delete();
        return response("Rol $role->name 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){
                $query = $query->load('permissions');
                return view('flatlab::roles.acciones', compact('query'))->render();
            })
            ->rawColumns(['acciones'])
            ->make(true);
    }

}
