<?php

namespace App\Http\Middleware;

use App\Models\UserAccess\UserAccess;
use App\Models\UserAccess\UserAccessOrganization;
use App\User;
use Auth;
use Closure;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;


class UserAccessCheck
{
    public function handle($request, Closure $next)
    {
			$ip = ip2long($request->ip());
			$time_now= time();
			$referer = "";
			//------------ Visitor Ip Insert ---------------------	
			  if (strpos($_SERVER['REQUEST_URI'], "/Image/") === false && strpos($_SERVER['REQUEST_URI'], "/get_issues_with_ajax") === false){
			  DB::select("INSERT INTO visitor_ip_address (ip_address,visitor_agent,visitor_count, created_on,updated_on) VALUES ('".$ip."','',1,".$time_now.",".$time_now.")
			    ON DUPLICATE KEY UPDATE visitor_count=visitor_count + 1, updated_on=".$time_now."");   
			
				DB::select("INSERT INTO visitor_ip_address_detail (ip_address,visitor_url,visitor_count, created_on,updated_on) VALUES ('".$ip."','".addslashes($_SERVER['REQUEST_URI'])."',1,".$time_now.",".$time_now.")
			    ");
			  }
			//-------------End Visitor----------------------------
		
        /* if(Auth::user() && !empty(Auth::user()->referral_login) && time() > Auth::user()->referral_login)
        {
            Auth::logout();
            session()->forget('referral_base_access');
            session()->forget('user_id');
            session()->forget('ip_base_access');
            session()->forget('user_base_access');
            session()->forget('access_org_name');
            session()->forget('access_user_data');
        }
        else
        {   
            header('Access-Control-Allow-Origin: *');
            header('Access-Control-Allow-Headers: Content-Type, x-csrf-token, x-xsrf-token');

            $referer = request()->headers->get('referer');
            //dd(hash('sha256', $referer));
			if(!empty($referer))
            {
            $users = User::GetUserReferral(hash('sha256', $referer));
            //dd($users);
				if(isset($users) && !empty($users->referral_url))
				{
					Auth::loginUsingId($users->id);
					session(['referral_base_access' => true]);
					$update_user['referral_login'] = strtotime('+24 hours');
					User::UpdateUser($users->id, $update_user);
				}
			}
        } */

        $access_data = UserAccess::CheckUserAccessByIP($ip);
			if(session()->has('openathens'))
			{
				
				$openathens = session()->get('openathens');
				
				$oauser  = User::where('openathensrealmName',$openathens['openathensrealmName'])
				->where('openathensderivedEduPersonScope', 'like', '%' . $openathens['openathensderivedEduPersonScope'] . '%');
				if(isset($openathens['openathenseduPersonScopedAffiliation'] )){
					$oauser = $oauser->orWhere('openathensderivedEduPersonScope', 'like', '%' . $openathens['openathenseduPersonScopedAffiliation'] . '%');
				}
				$oauser = $oauser->first();
				
				if($oauser){
					
					$param['access_org_id'] = $oauser->access_organization_id;
					$org_data               = UserAccessOrganization::GetActiveOrganizationDetails($param);
										
					if (isset($org_data[0]) && !empty($org_data[0]))
					{
						session(['access_org_name' => $org_data[0]->organization_name]);
					}
					session(['user_id' => $oauser->id]);
					$access_data[0] = UserAccess::GetUserAccessInfo(array('user_id'=>$oauser->id));
					if (isset($access_data[0])){
						for($a=0; $a<count($access_data); $a++)
						{
							if($access_data[$a]->access_type_on == "disease")
							{
								session(['disease_access' => true]);
							}
						} 
					}
					
					/*if($access_data[0]->access_base_type==0){
						session(['user_base_access' => true]);
						if ($user = Auth::user()) { 
						}else{
							Auth::loginUsingId($oauser->id);
							$user = Auth::user();
						}
						//session()->forget('openathens');
						
					}else{*/
						session(['ip_base_access' => true]);
					//}
					$spdata['entity_id'] = $openathens['openathensrealmName'];
					$spdata['scope'] = $openathens['openathensderivedEduPersonScope'];
					if(isset($openathens['openathenseduPersonScopedAffiliation'] )){
						$spdata['eduPersonScopedAffiliation'] = $openathens['openathenseduPersonScopedAffiliation'];
					}
					$spdata['ip_address'] = $ip;
					$spdata['lastupdated'] = time();					
					DB::table('tbl_openathens_logins')->insertGetId($spdata);
					
					session(['access_user_data' => $access_data]);
					//dd(session()->all());
					return $next($request);
							
				}else{
					
					$spdata['entity_id'] = $openathens['openathensrealmName'];
					$spdata['scope'] = $openathens['openathensderivedEduPersonScope'];
					if(isset($openathens['openathenseduPersonScopedAffiliation'] )){
						$spdata['eduPersonScopedAffiliation'] = $openathens['openathenseduPersonScopedAffiliation'];
					}
					$spdata['ip_address'] = $ip;
					$spdata['lastupdated'] = time();					
					DB::table('tbl_openathens_logins')->insertGetId($spdata);
					
					return redirect('/login')->with('message', 'You do not have sufficient access Or not registered with us');
				}
			}elseif (empty($access_data)) { //User base

				if ($user = Auth::user()) {                

					session(['user_id' => $user->id]);
					$access_data            = UserAccess::CheckUserAccessByUser($user->id);

					if($access_data){
						//--------Check if have disease base access-----------
						for($a=0; $a<count($access_data); $a++)
						{
							if($access_data[$a]->access_type_on == "disease")
							{
								session(['disease_access' => true]);
							}
						} 
						//-----------------------------
						$param['access_org_id'] = $user->access_organization_id;
						$org_data               = UserAccessOrganization::GetActiveOrganizationDetails($param);
						
						session(['user_base_access' => true]);
						if (isset($org_data[0]) && !empty($org_data[0]))
						{
							session(['access_org_name' => $org_data[0]->organization_name]);	
						}
						
						session(['access_user_data' => $access_data]);
					}
					
					return $next($request);

				}			
				else 
				{
					
					session()->forget('user_id');
					session()->forget('ip_base_access');
					session()->forget('user_base_access');
					session()->forget('access_org_name');
					session()->forget('access_user_data');
					return $next($request);
				}
			   

				return $next($request);

        
			} else {       //IP base     

					for($a=0; $a<count($access_data); $a++)
					{
						if($access_data[$a]->access_type_on == "disease")
						{
							session(['disease_access' => true]);
						}
					} 
					$user    = User::find($access_data[0]->user_id);            
					
					$param['access_org_id'] = $user->access_organization_id;
					$org_data               = UserAccessOrganization::GetActiveOrganizationDetails($param);
					
					session(['ip_base_access' => true]);
					
					if (isset($org_data[0]) && !empty($org_data[0]))
					{
						session(['access_org_name' => $org_data[0]->organization_name]);
					}
					session(['user_id' => $user->id]);
					session(['display_name' => $user->display_name]);
					session(['pic' => $user->pic]);
					if ($user = Auth::user())
					{                
						session(['user_id' => $user->id]);
						
						$user_base_access_data = UserAccess::CheckUserAccessByUser($user->id);
						
						if($user_base_access_data)
						{
						   
							$access_data = array_merge($access_data,$user_base_access_data);
							//--------Check if have disease base access-----------

						}
						
					}
					session(['access_user_data' => $access_data]);
				
				 return $next($request);
			}

    }
}
