<?php

namespace App\Http\Middleware;

use Closure;
use App\User;

class SecretTokenMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // dd($request->route('local'), $request->header('secret'), $request->bearerToken());
        $secret = 'b303e42aa866fb54e88c055e4f923fe6';
        if(!$request->hasHeader('secret') || $secret != $request->header('secret')){
            return response()->json(['message' => __('main.unauthenticated'), 'status' => 401], 401);
        }

        $deviceId = $request->header('deviceId');
        $deviceToken = $request->header('deviceToken');
        $local = $request->header('local');

        if ($deviceId){
            $request['device_id'] = $deviceId;
        }
        if ($deviceToken){
            $request['device_token'] = $deviceToken;
        }
        $request['local'] = $local ?? getCurrentLocale();

        // update last seen
//        $token = $request->bearerToken();
//        $user = User::where('api_token', $token)->first();
        // set Last Seen time
//        if($user){
//            $user->last_seen_at = now();
//            $user->save();
//        }
        // dd($user->toArray());
        app()->setLocale(($request->header('local') ?? getCurrentLocale()));
//        $request->language_id = $request->header('language_id') ?? currentLanguage()->id;
        return $next($request);
    }
}
