<?php

namespace App\Http\Middleware;

use Closure;
use DB;
use curlHandler;
use steelAuth;
use session;

class ApiToken
{
    
    public function isUAfound($string, $owned_urls)
    {
        foreach ($owned_urls as $url) {
            //if (strstr($string, $url)) { // mine version
            if (stripos($string, $url) !== FALSE) { // Yoshi version
                //echo "Match found"; 
                return true;
            }
        }
        //echo "Not found!";
        return false;
    }    
    
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //START
            //insert a row for this api call        
            $cookievalue = '';
            
            if( count($_COOKIE) > 0 ){
                $cookievalue = json_encode($_COOKIE);
            }
            
            if(empty($_SERVER['HTTP_USER_AGENT'])){
                $ua = '';
                $ua = json_encode($request -> all());
            }else
                $ua = $_SERVER['HTTP_USER_AGENT'];
            
            if(empty($_SERVER['REMOTE_ADDR']))
                $ra = '';
            else
                $ra = $_SERVER['REMOTE_ADDR'];


        if( $request->has("resourceType") )
            $data['resourceType'] = $request->input("resourceType");
        
        if(  $request->has("accessToken") )    
            $data['accessToken'] = $request->input("accessToken");
            
        if( $request->has("memId") ){    
            $data['memId'] = $request->input("memId");
            $m = $request->input("memId");
        }    
        else
            $m = 0;

        if( $request->has("memid") ){    
            $data['memId'] = $request->input("memid");
            $m = $request->input("memid");
        }    
        else
            $m = 0;


//print_r($request->all());
    if ($m == 102020) {
        $_data = array(
    			'memid' => $m,
    			'f_url' => request()->fullUrl(),
    			'f_date' =>date("Y-m-d"),
    			'f_time' => date("H:i:s"),
    			'isNewWebsite' => 'Y',
    			"ipaddress" => $ra,
    			"f_useragent" => $ua,
    			"cookie_value" => $cookievalue,
    			"f_source" => "api/app/Http/Middleware/ApiToken.php",
    		    'server_variable' => base64_encode(serialize($_SERVER)),
    		    'request_variable' => json_encode($request -> all())
    			);
    	
    	DB::table('tbl_urls_visited_count')
    		->insertGetId($_data);         
    }
    			
//--------------------START--------------------
//insert in questDB
/*
			    include_once "/home/steelmin/public_html/questdb.php";
			    $arrQryParams = array(				
					'memid' => $m,
    				'f_url' => request()->fullUrl(),
    				'f_date' =>date("Y-m-d"),
    				'f_time' => date("H:i:s"),
    				'isNewWebsite' => 'Y',
    				"ipaddress" => $ra,
    				"f_useragent" => $ua,
    				"cookie_value" => $cookievalue,
    				"f_source" => "api/app/Http/Middleware/ApiToken.php"    				
					);
			    execQryForAnAction($arrQryParams, "insert", "tbl_urls_visited_count");
*/			    
//insert in questDB
//--------------------STOP--------------------        
        //echo json_encode($request);
        
        if ($m == 102020) {
            return response()->json([
                'status' => [
                    "code" => 2001,
                    'message' => "You are blocked!"
                ]
            ], 400);
        } elseif (empty($data['resourceType'])) {
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::accessTokenWasExpiredOrInvalidCode,
                    'message' => \App\RestApiResponseCodes::accessResourceTypeRequiredMsg
                ]
            ], 400);
        } else if (!empty($data['resourceType']) && empty($data['accessToken']) && empty($data['memId'])) {
           /* return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::accessTokenWasExpiredOrInvalidCode,
                    'message' => \App\RestApiResponseCodes::accessTokenWasExpiredOrInvalidMsg
                ]
            ], 400);*/
        } else if (!empty($data['resourceType']) && !in_array($data['resourceType'], ['app', 'web'])) {
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::accessTokenWasExpiredOrInvalidCode,
                    'message' => \App\RestApiResponseCodes::accessResourceTypeInvalidMsg
                ]
            ], 400);
        } else if (!empty($data['resourceType']) && $data['resourceType'] == 'app' && isset($data['memId'])) {
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::InvalidInputsCode,
                    'message' => "You cannot use both app resource and memId"
                ]
            ], 400);
        } else if (!empty($data['resourceType']) && $data['resourceType'] == 'web' && isset($data['accessToken'])) {
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::InvalidInputsCode,
                    'message' => "You cannot use both web resource and accessToken"
                ]
            ], 400);
        } else if (!empty($data['accessToken']) && !empty($data['memId'])) {
            $hasToken = \App\Token::select('*')->where('token', $data['accessToken'])->where('id', $data['memId'])->first();
            if (empty($hasToken)) {
                return \App\Helper::invalidAuthentication();
            }
        } else if (empty($data['accessToken']) || !empty($data['memId'])) {
            $hasToken = \App\Members::select('id')->where('id', $data['memId'])->first(); 
            if (empty($hasToken)) {
                return \App\Helper::invalidAuthentication();
            }
        } else if (!empty($data['accessToken']) || empty($data['memId'])) { 
            $hasToken = \App\Token::select('*')->where('token', $data['accessToken'])->first();
            if (empty($hasToken)) {
                return \App\Helper::invalidAuthentication();
            }
        } else if (empty($data['accessToken']) || empty($data['memId'])) {
            
            return \App\Helper::invalidAuthentication();
        }
        session()->put(['resourceType' => $data['resourceType'], 'memId' => $hasToken->id, 'token' => $hasToken->token]);
        
        
        return $next($request);
    }
}
