<?php
require_once (PATH_TABLES . "admin/UserPasswordHistoryTable.php") ;
require_once (PATH_MODELS . "admin/UserClass.php") ;
require_once (PATH_MODELS . "base/MasterBase.php") ;

class UserPasswordHistoryClass extends MasterBase {
	
	function __construct($db) {
		$this->db = $db ;
		$this->tbl = UserPasswordHistoryTable::C_TABLE ;
		$this->fldid = UserPasswordHistoryTable::C_USER_ID ;
	}
	function __destruct() {
	}

	function insertPasswordHistory($id, $pwd){
        $clsUser = new UserClass($this->db);
		$datas[] = $this->db->fieldValue(UserPasswordHistoryTable::C_USER_ID,$id) ;
		$datas[] = $this->db->fieldValue(UserPasswordHistoryTable::C_PWD1,$clsUser->encryptPwd1($pwd)) ;
		$datas[] = $this->db->fieldValue(UserPasswordHistoryTable::C_PWD2,$clsUser->encryptPwd2($pwd)) ;
		$datas[] = $this->db->fieldValue(UserPasswordHistoryTable::C_DATE,(new DateTime())->format('Y-m-d H:i:s')) ;
        
        try {
            $this->addRecord($datas);
        } catch (Exception $e){
            Log::write("[UserPasswordHistoryClass]" . $e->getMessage());
        }
        
    }

	function checkPasswordSimiliarToPrevious($id, $pwd){		
		$clsUser = new UserClass($this->db);
		$sql = "Select Top 4 * FROM " . UserPasswordHistoryTable::C_TABLE . " WHERE "
			   . UserPasswordHistoryTable::C_USER_ID . " = '" . $id . "'"
			   . " ORDER BY " . UserPasswordHistoryTable::C_DATE . " DESC";
		
		$results = $this->db->getTable($sql);

		foreach($results as $result){
			if($result[UserPasswordHistoryTable::C_PWD1] == $clsUser->encryptPwd1($pwd)){
				return false;
			}
		}		
		return true;
    }
}
?>