<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\DB;

class VerifyAdminKey
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //return $next($request);
        if ($request->header('Authorization')) {
            $key = $request->bearerToken();
            $valid_keys = ['2131566549', '147893256', '4565931586'];
            
      	    $software = DB::table('softwares')->where('api_key', $key)->first();    

            if ($software && $software->status == 1) { 
                if ($software->type == 'API') {
                    $software = DB::table('softwares')->where('id', $software->front_id)->first();    
                }
                $request['Software'] = $software;
                return $next($request);
            }
            return sendError("PERMISSIONS_NOT_GRANTED");
						/*
            // We check API key and UserToken in database
            if ( $key != null && in_array($key, $valid_keys) ) {
                return $next($request);
            } else {
                return response()->json([
                    'results' => 'PERMISSIONS_NOT_GRANTED'
                ]);
            }
            */
        }
        return sendError("Authorization failed");

    }
}
