<?php
class AutoLevelup extends EventDispatcher{
	
	private $db;
	private $btconf;
	
	const LEVEL_CHANGED = 'level_changed';
	
	public function __construct(){
		$this->db = DB::getInstance();
		$this->btconf = BartConfig::getInstance()->getConfig();
	}
	
	public function execCheckAndLevelUp($member_table_name, $member){
		
		$data = $this->btconf['alevel_data'];
		
		if(((int)$this->btconf['bc_alevel_useup']!=1 && (int)$this->btconf['bc_alevel_usedown']!=1) || count($data) <= 0) return;
		
		$new_level = 0;
		foreach($data as $level => $point){
			
/*			echo 'mb_level : '.$member['mb_level'].'<br>';
			echo 'mb_point : '.$member['mb_point'].'<br>';
			echo 'level : '.$level.'<br>';
			echo 'point : '.$point.'<br>';
			echo '--------------------------------------<br>';*/
			
			if($member['mb_point'] < $point){
				$new_level = $level-1;
				break;
			}
		}
		
		if($new_level <= 0) $new_level = $level;
		
		//레벨에 변동이 있으면
		if($new_level != $member['mb_level']){
			if($new_level > $member['mb_level']) $mode = 'up';
			else $mode = 'down';
			
			$sql = "UPDATE ".$member_table_name." SET mb_level=".$new_level." WHERE mb_id='".$this->db->esc($member['mb_id'])."'";
			//echo $sql.'<br>';
			$this->db->query($sql);
			$rowcnt = $this->db->affectedRow();
			
			//콜백실행
			if($rowcnt > 0 && $this->existCallBack(self::LEVEL_CHANGED)){
				$this->dispatchEvent(self::LEVEL_CHANGED, $member['mb_id'], $mode, $new_level, $point);
			}
		}
	}
}