<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

use Modules\User\Models\Visitor;
class TokenCheck
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $secret = '0b2a5f5606012ftnmltukfdbvvc19b107ad43rdf22';
        $header_secret = $request->header('secret');
        
        $lang = $request->header('lang') ?? 'ar';
        $availabLelocals = array_keys(config('laravellocalization.supportedLocales') ?? []);
        $lang = in_array($lang,$availabLelocals) ? $lang : LaravelLocalization::getCurrentLocale();
        LaravelLocalization::setLocale($lang);
        $tokenDevice = $request->header('tokenDevice');
        if($tokenDevice)
        {
            $visitor = Visitor::where('token',$tokenDevice)->first();
            if(!$visitor)
            {
                Visitor::create(['token'=>$tokenDevice]);
            }
        }
        else
        {
        //   return response()->json([
        //     'data'=>'device token error'
        //     ],  401); 
        }
        if($header_secret != $secret)
        {
            return response()->json([
            'data'=>'connection error'
            ],  401);
        }
        return $next($request);
    }
}
