<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class CheckRedmineAuth
{
  /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
  public function handle(Request $request, Closure $next)
  {
    try{
      $redmineUser = session('redmine_user');
      $azienda = session('azienda');
      // Tento l'autenticazione
      $response = Http::get($azienda->redmine_url.'/my/account.json', [
        'key' => $redmineUser->api_key
      ]);
      if(!$response->ok()){
        return redirect('login');
      }

      // $request->session()->put('redmine_user', $response->object()->user);
      return $next($request);

    }catch(\Exception $e){
      return redirect('login');
    }


  }
}
