<?
    class UserRegistration
    {
        public $userid;
        public $roleid;
        public $bankid;
        public $branchid;
        public $bankuserid;
		public $usermobileno;
		public $username;
		public $fullname;
		
		public $usermakerid; 
		public $userauthoriserid;
		public $userstatus;
		
        
        public $useremail;
		public $userfirstname;
		public $userlastname;
		public $usermobilecountrycode;
		public $usermobileverified;
		public $userpassword;
		public $userphotocount;
		public $userpostcount;
	    public $userprofiephotopath;
		public $userprofileviews;
		public $userregistereddate;
		public $userregisteredip;
		public $userreplycount;
		public $usersalutation;
		public $usersex;
		public $userstate;
		public $usertelno;
		public $usertype;
		public $userverified;
		public $dateofbirth;
		public $designation;
		public $facebookurl;
		public $invitationcode;
		public $invtationcodegenerationdate;
		public $isUserLoggedIn;
		public $isemailotpverify;
		public $ismobileotpverify;
		public $lastloginIP;
		public $lastlogindatetime;
		public $lastlogindevice;
		public $lastusertoken;
		public $linkedinurl;
		public $loggedoutdatetime;
		public $oauth_provider;
		public $oauth_uid;
		public $occupation;
		public $otpforverifyemail;
		public $otpforverifymobile;
		public $receivediscountoffers;
		public $receiveselloffers;
		public $status;
		public $twitter_oauth_token_secret;
		public $twitterurl;
		public $useraboutme;
		public $usercitycode;
		public $usercityname;
		public $usercountry;
		public $usercountrycode;
		public $userdeleted;
		public $userdeleteddate;
		public $CreatedByName;
		public $CreatedDateTime;
		public $UpdatedDateByName;
		public $UpdatedDateTime;
		public $usercookietoken;   
		public $extra1;
		public $extra2;
		public $extra3;
		public $extra4;
		public $display_name;
		public $magzinesname;
		public $PackageType;
		public $noofmagzinesread;
		public $user_cookieuserid;
		public $user_cookietoken;
		public $provider_name; // social media login provider name
        public $social_token; // token from social media to re-login
	    public $user_gmailpictureUrls; 
  		public $user_fbpictureUrls; 
  		public $user_profileURL;
        
		var $obj1;
		var $con;
		// constructor
		function __construct()
		{

			$this->obj1 = new dboperations();
		}
		
		function getUserDetail($userid='',$username='',$isuseractive=1)
		{
		    $isactivecondition =  "";
		    
		    if($userid > 0)
		    {
	        	$sql = 'Select * from USERMST where USERID = :userid '.$isactivecondition.'  limit 0,1';
				//echo $sql;
				$fieldsarray = array(':userid' => $userid); 	
				$users = $this-> obj1-> getInfo($sql,$fieldsarray);
		    }
		    else if($username != '')
		    {
		        $sql = 'Select * from USERMST where USERNM  = :usernm '.$isactivecondition.' limit 0,1';
			    //echo $sql;

				$fieldsarray = array(':usernm' => "$username");
				// print_r($fieldsarray);				
				$users = $this-> obj1-> getInfo($sql,$fieldsarray);
		    }
		    else
            {
                $sql = "select * from USERMST ";                 
    			$users = $this-> obj1-> getInfo($sql);
            }
		    
		    return $users;
		}
		
		
	
		
	    function getUserInfo($sql='',$fieldsarray='',$userid='',$username='',$userdeleted='')
		{
						
			$userdeleted = ($userdeleted=='')?' and userdeleted=0':$userdeleted;	
			if($sql!='' && $fieldsarray!='')
			{			
			//	echo $sql;
		//	print_r($fieldsarray);
				$users = $this-> obj1-> getInfo($sql,$fieldsarray);
				
			}
			else if($sql !='')
			{
				//	echo $sql;
				$users = $this-> obj1-> getInfo($sql);
			}
			else if($userid > 0)
			{
				$sql = 'Select * from mstusers where userid = :userid '.$userdeleted.'  limit 0,1';
				//echo $sql;
				$fieldsarray = array(':userid' => $userid); 	
				$users = $this-> obj1-> getInfo($sql,$fieldsarray);
			}
			else if($username > '')
			{
				$sql = 'Select * from mstusers where username = :username '.$userdeleted.' limit 0,1';
				//echo $sql;				
				$fieldsarray = array(':username' => "$username");
				//print_r($fieldsarray);				
				$users = $this-> obj1-> getInfo($sql,$fieldsarray);
			}
					
			if ($users)
			{
				$numrows = count($users);
			}
			return $users;
		}
		
        function AddUser($UserData,$table='USERMST')
		{
			if (!is_array($UserData))
			{
				return false;
			}
			else
			{
				// create a validate user function and validate user before adding to table
				// validate if user already exists
				// validate if email is properly formatted
				// validate if all required fields are present
				// more validatation to follow				
				$lastInsertID = $this->obj1->AddInfo($UserData,$table);
				return $lastInsertID;
			}
		}
								
		function EditUser($applicationdata,$wherecondition,$table='USERMST')
		{
			$applications = 1;
			if (is_array($applicationdata)== false)
			{
				//echo '1';			
				return false;
			}
			else
			{
				//echo '2';				
				//print_r($applicationdata);
				$applications = $this-> obj1->EditInfo($applicationdata, $wherecondition,$table);
				//print_r($applications);
				return $applications; // returns no of rows affected by update operation
			}
		}
		
		function DeleteUser($applicationdata,$table='USERMST')
		{
			if($applicationdata)
			{
				$applications = $this-> obj1->DeleteInfo($applicationdata,$table);
				return ($applications == 1)?"true":"false";
			}
		}
		
		
		// this function will be called to validate login everytime
		function ValidateLogin()
		{
			$returnvalue = "0";
			// first check if user already exists with username
			$username = $this->username;
			//$sqltext = "Select $fields from ".USER_TABLE." where username='".$username."' and isemailotpverify = 1";
			//$userdata = $this->getUserInfo('','*',$sqltext);
			
			$userdata = $this->getUserInfo('','*','',$username);
			$usercount = 0;
			if ($userdata)
			{
			    $usercount = count($userdata);
			}
			if ($usercount > 0 ) // user already exists
			{	
			    if($this->provider_name!='')
				{
					$provider_name_datafield = $this->provider_name.'_token';
					$provider_name_arrayfield = $this->provider_name."_token";
					
					// existing user logged in with social provider
					// update token
					$userid = $userdata[0]['userid'];
					$wherecondition =   " userid = $userid ";
					
					// $wherecondition = array('userid'=> $userdata[0]['userid']);
					$applicationdata[$provider_name_arrayfield]= $this->social_token;
					$applicationdata['userprofiephotopath'] = $this->user_pictureUrls;
					$applicationdata['isemailotpverify'] = '1';
					// check below fields in database -- by rajiv - 11th nov 2020
					//$applicationdata['fbuserprofilephoto'] = $this->user_fbpictureUrls;
					//$applicationdata['gmailuserprofilephoto'] = $this->user_gmailpictureUrls;		
					// end of checking - 
					
					// set site cookie and update in mstuser table and also put cookie					
					$retval = $this->EditUser($applicationdata,$wherecondition);
					//echo 'retval '.$retval;
					if ($retval==true) 
					{
						// user is edited successfully
						//debug_to_console('user edited successfully');
						//$username = $this->username;		
						$userdataUpdated = $this->getUserInfo($userid);
						//print_r($userdataUpdated);
						//exit();
						// added by rajiv to check if social login works with all options
						if($userdataUpdated[0]['usertype'] == '0')
			            {
			                $noofmagzinesread   =   $userdataUpdated[0]['noofmagzinesread'];
			                $packagevalues  =   explode('||',$this->checkPackageValue($userid));
    			            $userdataUpdated[0]['magzinesname']    =   $packagevalues[0];
					        $userdataUpdated[0]['PackageType']     =   $packagevalues[1];
					        $userdataUpdated[0]['UserPackageStatus']     =   $packagevalues[2];
			            }
			            else
			            {
    			            $packagevalues  =   explode('||',$this->checkPackageValue($userid));
    			            $userdataUpdated[0]['magzinesname']    =   $packagevalues[0];
					        $userdataUpdated[0]['PackageType']     =   $packagevalues[1];
					        $userdataUpdated[0]['UserPackageStatus']     =   $packagevalues[2];
                        }
						$retval = $this->updateUserValues($userdataUpdated);
						setCookieLogin($userdataUpdated[0]['userid']);
					    return $userid;
					}
					else
					{
						//debug_to_console($retval);						
						return $returnvalue;
					}							
				}
			    elseif($userdata[0]['isemailotpverify'] == '1')
			    {
			        $cur_date           =   date("Y-m-d");
    	            $userid             =   $userdata[0]['userid'];
			        if($userdata[0]['usertype'] == '0')
			        {
			            $noofmagzinesread   =   $userdata[0]['noofmagzinesread'];
			        }
			        else
			        {
    			        $packagevalues  =   explode('||',$this->checkPackageValue($userid));
    			        $userdata[0]['magzinesname']    =   $packagevalues[0];
					    $userdata[0]['PackageType']     =   $packagevalues[1];
					    $userdata[0]['UserPackageStatus']     =   $packagevalues[2];
                    }
				    $applicationdata = $this->updateUserValuesForDataBase();
				    $applicationdata['lastlogindatetime']=date("Y-m-d H:i:s");
				    $applicationdata['lastloginIP'] = $this->get_user_ip(); 
				    $applicationdata['lastlogindevice']='0'; // use class user_device_info class to store user device info details	
			        // add set cookie login here as well
			        // setCookieLogin($userdata[0]['userid']);
			    
			        if(($this->username!='')&&($this->userpassword!='')&&($this->userfirstName!=''))
				    {
					throw new customException("User Already Exists");
					return $returnvalue;				
				}				
				else if (($this->username!='')&&($this->userpassword!=''))
				{
				    if ($userdata[0]['userid']!="")
					{
						//$userpasswordtotest = md5($this->userpassword);
					    if ($userdata[0]['isOldUser'] == "0")
					    {
					        $userpasswordtotest = $this->userpassword;
    					//	if (($userpasswordtotest) == ($userdata[0]['userpassword']))
    					    if ((password_verify($userpasswordtotest,$userdata[0]['userpassword']))) 
    					    {
    							$retval = $this->updateUserValues($userdata);						
    							setCookieLogin($userdata[0]['userid']);								
    							$returnvalue = 1;							
    							return $returnvalue;
    						}
    						else 
    						{
    							throw new customException("Invalid UserName or Password.");						
    							return $returnvalue;
    						}
					    }
					    else
					    {
					        
                        	$wp_hasher = new PasswordHash(8, TRUE);
                            $password_hashed = $userdata[0]['userpassword'];
                        	$plain_password = $this->userpassword;
                        	
                        	if($wp_hasher->CheckPassword($plain_password, $password_hashed)) {
                        	   // echo "Success";
                        	    $retval = $this->updateUserValues($userdata);
    							setCookieLogin($userdata[0]['userid']);								
    							$returnvalue = 1;	
    							return $returnvalue;
                            }
                            else {
                        	   echo "Failed";
                        	   throw new customException("Invalid UserName or Password.");						
    							return $returnvalue;
                        	}
                            
					    }
					}	
				}
				else 
				{
					// user already exists but trying to register again with same username
					// send error
					throw new customException("User Already Exists");
					return $returnvalue;	
				}
			  }
			    else
			    {
					// user already exists but trying to register again with same username
					// send error
					throw new customException("Verify Your Email Id");
					return $returnvalue;	
			    }
			}
			elseif(($this->username!='')&&($this->userfirstName!='')&&($this->userlastName!='')) // user does not exists add to database
			{
			    // to add userdata in userdatatoadd array

				if ($this->userpassword=='')
				{
				    $sociallogin            =   '1';
				    $this->userpassword = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 8);
				}
				$this->userregistereddate = date("Y-m-d H:i:s");
				$this->userregisteredip = $this->get_user_ip();
				$this->usertype         =   '0';
				$this->noofmagzinesread =   '0';
				$mobileno               =   $this->usermobileno;
				$userdataToAdd = $this->updateUserValuesForDataBase();
			
		
				$lastinsertedID = $this->AddUser($userdataToAdd);
			//	if($lastinsertedID == 'true')
			//	{	
				    $username = $this->username;
			        $userdata = $this->getUserInfo('','*','',$username);
			        $usercount = count($userdata);	
			        if ($this->provider_name!='')
				    {
					    $provider_name_datafield = $this->provider_name.'_token';
					    $provider_name_arrayfield = $this->provider_name."_token";
					
					    $userid = $userdata[0]['userid'];
					    $wherecondition =   " userid = $userid ";
					    
					    $applicationdata[$provider_name_arrayfield]= $this->social_token;
					    $applicationdata['userprofiephotopath'] = $this->user_pictureUrls;
					    $applicationdata['isemailotpverify'] = '1';
					
					    // set site cookie and update in mstuser table and also put cookie					
					    $retval = $this->EditUser($applicationdata,$wherecondition);
					}
			        
			        if($userdata[0]['usertype'] == '0')
			        {
			            $noofmagzinesread   =   $userdata[0]['noofmagzinesread'];
			        }
			        else
			        {
    			        $packagevalues  =   explode('||',$this->checkPackageValue($userdata[0]['userid']));
    			        $userdata[0]['magzinesname']    =   $packagevalues[0];
					    $userdata[0]['PackageType']     =   $packagevalues[1];
					    $userdata[0]['UserPackageStatus']     =   $packagevalues[2];
                    }
                    
                    
			        if($sociallogin != 1)
			        {
			            $sociallogin =   $userdata[0]['userid'];
			            $retval = $this->updateUserValues($userdata);
			            setCookieLogin($userdata[0]['userid']);
			        }   
			        else
			        {
			            $retval = $this->updateUserValues($userdata);
			            setCookieLogin($userdata[0]['userid']);	
			        }
			        // send welcome email to user 
			        // नमस्कार. बहुविध परिवारात आपले स्वागत आहे. निवडक, संपादित साहित्याचा आनंद मिळवा. लॉगिन संबंधी काही अडचण आल्यास 9152255235 या क्रमांकावर संपर्क साधा.
			        // test this mail sending
			        // sendWelcomeMail();
			        return $sociallogin;
			//	}
			}
			else 
			{
					
					throw new customException("Username and Password does not exists. ");
					return $returnvalue;	
			}	
			
		}
	
		
		private function get_user_ip() {
    	$ipaddress = '';
    	if (isset($_SERVER['HTTP_CLIENT_IP']))
      	$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    	else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
      	$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    	else if(isset($_SERVER['HTTP_X_FORWARDED']))
      	$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    	else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
      	$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    	else if(isset($_SERVER['HTTP_FORWARDED']))
      	$ipaddress = $_SERVER['HTTP_FORWARDED'];
    	else if(isset($_SERVER['REMOTE_ADDR']))
      	$ipaddress = $_SERVER['REMOTE_ADDR'];
    	else
      	$ipaddress = 'UNKNOWN';
    	return $ipaddress;
		}
	    
	
			
	    function updateUserValuesForDataBase()
		{
				//$uservalueArray['userid'] = $this->user_id ;
				if ($this->username>'')
				{ 		
					$uservalueArray['username'] = $this->username ;
				}
				if ($this->useremail>'')
				{ 	
					$uservalueArray['useremail'] = $this->useremail ;
				}
				if ($this->usermobileno>'')
				{ 	
					$uservalueArray['usermobileno'] = $this->usermobileno ;
				}
				if ($this->userpassword >'')
				{ 		
				//	$uservalueArray['userpassword'] = password_hash($this->userpassword, PASSWORD_DEFAULT);
					$uservalueArray['userpassword'] = password_hash($this->userpassword,PASSWORD_DEFAULT);
					$uservalueArray['isemailotpverify'] = '1';
				}
				if ($this->userfirstName>'')
				{	
					$uservalueArray['userfirstname'] = $this->userfirstName  ;
				}	 
				if ($this->userlastName>'')
				{
      			    $uservalueArray['userlastname'] = $this->userlastName;
      		    }
      		    if ($this->userfirstName>'' && $this->userlastName>'')
      		    {
      			    $uservalueArray['display_name'] = $this->userfirstName.'_'.$this->userlastName;
      		    }
      		    if ($this->userregistereddate>'')
				{
      			    $uservalueArray['userregistereddate'] = $this->userregistereddate;
      		    }
      		    if ($this->usertype>'')
				{
      			    $uservalueArray['usertype'] = $this->usertype;
      			    $uservalueArray['UserByAdminAuthor'] = $this->usertype;
      			    $uservalueArray['noofmagzinesread'] =   $this->noofmagzinesread;
      		    }  
      		    if ($this->usersex>'')
				{
      			    $uservalueArray['usersex'] = $this->usersex;
      		    }
      		    if ($this->dateofbirth>'')
				{
      			    $uservalueArray['dateofbirth'] = $this->dateofbirth;
      		    }
      		    if ($this->userregisteredip > '')
      		    {
      		        $uservalueArray['userregisteredip'] = $this->userregisteredip;
      		    }
      		    if($this->user_gmailpictureUrls>'')
          		{
          			$uservalueArray['gmailuserprofilephoto'] = $this->user_gmailpictureUrls;
          		}	 
          		if($this->user_fbpictureUrls>'')
          		{
          			$uservalueArray['fbuserprofilephoto'] = $this->user_fbpictureUrls;
          		}	 
      		    $uservalueArray['status'] = '1';
      		    
      		return $uservalueArray;				
			
		}
		
		function updateCookieValueToDatabase () 
		{
			if(($this -> userid > 0)&&($this->user_cookietoken > ''))
			{
				$applicationdata['lastusertoken']=$this->user_cookietoken;
				$useridToUpdate = $this->userid;
			//	$wherecondition=array('userid'=>$useridToUpdate);
				    $wherecondition =   array('USERID' => $useridToUpdate);
				$retval = $this->EditUser($applicationdata,$wherecondition);				
				return $retval;			
			}	
		}
		
		
		
		function checkCookieinDatabase()
		{
			$chklogin = 0;
			if ($this->user_cookietoken!='')
			{
			    
		    	$sql = "select * from USERMST where lastusertoken = ?";
				//$applicationdata['lastusertoken']= $this->user_cookietoken;
				$applicationdata = array($this->user_cookietoken);
				$userdata = $this->getUserInfo($sql,$applicationdata);

				if ($userdata)
				{
				    $usercount = count($userdata);					
				    if ($usercount > 0)
				    {
					    $userid = $userdata[0]['userid'];
					    $useridEncDatabase =  hash_hmac('sha1',$userid, SECRET_KEY);
					    $cookieuserid = $this->user_cookietoken;
					    if ($useridEncDatabase==$cookieuserid)
					    {
						    // update cookie and token in database
						    $this->userid = $userid;
						    $retval = $this->updateUserValues($userdata);						
						    $chklogin = 1;
					    }
					    else
					    {
						    $chklogin = 2;
					    }
				    }
				    else 
				    {
					    $chklogin = 3;
				    }			
				}
				    
			}
			return $chklogin;
		}
		function setSiteCookieInDatabase()
		{
				$lastlogindatetime = date("Y-m-d H:i:s");
				$lastloginIP = $this->get_user_ip(); 
				$lastlogindevice = '0'; // keep 0 for time being for desktop once we start identifying devices then we make it 1 for tablet and 2 for mobile
			
				$appData['lastlogindatetime']	= $lastlogindatetime;
				$appData['lastloginIP']			= $lastloginIP;
				$appData['lastlogindevice']		= $lastlogindevice;
				$appData['isUserLoggedIn']		= '1';
				$appData['lastusertoken']		= $this->user_cookietoken;
				
				$useridToUpdate = $this->userid;
				$wherecondition =   array("USERID" => $useridToUpdate);      
				$retval = $this->EditUser($appData,$wherecondition);                              
				
				if ($retval) 
				{    
				    $G_UserPermission       = $this->UserCheckPermission($useridToUpdate);
				    $admindataUpdated = $this->getUserDetail($useridToUpdate);                                                                         
				    //print_r($admindataUpdated);
				    $this->updateUserValues($admindataUpdated);                                     
				    
				} 
				
				return (($retval!=0)?1:0);		
		}
		function unSetSiteCookieInDatabase()
		{
				$lastlogindatetime = date("Y-m-d H:i:s");
				$lastlogindevice = '0'; // keep 0 for time being for desktop once we start identifying devices then we make it 1 for tablet and 2 for mobile
			
				//$appData['lastlogindatetime']	= $lastlogindatetime;
				$appData['loggedoutdatetime']	= $lastlogindatetime;
				$appData['lastlogindevice']		= $lastlogindevice;
				$appData['isUserLoggedIn']		= '0';
				$appData['lastusertoken']		= '';
				
				$useridToUpdate=$this->userid;
				$wherecondition =   array("userid" => $useridToUpdate);
				$retval = $this->EditUser($appData,$wherecondition);
				return (($retval!=0)?1:0);		
		}	
		
		function updateUserValues($uservalueArray='')
		{
			if(is_array($uservalueArray))
			{
			    //global $G_UserPermission;
				$this->userid 			= $uservalueArray[0]['USERID'];	
				$this->bankid           = $uservalueArray[0]['BANKID'];
                $this->roleid           = $uservalueArray[0]['ROLEID'];	
                $this->branchid         = $uservalueArray[0]['BRANCHID'];	
                $this->bankuserid       = $uservalueArray[0]['BANKUSERID'];	
				$this->username			= $uservalueArray[0]['USERNM'];
        		$this->usermobileno     = $uservalueArray[0]['USERMOBILE'];	
        		$this->fullname         = $uservalueArray[0]['FULLNAME'];	
        		$this->userphoto         = $uservalueArray[0]['FULLNAME'];	
        		$this->usermakerid          = $uservalueArray[0]['MAKERID'];	
        		$this->userauthoriserid         = $uservalueArray[0]['AUTHORISERID'];	
        		$this->userstatus         = $uservalueArray[0]['ACTIVE'];	

                
      		    
      		    session::start_secure_session();
      		    session::add_param('userid',$this->userid);
		        session::add_param('bankid',$this->bankid);
                session::add_param('roleid',$this->roleid);
		        session::add_param('branchid',$this->branchid);
		        session::add_param('bankuserid',$this->bankuserid);
			    session::add_param('username',$this->username); 
			    session::add_param('usermobileno',$this->usermobileno); 
			    session::add_param('fullname',$this->fullname); 
			    session::add_param('userphoto',$this->userphoto); 
	            session::add_param('usermakerid',$this->usermakerid); 
			    session::add_param('userauthoriserid',$this->userauthoriserid); 
			    session::add_param('userstatus',$this->userstatus);                                       
                
                                                                                           
				$this->UpdateSessionValueToVariables();                
			}
		}
		      
    function UserCheckPermission($USERID)    
    {      
        global $G_UserPermission;                 
         $query="SELECT a.USERID,a.USERROLEASSIGNMSTID,a.ROLEID,a.MODULEID,a.ADD,a.EDIT,a.VIEW,a.DELETE,a.AUTHORISE,b.ROLENAME,c.MODULENAME,c.MODULEPAGENAME,c.TABLENAME,c.MAINMENUNAME
                FROM USERROLEASSIGNMST a 
                INNER join ROLEMST b on a.ROLEID=b.ROLEID
                INNER join MODULESLIST c on a.MODULEID=c.MODULEID                                       
                where a.USERID=$USERID and b.ACTIVE=1 and c.ACTIVE=1";        
        $data = $this->getUserInfo($query);
        
        $count = count($data);     
      
        if($count > 0)
        {   
            for($i=0;$i<$count;$i++)                     
            {                   
                //$MODULENAME         = str_replace(" ","_",$data[$i]['MODULENAME']);  
                $MODULEPAGENAME         = $data[$i]['MODULEPAGENAME'];  
                $array[$MODULEPAGENAME] = array($data[$i]); 
            }
        }                                                                    
        session::start_secure_session();
      	session::add_param('UserPermission',$array);
        $G_UserPermission	= session::get_param('UserPermission');	         
        return  $G_UserPermission;
    }
    
    
    function Menu($USERID,$activemodule="")        
    {      
                          
           $query="SELECT a.USERID,a.USERROLEASSIGNMSTID,a.ROLEID,a.MODULEID,a.ADD,a.EDIT,a.VIEW,a.DELETE,a.AUTHORISE,b.ROLENAME,c.MODULENAME,c.MODULEPAGENAME,c.TABLENAME,c.MAINMENUNAME,c.MENU,c.MENUICON
                FROM USERROLEASSIGNMST a 
                INNER join ROLEMST b on a.ROLEID=b.ROLEID
                INNER join MODULESLIST c on a.MODULEID=c.MODULEID                                                           
                where a.USERID=$USERID and b.ACTIVE=1 and c.ACTIVE=1 GROUP by c.MENU ORDER by c.MODULEID asc";        
        $data = $this->getUserInfo($query);
                                               
        $count = count($data);                                                                   
       
        if($count > 0)                                                                                             
        {                                             
                                         
            for($i=0;$i<$count;$i++)                                                            
            {                                                                                                                        
                $MENUICON         = $data[$i]['MENUICON'];  
                $MENU         = $data[$i]['MENU'];  
                 $MasterMenu= $this->MasterMenu($USERID,$MENU,$activemodule);             
                 
                 if($activemodule == $data[$i]['MODULEPAGENAME'])
                 {
                    $displaydata .='<li class="nav-item has-treeview menu-open">
                          <a href="#" class="nav-link">
                            <i class="'.$MENUICON.'"></i>
                            <p>                                  
                             '.$MENU.'                                                
                              <i class="right fas fa-angle-right"></i>
                            </p>
                          </a>                                                      
                         <ul class="nav nav-treeview" style="display: block;"> 
                          '.$MasterMenu.'
                         </ul>
                        </li>
                      ';  
                 }
                 else
                 {
                                                       
                 $displaydata .='<li class="nav-item has-treeview">
                          <a href="#" class="nav-link">
                            <i class="'.$MENUICON.'"></i>
                            <p>                                  
                             '.$MENU.'                                                
                              <i class="right fas fa-angle-right"></i>
                            </p>
                          </a>                                                      
                         <ul class="nav nav-treeview"> 
                          '.$MasterMenu.'
                         </ul>
                        </li>
                      ';  
                 }
            }                                          
           
        }                                                                    
           
        return  $displaydata;
    }
    
    
    function MasterMenu($USERID,$MENU,$activemodule='')     
    {      
                          
           $query="SELECT a.USERID,a.USERROLEASSIGNMSTID,a.ROLEID,a.MODULEID,a.ADD,a.EDIT,a.VIEW,a.DELETE,a.AUTHORISE,b.ROLENAME,c.MODULENAME,c.MODULEPAGENAME,c.TABLENAME,c.MAINMENUNAME
                FROM USERROLEASSIGNMST a 
                INNER join ROLEMST b on a.ROLEID=b.ROLEID      
                INNER join MODULESLIST c on a.MODULEID=c.MODULEID                                                           
                where a.USERID=$USERID and MENU='$MENU' and b.ACTIVE=1 and c.ACTIVE=1 GROUP by c.MAINMENUNAME ORDER by c.MODULEID asc";        
        $data = $this->getUserInfo($query);
                                               
        $count = count($data);     
      
        if($count > 0)                                                                                             
        {                                             
                                         
            for($i=0;$i<$count;$i++)                                        
            {                                                                                                                        
                $MAINMENUNAME         = $data[$i]['MAINMENUNAME'];  
                 $submenu= $this->MasterSubMenu($USERID,$MAINMENUNAME,$activemodule);
                 
                 if($activemodule == $data[$i]['MODULEPAGENAME'])
                 {
                     $displaydata .='<li class="nav-item has-treeview menu-open">
                              <a href="#" class="nav-link">
                                <i class="far fa-circle nav-icon"></i>
                                <p>                               
                                 '.$MAINMENUNAME.'                                                
                                  <i class="right fas fa-angle-right"></i>
                                </p>
                              </a>                                                      
                             <ul class="nav nav-treeview" style="display: block;"> 
                              '.$submenu.'
                             </ul>
                            </li>
                          '; 
                 }
                 else
                 {
                     $displaydata .='<li class="nav-item has-treeview">
                              <a href="#" class="nav-link">
                                <i class="far fa-circle nav-icon"></i>
                                <p>                               
                                 '.$MAINMENUNAME.'                                                
                                  <i class="right fas fa-angle-right"></i>
                                </p>
                              </a>                                                      
                             <ul class="nav nav-treeview"> 
                              '.$submenu.'
                             </ul>
                            </li>
                          ';      
                }
            }                                          
           
        }                                                                    
           
        return  $displaydata;
    }
    
    function MasterSubMenu($USERID,$MAINMENUNAME,$activemodule='')     
    {      
                      
         $query="SELECT a.USERID,a.USERROLEASSIGNMSTID,a.ROLEID,a.MODULEID,a.ADD,a.EDIT,a.VIEW,a.DELETE,a.AUTHORISE,b.ROLENAME,c.MODULENAME,c.MODULEPAGENAME,c.TABLENAME,c.MAINMENUNAME
                FROM USERROLEASSIGNMST a 
                INNER join ROLEMST b on a.ROLEID=b.ROLEID
                INNER join MODULESLIST c on a.MODULEID=c.MODULEID                                       
                where a.USERID=$USERID and MAINMENUNAME='$MAINMENUNAME' and b.ACTIVE=1 and c.ACTIVE=1";        
        $data = $this->getUserInfo($query);
        
        $count = count($data);     
      
        if($count > 0)
        {   
           
            for($i=0;$i<$count;$i++)                     
            {                                     
                $VIEW         = $data[$i]['VIEW'];
                $ADD         = $data[$i]['ADD'];
                $MODULENAME         = $data[$i]['MODULENAME'];
                $MODULEPAGENAME         = $data[$i]['MODULEPAGENAME'];
                
                $activeclass = $data[$i]['MODULEPAGENAME'] == $activemodule ? 'active' : '';
                if($VIEW == 1)
                {
                    $subdata .='<li class="nav-item '.$activeclass.'">
                                  <a href="'.DOC_ROOT.$MODULEPAGENAME.'/view" class="nav-link">  
                                    <i class="far fa-dot-circle nav-icon"></i>
                                    <p>'.$MODULENAME.'</p>
                                  </a>
                                </li>';
                }
                else if($ADD == 1)
                {                                          
                     $subdata .='<li class="nav-item '.$activeclass.'">
                                  <a href="'.DOC_ROOT.$MODULEPAGENAME.'/add" class="nav-link">  
                                    <i class="far fa-dot-circle nav-icon"></i>
                                    <p>'.$MODULENAME.'</p>
                                  </a>
                                </li>';
                }
                else
                {
                    $subdata .='';
                }
            }
             
        }                                                                    
           
        return  $subdata;
    } 
		function UpdateSessionValueToVariables()
		{
			global $G_userid;
			global $G_bankid;
			global $G_roleid;
			global $G_branchid;
			global $G_bankuserid;
			global $G_username;
			global $G_usermoblieno;
			global $G_fullname;
			global $G_userphoto;   
			global $G_usermakerid;
			global $G_userauthoriserid;
			global $G_userstatus;         
			global $G_UserPermission;
          
                
			$G_userid		        = session::get_param('userid');
			$G_bankid               = session::get_param('bankid');
            $G_roleid               = session::get_param('roleid');
			$G_branchid             = session::get_param('branchid');
            $G_bankuserid           = session::get_param('bankuserid');
			$G_username		        = session::get_param('username');
			$G_usermobileno         = session::get_param('usermobileno'); 
            $G_fullname             = session::get_param('fullname'); 
			$G_userphoto            = session::get_param('userphoto'); 
			$G_usermakerid          = session::get_param('usermakerid'); 
            $G_userauthoriserid     = session::get_param('userauthoriserid'); 
			$G_userstatus           = session::get_param('userstatus'); 
            $G_UserPermission       = $this->UserCheckPermission($G_userid);
           
			

		}
		
		 
	function GETUserCheckModulesPermission($G_userid,$G_UserPermission,$Module,$page)    
    {   
        if($G_userid > 0)
        {
            $PagePermission = $G_UserPermission[$Module][0][$page]; 
        }
        return  $PagePermission;
    }
    
 
    
	
    }
?>