<?php

namespace Sargilla\FlatLab\Controllers;

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

class PermisosController extends Controller
{
     public function __construct() {

        $this->middleware(['auth', 'isAdmin']);

    }

    public function index() {

        $permisos = Permiso::all(); 

        return view('flatlab::permisos.index')->with('permisos', $permisos);

    }

    public function create() {

        $roles = Role::get(); 

        return view('flatlab::permisos.create')->with('roles', $roles);

    }

    public function store() {

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

        $permiso = Permiso::create(request()->except('roles'));

        $permiso->roles()->sync(request()->roles);

        Toastr::success('Permiso Creado!')->push();

        return redirect()->route('permisos.index');
           
    }

    public function show($id) {

        return redirect('flatlab::permisos');

    }


    public function edit(Permiso $permiso) {

        return view('flatlab::permisos.edit', compact('permiso'));

    }

    public function update(Permiso $permiso) {
       
        $this->validate(request(), ['name'=>'required|max:40|unique:permissions,name,'.$permiso->id]);
        
        $permiso->update(request()->all());

        Toastr::success('Permiso Actualizado!')->push();

        return redirect()->route('permisos.index');    
    }

    public function destroy(Permiso $permiso) {
        
        if ($permiso->name == "Administrar Usuarios") {
            return response()->json('No puedes borrar este permiso!', 401);
        }

        $permiso->delete();

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

    }

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

        return Datatables::of(Permiso::all())            
            ->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);    
    }
    
}
