<?php

namespace App\Http\Controllers\Auth;

use DB;

/**
 * Class to handle internel authentication related function 
 * Used by UserController, ActionController, TokenController
 * 
 * @version	0.1
 * @author varun palekar
 * @github varunpalekar
 *
 */
class authentication
{

	public function authToken_tarun($token, $appType='SM')
	{
	    echo "test";
	    //DB::enableQueryLog(); 
		$user_id = (array)DB::table($_ENV['TOKEN_TABLE'])
							->where($_ENV['TOKEN_COLUMN'] ,$token)
							->where("appType" , "=" , $appType )
							->get();
					//dd(DB::getQueryLog());		
print_r ($user_id);
		if (count($user_id) == 0 )
			return 0;
		elseif (count($user_id) == 1)
		{
           // print_r($user_id);
           // echo $_ENV['USER_ID'];die;
			return $user_id[0][$_ENV['USER_ID']] ;
		}
		else {
			return 0;
		}
		/* if (count($user_id) == 0 )
			abort(403, 'Unauthorized action. Token access denied');
		elseif (count($user_id) == 1)
		{
           // print_r($user_id);
           // echo $_ENV['USER_ID'];die;
			return $user_id[0][$_ENV['USER_ID']] ;
		}
		else {
			abort(403, 'Unauthorized action. Token access denied');
		} */
	}

	
	public function authToken($token, $appType='SM')
	{
		if($token=='do_not_change_price_only' || $token=='do_not_change_professional')
			$appType='SM';
		$user_id = (array)DB::table($_ENV['TOKEN_TABLE'])
							->where($_ENV['TOKEN_COLUMN'] ,$token)
							->where("appType" , "=" , $appType )
							->get();
//print_r ($user_id);
		if (count($user_id) == 0 )
			return 0;
		elseif (count($user_id) == 1)
		{
           // print_r($user_id);
           // echo $_ENV['USER_ID'];die;
			return $user_id[0][$_ENV['USER_ID']] ;
		}
		else {
			return 0;
		}
		/* if (count($user_id) == 0 )
			abort(403, 'Unauthorized action. Token access denied');
		elseif (count($user_id) == 1)
		{
           // print_r($user_id);
           // echo $_ENV['USER_ID'];die;
			return $user_id[0][$_ENV['USER_ID']] ;
		}
		else {
			abort(403, 'Unauthorized action. Token access denied');
		} */
	}
	
	public function authUserId($user_id)
	{
		$user_id = (array)DB::table($_ENV['USER_TABLE'])
							->where($_ENV['USER_ID'] ,$user_id)
							->get();

		if (count($user_id) == 0 )
			return 0;
		elseif (count($user_id) == 1)
		{
			/* DB::table('tbl_loggedin_users')
				->where("mem_id" , "=" , $user_id[0][$_ENV['USER_ID']] )
				->update(["log_time" => $GLOBALS['currDateTime'] ]) ;	 */		
          return $user_id[0][$_ENV['USER_ID']] ;
		}
		else {
			return 0;
		}	
	}

	public function authRefreshToken($refresh_token, $appType='SM')
	{
		$user = DB::table($_ENV['REFRESH_TOKEN_TABLE'])
							->select($_ENV['USER_ID'])
							->where("appType" , "=" , $appType )
							->where($_ENV['REFRESH_TOKEN_COLUMN'] ,$refresh_token)
							->get();

		if (count($user) == 0 )
			return false;
		elseif (count($user) == 1)
		{
			return $user[0][$_ENV['USER_ID']] ;
		}
		else {
			// log multiple entries, report 
			abort(404, "refresh token authentication error");
		}
	}

	#------------------------------------------

	public function userLogout($user_id, $appType='SM')
	{
		$result = DB::table($_ENV['REFRESH_TOKEN_TABLE'])
			->select($_ENV['USER_ID'] )
			->where($_ENV['USER_ID'], '=', $user_id )
			->where('appType', '=', $appType )
			->get();

		if (count($result) == 0 )
		{
			return false;
		}

		DB::table($_ENV['REFRESH_TOKEN_TABLE'])
			->where($_ENV['USER_ID'], '=', $user_id )
			->where('appType', '=', $appType )
			->delete();

		DB::table($_ENV['TOKEN_TABLE'])
			->where($_ENV['USER_ID'], '=', $user_id )
			->where('appType', '=', $appType ) 
			->delete();
		return true;
	}

	public function userLogout_user_pass($username, $password)
	{
		$result = DB::table($_ENV['USER_TABLE'])
							->select($_ENV['USER_ID'] , $_ENV['VERIFIED_COLUMN'] )
							->where($_ENV['USERNAME'] ,$username)
							->where($_ENV['PASSWORD'] ,$password)
							->get();
		if (count($result) == 0 )
		{
			$result = DB::table($_ENV['USER_TABLE'])
				->select('email' , $_ENV['VERIFIED_COLUMN'], $_ENV['USER_ID'] )
				->where('email' ,$username)
				->where($_ENV['PASSWORD'] ,$password)
				->get();
			if (count($result) == 0 )
				return false;
		}

		if (count($result) == 1)
		{
			$user_id = $result[0][$_ENV['USER_ID']] ;
			$this->userLogout($user_id);
			return true;
		}
		return false;	
	}
	
	#------------------------------------------
	public function generateRefreshTokenV2019ByOTP($resourceType, $username, $OTP, $isdCode, $deviceID,  $_REQUESTARR=array(), $remember=0, $appType='SM')
	{
		///$this->userLogout_user_pass($username, $password);
		# Get result
		//DB::enableQueryLog(); 
		/* $result = DB::table($_ENV['USER_TABLE'])
							->select($_ENV['USER_ID'] , $_ENV['VERIFIED_COLUMN'], 'id' )
							->where($_ENV['USERNAME'] ,$username)
							->where($_ENV['PASSWORD'] ,$password)
							->get(); */
		//$isdCode.
		//DB::enableQueryLog(); 

		$result = DB::table('tbl_loggin_by_otp')
				->select('id' )				
				->where('emailOrPhone' ,$username)
				->where('otp' , $OTP)
				->where('deviceID' ,$deviceID)
				//->where('memid' ,$memid)
				->first();
			//dd(DB::getQueryLog());	
		//print_r($result);
		if (count($result) == 0 )
		{
			return false;
		}
	
		if (count($result) == 1)
		{
		    $result = DB::table($_ENV['USER_TABLE'])
				->select('email' , $_ENV['VERIFIED_COLUMN'], $_ENV['USER_ID'], 'id', 'status','name', 'billing_name','session', 'logstatus','ipaddress', 'company', 'city', 'state', 'country', 'on_verify_link', 'username', 'password' )
				->where(function($q) use ($username) {
							$q->where('email' ,$username)
							->orWhere('phoneno' ,$username)
							->orWhere('alternate_mob_no' ,$username)
							->orWhere('addtnl_email' ,$username);
							//->where($_ENV['VERIFIED_COLUMN'] ,1);
						})
				//->where($_ENV['PASSWORD'] ,$password)
				->get();
				///print_r($result);
			if (count($result) == 0 )
				return "USER_NOT_EXIST";
				//return false;
			
			///if ($result[0][$_ENV['VERIFIED_COLUMN']])
			if (1)
			{
				$user_id = $result[0][$_ENV['USER_ID']] ;
				$ip =  $_SERVER['REMOTE_ADDR'] ; 				
				$username = $result[0]['username'];	
				/* $password = $result[0]['password'];	
				if($resourceType=='app')
					$this->userLogout_user_pass($username, $password); */
				if($resourceType=='app')
					$this->userLogout($user_id, $appType);
				
				if ($result[0][$_ENV['VERIFIED_COLUMN']]==0 && strpos($username, "@") !== false){
					////$data['is_mobile_verified'] = 1;
					$data['verified'] = 1;
					DB::table('tbl_members')
						->where('id', $user_id)
						->update($data);
				}
								
				if($resourceType=='web'){
					
					$suffix='';
					$arrWhitelistedEmails = array("dipen@steelmint.com", "sumit@steelmint.com", "dhruv@steelmin11t.com", "rohan@steelmint.com",'aditi.tiwari@steelmintgroup.com', 'reena@steelmint.com', 'pushpaktantia@steelmintgroup.com','abhishek.bhalla@steelmint.com');
		
					$arrWhitelistedIPs = array("182.73.37.246", "122.163.40.83", "103.46.241.130", "122.176.64.108", "182.71.107.226", '121.46.94.60', '122.160.113.195', '103.242.186.14'); //121.46.94.60 => kedar
					$exIp = explode(".", $ip);
					$finalIp = $exIp[0] . "." . $exIp[1] . ".";
					if	( 
							!in_array($username, $arrWhitelistedEmails)
							&& (strpos($username, "steelmint.com") !== false || strpos($username, "steel-360.com") !== false || strpos($username, "steelmintgroup.com") !== false || strpos($username, "plantbee.com") !== false || strpos($username, "coalmint.com") !== false)
							&& !in_array($ip, $arrWhitelistedIPs)
							&& !in_array($finalIp, $arrWhitelistedIPs)
						)
					{//chekc if its steelmint user and accessing from office of outside office
						//return 'falseIPBL';//steelmintgroup emails, excepts mentioned in $arrWhitelistedEmails, must be 
					}
					///check any active service
					$res = DB::table('tbl_updated_reg_logs_bm')
							->select('id')
							->where('memid', '=', $user_id )
							->where('status', '=', 'Active' )
							->whereIn('services', array('W','E','S','MA') )
							->orderBy('id' , 'desc')
							->first();
					if (count($res) == 0 ) {
						// Multiple login requests
						//return 'NA'; 
						$res1 = DB::table('tbl_reg_logs')
								->select('subrm')
								->where('memid', '=', $user_id )
								->whereIn('f_product', array('W','E','S','MA') )
								->orderBy('id' , 'desc')
								->first();
						if (count($res1) > 0 ) {
							// Multiple login requests
							$subrm = $res1['subrm'];
							$res11 = DB::table('tbl_rel_manager')
								->select('rel_manager')
								->where('id', '=', $subrm )
								->first();
							$rel_manager = $res11['rel_manager'];	
							//$rel_manager = 'mohan@theitbooth.com';	
							
							DB::table('tbl_expired_user_login_try')->insert([ 'memid' => $user_id,
								'RM' => $rel_manager,
								'created_on' => $GLOBALS['currDateTime']]); 
							
							//require_once("/home/steelmin/public_html/mf.php");
							//sendNoActiveWebLogMailToAdmin($username, $result[0]['name'], $user_id, $result[0]['company'], $rel_manager, $GLOBALS['currDateTime'], $result[0]['city'], $result[0]['state'], $result[0]['country'],$company_name='SteelMint');
						}
						$suffix = 'NA'; 
					}
					
					//if(!isset($_COOKIE['uid'])){
					if(1){
						//commented by tarun on 2020-05-26
						/* $res12 = DB::table('tb1_online_member')
								->select('device')
								->where('mem_id', '=', $user_id )
								->where('status', '=', 'on' )
								->first(); */
						$rel_manager = $res11['rel_manager'];
						$tm = REALTIME;
						$company='SteelMint';
						$b_url  = isset($_REQUESTARR['b_url'])?$_REQUESTARR['b_url']:'';
						$browser = get_browser(null, true);
						$_sender = $browser['parent'];
						$platform = $browser['device_type'];
						$device = $browser['platform'];
						$_sender_agent = $browser['browser_name_pattern'];
					
						$parent_loggedin_id=0;
						$_REQUESTARR['sender'] = isset($_REQUESTARR['sender'])?$_REQUESTARR['sender']:'';
						$_REQUESTARR['tokinx'] = isset($_REQUESTARR['tokinx'])?$_REQUESTARR['tokinx']:'';					
						$_REQUESTARR['parent'] = isset($_REQUESTARR['parent'])?$_REQUESTARR['parent']:'';					
						
						require_once("/home/steelmin/public_html/hf.php");
						$ip_country = ipTocntry("$ip");
							
						//if(count($res12) > 0 && $user_id != 2 ){
						if(0 ){
							///$devices = explode(',', $res12['device']);
							//$first_device = $devices[0];
							
							$_REQUESTARR['sender'] .=  '(' . $_SERVER['REMOTE_ADDR'] . ')';
							
							$userSysDtls = $_REQUESTARR['sender'] . '|' . $_REQUESTARR['tokinx'] . '|' . date('Y-m-d H:i');
							//commented by tarun on 2020-05-26
							/* DB::table('tb1_online_member')
								->where("mem_id" , "=" , $user_id )
								->update(["device" => $userSysDtls ]) ; */
							
							
							$res13 = DB::table('tb1_online_member_loggin_try')
								->select('id')
								->where('mem_id', '=', $user_id )
								->where('parent_loggedin_id', '=', 'id' )
								->orderBy('id' , 'desc')
								->first();
							if(count($res13) > 0)
								$parent_loggedin_id = $res13['id'];
							
									if( $_REQUESTARR['tokinx'] = '' )
    								    $_REQUESTARR['tokinx'] = '';
    								if( $_REQUESTARR['parent'] = '' )
    								    $_REQUESTARR['parent'] = '';
    								if( $_sender_agent = '' )
    								    $_sender_agent = '';
    								if( $device = '' )
    								    $device = '';
    								if( $platform = '' )
    								    $platform = '';
    								if( $b_url = '' )
    								    $b_url = '';							
							//DB::enableQueryLog(); 
							DB::table('tb1_online_member_loggin_try')
								->insert([ 'mem_id' => $user_id,
								'log_date' => $GLOBALS['currDate'],
								'ip_country' => $ip_country,
								'ip_address' => $ip,
								'parent_loggedin_id' => $parent_loggedin_id,
								'lan_ip' => $_REQUESTARR['tokinx'],
								'device_id' => $_REQUESTARR['parent'],
								'device' => $_sender_agent,
								'device_name' => $device,
								'company' => $company,
								'platform' => $platform,
								'url' => $b_url,
								'log_time' => $GLOBALS['currDateTime']]);
								calculate_coc($user_id); 
							//dd(DB::getQueryLog());
							return "falseAccess"; 	
						}else{///
							
							$userSysDtls = $_REQUESTARR['sender'] . '|' . $_REQUESTARR['tokinx'] . '|' . date('Y-m-d H:i');
							//commented by tarun on 2020-05-26
							/* DB::table('tb1_online_member')
								->insert([ 'mem_id' => $user_id,
								'log_time' => $GLOBALS['currDateTime'],
								'ip_address' => $ip,
								'status' => 'on',
								'remember_me' => $remember==1?'Y':'N',
								'device' => $userSysDtls]); */ 
									if( $_REQUESTARR['tokinx'] = '' )
    								    $_REQUESTARR['tokinx'] = '';
    								if( $_REQUESTARR['parent'] = '' )
    								    $_REQUESTARR['parent'] = '';
    								if( $_sender_agent = '' )
    								    $_sender_agent = '';
    								if( $device = '' )
    								    $device = '';
    								if( $platform = '' )
    								    $platform = '';
    								if( $b_url = '' )
    								    $b_url = '';							
								
							DB::table('tb1_online_member_loggin_try')
								->insert([ 'mem_id' => $user_id,
								'log_date' => $GLOBALS['currDate'],
								'ip_country' => $ip_country,
								'ip_address' => $ip,
								'parent_loggedin_id' => $parent_loggedin_id,
								'lan_ip' => $_REQUESTARR['tokinx'],
								'device_id' => $_REQUESTARR['parent'],
								'device' => $_sender_agent,
								'device_name' => $device,
								'company' => $company,
								'platform' => $platform,
								'url' => $b_url,
								'log_time' => $GLOBALS['currDateTime']]);
								calculate_coc($user_id); 
						}
						
						$currDateTime = $GLOBALS['currDateTime'];
						$sesidcookie = base64_encode($ip.$username); 
						$cookiename = 'logdetails'; 
						$cookie_user_name = 'Patron';
						if(trim($result[0]['billing_name'])!='')
							$cookie_user_name = trim($result[0]['billing_name']);
						elseif(trim($result[0]['name'])!='')
							$cookie_user_name = trim($result[0]['name']);
						
						if($remember == 1)
						{
							$datetim = strtotime($currDateTime . "+100 days");
							 setcookie($cookiename, $sesidcookie, time()+60*60*24*100, '/', '.bigmint.co', 'true');
							 setcookie("userName",$username, time()+60*60*24*100, '/', '.bigmint.co', 'true');
							 setcookie("billing_name",$cookie_user_name, time()+60*60*24*100, '/', '.bigmint.co', 'true');
							 //setcookie("billing_name",$result[0]['name'], time()+60*60*24*100, '/');
							 setcookie("uid",$user_id, time()+60*60*24*100, '/', '.bigmint.co', 'true');
							 setcookie("testCookieName","testCookieValue", time()+60*60*24*100, '/', '.bigmint.co', 'true');
						}
						else
						{
							$datetim = strtotime($currDateTime . "+8 hours");
							 setcookie($cookiename, $sesidcookie, time()+60*60*18, '/', '.bigmint.co', 'true');
							 setcookie("userName",$username, time()+60*60*18, '/', '.bigmint.co', 'true');
							 //setcookie("billing_name",$result[0]['name'], time()+60*60*18, '/');
							 setcookie("billing_name",$cookie_user_name, time()+60*60*18, '/', '.bigmint.co', 'true');
							 setcookie("uid",$user_id, time()+60*60*18, '/', '.bigmint.co', 'true');
							 setcookie("testCookieName","testCookieValue", time()+60*60*24*100, '/', '.bigmint.co', 'true');
						}
						///setcookie("firsttimelogin",$user_id, time()+60*60*24*100, '/');
						
						$_val = 10;
						$res14 = DB::table('tbl_updated_reg_logs_bm')
								->select('id')
								->where('memid', '=', $user_id )
								->where('status', '=', 'Active' )
								->orderBy('id' , 'desc')
								->first();
											
						$res_w = mysql_fetch_array($r11);	
						if( count($res14) > 0){
							$_val = 15;
						}
						
						$on_verify_link=$result[0]['on_verify_link'];
						if($on_verify_link == 1){
							$on_verify_link = 2;
						}
						DB::table('tbl_members')
								->where("id" , "=" , $user_id )
								->update(
									["logstatus" => 'Active', 
									'session' => $sesidcookie, 
									'logtime' => $datetim, 
									'activity_meter' => DB::raw('activity_meter + '.$_val), 
									'on_verify_link'=> $on_verify_link]
								) ;
						
						$_resultArr['uid'] = $user_id;
						$_resultArr['mid'] = $user_id;
						$_resultArr['uname'] = $username;
						$_resultArr['name'] = $result[0]['name'];
						
						return $_resultArr;		
					}else{
						return 'trueAL';
					}
					
				}//end web logic
				
                //start app logic
				/*                 
                                // Check if already loggedin user
                                $res = DB::table($_ENV['REFRESH_TOKEN_TABLE'])
                                            ->select('id')
                                            ->where($_ENV['USER_ID'], '=', $user_id )
                                            ->get();
                                if (count($res) >= 1 ) {
                                    // Multiple login requests
                                    return 'MLR'; 
                                } */
                                
				//Delete old token if exists
				DB::table($_ENV['REFRESH_TOKEN_TABLE'])
						->where($_ENV['USER_ID'], '=', $user_id )
						->where("appType" , "=" , $appType )
						->delete();
				
				$gcm_device_table = $appType=="CM"?"gcm_device_cm":"gcm_device";
				//Remove User Id from gcm_device table
				DB::table($gcm_device_table)
                        ->where("user_id" , "=" , $user_id )
                        ->update(["user_id" => 0 ]) ;
				
				// Create new token
				$rand = str_random($_ENV['REFRESH_TOKEN_LENGTH']) ;
				
				//////////////	for history ///////////////////		
				$physical_id = isset($_REQUESTARR['deviceID'])?$_REQUESTARR['deviceID']:'';
				$fcm_token = isset($_REQUESTARR['fcmToken'])?$_REQUESTARR['fcmToken']:'';
				$device_name = isset($_REQUESTARR['device_name'])?$_REQUESTARR['device_name']:'';
				
				$userSysDtls = $fcm_token . '|' . $rand;
				$loggin_try['mem_id'] = $user_id ;
				$loggin_try['log_time'] = $GLOBALS['currDateTime']; 
				$loggin_try['log_date'] = date("Y-m-d"); 
				$loggin_try['ip_address'] = $_SERVER['REMOTE_ADDR']; 
				
				$loggin_try['device'] = $userSysDtls;
				//$loggin_try['device_name'] = $device_type;
				$loggin_try['device_name'] = $device_name;	
				if($physical_id!=''){
					$loggin_try['company'] = ($appType == 'CM')?'CoalMint':'SteelMint';
					$loggin_try['device_id'] = $physical_id;					
					//$loggin_try['device_name'] = 'android';
				}else{
					//$loggin_try['device_name'] = 'IOS';
					//$loggin_try['device_id'] = $fcm_token;
					if($appType == 'CM'){
						$loggin_try['company'] = 'CoalMint';
					}else
						$loggin_try['company'] = 'SteelMint';
				}

				require_once("/home/steelmin/public_html/hf.php");
				$loggin_try['ip_country'] = ipTocntry("$ip");			
				//print_r($loggin_try);
				$creden = DB::table('tb1_online_member_loggin_try')
									->select(array('id'))
									->where('mem_id', '=', $user_id )
									->whereIn('device_name', array('android','IOS') )
									->where('company', '=', $loggin_try['company'] )
									->first();
				
				$online_member_loggin_iid = (isset($creden['id']))?$creden['id']:0;
				$loggin_try['parent_loggedin_id'] = $online_member_loggin_iid; 
				
				$loggin_try['platform'] = "Mobile APP";
				$loggin_try['url'] = "public/user/refresh_token : refreshToken - method";
				
				DB::table('tb1_online_member_loggin_try')
						->insert($loggin_try);
						
				if($online_member_loggin_iid==0){
					$last_id = DB::getPdo()->lastInsertId();;
					DB::table('tb1_online_member_loggin_try')
						->where('id', '=', $last_id )
						->update( [ 'parent_loggedin_id' => $last_id]);
					//echo 'get id:'.dd($last_id);
				}
				/////
				calculate_coc($user_id);
				if (DB::table($_ENV['REFRESH_TOKEN_TABLE'])
							->insert( [  $_ENV['USER_ID']=> $result[0][$_ENV['USER_ID']] , $_ENV['REFRESH_TOKEN_COLUMN'] => $rand, 'appType' => $appType ]))
					return $rand ;
				else 
				{
					// Log database entry error
					return false;
				}
			}
			else
			{
				// log user not verified
				file_get_contents("https://www.steelmint.com/registrationAJAX.php?id=" . $result[0]['id'] . "&src=fromAuthentication.php&username=" . $username);		
				//falseNV
 				return 'NV';
			}
			
		}
		else {
			// Log duplication entry found may be issue with generator
			return false;
		}
	}
	public function generateRefreshTokenV2022ByOTP($resourceType, $username, $OTP, $isdCode, $deviceID,  $_REQUESTARR=array(), $remember=0, $appType='SM')
	{
		///$this->userLogout_user_pass($username, $password);
		# Get result
		//DB::enableQueryLog(); 
		/* $result = DB::table($_ENV['USER_TABLE'])
							->select($_ENV['USER_ID'] , $_ENV['VERIFIED_COLUMN'], 'id' )
							->where($_ENV['USERNAME'] ,$username)
							->where($_ENV['PASSWORD'] ,$password)
							->get(); */
		//$isdCode.
		//DB::enableQueryLog(); 

		// $result = DB::table('tbl_loggin_by_otp')
				// ->select('id' )				
				// ->where('emailOrPhone' ,$username)
				// ->where('otp' , $OTP)
				// ->where('deviceID' ,$deviceID)
				// //->where('memid' ,$memid)
				// ->first();
			// //dd(DB::getQueryLog());	
		// //print_r($result);
		// if (count($result) == 0 )
		// {
			// return false;
		// }
	
		if (1)
		{
		    $result = DB::table($_ENV['USER_TABLE'])
				->select('email' , $_ENV['VERIFIED_COLUMN'], $_ENV['USER_ID'], 'id', 'status','name', 'billing_name','session', 'logstatus','ipaddress', 'company', 'city', 'state', 'country', 'on_verify_link', 'username', 'password' )
				->where(function($q) use ($username) {
							$q->where('email' ,$username)
							->orWhere('phoneno' ,$username)
							->orWhere('alternate_mob_no' ,$username)
							->orWhere('addtnl_email' ,$username);
							//->where($_ENV['VERIFIED_COLUMN'] ,1);
						})
				//->where($_ENV['PASSWORD'] ,$password)
				->get();
				///print_r($result);
			if (count($result) == 0 )
				return "USER_NOT_EXIST";
				//return false;
			
			///if ($result[0][$_ENV['VERIFIED_COLUMN']])
			if (1)
			{
				$user_id = $result[0][$_ENV['USER_ID']] ;
				$ip =  $_SERVER['REMOTE_ADDR'] ; 				
				$username = $result[0]['username'];	
				/* $password = $result[0]['password'];	
				if($resourceType=='app')
					$this->userLogout_user_pass($username, $password); */
				if($resourceType=='app')
					$this->userLogout($user_id, $appType);
				
				if ($result[0][$_ENV['VERIFIED_COLUMN']]==0 && strpos($username, "@") !== false){
					////$data['is_mobile_verified'] = 1;
					$data['verified'] = 1;
					DB::table('tbl_members')
						->where('id', $user_id)
						->update($data);
				}
								
				if($resourceType=='web'){
					
					$suffix='';
					$arrWhitelistedEmails = array("dipen@steelmint.com", "sumit@steelmint.com", "dhruv@steelmin11t.com", "rohan@steelmint.com",'aditi.tiwari@steelmintgroup.com', 'reena@steelmint.com', 'pushpaktantia@steelmintgroup.com','abhishek.bhalla@steelmint.com');
		
					$arrWhitelistedIPs = array("182.73.37.246", "122.163.40.83", "103.46.241.130", "122.176.64.108", "182.71.107.226", '121.46.94.60', '122.160.113.195', '103.242.186.14'); //121.46.94.60 => kedar
					$exIp = explode(".", $ip);
					$finalIp = $exIp[0] . "." . $exIp[1] . ".";
					if	( 
							!in_array($username, $arrWhitelistedEmails)
							&& (strpos($username, "steelmint.com") !== false || strpos($username, "steel-360.com") !== false || strpos($username, "steelmintgroup.com") !== false || strpos($username, "plantbee.com") !== false || strpos($username, "coalmint.com") !== false)
							&& !in_array($ip, $arrWhitelistedIPs)
							&& !in_array($finalIp, $arrWhitelistedIPs)
						)
					{//chekc if its steelmint user and accessing from office of outside office
						//return 'falseIPBL';//steelmintgroup emails, excepts mentioned in $arrWhitelistedEmails, must be 
					}
					///check any active service
					$res = DB::table('tbl_updated_reg_logs_bm')
							->select('id')
							->where('memid', '=', $user_id )
							->where('status', '=', 'Active' )
							->whereIn('services', array('W','E','S','MA') )
							->orderBy('id' , 'desc')
							->first();
					if (count($res) == 0 ) {
						// Multiple login requests
						//return 'NA'; 
						$res1 = DB::table('tbl_reg_logs')
								->select('subrm')
								->where('memid', '=', $user_id )
								->whereIn('f_product', array('W','E','S','MA') )
								->orderBy('id' , 'desc')
								->first();
						if (count($res1) > 0 ) {
							// Multiple login requests
							$subrm = $res1['subrm'];
							$res11 = DB::table('tbl_rel_manager')
								->select('rel_manager')
								->where('id', '=', $subrm )
								->first();
							$rel_manager = $res11['rel_manager'];	
							//$rel_manager = 'mohan@theitbooth.com';	
							
							DB::table('tbl_expired_user_login_try')->insert([ 'memid' => $user_id,
								'RM' => $rel_manager,
								'created_on' => $GLOBALS['currDateTime']]); 
							
							//require_once("/home/steelmin/public_html/mf.php");
							//sendNoActiveWebLogMailToAdmin($username, $result[0]['name'], $user_id, $result[0]['company'], $rel_manager, $GLOBALS['currDateTime'], $result[0]['city'], $result[0]['state'], $result[0]['country'],$company_name='SteelMint');
						}
						$suffix = 'NA'; 
					}
					
					//if(!isset($_COOKIE['uid'])){
					if(1){
						//commented by tarun on 2020-05-26
						/* $res12 = DB::table('tb1_online_member')
								->select('device')
								->where('mem_id', '=', $user_id )
								->where('status', '=', 'on' )
								->first(); */
						$rel_manager = $res11['rel_manager'];
						$tm = REALTIME;
						$company='SteelMint';
						$b_url  = isset($_REQUESTARR['b_url'])?$_REQUESTARR['b_url']:'';
						$browser = get_browser(null, true);
						$_sender = $browser['parent'];
						$platform = $browser['device_type'];
						$device = $browser['platform'];
						$_sender_agent = $browser['browser_name_pattern'];
					
						$parent_loggedin_id=0;
						$_REQUESTARR['sender'] = isset($_REQUESTARR['sender'])?$_REQUESTARR['sender']:'';
						$_REQUESTARR['tokinx'] = isset($_REQUESTARR['tokinx'])?$_REQUESTARR['tokinx']:'';					
						$_REQUESTARR['parent'] = isset($_REQUESTARR['parent'])?$_REQUESTARR['parent']:'';					
						
						require_once("/home/steelmin/public_html/hf.php");
						$ip_country = ipTocntry("$ip");
							
						//if(count($res12) > 0 && $user_id != 2 ){
						if(0 ){
							///$devices = explode(',', $res12['device']);
							//$first_device = $devices[0];
							
							$_REQUESTARR['sender'] .=  '(' . $_SERVER['REMOTE_ADDR'] . ')';
							
							$userSysDtls = $_REQUESTARR['sender'] . '|' . $_REQUESTARR['tokinx'] . '|' . date('Y-m-d H:i');
							//commented by tarun on 2020-05-26
							/* DB::table('tb1_online_member')
								->where("mem_id" , "=" , $user_id )
								->update(["device" => $userSysDtls ]) ; */
							
							
							$res13 = DB::table('tb1_online_member_loggin_try')
								->select('id')
								->where('mem_id', '=', $user_id )
								->where('parent_loggedin_id', '=', 'id' )
								->orderBy('id' , 'desc')
								->first();
							if(count($res13) > 0)
								$parent_loggedin_id = $res13['id'];
							
									if( $_REQUESTARR['tokinx'] = '' )
    								    $_REQUESTARR['tokinx'] = '';
    								if( $_REQUESTARR['parent'] = '' )
    								    $_REQUESTARR['parent'] = '';
    								if( $_sender_agent = '' )
    								    $_sender_agent = '';
    								if( $device = '' )
    								    $device = '';
    								if( $platform = '' )
    								    $platform = '';
    								if( $b_url = '' )
    								    $b_url = '';							
							//DB::enableQueryLog(); 
							DB::table('tb1_online_member_loggin_try')
								->insert([ 'mem_id' => $user_id,
								'log_date' => $GLOBALS['currDate'],
								'ip_country' => $ip_country,
								'ip_address' => $ip,
								'parent_loggedin_id' => $parent_loggedin_id,
								'lan_ip' => $_REQUESTARR['tokinx'],
								'device_id' => $_REQUESTARR['parent'],
								'device' => $_sender_agent,
								'device_name' => $device,
								'company' => $company,
								'platform' => $platform,
								'url' => $b_url,
								'log_time' => $GLOBALS['currDateTime']]);
								calculate_coc($user_id); 
							//dd(DB::getQueryLog());
							return "falseAccess"; 	
						}else{///
							
							$userSysDtls = $_REQUESTARR['sender'] . '|' . $_REQUESTARR['tokinx'] . '|' . date('Y-m-d H:i');
							//commented by tarun on 2020-05-26
							/* DB::table('tb1_online_member')
								->insert([ 'mem_id' => $user_id,
								'log_time' => $GLOBALS['currDateTime'],
								'ip_address' => $ip,
								'status' => 'on',
								'remember_me' => $remember==1?'Y':'N',
								'device' => $userSysDtls]); */ 
									if( $_REQUESTARR['tokinx'] = '' )
    								    $_REQUESTARR['tokinx'] = '';
    								if( $_REQUESTARR['parent'] = '' )
    								    $_REQUESTARR['parent'] = '';
    								if( $_sender_agent = '' )
    								    $_sender_agent = '';
    								if( $device = '' )
    								    $device = '';
    								if( $platform = '' )
    								    $platform = '';
    								if( $b_url = '' )
    								    $b_url = '';							
								
							DB::table('tb1_online_member_loggin_try')
								->insert([ 'mem_id' => $user_id,
								'log_date' => $GLOBALS['currDate'],
								'ip_country' => $ip_country,
								'ip_address' => $ip,
								'parent_loggedin_id' => $parent_loggedin_id,
								'lan_ip' => $_REQUESTARR['tokinx'],
								'device_id' => $_REQUESTARR['parent'],
								'device' => $_sender_agent,
								'device_name' => $device,
								'company' => $company,
								'platform' => $platform,
								'url' => $b_url,
								'log_time' => $GLOBALS['currDateTime']]);
								calculate_coc($user_id); 
						}
						
						$currDateTime = $GLOBALS['currDateTime'];
						$sesidcookie = base64_encode($ip.$username); 
						$cookiename = 'logdetails'; 
						$cookie_user_name = 'Patron';
						if(trim($result[0]['billing_name'])!='')
							$cookie_user_name = trim($result[0]['billing_name']);
						elseif(trim($result[0]['name'])!='')
							$cookie_user_name = trim($result[0]['name']);
						
						if($remember == 1)
						{
							$datetim = strtotime($currDateTime . "+100 days");
							 setcookie($cookiename, $sesidcookie, time()+60*60*24*100, '/', '.bigmint.co', 'true');
							 setcookie("userName",$username, time()+60*60*24*100, '/', '.bigmint.co', 'true');
							 setcookie("billing_name",$cookie_user_name, time()+60*60*24*100, '/', '.bigmint.co', 'true');
							 //setcookie("billing_name",$result[0]['name'], time()+60*60*24*100, '/');
							 setcookie("uid",$user_id, time()+60*60*24*100, '/', '.bigmint.co', 'true');
							 setcookie("testCookieName","testCookieValue", time()+60*60*24*100, '/', '.bigmint.co', 'true');
						}
						else
						{
							$datetim = strtotime($currDateTime . "+8 hours");
							 setcookie($cookiename, $sesidcookie, time()+60*60*18, '/', '.bigmint.co', 'true');
							 setcookie("userName",$username, time()+60*60*18, '/', '.bigmint.co', 'true');
							 //setcookie("billing_name",$result[0]['name'], time()+60*60*18, '/');
							 setcookie("billing_name",$cookie_user_name, time()+60*60*18, '/', '.bigmint.co', 'true');
							 setcookie("uid",$user_id, time()+60*60*18, '/', '.bigmint.co', 'true');
							 setcookie("testCookieName","testCookieValue", time()+60*60*24*100, '/', '.bigmint.co', 'true');
						}
						///setcookie("firsttimelogin",$user_id, time()+60*60*24*100, '/');
						
						$_val = 10;
						$res14 = DB::table('tbl_updated_reg_logs_bm')
								->select('id')
								->where('memid', '=', $user_id )
								->where('status', '=', 'Active' )
								->orderBy('id' , 'desc')
								->first();
											
						$res_w = mysql_fetch_array($r11);	
						if( count($res14) > 0){
							$_val = 15;
						}
						
						$on_verify_link=$result[0]['on_verify_link'];
						if($on_verify_link == 1){
							$on_verify_link = 2;
						}
						DB::table('tbl_members')
								->where("id" , "=" , $user_id )
								->update(
									["logstatus" => 'Active', 
									'session' => $sesidcookie, 
									'logtime' => $datetim, 
									'activity_meter' => DB::raw('activity_meter + '.$_val), 
									'on_verify_link'=> $on_verify_link]
								) ;
						
						$_resultArr['uid'] = $user_id;
						$_resultArr['mid'] = $user_id;
						$_resultArr['uname'] = $username;
						$_resultArr['name'] = $result[0]['name'];
						
						return $_resultArr;		
					}else{
						return 'trueAL';
					}
					
				}//end web logic
				
                //start app logic
				/*                 
                                // Check if already loggedin user
                                $res = DB::table($_ENV['REFRESH_TOKEN_TABLE'])
                                            ->select('id')
                                            ->where($_ENV['USER_ID'], '=', $user_id )
                                            ->get();
                                if (count($res) >= 1 ) {
                                    // Multiple login requests
                                    return 'MLR'; 
                                } */
                                
				//Delete old token if exists
				DB::table($_ENV['REFRESH_TOKEN_TABLE'])
						->where($_ENV['USER_ID'], '=', $user_id )
						->where("appType" , "=" , $appType )
						->delete();
				
				$gcm_device_table = $appType=="CM"?"gcm_device_cm":"gcm_device";
				//Remove User Id from gcm_device table
				DB::table($gcm_device_table)
                        ->where("user_id" , "=" , $user_id )
                        ->update(["user_id" => 0 ]) ;
				
				// Create new token
				$rand = str_random($_ENV['REFRESH_TOKEN_LENGTH']) ;
				
				//////////////	for history ///////////////////		
				$physical_id = isset($_REQUESTARR['deviceID'])?$_REQUESTARR['deviceID']:'';
				$fcm_token = isset($_REQUESTARR['fcmToken'])?$_REQUESTARR['fcmToken']:'';
				$device_name = isset($_REQUESTARR['device_name'])?$_REQUESTARR['device_name']:'';
				
				$userSysDtls = $fcm_token . '|' . $rand;
				$loggin_try['mem_id'] = $user_id ;
				$loggin_try['log_time'] = $GLOBALS['currDateTime']; 
				$loggin_try['log_date'] = date("Y-m-d"); 
				$loggin_try['ip_address'] = $_SERVER['REMOTE_ADDR']; 
				
				$loggin_try['device'] = $userSysDtls;
				//$loggin_try['device_name'] = $device_type;
				$loggin_try['device_name'] = $device_name;	
				if($physical_id!=''){
					$loggin_try['company'] = ($appType == 'CM')?'CoalMint':'SteelMint';
					$loggin_try['device_id'] = $physical_id;					
					//$loggin_try['device_name'] = 'android';
				}else{
					//$loggin_try['device_name'] = 'IOS';
					//$loggin_try['device_id'] = $fcm_token;
					if($appType == 'CM'){
						$loggin_try['company'] = 'CoalMint';
					}else
						$loggin_try['company'] = 'SteelMint';
				}

				require_once("/home/steelmin/public_html/hf.php");
				$loggin_try['ip_country'] = ipTocntry("$ip");			
				//print_r($loggin_try);
				$creden = DB::table('tb1_online_member_loggin_try')
									->select(array('id'))
									->where('mem_id', '=', $user_id )
									->whereIn('device_name', array('android','IOS') )
									->where('company', '=', $loggin_try['company'] )
									->first();
				
				$online_member_loggin_iid = (isset($creden['id']))?$creden['id']:0;
				$loggin_try['parent_loggedin_id'] = $online_member_loggin_iid; 
				
				$loggin_try['platform'] = "Mobile APP";
				$loggin_try['url'] = "public/user/refresh_token : refreshToken - method";
				
				DB::table('tb1_online_member_loggin_try')
						->insert($loggin_try);
						
				if($online_member_loggin_iid==0){
					$last_id = DB::getPdo()->lastInsertId();;
					DB::table('tb1_online_member_loggin_try')
						->where('id', '=', $last_id )
						->update( [ 'parent_loggedin_id' => $last_id]);
					//echo 'get id:'.dd($last_id);
				}
				/////
				calculate_coc($user_id);
				if (DB::table($_ENV['REFRESH_TOKEN_TABLE'])
							->insert( [  $_ENV['USER_ID']=> $result[0][$_ENV['USER_ID']] , $_ENV['REFRESH_TOKEN_COLUMN'] => $rand, 'appType' => $appType ]))
					return $rand ;
				else 
				{
					// Log database entry error
					return false;
				}
			}
			else
			{
				// log user not verified
				file_get_contents("https://www.steelmint.com/registrationAJAX.php?id=" . $result[0]['id'] . "&src=fromAuthentication.php&username=" . $username);		
				//falseNV
 				return 'NV';
			}
			
		}
		else {
			// Log duplication entry found may be issue with generator
			return false;
		}
	}
	
	public function generateRefreshTokenV2019OLD($resourceType='app', $username, $password, $_REQUESTARR=array(), $remember=false)
	{
		$this->userLogout_user_pass($username, $password);
		# Get result
		//DB::enableQueryLog(); 
		$result = DB::table($_ENV['USER_TABLE'])
							->select($_ENV['USER_ID'] , $_ENV['VERIFIED_COLUMN'], 'id' )
							->where($_ENV['USERNAME'] ,$username)
							->where($_ENV['PASSWORD'] ,$password)
							->get();
				
		if (count($result) == 0 )
		{
			$result = DB::table($_ENV['USER_TABLE'])
				->select('email' , $_ENV['VERIFIED_COLUMN'], $_ENV['USER_ID'] )
				->where(function($q) use ($username) {
							$q->where('email' ,$username)
							->orWhere('phoneno' ,$username);
						})
				->where($_ENV['PASSWORD'] ,$password)
				->get();
			if (count($result) == 0 )
				return false;
		}
		//dd(DB::getQueryLog());	
		if (count($result) == 1)
		{
		    if ($result[0][$_ENV['VERIFIED_COLUMN']])
			{
				$user_id = $result[0][$_ENV['USER_ID']] ;
                if($resourceType=='web'){
					$ip =  $_SERVER['REMOTE_ADDR'] ; 
					
					$_resultArr['uid'] = $user_id;
					$_resultArr['mid'] = $user_id;
					$_resultArr['uname'] = $username;
					$_resultArr['on_verify_link'] = 1;
						
					return $_resultArr;	
				}
                
				// Check if already loggedin user
				$res = DB::table($_ENV['REFRESH_TOKEN_TABLE'])
							->select('id')
							->where($_ENV['USER_ID'], '=', $user_id )
							->get();
				if (count($res) >= 1 ) {
					// Multiple login requests
					return 'MLR'; 
				}
                                
				//Delete old token if exists
				DB::table($_ENV['REFRESH_TOKEN_TABLE'])
						->where($_ENV['USER_ID'], '=', $user_id )
						->delete();

				//Remove User Id from gcm_device table
				DB::table('gcm_device')
                        ->where("user_id" , "=" , $user_id )
                        ->update(["user_id" => 0 ]) ;
				
				// Create new token
				$rand = str_random($_ENV['REFRESH_TOKEN_LENGTH']) ;

				if (DB::table($_ENV['REFRESH_TOKEN_TABLE'])
							->insert( [  $_ENV['USER_ID']=> $result[0][$_ENV['USER_ID']] , $_ENV['REFRESH_TOKEN_COLUMN'] => $rand ]))
					return $rand ;
				else 
				{
					// Log database entry error
					return false;
				}
			}
			else
			{
				// log user not verified
				file_get_contents("https://www.steelmint.com/registrationAJAX.php?id=" . $result[0]['id'] . "&src=fromAuthentication.php&username=" . $username);		
				
 				return 'NV';
			}
			
		}
		else {
			// Log duplication entry found may be issue with generator
			return false;
		}
	}
		
	public function generateRefreshTokenV2019($resourceType='app', $username, $password, $_REQUESTARR=array(), $remember=0, $appType='SM')
	{
		/* if($resourceType=='app')
			$this->userLogout_user_pass($username, $password); */
		# Get result
		///DB::enableQueryLog(); 
		$result = DB::table($_ENV['USER_TABLE'])
							->select($_ENV['USER_ID'] , $_ENV['VERIFIED_COLUMN'], 'id', 'status','name', 'billing_name','session', 'logstatus','ipaddress', 'company', 'city', 'state', 'country', 'on_verify_link' )
							->where($_ENV['USERNAME'] ,$username)
							->where($_ENV['PASSWORD'] ,$password)
							->get();
		///dd(DB::getQueryLog());	
		///print_r($result);		
		if (count($result) == 0 )
		{
			$result = DB::table($_ENV['USER_TABLE'])
				->select('email' , $_ENV['VERIFIED_COLUMN'], $_ENV['USER_ID'], 'status','name', 'billing_name','session', 'logstatus','ipaddress', 'company', 'city', 'state', 'country', 'on_verify_link' )
				->where(function($q) use ($username) {
							$q->where('email' ,$username)
							->orWhere('addtnl_email' ,$username)
							->orWhere('phoneno' ,$username);
						})
				->where($_ENV['PASSWORD'] ,$password)
				->get();
			if (count($result) == 0 )
				return false;
		}
		//dd(DB::getQueryLog());	
		if (count($result) == 1)
		{
		    if ($result[0][$_ENV['VERIFIED_COLUMN']])
			{
				$user_id = $result[0][$_ENV['USER_ID']] ;
				$ip =  $_SERVER['REMOTE_ADDR'] ; 
				
				if($resourceType=='app')
					$this->userLogout($user_id, $appType);
				
                if($resourceType=='web'){
					
					$suffix='';
					$arrWhitelistedEmails = array("dhruv@steelmint.com", "sumit@steelmint.com", "dhruv@steelmin11t.com", "rohan@steelmint.com",'aditi.tiwari@steelmintgroup.com',  'ankita.chakraborty@steelmint.com','reena@steelmint.com', 'pushpaktantia@steelmintgroup.com','abhishek.bhalla@steelmint.com');
		
					$arrWhitelistedIPs = array("182.73.37.246", "122.163.40.83", "103.46.241.130", "122.176.64.108", "182.71.107.226",  '122.160.113.195', '103.242.186.14'); 
					
					$exIp = explode(".", $ip);
					$finalIp = $exIp[0] . "." . $exIp[1] . ".";
					if	( 
							!in_array($username, $arrWhitelistedEmails)
							&& (strpos($username, "steelmint.com") !== false || strpos($username, "steel-360.com") !== false || strpos($username, "steelmintgroup.com") !== false || strpos($username, "plantbee.com") !== false || strpos($username, "coalmint.com") !== false)
							&& !in_array($ip, $arrWhitelistedIPs)
							&& !in_array($finalIp, $arrWhitelistedIPs)
						)
					{//chekc if its steelmint user and accessing from office of outside office
						//return 'falseIPBL';//steelmintgroup emails, excepts mentioned in $arrWhitelistedEmails, must be 
					}
					///check any active service
					$res = DB::table('tbl_updated_reg_logs_bm')
							->select('id')
							->where('memid', '=', $user_id )
							->where('status', '=', 'Active' )
							->whereIn('services', array('W','E','S','MA') )
							->orderBy('id' , 'desc')
							->first();
					if (count($res) == 0 ) {
						// Multiple login requests
						//return 'NA'; 
						$res1 = DB::table('tbl_reg_logs')
								->select('subrm')
								->where('memid', '=', $user_id )
								->whereIn('f_product', array('W','E','S','MA') )
								->orderBy('id' , 'desc')
								->first();
						if (count($res1) > 0 ) {
							// Multiple login requests
							$subrm = $res1['subrm'];
							$res11 = DB::table('tbl_rel_manager')
								->select('rel_manager')
								->where('id', '=', $subrm )
								->first();
							//$rel_manager = $res11['rel_manager'];	
							$rel_manager = 'mohan@theitbooth.com';	
							
							DB::table('tbl_expired_user_login_try')->insert([ 'memid' => $user_id,
								'RM' => $rel_manager,
								'created_on' => $GLOBALS['currDateTime']]); 
							
							//require_once("/home/steelmin/public_html/mf.php");
							//sendNoActiveWebLogMailToAdmin($username, $result[0]['name'], $user_id, $result[0]['company'], $rel_manager, $GLOBALS['currDateTime'], $result[0]['city'], $result[0]['state'], $result[0]['country'],$company_name='SteelMint');
						}
						$suffix = 'NA'; 
					}
					
					//if(!isset($_COOKIE['uid'])){
					if(1){
						//commented by tarun on 2020-05-26
						/* $res12 = DB::table('tb1_online_member')
								->select('device')
								->where('mem_id', '=', $user_id )
								->where('status', '=', 'on' )
								->first(); */
						$rel_manager = $res11['rel_manager'];
						$tm = REALTIME;
						$company='SteelMint';
						$b_url  = isset($_REQUESTARR['b_url'])?$_REQUESTARR['b_url']:'';
						$browser = get_browser(null, true);
						$_sender = $browser['parent'];
						$platform = $browser['device_type'];
						$device = $browser['platform'];
						$_sender_agent = $browser['browser_name_pattern'];
					
						$parent_loggedin_id=0;
						$_REQUESTARR['sender'] = isset($_REQUESTARR['sender'])?$_REQUESTARR['sender']:'';
						$_REQUESTARR['tokinx'] = isset($_REQUESTARR['tokinx'])?$_REQUESTARR['tokinx']:'';					
						$_REQUESTARR['parent'] = isset($_REQUESTARR['parent'])?$_REQUESTARR['parent']:'';					
						
						require_once("/home/steelmin/public_html/hf.php");
						$ip_country = ipTocntry("$ip");
							
						//if(count($res12) > 0 && $user_id != 2 ){
						if(0){
							///$devices = explode(',', $res12['device']);
							//$first_device = $devices[0];
							
							$_REQUESTARR['sender'] .=  '(' . $_SERVER['REMOTE_ADDR'] . ')';
							
							$userSysDtls = $_REQUESTARR['sender'] . '|' . $_REQUESTARR['tokinx'] . '|' . date('Y-m-d H:i');
							//commented by tarun on 2020-05-26
							/* DB::table('tb1_online_member')
								->where("mem_id" , "=" , $user_id )
								->update(["device" => $userSysDtls ]) ; */
							
							
							$res13 = DB::table('tb1_online_member_loggin_try')
								->select('id')
								->where('mem_id', '=', $user_id )
								->where('parent_loggedin_id', '=', 'id' )
								->orderBy('id' , 'desc')
								->first();
							if(count($res13) > 0)
								$parent_loggedin_id = $res13['id'];
							
									if( $_REQUESTARR['tokinx'] = '' )
    								    $_REQUESTARR['tokinx'] = '';
    								if( $_REQUESTARR['parent'] = '' )
    								    $_REQUESTARR['parent'] = '';
    								if( $_sender_agent = '' )
    								    $_sender_agent = '';
    								if( $device = '' )
    								    $device = '';
    								if( $platform = '' )
    								    $platform = '';
    								if( $b_url = '' )
    								    $b_url = '';							
							
							//DB::enableQueryLog(); 
							DB::table('tb1_online_member_loggin_try')
								->insert([ 'mem_id' => $user_id,
								'log_date' => $GLOBALS['currDate'],
								'ip_country' => $ip_country,
								'ip_address' => $ip,
								'parent_loggedin_id' => $parent_loggedin_id,
								'lan_ip' => $_REQUESTARR['tokinx'],
								'device_id' => $_REQUESTARR['parent'],
								'device' => $_sender_agent,
								'device_name' => $device,
								'company' => $company,
								'platform' => $platform,
								'url' => $b_url,
								'log_time' => $GLOBALS['currDateTime']]); 
							//dd(DB::getQueryLog());
							return "falseAccess"; 	
						}else{///
							
							$userSysDtls = $_REQUESTARR['sender'] . '|' . $_REQUESTARR['tokinx'] . '|' . date('Y-m-d H:i');
							//commented by tarun on 2020-05-26
							/* DB::table('tb1_online_member')
								->insert([ 'mem_id' => $user_id,
								'log_time' => $GLOBALS['currDateTime'],
								'ip_address' => $ip,
								'status' => 'on',
								'remember_me' => $remember==1?'Y':'N',
								'device' => $userSysDtls]);  */

    								
    								if( $_REQUESTARR['tokinx'] = '' )
    								    $_REQUESTARR['tokinx'] = '';
    								if( $_REQUESTARR['parent'] = '' )
    								    $_REQUESTARR['parent'] = '';
    								if( $_sender_agent = '' )
    								    $_sender_agent = '';
    								if( $device = '' )
    								    $device = '';
    								if( $platform = '' )
    								    $platform = '';
    								if( $b_url = '' )
    								    $b_url = '';
    						
    						//$useriden = $_SERVER['SERVER_ADDR'] . ' -- ' . $_SERVER['SERVER_PORT'] . " -- " . $_SERVER['SERVER_SIGNATURE']	 . " -- " . $_SERVER['REMOTE_PORT']	 . " -- " . $_SERVER['REMOTE_HOST'];
    						//populate tb1_online_member_loggin_try.lan_ip here
    						//tv=track visitor
    						if(!isset($_COOKIE["tv"])) {
        						$tv = uniqid() . date('ymdhis') . $user_id;
        						setcookie("tv", $tv, time()+60*60*24*100, '/', '.bigmint.co', 'true');	
        						
    						} else {
    						    $tv = $_COOKIE["tv"];
    						}
    						
    						
							DB::table('tb1_online_member_loggin_try')
								->insert([ 'mem_id' => $user_id,
								'log_date' => $GLOBALS['currDate'],
								'ip_country' => $ip_country,
								'ip_address' => $ip,
								'parent_loggedin_id' => $parent_loggedin_id,
								'lan_ip' => $_REQUESTARR['tokinx']  . $tv,
								'device_id' => $_REQUESTARR['parent'],
								'device' => $_sender_agent,
								'device_name' => $device,
								'company' => $company,
								'platform' => $platform,
								'url' => $b_url,
								'log_time' => $GLOBALS['currDateTime']]); 
								calculate_coc($user_id);
						}
						
						$currDateTime = $GLOBALS['currDateTime'];
						$sesidcookie = base64_encode($ip.$username); 
						$cookiename = 'logdetails'; 
						$cookie_user_name = 'Patron';
						if(trim($result[0]['billing_name'])!='')
							$cookie_user_name = trim($result[0]['billing_name']);
						elseif(trim($result[0]['name'])!='')
							$cookie_user_name = trim($result[0]['name']);
							
						if($remember == 1)
						{
							$datetim = strtotime($currDateTime . "+100 days");
							 setcookie($cookiename, $sesidcookie, time()+60*60*24*100, '/', '.bigmint.co', 'true');
							 setcookie("userName",$username, time()+60*60*24*100, '/', '.bigmint.co', 'true');
							 //setcookie("billing_name",$result[0]['name'], time()+60*60*24*100, '/');
							 setcookie("billing_name",$cookie_user_name, time()+60*60*24*100, '/', '.bigmint.co', 'true');
							 setcookie("uid",$user_id, time()+60*60*24*100, '/', '.bigmint.co', 'true');
							 setcookie("testCookieName","testCookieValue", time()+60*60*24*100, '/', '.bigmint.co', 'true');
						}
						else
						{
							$datetim = strtotime($currDateTime . "+8 hours");
							 setcookie($cookiename, $sesidcookie, time()+60*60*18, '/', '.bigmint.co', 'true');
							 setcookie("userName",$username, time()+60*60*18, '/', '.bigmint.co', 'true');
							 //setcookie("billing_name",$result[0]['name'], time()+60*60*18, '/');
							 setcookie("billing_name",$cookie_user_name, time()+60*60*18, '/', '.bigmint.co', 'true');
							 setcookie("uid",$user_id, time()+60*60*18, '/', '.bigmint.co', 'true');
							 setcookie("testCookieName","testCookieValue", time()+60*60*24*100, '/', '.bigmint.co', 'true');
						}
						///setcookie("firsttimelogin",$user_id, time()+60*60*24*100, '/');
						
						$_val = 10;
						$res14 = DB::table('tbl_updated_reg_logs_bm')
								->select('id')
								->where('memid', '=', $user_id )
								->where('status', '=', 'Active' )
								->orderBy('id' , 'desc')
								->first();
											
						$res_w = mysql_fetch_array($r11);	
						if( count($res14) > 0){
							$_val = 15;
						}
						
						$on_verify_link=$result[0]['on_verify_link'];
						if($on_verify_link == 1){
							$on_verify_link = 2;
						}
						DB::table('tbl_members')
								->where("id" , "=" , $user_id )
								->update(
									["logstatus" => 'Active', 
									'session' => $sesidcookie, 
									'logtime' => $datetim, 
									'activity_meter' => DB::raw('activity_meter + '.$_val), 
									'on_verify_link'=> $on_verify_link]
								) ;
						
						$_resultArr['uid'] = $user_id;
						$_resultArr['mid'] = $user_id;
						$_resultArr['uname'] = $username;
						$_resultArr['name'] = $result[0]['name'];
						$_resultArr['billing_name'] = $result[0]['billing_name'];
						
						return $_resultArr;		
					}else{
						return 'trueAL';
					}
					
				}//end web logic
                //start app logic
				// Check if already loggedin user
				$res = DB::table($_ENV['REFRESH_TOKEN_TABLE'])
							->select('id')
							->where($_ENV['USER_ID'], '=', $user_id )
							->where("appType" , "=" , $appType )
							->get();
				if (count($res) >= 1 ) {
					// Multiple login requests
					return 'MLR'; 
				}
                                
				//Delete old token if exists
				DB::table($_ENV['REFRESH_TOKEN_TABLE'])
						->where($_ENV['USER_ID'], '=', $user_id )
						->where("appType" , "=" , $appType )
						->delete();
				
				$gcm_device_table = $appType=="CM"?"gcm_device_cm":"gcm_device";
				//Remove User Id from gcm_device table
				DB::table($gcm_device_table)
                        ->where("user_id" , "=" , $user_id )
                        ->update(["user_id" => 0 ]) ;
				
				// Create new token
				$rand = str_random($_ENV['REFRESH_TOKEN_LENGTH']) ;
				
				//////////////			
				$physical_id = isset($_REQUESTARR['deviceID'])?$_REQUESTARR['deviceID']:'';
				$fcm_token = isset($_REQUESTARR['fcmToken'])?$_REQUESTARR['fcmToken']:'';
				$device_name = isset($_REQUESTARR['device_name'])?$_REQUESTARR['device_name']:'';
				
				$userSysDtls = $fcm_token . '|' . $rand;
				$loggin_try['mem_id'] = $user_id ;
				$loggin_try['log_time'] = $GLOBALS['currDateTime']; 
				$loggin_try['log_date'] = date("Y-m-d"); 
				$loggin_try['ip_address'] = $_SERVER['REMOTE_ADDR']; 
				
				$loggin_try['device'] = $userSysDtls;
				//$loggin_try['device_name'] = $device_type;
				$loggin_try['device_name'] = $device_name;	
				if($physical_id!=''){
					$loggin_try['company'] = ($appType == 'CM')?'CoalMint':'SteelMint';
					$loggin_try['device_id'] = $physical_id;					
					//$loggin_try['device_name'] = 'android';
				}else{
					//$loggin_try['device_name'] = 'IOS';
					//$loggin_try['device_id'] = $fcm_token;
					if($appType == 'CM'){
						$loggin_try['company'] = 'CoalMint';
					}else
						$loggin_try['company'] = 'SteelMint';
				}

				require_once("/home/steelmin/public_html/hf.php");
				$loggin_try['ip_country'] = ipTocntry("$ip");			
				//print_r($loggin_try);
				$creden = DB::table('tb1_online_member_loggin_try')
									->select(array('id'))
									->where('mem_id', '=', $user_id )
									->whereIn('device_name', array('android','IOS') )
									->where('company', '=', $loggin_try['company'] )
									->first();
				
				$online_member_loggin_iid = (isset($creden['id']))?$creden['id']:0;
				$loggin_try['parent_loggedin_id'] = $online_member_loggin_iid; 
				
				$loggin_try['platform'] = "Mobile APP";
				$loggin_try['url'] = "public/user/refresh_token : refreshToken - method";
				
				DB::table('tb1_online_member_loggin_try')
						->insert($loggin_try);
						
				if($online_member_loggin_iid==0){
					$last_id = DB::getPdo()->lastInsertId();;
					DB::table('tb1_online_member_loggin_try')
						->where('id', '=', $last_id )
						->update( [ 'parent_loggedin_id' => $last_id]);
					//echo 'get id:'.dd($last_id);
				}
				/////
				calculate_coc($user_id);
				if (DB::table($_ENV['REFRESH_TOKEN_TABLE'])
							->insert( [  $_ENV['USER_ID']=> $result[0][$_ENV['USER_ID']] , $_ENV['REFRESH_TOKEN_COLUMN'] => $rand, 'appType' => $appType ]))
					return $rand ;
				else 
				{
					// Log database entry error
					return false;
				}
			}
			else
			{
				// log user not verified
				file_get_contents("https://www.steelmint.com/registrationAJAX.php?id=" . $result[0]['id'] . "&src=fromAuthentication.php&username=" . $username);		
				
 				return 'NV';
			}
			
		}
		else {
			// Log duplication entry found may be issue with generator
			return false;
		}
	}
		

	public function generateRefreshToken($username, $password)
	{
		$this->userLogout_user_pass($username, $password);
		# Get result
		$result = DB::table($_ENV['USER_TABLE'])
							->select($_ENV['USER_ID'] , $_ENV['VERIFIED_COLUMN'], 'id' )
							->where($_ENV['USERNAME'] ,$username)
							->where($_ENV['PASSWORD'] ,$password)
							->get();
				
		if (count($result) == 0 )
		{
			$result = DB::table($_ENV['USER_TABLE'])
				->select('email' , $_ENV['VERIFIED_COLUMN'], $_ENV['USER_ID'] )
				->where('email' ,$username)
				->where($_ENV['PASSWORD'] ,$password)
				->get();
			if (count($result) == 0 )
				return false;
		}
		if (count($result) == 1)
		{
		    if ($result[0][$_ENV['VERIFIED_COLUMN']])
			{
				$user_id = $result[0][$_ENV['USER_ID']] ;
                                
                                // Check if already loggedin user
                                $res = DB::table($_ENV['REFRESH_TOKEN_TABLE'])
                                            ->select('id')
                                            ->where($_ENV['USER_ID'], '=', $user_id )
                                            ->get();
                                if (count($res) >= 1 ) {
                                    // Multiple login requests
                                    return 'MLR'; 
                                }
                                
				//Delete old token if exists
				DB::table($_ENV['REFRESH_TOKEN_TABLE'])
						->where($_ENV['USER_ID'], '=', $user_id )
						->delete();

				//Remove User Id from gcm_device table
				DB::table('gcm_device')
                        ->where("user_id" , "=" , $user_id )
                        ->update(["user_id" => 0 ]) ;
				
				// Create new token
				$rand = str_random($_ENV['REFRESH_TOKEN_LENGTH']) ;

				if (DB::table($_ENV['REFRESH_TOKEN_TABLE'])
							->insert( [  $_ENV['USER_ID']=> $result[0][$_ENV['USER_ID']] , $_ENV['REFRESH_TOKEN_COLUMN'] => $rand ]))
					return $rand ;
				else 
				{
					// Log database entry error
					return false;
				}
			}
			else
			{
				// log user not verified
				file_get_contents("https://www.steelmint.com/registrationAJAX.php?id=" . $result[0]['id'] . "&src=fromAuthentication.php&username=" . $username);		
				
 				return 'NV';
			}
			
		}
		else {
			// Log duplication entry found may be issue with generator
			return false;
		}
	}

	public function generateToken($refresh_token, $appType='SM' )
	{
		$user_id = $this->authRefreshToken($refresh_token, $appType) ;
		if ( $user_id )
		{
			//Delete old token if exists
			DB::table($_ENV['TOKEN_TABLE'])
					->where($_ENV['USER_ID'], '=', $user_id )
					->where("appType" , "=" , $appType )
					->delete();

			// Generate new token
			$rand = str_random($_ENV['TOKEN_LENGHT']) ;
			if (DB::table($_ENV['TOKEN_TABLE'])
						->insert( [  $_ENV['USER_ID']=> $user_id , $_ENV['TOKEN_COLUMN'] => $rand, "appType" => $appType ]))
				return $rand ;
			else 
			{
				// Log database entry error
				return false;
			}
		}
		else 
			return false;
		
	}
}
