<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use App\Device;

class tokencheck
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $secret = '0b2a14a06cdasdflohc6c19b107ad432432';
        $header_secret = $request->header('secret');
        if(is_null($request->header('language'))){
             return response()->json([
            'data'=>'lanuguage required'
            ],  401);
        }

        if($request->header('ip') && $request->header('token'))
        {
            $ip = $request->header('ip');

            $device = Device::where('ip',$ip)->first();
            
            if(!$device){
                Device::create(['device_token'=>$request->header('token'),'ip'=>$request->header('ip'),'language'=>$request->header('language')]);
            }
            else{
                $device->update(['device_token'=>$request->header('token'),'language'=>$request->header('language')]);
            }
        }

        if($header_secret != $secret){
             return response()->json([
            'data'=>'connection error'
            ],  401);
        }
        return $next($request);
    }
}
