<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Role;
use App\Models\Permission;
use Yajra\DataTables\DataTables;
use App\DataTables\RoleDataTableEditor;
use App\DataTables\RoleDataTable;
use App\Models\User;
use Session;
use Auth;

class RoleController extends Controller
{
  public static $permission_group = "Ruoli e permessi";
  public static $permissions = [
    'create-roles-permissions' => 'Permetti di modificare i ruoli/permessi',
    'edit-roles-permissions' => 'Permetti di modificare i ruoli/permessi',
  ];

  public function __construct(){
    $this->middleware('permission:edit-roles-permissions')->only(['index']);
  }

  public function index(RoleDataTable $dataTable)
  {
    return $dataTable->render('role.index');
  }

  public function store(RoleDataTableEditor $editor)
  {
    $request = request();
    $input = $request->all();

    if($request->has('action')){
      switch($input['action']){
        case 'create':
        if(!Auth::user()->can('create-roles-permissions')) return;
        break;

        case 'edit':
        if(!Auth::user()->can('edit-roles-permissions')) return;
        break;

        case 'remove':
        if(!Auth::user()->can('edit-roles-permissions')) return;
        break;
      }
    }


    return $editor->process(request());
  }

  public function updatePermission(Request $request){
    $input = $request->all();
    $permissions = [];
    $role = Role::find($input['role_id']);

    if($request->has('permesso')){
      foreach($input['permesso'] as $key => $value){
        $p = Permission::find($value);
        if($p != null){
          array_push($permissions, $p->name);
        }
      }

      $role->syncPermissions($permissions);
    }

    Session::flash('flash_message', 'Permessi aggiornati!');
    return redirect()->route('roles.index');
  }

  public function role_user(Request $request)
  {
    $input = $request->all();
    if($request->has('role_id')){
      $role = Role::find($input['role_id']);
      return view('role.user', ['role' => $role]);
    }
  }

  public function rimuovi_utente(Request $request){
    $input = $request->all();
    $role = Role::find($input['role_id']);
    $user = User::find($input['user_id']);

    $user->removeRole($role->name);
  }
}
