<?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($token)
	{
		$user_id = (array)DB::table($_ENV['TOKEN_TABLE'])
							->where($_ENV['TOKEN_COLUMN'] ,$token)
							->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)
		{
          return $user_id[0][$_ENV['USER_ID']] ;
		}
		else {
			return 0;
		}	
	}

	public function authRefreshToken($refresh_token)
	{
		$user = DB::table($_ENV['REFRESH_TOKEN_TABLE'])
							->select($_ENV['USER_ID'])
							->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)
	{
		$result = DB::table($_ENV['REFRESH_TOKEN_TABLE'])
			->select($_ENV['USER_ID'] )
			->where($_ENV['USER_ID'], '=', $user_id )
			->get();

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

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

		DB::table($_ENV['TOKEN_TABLE'])
			->where($_ENV['USER_ID'], '=', $user_id )
			->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 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 )
	{
		$user_id = $this->authRefreshToken($refresh_token) ;
		if ( $user_id )
		{
			//Delete old token if exists
			DB::table($_ENV['TOKEN_TABLE'])
					->where($_ENV['USER_ID'], '=', $user_id )
					->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 ]))
				return $rand ;
			else 
			{
				// Log database entry error
				return false;
			}
		}
		else 
			return false;
		
	}
}
