<?php

namespace App\Http\Middleware;

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

class StrictAuthApi
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $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()]);
                }
                else
                {
                    if(getCurrentLocale() == 'ar')
                    {
                        $errors = ['authorized'=>'يجب عليك تسجيل الدخول اولا'];
                        $message = $errors['authorized'];
                    }
                    else
                    {
                        $errors = ['authorized'=>['Login First']];
                        $message = $errors['authorized'][0];
                    }
                
                    
                        throw new HttpResponseException(response()->json(['message'=> $message, 'errors' => $errors],  401));
        
                }
            
        }
        else
        {
            
            if(getCurrentLocale() == 'ar')
            {
                $errors = ['authorized'=>'يجب عليك تسجيل الدخول اولا'];
                $message = $errors['authorized'];
            }
            else
            {
                $errors = ['authorized'=>['Login First']];
                $message = $errors['authorized'][0];
            }
        
            
                throw new HttpResponseException(response()->json(['message'=> $message, 'errors' => $errors],  401));
        
        }
       
        return $next($request);
    }
}
