<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Role;
use App\Models\Permission;
use Yajra\DataTables\DataTables;
use App\DataTables\UserDataTableEditor;
use App\DataTables\UserDataTable;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Collection;
use Session;
use Auth;

class UserController extends Controller
{
  public static $permission_group = "Utenti";
  public static $permissions = [
    'view-users' => 'Permetti di vedere la pagina',
    'create-users' => 'Permetti la creazione',
    'edit-users' => 'Permetti la modifica',
    'remove-users' => 'Permetti la cancellazione',
    'edit-role_user' => 'Permetti la modifica di ruoli e permessi degli utenti'
  ];

  public function __construct(){
    $this->middleware('permission:view-users')->only(['index', 'load_progetti']);
    $this->middleware('permission:create-users|edit-users|remove-users')->only(['store', 'update_progetti']);
  }

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

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

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

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

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


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

  public function roles(Request $request){
    $input = $request->all();
    if($request->has('user_id')){
      $user = User::find($input['user_id']);
      return view('user.roles', ['user' => $user]);
    }
  }

  public function updateRole(Request $request){
    $input = $request->all();

    // Ruoli
    $roles = [];
    $user = User::find($input['user_id']);

    if($request->has('ruolo')){
      foreach($input['ruolo'] as $key => $value){
        $r = Role::find($value);
        if($r != null){
          array_push($roles, $r->name);
        }
      }

      $user->syncRoles($roles);
    }

    // Permessi diretti
    $permissions = [];

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

      $user->syncPermissions($permissions);
    }

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

  public function load_progetti(Request $request){
    $redmineUser = session('redmine_user');
    $user = User::find($request->user_id);
    $userProg = json_decode($user->progetti);
    if($userProg == null){
      $userProg = array();
    }

    $progettiUser = new Collection;
    $progetti = new Collection;

    // Lista di tutti i progetti assegnati all'utente
    $projectResponseUser = Http::get(config('redmine.url').'/projects.json', [
      'key' => $redmineUser->api_key,
      'id' => ($userProg!=null && count($userProg)>0)?implode('|', $userProg):'',
      'limit' => 100
    ]);

    // Lista di 30 progetti filtrati per ricerca
    $projectResponse = Http::get(config('redmine.url').'/projects.json', [
      'key' => $redmineUser->api_key,
      'name' => '~'.($request->has('filter')?$request->filter:''),
      'limit' => 30
    ]);

    foreach($projectResponseUser->object()->projects as $project){
      if(in_array($project->id, $userProg)){
        $progettiUser->push($project);
      }
    }

    foreach($projectResponse->object()->projects as $project){
      if(!in_array($project->id, $userProg)){
        $progetti->push($project);
      }
    }

    return view('user.progetti')->with(['user' => $user, 'progetti' => $progetti, 'progettiUser' => $progettiUser]);
  }

  public function update_progetti(Request $request){
    $user = User::find($request->user_id);
    $user->progetti = json_encode($request->progetto);
    $user->save();

    Session::flash('flash_message', 'Progetti aggiornati');
    return redirect()->route('user.index');
  }
}
