<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/
//$Id: AuthModel.php, v 1.0 2013/03/14 14:14:14
class AuthModel extends Model 
{
	/* function to create/fetch the access token based on the access token expiry */
    public function generateAccessToken($params,$create='') {
		extract($params);
		if($userType=='B') {
			$table = 'business_access_tokens';
		} else {
			$table = 'access_tokens';
		}
		$currentTime	= date('Y-m-d H:i:s');
                if($create=='') {
                    $res	= $this->getAccessToken($params);
                } else {
                    $res        = array();
                }
		/* check the access token is expired or not */
		if(!empty($res)){
			/* token is not expired , So existed token is returned to controller with accessTokenType=Updated */
			$accessToken		= $res['accessToken'];
			$accessTokenType	= 'updated';
			$sql = "
				UPDATE 
					" . DB_PREFIX .$table. "
				SET
					lastAccessed='".$currentTime."'
				WHERE
					userID='".$userID."'
					AND
					accessToken='".$accessToken."'
					AND
					userType='".$userType."'";
		}
		else{
			/* token is expired , So create a new token and return to controller with accessTokenType=New */
			$accessToken		= md5(uniqid());
			$accessTokenType	= 'new';
			$sql = "
				INSERT INTO	" . DB_PREFIX .$table ."
					(
					userID,
					userType,
					accessToken,
					lastAccessed
					)
				VALUES	
					(
					'".$userID."',
					'".$userType."',
					'".$accessToken."',
					'".$currentTime."'
					)
				";
		}
        $this->ObjDatabase->setQuery($sql);
		return array(
			'accessToken'=>$accessToken,
			'accessTokenType'=>$accessTokenType
		);
        
    }
	
	/* function to get the access token details  */
	public function getAccessToken($params){
		extract($params);
		$currentTime	=	date('Y-m-d H:i:s');
        if($userType=='B') {
			$table = 'business_access_tokens';
		} else {
			$table = 'access_tokens';
		}
		/* delete all expired access tokens */
		$this->deleteExpiredTokens($params);	
		$sql	="
				SELECT 
					accessToken,
					lastAccessed
				FROM
					" . DB_PREFIX . $table."
				WHERE
					userID='".$userID."'
					AND
					userType='".$userType."'";
					
		return $this->ObjDatabase->readValue($sql);
	}
	
	/* function to get the user ID from the table access_token if the request contains the access token */
	public function getUserID($params,$statusCheck=''){
		extract($params);
		$currentTime	=	date('Y-m-d H:i:s');
		/* delete all expired access tokens */
		if($userType=='B') {
			$table = 'business_access_tokens';
		} else {
			$table = 'access_tokens';
		}
		$this->deleteExpiredTokens($params);	
		$sql	="
				SELECT 
					tkn.userID,
					tkn.userType,
					tkn.lastAccessed
				FROM
					" . DB_PREFIX . $table." AS tkn
                                
				WHERE
					tkn.accessToken='".$accessToken."'";
             //   LEFT JOIN " . DB_PREFIX . "users AS usr ON tkn.userID = usr.userID
		$result=$this->ObjDatabase->readValue($sql);
              
		switch($result['userType']){
			/* If the user is NormalUser/SiteUser/Customer */
			case 'N':	
                           
				/* check the user is in active status; returns YES/NO */
                                if($statusCheck=='') {
				if($this->ObjDatabase->checkExist('users','userID',$result['userID']," userStatus='Active' ")=='YES'){
                                            $sqlUserGroup = "select userGroupID from " . DB_PREFIX."users where userID='".$result['userID']."'";
                                            $resUserGroup = $this->ObjDatabase->readValue($sqlUserGroup);
                                            $result['userGroupID'] = !empty($resUserGroup) ? $resUserGroup['userGroupID']:0;
					return $result;
				}
                                } else {
                                    if($statusCheck=='L') {
                                        if($this->ObjDatabase->checkExist('users','userID',$result['userID'])=='YES'){

                                                return $result;
                                        }
                                    } else {
                                        if($this->ObjDatabase->checkExist('users','userID',$result['userID']," userStatus!='Deleted'")=='YES'){

                                                return $result;
                                        }
                                    }
                                }
				break;
			/* If the user is Business User */
			case 'B':
				/* check the user is in active status; returns YES/NO */
				if($this->ObjDatabase->checkExist('business','businessID',$result['userID']," businessStatus='Active' ")=='YES'){
					return $result;
				}			
				break;
			/* If the user is Business User */
			case 'BU':
				/* check the user is in active status; returns YES/NO */
				if($this->ObjDatabase->checkExist('business_users','businessUserID',$result['userID']," businessUserStatus='Active' ")=='YES'){
					return $result;
				}			
				break;
				
		}
		return array();
	}
	/* function to delete all expired access tokens */
	private function deleteExpiredTokens($params){
		extract($params);
		if($userType=='B') {
			$table = 'business_access_tokens';
		} else {
			$table = 'access_tokens';
		}
		/* delete the access tokens based on the admin settings :- access_token_expiry_days(mobileweb_settings) */
		if($accessTokenExpireDays!='' && $accessTokenExpireDays>=0){
			$currentTime	=	date('Y-m-d H:i:s');
			$sql="
					DELETE FROM 
						" . DB_PREFIX . $table." 
					WHERE
						DATE_ADD(lastAccessed,INTERVAL ".$accessTokenExpireDays." DAY) <='".$currentTime."'";
						
			return $this->ObjDatabase->setQuery($sql);
		}
		else{
			return true;
		}
	}
}