<?php

namespace Sargilla\Flatlab4\Controllers;

use Auth;
use Illuminate\Support\Arr;
use Yajra\DataTables\DataTables;
use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Permission as Permiso;

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

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

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

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

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

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

    public function destroy(Permiso $permiso) {

        if ($permiso->name == "Administrar Usuarios") {
            return response()->json('No puedes borrar este permiso!', 401);
        }
        $permiso->delete();
        return response("Rol $permiso->name Borrado!");

    }

    public function getPermisos()
    {
        if (!request()->ajax()) {
            return redirect()->route('permisos.index');
        }
        return DataTables::of(Permiso::all())
            ->addColumn('roles', function($query){
                return  str_replace(array('[',']','"'),'', $query->roles()->pluck('name'));
            })
            ->addColumn('acciones', function($query){
                $query = $query->load('roles');
                return view('flatlab::permisos.acciones', compact('query'))->render();
            })
            ->rawColumns(['acciones'])
            ->make(true);
    }

}
