<?php 
/*
 * All User Entity Logics should come here.
 */
class Group{
   /*
Function to Register a  new Customer
*/
   public static  function createGroup($objGroupVo)
 {         
            $objResult                      =   new Messages();
            $objResult->status              =   "SUCCESS";
//           //Check Entered User Email Exists OR NOT then stop user sign up if email exists
//            $objUserEmailCount              =   self::checkUserEmailExists($objUserVo->email);
//                    if($objUserEmailCount>0) {
//                        $objResult->status          =   "ERROR";
//                        $objResult->message         =   USER_EMAIL_EXIST; // Email Alreday Exists
//                    }
//         //  Check Entered User name  Exists OR NOT then stop user sign up if username  exists
//          $objUsernameCount              =   self::checkUserNameExists($objUserVo->user_name);
//                    if($objUsernameCount>0) {
//
//                            $objResult->status         =   ERROR;
//                            $objResult->message        =   USER_NAME_EXIST; // Username  Alreday Exists
//                    }
//        // Insert User data to to User table 
                if($objResult->status=="SUCCESS") {
                 $db                             =   new Db();

                 $tableName                      =   Utils::setTablePrefix('groups');
                 
                 $excludeId                      =    '';
                 
                 $GroupAliasName                  =   Utils::generateAlias($tableName,$objGroupVo->bbf_group_name, $idColumn="bbf_group_id",$id = $excludeId, $aliasColumn="bbf_group_alias");


                 $groupId                     =   $db->insert($tableName, array(  'bbf_group_name'     =>  Utils::escapeString($objGroupVo->bbf_group_name),
                                                                                     'bbf_status'     =>  Utils::escapeString($objGroupVo->bbf_status),
                                                                                     'bbf_image_id'    => $objGroupVo->bbf_image_id,
                                                                                     'bbf_created_by'    =>  $objGroupVo->bbf_created_by,
                                                                                     'bbf_created_on'    =>  $objGroupVo->bbf_created_on,
                                                                                     'bbf_group_alias'         =>  Utils::escapeString($GroupAliasName)
                                                                                  ));
                 $objUserVo->bbf_group_id              =   $groupId;
                 $objResult->data                 =   $objGroupVo;
          }
          Logger::info($objResult);
          return $objResult;
                
 }   
 
 
 
  /*
Function to edit user profile information
   * Parameter -  Group Data
*/
  public  function editGroup($groupId='',$objGroupVo)
 {
      
      
       $objResult                      =   new Messages();
            $objResult->status              =   "SUCCESS";
          //Check Entered User Email Exists OR NOT then stop user sign up if email exists
          
                    if($groupId == '') {
                        $objResult->status          =   "ERROR";
                        $objResult->message         =   GROUP_ID_NOT_EXIST; // Email Alreday Exists
                    }

        
                    
        // Update Group data to  User table 
                 
                if($objResult->status=="SUCCESS") {

                 $db                             =   new Db();

                 $tableName                      =   Utils::setTablePrefix('groups');
                 $where                          =   "bbf_group_id = ".Utils::escapeString($groupId)." ";
                 $customerId                     =   $db->update($tableName, array( 'bbf_group_name'     =>  Utils::escapeString($objGroupVo->bbf_group_name),
                                                                                     'bbf_status'     =>  Utils::escapeString($objGroupVo->bbf_status),
                                                                                     'bbf_image_id'    => $objGroupVo->bbf_image_id,
                                                                                     'bbf_created_by'    =>  $objGroupVo->bbf_created_by,
                                                                                     'bbf_created_on'    =>  $objGroupVo->bbf_created_on,
                                                                                    
                                                                                   ),$where,$doAudit=false);
                 $objUserVo->bbf_group_id         =   $groupId;
                 $objResult->data                 =   $objGroupVo;

          }

          Logger::info($objResult);

          return $objResult;
     
                
 }  
 
  /*
Function to check Customer Exists or not if exists re-direct to login 
   * Parameters  : Username , Email Address , Password
*/

  /*
Function to check Customer Exists or not if exists re-direct to login 
   * Parameters  : User Id 
*/
 public static function changeGroupStatus($groupId,$objGroupVo='')
 {         
            $objResult                      =   new Messages();
            $objResult->status              =   "SUCCESS";
         //  Check Entered User Id  exists in the system
         if($userId!='') {  
             
                                 $objResult->status           =   "ERROR";
                                 $objResult->message          =   GROUP_ID_NOT_EXIST; // User Id not  Exists
                         
         }         
        // Update User status to deleted  if user  already exists
                if($objResult->status=="SUCCESS") {

                 $db                             =   new Db();
                 $tableName                      =   Utils::setTablePrefix('groups');
                 $selectCase                     =   '';
              
                 $where                          =  "bbf_group_id='".Utils::escapeString($groupId)."' ";    
                 $resultRows                     =  $db->update($tableName, array( 'bbf_status'     =>  Utils::escapeString($objGroupVo->bbf_status),
                                                                                  ),$where,$doAudit=false);
                 // Update  User Account with deleted status  and Set Corresponding Message
                 if($resultRows>0)
                 { 
                      $objResult->message        =   USER_DELETED_SUCCESS; // User Deleted Successfully
                 }
                 
          }

            logger::info($objResult);
            return $objResult;

 }
 
  /*
Function to get user details
   * Parameters  : User id
*/
 public static function getUser($userId)
 {         
                $objResult                        =   new Messages();
                $objResult->status                =   "SUCCESS";
         //Select User Record If User id is not null
                if($userId!='') {
                 $db                             =   new Db();
                 $tableName                      =   'users';
                 $selectCase                     =   '  user_id ='.Utils::escapeString($userId).' ';
                 logger::info($selectCase);
                 
                 $objResultRow                   =  $db->selectRecord($tableName,'*',$selectCase);
         // If user exists then assign user data to result object
                 if($objResultRow)
                      $objResult->data           =   $objResultRow; // Assign user record  to object
                 else{
                     $objResult->status          =   "ERROR";
                     $objResult->message         =   USER_ID_NOT_EXIST; // User not exists
                  }
          }

            logger::info($objResult);
            return $objResult;
 }
 
  /*
Function to update user password
   * Parameters  : User value object , userId , new password
*/
 public static function updatePassword($objUserVo)
 {      
                $objResult                          =   new Messages();
                $objResult->status                  =   "SUCCESS";
         //Update User Password
                if($objUserVo->user_id!='') {
                    $db                             =   new Db();
                    $tableName                      =   Utils::setTablePrefix('users');
                    $where                          =   "user_id='".Utils::escapeString($objUserVo->user_id)."' "; 
                    $resultRows                     =   $db->update($tableName, array('password'     =>  Utils::escapeString(md5($objUserVo->newpassword)),
                                                                                  ),$where,$doAudit=false);
                 if($resultRows>0){
                      $objResult->message           =   USER_PASSWORD_UPDATED_SUCCESS; // User password changed successfully
                      $objUserVo->password          =   $objUserVo->newpassword;
                      $objResult->data              =   $objUserVo;
                 }   
                 else {  // Reset password failed
                       $objResult->status           =   "ERROR";
                       $objResult->message          =   USER_PASSWORD_UPDATED_FAILED;
                 }
          }

            logger::info($objResult);
            return $objResult;
 }
 
  /*
Function to reset user password
   * Parameters  : User id
*/
 public static function resetPassword($userId)
 {      
                $objResult                              =   new Messages();
                $objResult->status                      =   "SUCCESS";
         //Update User Password
                if($userId!='') {
                    $objUserCount                       =   self::checkUserExists($userId);
                    //If User exists then reset User password
                    if($objUserCount>0){
                        $db                             =   new Db();
                        $newPassword                    =   Utils::generateRandomPassword();
                        $tableName                      =   Utils::setTablePrefix('users');
                        $where                          =   "user_id='".Utils::escapeString($userId)."' "; 
                        $resultRows                     =   $db->update($tableName, array('bbf_password'     =>  Utils::escapeString(md5($newPassword)),
                                                                                      ),$where,$doAudit=false);
                                                                                      
                        // generating and adding the random key
                        $tableName                      =   Utils::setTablePrefix('pwd_requests');
						$activationkey 					= 	Utils::generateResetPasswordActivationKey();
                 		$customerId                    	=   $db->insert($tableName, array(  'pr_userid' => $userId,
                                                                                     		'pr_key'    =>  $activationkey,
                                                                                     		'pr_date'   =>  time(),
                                                                                     		'pr_status' => 1 ));   
						$objUserVo->resetkey = $activationkey;
                                                                                  		
                                                                                      
                    }  else{
                        $objResult->status          =   "ERROR";
                        $objResult->message         =   USER_ID_NOT_EXIST; // User not exists
                    } 
                    
                 if($resultRows>0){
                      $objResult->message           =   USER_PASSWORD_RESETTED_SUCCESS; // User password reset successfully
                      $objUserVo->password          =   $newPassword;
                      $objResult->data              =   $objUserVo;
                 }   
                 else {  // Reset password failed
                       $objResult->status           =   "ERROR";
                       $objResult->message          =   USER_PASSWORD_RESETTED_FAILED;
                 }
          }

            logger::info($objResult);
            return $objResult;
 }
 
 /*
Function to publish a user
   * Parameters  : User id , publishedStatus
*/
 public static function publishUser($userId,$publishedStatus)
 {      
                $objResult                              =   new Messages();
                $objResult->status                      =   "SUCCESS";
                if($userId!='') {
                    //If User exists then activte a  User Account
                        $db                             =   new Db();
                        $tableName                      =   Utils::setTablePrefix('users');
                        $where                          =   "user_id='".Utils::escapeString($userId)."' "; 
                        $resultRows                     =   $db->update($tableName, array('published'     =>  Utils::escapeString($publishedStatus),
                                                                                      ),$where,$doAudit=false);
                    }  
                    
                    if($resultRows>0){
                         $objResult->message           =   USER_PUBLISHED_SUCCESS; // User Account published successfully
                    }   
                    else {  // Reset password failed
                          $objResult->status           =   "ERROR";
                          $objResult->message          =   USER_PUBLISHED_FAILURE;
                    }
                    
             logger::info($objResult);
             return $objResult;
 }
 
 /*
Function to list All Users
  * Paramater : Table Delimeters
  */
 public  function listUsers($objTableVo)
 {    
            if($objTableVo->coulmns=='')
            {
                $objTableVo->coulmns  = '*';
            }
            
             $objTableVo->tablename          =   'users';
             $objResult                      =   new Messages();
             $objResult->status              =   "SUCCESS";
             $db                             =   new Db();
             $objResultRows                  =   $db->getPagingData($objTableVo->coulmns,$objTableVo->tablename,$objTableVo->join,$objTableVo->criteria,$objTableVo->group_by,$objTableVo->sort_order,$objTableVo->sort_field,$objTableVo->limit);
            //Check User Details exist 
                  if($objResultRows)
              // Assign User details to object
                      $objResult->data             =    $objResultRows;          
                 else {
                        $objResult->status         =   "ERROR";
                        $objResult->message        =   USER_NOT_EXIST; // Store details not exists 
                     }
       
            Logger::info($objResult);
          
            return $objResult;
 } 
	
	/*
	 * function to update the password
	 */
	public function updateUserPassword($objPassword){
		$tableName                      =  'pwd_requests';
        $db                             =   new db();
        $requestkey = $objPassword->resetkey;
        if($requestkey != ''){
        	// get the userid from the pwd reset key
        	$userId =  $db->selectRow($tableName,'pr_userid','pr_key = "'.Utils::escapeString($requestkey).'" ' );
        	if($userId){ // valid activation key
        		$objUserPwd    				= new stdClass();
        		$objUserPwd->user_id 		= $userId;
        		$objUserPwd->newpassword 	= $objPassword->password;
        		$objResult = self::updatePassword($objUserPwd);
          	}
        	else {		// invalid activation key
        		$objResult                   =   new Messages();
        		$objResult->status           =   "ERROR";
                $objResult->message          =   PWD_RESET_INVALID_KEY;
        	}
        	return $objResult;
        }
	}
	
	
}
?>