<?php

namespace App\Http\Middleware;
use App\API_User;
use Closure;
use Response;
use Illuminate\Support\Facades\Log;
use Hash;

class APIkey
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */

    protected $log;

    public function __construct()
    {
         $this->log = Log::channel('app');
    }

    public function handle($request, Closure $next)
    {
        //date 

            $this->log->debug('api_token:'. request('api_token'));
            $this->log->debug('username:'. request('username'));
            $this->log->debug('passkey:'. request('passkey'));


        if ($request->api_token == '') 
        { 
            $this->log->error('Token authenticated failed...');
            $this->log->error('API Key is Empty...');
            $this->content['error'] = "Token Empty";
            $status = 502;
            
        } 
        else 
        { 

            $passkey =bcrypt(request('passkey'));
            $users = API_User::where('api_token', request('api_token'))
                            ->where('username',request('username'))
                            ->first();


            if (!Hash::check(request('passkey'), $users->passkey)) {
    
                // Log::error('Token authenticated failed...');
                $this->content['error'] = "Token authentication failed";
                $status = 503;
                $this->log->error('Token authentication failed');

            } 
            else 
            { 
                $this->log->debug('API key authentication successful');
                return $next($request);
            }
        }

        return response()->json(['content' => $this->content,'status' => $status]); 
    }
}
