<?php
// 'user' object
class AppUser{
 
    // database connection and table name
    private $conn;
    private $table_name = "AppUsers";
 
    // object properties
    public $id;
	public $email;
    public $name;
    public $surname;
    public $celnr;
    public $country;
    public $address1;
    public $address2;
    public $photo;
    public $password;
    public $resetPasswordCode;
    public $consultantId;
    public $consultantEmail;
    public $verificationCode;
    public $accountVerification;
    public $notifications;
    public $userProfile;
    public $versionControl = 0;
	public $feedback;

	
 
    // constructor
    public function __construct($db){
        $this->conn = $db;
    }
 
// create new AppUser record
//=================== SAIA, Not PocketStylists ===================
function create(){
 
    // insert query
    $query = "INSERT INTO `AppUsers` ( `email`, `name`, `surname`, `celnr`,`address1`, `address2`, `password`,`photo`,`consultant_id`) VALUES (:email,:name,:surname,:celnr,:address1,:address2,:password,:photo,:consultantId)";
 
    // prepare the query
    $stmt = $this->conn->prepare($query);
 
    // sanitize
    $this->name=htmlspecialchars(strip_tags($this->name));
    $this->surname=htmlspecialchars(strip_tags($this->surname));
    $this->email=htmlspecialchars(strip_tags($this->email));
    $this->celnr=htmlspecialchars(strip_tags($this->celnr));
    $this->address1=htmlspecialchars(strip_tags($this->address1));
    $this->address2=htmlspecialchars(strip_tags($this->address2));
    $this->password=htmlspecialchars(strip_tags($this->password));
    
 
    // bind the values
    $stmt->bindParam(':name', $this->name);
    $stmt->bindParam(':surname', $this->surname);
    $stmt->bindParam(':email', $this->email);
    $stmt->bindParam(':celnr', $this->celnr);
    $stmt->bindParam(':address1', $this->address1);
    $stmt->bindParam(':address2', $this->address2);
    
   
    // hash the password before saving to database
    $password_hash = password_hash($this->password, PASSWORD_BCRYPT);
    $stmt->bindParam(':password', $password_hash);
    $stmt->bindParam(':photo', $this->photo);
    $stmt->bindParam(':consultantId', $this->consultantId);


    //return $stmt->execute();
    if($stmt->execute()){
        if(strcmp($this->getAppUserId(),"true")==0){
             return "true";
        }else{
             $this->id = 0;
             return "true";
        }
       
    }

    // execute the query, also check if query was successful
   // if($stmt->execute()){
   //     return true;
   // }
 
    return "false";
}



// =================== Update AppUser =============================
//=================== SAIA, Not PocketStylists ===================

function updateAppUserSaia(){
    // insert query
    $noPhoto="NO PHOTO";
    if(strcmp($this->photo,$noPhoto)==0){
       $query = "UPDATE `AppUsers` SET `email`=:email,`name`=:name,`surname`=:surname,`celnr`=:celnr,`address1`=:address1, `address2`= :address2, `consultant_id`=:consultantId, `updated_at`=:updateDateTime, `versionControl`=:versionControl WHERE `id`=:id ";
      // return  $query;
    }else{
       $query = "UPDATE `AppUsers` SET `email`=:email,`name`=:name,`surname`=:surname,`celnr`=:celnr,`address1`=:address1, `address2`= :address2,`photo`=:photo, `consultant_id`=:consultantId, `updated_at`=:updateDateTime,`versionControl`=:versionControl WHERE `id`=:id ";
    }
    
   //  $query = "UPDATE `AppUsers` SET `email`=:email,`name`=:name,`surname`=:surname,`celnr`=:celnr,`consultant_id`=:consultantId WHERE `id`=:id ";
 
    // prepare the query
    $stmt = $this->conn->prepare($query);
 
    // sanitize
    $this->name=htmlspecialchars(strip_tags($this->name));
    $this->surname=htmlspecialchars(strip_tags($this->surname));
    $this->email=htmlspecialchars(strip_tags($this->email));
    $this->celnr=htmlspecialchars(strip_tags($this->celnr));
    $this->address1=htmlspecialchars(strip_tags($this->address1));
    $this->address2=htmlspecialchars(strip_tags($this->address2));
    $this->versionControl=htmlspecialchars(strip_tags($this->versionControl));
 
    // bind the values
    $stmt->bindParam(':email', $this->email);
    $stmt->bindParam(':name', $this->name);
    $stmt->bindParam(':surname', $this->surname);

    $stmt->bindParam(':celnr', $this->celnr);
    $stmt->bindParam(':address1', $this->address1);
    $stmt->bindParam(':address2', $this->address2);
    if(strcmp($this->photo,$noPhoto)!=0){
         $stmt->bindParam(':photo', $this->photo);

    }
  
    $stmt->bindParam(':consultantId',  $this->consultantId);
    $stmt->bindParam(':id',  $this->id);
    $stmt->bindParam(':versionControl',  $this->versionControl);
    
    date_default_timezone_set('Africa/Johannesburg');
    $dateTime = date('Y-m-d H:i:s', strtotime("now"));

    
     $stmt->bindParam(':updateDateTime', $dateTime );

     $stmt->execute();
     
     $count = $stmt->rowCount();

    if($count > '0'){
       return "true";
    }
    else{
        return "false";
    }
     

}
//========================== Update Password ========================
function updatePassword(){
     $query = "UPDATE `AppUsers` SET `password`=:password,`consultant_id`=:consultantId, `updated_at`=:updateDateTime WHERE `id`=:id ";
      // prepare the query
      
    $stmt = $this->conn->prepare($query);
     
     $this->password=htmlspecialchars(strip_tags($this->password));
    // hash the password before saving to database
    $password_hash = password_hash($this->password, PASSWORD_BCRYPT);

    
    $stmt->bindParam(':password', $password_hash);
    $stmt->bindParam(':consultantId',  $this->consultantId);
       
    $stmt->bindParam(':id',  $this->id);

    date_default_timezone_set('Africa/Johannesburg');
    $dateTime = date('Y-m-d H:i:s', strtotime("now"));
   // $currentDateTime = date('Y-m-d H:i:s');
    //return  $dateTime;
    
     $stmt->bindParam(':updateDateTime', $dateTime );
      $stmt->execute();
     
     $count = $stmt->rowCount();

    if($count > '0'){
       return "true";
    }
    else{
        return "false";
    }
}

//=================================================================


function getAppUserId(){
    
    // query to check if email exists
    $query = "SELECT id FROM `AppUsers`  WHERE email = :email
            LIMIT 0,1";
 
    // prepare the query
    $stmt = $this->conn->prepare( $query );
 
    // sanitize
    $this->email=htmlspecialchars(strip_tags($this->email));
 
    // bind given email value
    $stmt->bindParam(':email', $this->email);
 
    // execute the query
    $stmt->execute();
 
    // get number of rows
    $num = $stmt->rowCount();
 
    // if email exists, assign values to object properties for easy access and use for php sessions
    if($num>0){
 
        // get record details / values
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
 
        // assign values to object properties
        $this->id = $row['id'];
 
        // return true because email exists in the database
        return "true";
    }
     return "false";
    
}

function getAllUsers(){
     $response = array();
      // query to check if email exists
    $query = "SELECT `id`, `email`, `name`, `surname`, `celnr` FROM `AppUsers` WHERE `consultant_id` = ?";
    
             // prepare the query
    $stmt = $this->conn->prepare( $query );

      // bind given consultantId 
    //   $stmt->bindParam(':clubid',  $clubid, PDO::PARAM_INT);
    $stmt->bindParam(1, $this->consultantId);
    $stmt->execute(); 
    $num = $stmt->rowCount();
    if ($stmt->rowCount() > 0) {
       

        $response["Status"] = "Success";
	    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
			$innerObject["id"] = $row["id"];
			$innerObject["email"] = $row["email"];
			$innerObject["name"] = $row["name"];
			$innerObject["surname"] = $row["surname"];
			$innerObject["celnr"] = $row["celnr"];
			$innerObject["consultantId"] = $this->consultantId ;
		  $response["userList"][] = $innerObject;
		 }
	    return 	json_encode($response);
      
    }else{
         //$response["userList"]["Error"] = "Error";
         $response["Status"] = "No Data";
         return json_encode($response);
    }
}

function getSingleUser(){
     $response = array();
      // query to check if email exists
    $query = "SELECT `id`, `email`, `name`, `surname`, `celnr`,`address1`, `address2`, `photo` FROM `AppUsers` WHERE `id` =:clientId";
    
             // prepare the query
    $stmt = $this->conn->prepare( $query );

      // bind given consultantId 
    //   $stmt->bindParam(':clubid',  $clubid, PDO::PARAM_INT);
  //  $stmt->bindParam(1, $this->id);
    $stmt->bindParam(':clientId',  $this->id);
    $stmt->execute(); 
    $num = $stmt->rowCount();

    if ($stmt->rowCount() > 0) {
       

        $response["Status"] = "Success";
	    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
			$innerObject["id"] = $row["id"];
			$innerObject["email"] = $row["email"];
			$innerObject["name"] = $row["name"];
			$innerObject["surname"] = $row["surname"];
			$innerObject["celnr"] = $row["celnr"];
			$innerObject["address1"] = $row["address1"];
			$innerObject["address2"] = $row["address2"];
			$innerObject["photo"] =  base64_encode($row["photo"]);
			$innerObject["consultantId"] = $this->consultantId ;
		  $response["userList"][] = $innerObject;
		 }
	    return 	json_encode($response);
      
    }else{
         //$response["userList"]["Error"] = "Error";
         $response["Status"] = "No Data";
         return json_encode($response);
    }
}

//=============================================================================
//***************       POCKETSTYLIST CODE    *********************************
//==============================================================================


//==================== Register Email Address =====================

function registerUser(){

    try{
          // insert query
         $query = "INSERT INTO `AppUsers` ( `email`, `name`,`celnr`,`country`, `password`, `verification_code`,`versionControl`) VALUES (:email,:name,:celnr,:country,:userPassword, :verificationCode, :versionControl)";
 
        // prepare the query
         $stmt = $this->conn->prepare($query);
 

        $versionControl = 1;
     
        // bind the values
        $stmt->bindParam(':name', $this->name);
    
        $stmt->bindParam(':email', $this->email);
        $stmt->bindParam(':celnr', $this->celnr);
        $stmt->bindParam(':country', $this->country);
        // hash the password before saving to database
        $password_hash = password_hash($this->password, PASSWORD_BCRYPT);
        $stmt->bindParam(':userPassword', $password_hash);
        $stmt->bindParam(':verificationCode', $this->verificationCode);
        $stmt->bindParam(':versionControl', $versionControl);

        if($stmt->execute()){
            $true = "true";
    
            if(strcmp($this->getAppUserId(), $true)==0){
                 return "true";
            }else{
                 $this->id = 0;
                 return "false";
            }
           
        }else{
                 $this->id = 0;
                 return "false";
            
        }
        
    }catch (Exception $e){
        $this->id = 0;
        $this->feedback =  $e;
        return "false";
    }

}


function resetPassword($confirmationCode,$newPassword){

      //== query to check if confirmation code exists and allocated to email==
    $query = "SELECT `id` FROM `AppUsers` WHERE `email` = :email and `resetPasswordCode` = :verificationCode";

    //=== prepare the query
    $stmt = $this->conn->prepare( $query );

    //== bind given values
    $stmt->bindParam(':email', $this->email);
    $stmt->bindParam(':verificationCode', $confirmationCode);

    // execute the query
    $stmt->execute();
 
    // get number of rows
    $num = $stmt->rowCount();
 
    // if email exists, assign values to object properties for easy access and use for php sessions
    if($num>0){
 
        // get record details / values
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
 
        // assign values to object properties
        $this->id = $row['id'];
        if($this->id > 0){
            $resetStatus = $this->updateUserPassword($newPassword,$this->id);

        }else{
            $resetStatus = "false";
        }
        if(strcmp($resetStatus, "true") == 0){
            return "Password Changed";
            
        }else{
            return "Could not Change Password. Unable to save.";
        }
       

    }else{
         return "Could not Change Password. Invalid credentials.";
    }
    
}

function updateUserPassword($newPassword,$recId){
   // date_default_timezone_set('Africa/Johannesburg');
   // $date = date('Y-m-d H:i:s');
    date_default_timezone_set('Africa/Johannesburg');
    $dateTime = date('Y-m-d H:i:s', strtotime("now"));
    
   $query = "UPDATE `AppUsers` SET `password`=:newPassword,resetPasswordDate =:updateDate,resetPasswordCode =:resetPasswordCode WHERE `id`=:id ";
      // prepare the query
      
    $stmt = $this->conn->prepare($query);
    
    $password_hash = password_hash($newPassword, PASSWORD_BCRYPT);
    $emptyResetCode = "";
    $stmt->bindParam(':newPassword',  $password_hash);
    $stmt->bindParam(':updateDate',  $dateTime);
    $stmt->bindParam(':resetPasswordCode',  $emptyResetCode);
    $stmt->bindParam(':id', $recId);
    $stmt->execute();
     
     $count = $stmt->rowCount();

    if($count > 0){
       return "true";
    }
    else{
        return "false";
    }  
}
//========================= Verify if account exists ==========================
function verifyAccount(){
      // query to check if email exists
    $query = "SELECT `id` FROM `AppUsers` WHERE `email` = :email and `verification_code` = :verificationCode";

    // prepare the query
    $stmt = $this->conn->prepare( $query );
 
    // sanitize
    $this->email=htmlspecialchars(strip_tags($this->email));
     $this->verificationCode=htmlspecialchars(strip_tags($this->verificationCode));
 
    // bind given email value
    $stmt->bindParam(':email', $this->email);
    $stmt->bindParam(':verificationCode', $this->verificationCode);

    // execute the query
    $stmt->execute();
 
    // get number of rows
    $num = $stmt->rowCount();
 
    // if email exists, assign values to object properties for easy access and use for php sessions
    if($num>0){
 
        // get record details / values
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
 
        // assign values to object properties
        $this->id = $row['id'];
       $updateVerificationStatus = $this->updateAccountVerificationStatus();

 
        // return true because email exists in the database
        return true;
    }
 
    // return false if email does not exist in the database
    return false;
    
}

//===================== Verify Account based on WJT email ==============

function verifyAccountJwt(){
         // query to check if email exists
    $query = "SELECT `id` FROM `AppUsers` WHERE `email` = :email ";

    // prepare the query
    $stmt = $this->conn->prepare( $query );
 
    // sanitize
    $this->email=htmlspecialchars(strip_tags($this->email));

    // bind given email value
    $stmt->bindParam(':email', $this->email);

    // execute the query
    $stmt->execute();
 
    // get number of rows
    $num = $stmt->rowCount();
 
    // if email exists, assign values to object properties for easy access and use for php sessions
    if($num>0){
 
        // get record details / values
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
 
        // assign values to object properties
        $this->id = $row['id'];
       $updateVerificationStatus = $this->updateAccountVerificationStatus();

 
        // return true because email exists in the database
        return true;
    }
 
    // return false if email does not exist in the database
    return false;
    
}

//============ Verify if account exists and if jwt id, email is same person ===
function verifyJwtIdEmail($email,$id){
         // query to check if email exists
    $query = "SELECT count(`id`) as countId FROM `AppUsers` WHERE `email` = :email and id =:id";

    // prepare the query
    $stmt = $this->conn->prepare( $query );
 
    // sanitize
   // $email=htmlspecialchars(strip_tags($email));
   // $id=htmlspecialchars(strip_tags($id));
    // bind given email value
    $stmt->bindParam(':email', $email);
    $stmt->bindParam(':id', $id);
    // execute the query
    $stmt->execute();
 
    // get number of rows
    $num = $stmt->rowCount();

    // if email exists, assign values to object properties for easy access and use for php sessions
    if($num>0){

        // get record details / values
         $row = $stmt->fetch(PDO::FETCH_ASSOC);
         if($row['countId']>0){
            $this->populateUser($id);
             return true;
         }
         


    }
 
    // return false if email does not exist in the database
    return false;
    
}

function populateUser($id){
    
     $query = "SELECT * FROM `AppUsers` WHERE  id =:id";

    // prepare the query
    $stmt = $this->conn->prepare( $query );
    $stmt->bindParam(':id', $id);
    // execute the query
    $stmt->execute();
    $num = $stmt->rowCount();
    if($num>0){
         $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $this->name = $row['name'];
        $this->email = $row['email'];
        $this->celnr = $row['celnr'];



    }
}

//========================== Save userProfiles=================================
function saveUserProfile($profile){
    try{
          $query = "UPDATE `AppUsers` SET `name`=:name,
        `celnr`=:celnr,`country`=:country,
        `userProfile`= :userProfile,
        `consultant_id`=:consultantId,
        `consultantEmail`=:consultantEmail,
        `notifications`=:notifications,
        `versionControl`=:versionControl 
        WHERE `id`=:id ";
      // prepare the query
      
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':name', $this->name);
        $stmt->bindParam(':celnr', $this->celnr);
        $stmt->bindParam(':country', $this->country);
        $stmt->bindParam(':userProfile', $profile);
        $stmt->bindParam(':consultantId', $this->consultantId);
        $stmt->bindParam(':consultantEmail',$this->consultantEmail);
        $stmt->bindParam(':notifications',$this->notifications);
        $stmt->bindParam(':versionControl',$this->versionControl);
        $stmt->bindParam(':id',  $this->id);
        $stmt->execute();
     
        $count = $stmt->rowCount();

        if($count > 0){
            return "true";
        }
        else{
            return "false";
        }
    }catch (Exception $e){
        return "false";
    }
   
}
function deleteUserAccount($emailToDelete,$idToDelete){
    try{
        $query = "SELECT  `email`, `country`, `userProfile`,`verified_date`,"
                  . "`sign_in_count`,`current_sign_in_at`,`last_sign_in_at`,"
                  . "`created_at`,`updated_at`,`consultant_id`,`consultantEmail`,"
                  . "`account_verification_status`,`versionControl`"
                  . " FROM `AppUsers` WHERE `id`=:id and "
                  . "`email` =:emailToDelete ";

                 // prepare the query
        $stmt = $this->conn->prepare( $query );
        $stmt->bindParam(':id', $idToDelete);
        $stmt->bindParam(':emailToDelete', $emailToDelete);
        $stmt->execute(); 
        $num = $stmt->rowCount();
        if ($stmt->rowCount() > 0) {
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $emailBackup = $row["email"];
                $countryBackup = $row["country"];
                $userProfileBackup = $row["userProfile"];
                $verifiedDateBackup = $row["verified_date"];
                $signInCountBackup = $row["sign_in_count"] ;
                $currentSignedInAtBackup = $row["current_sign_in_at"] ;
                $lastSignedInAtBackup = $row["last_sign_in_at"] ;
                $createdAtBackup = $row["created_at"] ;
                $updatedAtBackup = $row["updated_at"] ;
                $consultantIdBackup = $row["consultant_id"];
                $consultantEmailBackup = $row["consultantEmail"];
                $accountVerificationStatusBackup = $row["account_verification_status"];
                $versionControlBackup = $row["versionControl"];
            }


        }else{

             return "Auth DataError";
        }
        $query = "INSERT INTO `appuser_backup` ( `userId`,`country`, `userProfile`,"
                  . " `verified_date`,`sign_in_count`,`current_sign_in_at`,"
                . "`last_sign_in_at`,`created_at`,`updated_at`,`consultant_id`,"
                . "`consultantEmail`,`account_verification_status`,"
                . "`versionControl`)"
                . " VALUES "
                . "(:userId,:country,:userProfile, "
                . ":verified_date, :sign_in_count,:current_sign_in_at,"
                . ":last_sign_in_at,:created_at,:updated_at,:consultant_id,"
                . ":consultantEmail,:account_verification_status,:versionControl)";

            // prepare the query
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':userId', $idToDelete);   
        $stmt->bindParam(':country', $countryBackup);
        $stmt->bindParam(':userProfile', $userProfileBackup);
        $stmt->bindParam(':verified_date', $verifiedDateBackup);
        $stmt->bindParam(':sign_in_count', $signInCountBackup);
        $stmt->bindParam(':current_sign_in_at', $currentSignedInAtBackup);
        $stmt->bindParam(':last_sign_in_at', $lastSignedInAtBackup);
        $stmt->bindParam(':created_at', $createdAtBackup);
        $stmt->bindParam(':updated_at', $updatedAtBackup);
        $stmt->bindParam(':consultant_id', $consultantIdBackup);
        $stmt->bindParam(':consultantEmail', $consultantEmailBackup);
        $stmt->bindParam(':account_verification_status', $accountVerificationStatusBackup);
        $stmt->bindParam(':versionControl', $versionControlBackup);
        $stmt->execute();

        $query = "INSERT INTO `appuserdeletelog` "
                ."(`user`, `userId`, `dateDeleted`, `authorization`)"
                . " VALUES "
                . "(:user,:userId,:dateDeleted,:delAuthorization)";
        date_default_timezone_set('Africa/Johannesburg');
        $dateTime = date('Y-m-d H:i:s', strtotime("now"));

        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':user', $emailToDelete);
        $stmt->bindParam(':userId', $idToDelete);   
        $stmt->bindParam(':dateDeleted', $dateTime);
        $stmt->bindParam(':delAuthorization', $emailToDelete);   
        $stmt->execute();
        $query = "DELETE FROM `AppUsers` WHERE `id` =:id and `email` = :email";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':id', $idToDelete);
        $stmt->bindParam(':email', $emailToDelete);

        if($stmt->execute()){
            return "success";

        }else{

            return "error- unknown";

        }
    } catch (Exception $ex) {
        return "error- server";
    }
     
}



//==========================  Update Appuser with verification status ==========

function updateAccountVerificationStatus(){
     $query = "UPDATE `AppUsers` SET `account_verification_status`= 'Yes' WHERE `id`=:id ";
      // prepare the query
      
    $stmt = $this->conn->prepare($query);

    $stmt->bindParam(':id',  $this->id);
    $stmt->execute();
     
     $count = $stmt->rowCount();

    if($count > 0){
       return "true";
    }
    else{
        return "false";
    }
}

function updateResetAuthCode($email){
     $query = "UPDATE `AppUsers` SET `resetPasswordCode`= :resetCode WHERE `email`=:email ";
      // prepare the query
      
    $stmt = $this->conn->prepare($query);

    
    $stmt->bindParam(':resetCode',  $this->resetPasswordCode);
    $stmt->bindParam(':email',  $email);
    
    $stmt->execute();
     
     $count = $stmt->rowCount();
    // return $this->email;

    if($count > 0){
       return "true";
    }
    else{
        return "false";
    }
}

//================= Get verification Code for resend =========================

function getConfirmationCode($email){
     // query to check if email exists
    $query = "SELECT `verification_code` 
            FROM `AppUsers` 
            WHERE email = :email
            LIMIT 0,1";
 
    // prepare the query
    $stmt = $this->conn->prepare( $query );
 
    // sanitize
   
    // bind given email value
    $stmt->bindParam(":email", $email);
 
    // execute the query
    $stmt->execute();
 
    // get number of rows
    $num = $stmt->rowCount();
 
    // if email exists, assign values to object properties for easy access and use for php sessions
    $versionControl = 0;
    if($num>0){
 
        // get record details / values
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        // assign values to object properties

        $this->verificationCode = $row['verification_code'];
        // return true because email exists in the database
        return true;
    }
 
    // return false if email does not exist in the database
    return false;
    
}
//============================================================================

function updateVerificationCode(){
     $query = "UPDATE `AppUsers` SET `verification_code`= :code WHERE `email`=:email ";
      // prepare the query
      
    $stmt = $this->conn->prepare($query);

    
    $stmt->bindParam(':code',  $this->verificationCode);
    $stmt->bindParam(':email',  $this->email);
    
    $stmt->execute();
     
     $count = $stmt->rowCount();
    // return $this->email;

    if($count > 0){
       return "true";
    }
    else{
        return "false";
    }
}

//================= Get Password Reset AuthCode for Resend =====================

function getAuthCode($email){
     // query to check if email exists
    $query = "SELECT `resetPasswordCode` 
            FROM " . $this->table_name . "
            WHERE email = ?
            LIMIT 0,1";
 
    // prepare the query
    $stmt = $this->conn->prepare( $query );
 
    // sanitize
   
    // bind given email value
    $stmt->bindParam(1, $email);
 
    // execute the query
    $stmt->execute();
 
    // get number of rows
    $num = $stmt->rowCount();
 
    // if email exists, assign values to object properties for easy access and use for php sessions
    $versionControl = 0;
    if($num>0){
 
        // get record details / values
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        // assign values to object properties
        $this->resetPasswordCode = $row['resetPasswordCode'];
        // return true because email exists in the database
        return true;
    }
 
    // return false if email does not exist in the database
    return false;
    
}

 
// check if given email exist in the database and if account has already been verified. If not, resend verification cade and update db with new verification code.
function emailExists(){
 
    // query to check if email exists
    $query = "SELECT id, name, surname,celnr, password,account_verification_status,verification_code,versionControl 
            FROM " . $this->table_name . "
            WHERE email = ?
            LIMIT 0,1";
 
    // prepare the query
    $stmt = $this->conn->prepare( $query );
 
    // sanitize
    $this->email=htmlspecialchars(strip_tags($this->email));
 
    // bind given email value
    $stmt->bindParam(1, $this->email);
 
    // execute the query
    $stmt->execute();
 
    // get number of rows
    $num = $stmt->rowCount();
 
    // if email exists, assign values to object properties for easy access and use for php sessions
    $versionControl = 0;
    if($num>0){
 
        // get record details / values
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
 
        // assign values to object properties
        $this->id = $row['id'];
        $this->name = $row['name'];
        $this->surname = $row['surname'];
        $this->celnr = $row['celnr'];
        $this->password = $row['password'];
        $this->accountVerification = $row['account_verification_status'];
        $this->verificationCode =  $row['verification_code'];
        $versionControl = $row['versionControl'];
        $this->versionControl = $versionControl;
 
        // return true because email exists in the database
        return true;
    }
 
    // return false if email does not exist in the database
    return false;
}

 function sendEmail($code,$emailAddress){
     $msg = "Confirmation Code: " . $code;
      $msg = wordwrap($msg,70);
    $headers = "From: authenticator@pocketstylists.com";
    // send email
    $mailResults = mail($emailAddress,"PocketStylist Registration Confirmation Code",$msg,$headers);
    if($mailResults){
        return "Email send";
    }else{
        return "Could not send";
    }
 }
 
 //=============== Get Registration detail and user Profile from userID ========
 //=========== 2022-04-29 ================================
 
 function getAppUserProfile(){
     
         $response = array();
      // query to check if email exists
    $query = "SELECT  `email`, `name`, `celnr`,`country`, `userProfile`,`consultant_id`,`consultantEmail`,`notifications`,`versionControl` FROM `AppUsers` WHERE `id`=:id";
    
             // prepare the query
    $stmt = $this->conn->prepare( $query );
    $stmt->bindParam(':id', $this->id);
    $stmt->execute(); 
    $num = $stmt->rowCount();
    if ($stmt->rowCount() > 0) {
        $response["responseCode"] = 200;
	        $response["result"] = "found";
	    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
			$response["email"] = $row["email"];
			$response["name"] = $row["name"];
			$response["celnr"] = $row["celnr"];
			$response["country"] = $row["country"];
			$response["userProfile"] = $row["userProfile"] ;
			$response["consultantId"] = $row["consultant_id"] ;
			$response["consultantEmail"] = $row["consultantEmail"] ;
			$response["notifications"] = $row["notifications"] ;
			$response["versionControl"] = $row["versionControl"] ;
		 }
	    return 	json_encode($response);
      
    }else{
         //$response["userList"]["Error"] = "Error";
         $response["responseCode"] = 200;
         $response["result"] = "no data";
         	$response["email"] ="";
			$response["name"] = "";
			$response["celnr"] = "";
			$response["country"] = "";
			$response["userProfile"] ="" ;
			$response["consultantId"] = 0;
			$response["consultantEmail"] ="";
			$response["notifications"] = "";
			$response["versionControl"] = 0;
         return json_encode($response);
    }
     
 }
 
 //=========== Update UserPersonal detial. Single fields ==============
function updateAppUserPersonalDetails($updateType,$value,$versionControl){

	switch($updateType){
		case "name":
			$statementBuild = " `name`=:updateValue ";					
			break;
		case "email":
			$statementBuild = " `email`=:updateValue ";	
			$this->feedback = "New JWT";
			$this->email = $value;
			break;
		case "celnr":
			$statementBuild = " `celnr`=:updateValue ";	
			break;
		case "country":
			$statementBuild = " `country`=:updateValue ";	
			break;
		case "notifications":
			$statementBuild = " `notifications`=:updateValue ";	
			break;
		case "password":
			$statementBuild = " `password`=:updateValue ";	
			$password_hash = password_hash($value, PASSWORD_BCRYPT);
			$value = $password_hash;		
			break;
	}
	
	 $statementBuild = $statementBuild . ", `versionControl`=:versionControl, `updated_at`=:updateDateTime";
	

	$query = "UPDATE `AppUsers` SET ".$statementBuild. " WHERE `id`=:id ";
	
	
    //======= prepare the query  ==================   
	$stmt = $this->conn->prepare($query);
    
	$stmt->bindParam(':updateValue', $value);
	$stmt->bindParam(':versionControl', $versionControl);

	date_default_timezone_set('Africa/Johannesburg');
    $dateTime = date('Y-m-d H:i:s', strtotime("now"));
    $stmt->bindParam(':updateDateTime', $dateTime );
    $stmt->bindParam(':id', $this->id);

   
    $stmt->execute();
     
    $count = $stmt->rowCount();

    if($count > '0'){
       return "saved";
    }
    else{
        return "not saved";
    }
    return "saved";
    
}
 
//=========== Update only user data from UserSetup in App ==============
function updateAppUser(){
     
     $statementBuild = "";
     if(strcmp($this->email, "") != 0 ){
       //   $this->email=htmlspecialchars(strip_tags($this->email));
          $statementBuild = $statementBuild . " `email`=:email ";
         
     }
     
     if(strcmp($this->name, "") != 0 ){
       //  $this->name=htmlspecialchars(strip_tags($this->name));
         if($statementBuild != ""){
             $statementBuild = $statementBuild . ", `name`=:name ";
         }else{
              $statementBuild = $statementBuild . " `name`=:name ";
         }
     }
     
     if(strcmp($this->celnr, "") != 0 ){
       //   $this->celnr=htmlspecialchars(strip_tags($this->celnr));
         if($statementBuild != ""){
             $statementBuild = $statementBuild . ", `celnr`=:celnr ";
         }else{
              $statementBuild = $statementBuild . " `celnr`=:celnr ";
         }
     }
     
      if(strcmp($this->country, "") != 0 ){
       //  $this->country=htmlspecialchars(strip_tags($this->country));
         if($statementBuild != ""){
             $statementBuild = $statementBuild . ", `country`=:country ";
         }else{
              $statementBuild = $statementBuild . " `country`=:country ";
         }
     }
     
     if(strcmp($this->password, "") != 0 ){
       //  $this->country=htmlspecialchars(strip_tags($this->country));
         if($statementBuild != ""){
             $statementBuild = $statementBuild . ", `password`=:password ";
         }else{
              $statementBuild = $statementBuild . " `password`=:password ";
         }
     }
     
     
     
      if(strcmp($this->notifications, "") != 0 ){

         if($statementBuild != ""){
             $statementBuild = $statementBuild . ", `notifications`=:notifications";
         }else{
              $statementBuild = $statementBuild . " `notifications`=:notifications ";
         }
     }
     
    if($this->versionControl > 0 ){

        if($statementBuild != ""){
         $statementBuild = $statementBuild . ", `versionControl`=:versionControl";
        }else{
            $statementBuild = $statementBuild . " `versionControl`=:versionControl ";
        }
    }
     

     
      if($statementBuild != ""){
         $statementBuild = $statementBuild . ", `updated_at`=:updateDateTime";
      }else{
        $statementBuild = $statementBuild . " `updated_at`=:updateDateTime ";
     }
     
     
     
     
    
    $query = "UPDATE `AppUsers` SET ".$statementBuild. " WHERE `id`=:id ";
      // prepare the query
      
    $stmt = $this->conn->prepare($query);
    
    if(strcmp($this->email, "") != 0 ){
         $stmt->bindParam(':email', $this->email);
    }
    
    if(strcmp($this->name, "") != 0 ){
         $stmt->bindParam(':name', $this->name);
    }
    
     if(strcmp($this->celnr, "") != 0 ){
         $stmt->bindParam(':celnr', $this->celnr);
    }
    
     if(strcmp($this->country, "") != 0 ){
         $stmt->bindParam(':country', $this->country);
    }
    
    if(strcmp($this->password, "") != 0 ){
         $this->password=htmlspecialchars(strip_tags($this->password));
        $password_hash = password_hash($this->password, PASSWORD_BCRYPT);
        $stmt->bindParam(':password', $password_hash);
    }
    
    if(strcmp($this->notifications, "") != 0 ){
         $stmt->bindParam(':notifications', $this->notifications);
    }
    
   
    
     date_default_timezone_set('Africa/Johannesburg');
    $dateTime = date('Y-m-d H:i:s', strtotime("now"));
     $stmt->bindParam(':updateDateTime', $dateTime );
     
    if($this->versionControl > 0 ){
        $stmt->bindParam(':versionControl', $this->versionControl);
    }
    
    $stmt->bindParam(':id', $this->id);

   
    $stmt->execute();
     
    $count = $stmt->rowCount();

    if($count > '0'){
       return "saved";
    }
    else{
        return "not saved";
    }
    
}
}