<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Illuminate\Http\Exceptions\HttpResponseException;

use Modules\User\Models\User;

class StrictAuthApi
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $res = false;
        $token= $request->bearerToken();
        if($token)
        {
            $user = User::where('api_token',$token)->first();
            if($user)
            {
                Auth::login($user);
                if($request->header('tokenDevice'))
                {
                    $user->update(['device_token'=>$request->header('tokenDevice')]);
                }  
                $user->update(['language'=>getCurrentLocale()]);
                $res = true;
            }
        }
        if($res == false)
        {
            $errors = ['authorized'=>__('web.login_first')];
            $message = $errors['authorized'];
            throw new HttpResponseException(response()->json(['message'=> $message, 'errors' => $errors],  401));
        }
        return $next($request);
    }
}
