<?php
include 'common.php';

function InsertInvenPotion($dbhandle, $account_id, $char_uid, $item_uid,$count,$parts_type)
{
	
	if(AlreadyExistsItem($dbhandle, $char_uid,$item_uid ))
	{
		$query = "UPDATE owned_item set count=count+".$count." where character_uid=".$char_uid." and item_uid=".$item_uid;
	}
	else
	{
		$query = "INSERT INTO owned_item (character_uid, item_uid, count, is_equiped, parts_type) VALUES (".$char_uid.",".$item_uid.",".$count.",0,".$parts_type." )";
		
	}
	
	
	//Query Result
	$result = @mysqli_query($dbhandle,$query);
	
	if($result)
	{
		return true;
	}
	else
	{
		//$error = mysqli_error($dbhandle);
		return false;
	}
	
	
   
}

function Available_PotionDailyEvent($dbhandle,$account_id, $char_uid)
{
	$now = new DateTime();
	$now->setTimezone(new DateTimeZone('UTC'));
	$login_time =  date_format($now, "Y-m-d");
	
	
	//기간체크
	$time_now = strtotime($login_time);
	$event_start = strtotime('2020-11-10 00:00:00');
	$event_end = strtotime('2020-11-15 23:59:59');
	if($time_now >= $event_start &&  $time_now <= $event_end)
	{
		
		
		$stmt = $dbhandle->prepare("select count(*) as cnt from potion_event_log where user_id=? and character_uid=? and DATE_FORMAT(log_time,'%Y-%m-%d') =?");	
		$stmt->bind_param("sis", $account_id, $char_uid, $login_time);
		$stmt->execute();
		$result = $stmt->get_result();
		$num = $result->fetch_assoc();
		
		mysqli_stmt_free_result($stmt);
		
		if($num["cnt"] > 0)
		{				
			
			return false;
		}
		else
		{
			
			
			return true;
		}
	
	}
	else
	{
		
		return false;
	}
	
	
	
		

	
	
	
}

function UpdatePotionAndLog($dbhandle,$account_id, $char_uid, $item_uid,$count,$parts_type)
{
	//$amount =200;		
	//$stmt = $dbhandle->prepare("update owned_item set count where user_id=?");
	//$stmt->bind_param("ss", $amount,$account_id);
	//$result = $stmt->execute();
	//$stmt->close();
	
	
	$now = new DateTime();
	$now->setTimezone(new DateTimeZone('UTC'));
	$login_time =  date_format($now, "Y-m-d");
	
	
	//기간체크
	$time_now = strtotime($login_time);
	$event_start = strtotime('2020-11-11 00:00:00');
	$event_end = strtotime('2020-11-15 23:59:59');
	if($time_now >= $event_start &&  $time_now <= $event_end)
	{
		$count = 1000;
	}
	
	InsertInvenPotion($dbhandle, $account_id, $char_uid, $item_uid,$count,$parts_type);
	
	
	$now = new DateTime();
	$now->setTimezone(new DateTimeZone('UTC'));
	$login_time =  date_format($now, "Y-m-d H:i:s");
	
	
	
	$stmt = $dbhandle->prepare("insert into potion_event_log (user_id, character_uid, amount, log_time) values(?,?,?,?)");
	$stmt->bind_param("siis", $account_id, $char_uid, $count, $login_time);
	
	$result = $stmt->execute();
	$stmt->close();
	
	
}

function GetLang($dbhandle, $account_id)
{
	//$strQuery = "select count(*),cash from account where user_id='".$account_id."'"; 
	$lang ="en";
	$stmt = $dbhandle->prepare("select lang from account where user_id=?");	
	$stmt->bind_param("s", $account_id);
	$stmt->execute();
	$result = $stmt->get_result();	
	if($result)
	{		
		if($row = $result->fetch_assoc())
		{
			$lang = $row["lang"];
			mysqli_stmt_free_result($stmt);
		}
	}
	else{
		$error = mysqli_error($dbhandle);
	}
	
	
	return $lang;
}

function GetOpenedZoneID($dbhandle, $char_uid)
{
	$opened_zone_id = 0;
	
	
	
	$stmt = $dbhandle->prepare("select opened_zone_id from character_list where character_uid=?");	
	$stmt->bind_param("i", $char_uid);
	$stmt->execute();
	$result = $stmt->get_result();	
	if($result)
	{		
		if($row = $result->fetch_assoc())
		{
			$opened_zone_id = $row["opened_zone_id"];
			mysqli_stmt_free_result($stmt);
		}
	}
	else{
		$error = mysqli_error($dbhandle);
	}
	
	
	return $opened_zone_id;
}

function SubUpdateOpenedZoneID($dbhandle, $char_uid, $zone_id) {	
	
	$update_query = "update character_list set opened_zone_id=".$zone_id." where character_uid=".$char_uid." and deleted=false";
	

	//Query Result
	$result = @mysqli_query($dbhandle,$update_query);
	if($result != 1)
	{
		return false;		
	}
	
	return true;
}

function SubUpdateZoneID($dbhandle, $char_uid, $zone_id, $lang) {	
	
	
	$now = new DateTime();
	$now->setTimezone(new DateTimeZone('UTC'));
	$strTime =  date_format($now, "Y-m-d H:i:s");
	
	$update_query = "update character_list set zone_id=".$zone_id." , lang='".$lang."' , login_time='".$strTime."' where character_uid=".$char_uid." and deleted=false";
	

	//Query Result
	$result = @mysqli_query($dbhandle,$update_query);
	if($result != 1)
	{
		return false;		
	}
	
	return true;
}

function SubGetCharacterLevel($dbhandle,$char_uid, $zone_id,$cash) {

	$response = "LOGIN_FAILED";
	$level = 1;
	$exp = 0;
	
	$strQuery = "select level, character_exp, current_quest_id, current_quest_state, quest_is_rewarded, quest_kill_count, character_uid, class_id, parts_head_uid, parts_body_uid, parts_leg_uid, parts_weapon_uid, parts_shield_uid, parts_quiver_uid, parts_arm_uid, gold, inven_extra_count, stat_strength, stat_intellect, stat_agility, stat_wisdom, stat_health, skill_slot_0, skill_slot_1, skill_slot_2, skill_slot_3, stat_point, opened_zone_id from character_list where character_uid=".$char_uid." and deleted=false";
	if($query_result = mysqli_query($dbhandle, $strQuery))
	{
		$data = mysqli_fetch_row($query_result);
		if(count($data) > 0)
		{
			$response = "LOGIN_OK";
			$error = "";
			$level = $data[0];
			$exp = $data[1];
			$quest_id = $data[2];
			$quest_state = $data[3];
			$quest_is_rewarded = $data[4];
			$quest_kill_count = $data[5];			
			$character_uid = $data[6];
			$class_id = $data[7];			
			$parts_head_uid = $data[8];
			$parts_body_uid = $data[9];
			$parts_leg_uid = $data[10];
			$parts_weapon_uid = $data[11];
			$parts_shield_uid = $data[12];
			$parts_quiver_uid = $data[13];
			$parts_arm_uid = $data[14];
			$gold = $data[15];
			$inven_extra_count = $data[16];
			$stat_strength = $data[17];
			$stat_intellect = $data[18];
			$stat_agility = $data[19];
			$stat_wisdom = $data[20];
			$stat_health = $data[21];
			$skill_slot_0 = $data[22];
			$skill_slot_1 = $data[23];
			$skill_slot_2 = $data[24];
			$skill_slot_3 = $data[25];
			$stat_point = $data[26];
			$opened_zone_id = $data[27];
			
		}
	}
	else{
		$error = mysqli_error($dbhandle);
	}
	
	
	
	
	
	$isXmlHttpRequest = (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) ?
	(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') ? true : false: false;
	($isXmlHttpRequest) ? header('Content-type: application/json') : header('Content-type: text/plain');
 
    //$error = get_ip(); //TEST
 
	echo json_encode(array(
	'result'=>$response,
	'error'=>$error,
	'level'=>$level,
	'exp'=>$exp,
	'quest_id'=>$quest_id,
	'quest_state'=>$quest_state,
	'quest_is_rewarded'=>$quest_is_rewarded,
	'quest_kill_count'=>$quest_kill_count,
	'character_uid'=>$character_uid,
	'class_id'=>$class_id,	
	'parts_head_uid'=>$parts_head_uid,
	'parts_body_uid'=>$parts_body_uid,
	'parts_leg_uid'=>$parts_leg_uid,
	'parts_weapon_uid'=>$parts_weapon_uid,
	'parts_shield_uid'=>$parts_shield_uid,
	'parts_quiver_uid'=>$parts_quiver_uid,
	'parts_arm_uid'=>$parts_arm_uid,
	'gold'=>$gold,
	'inven_extra_count'=>$inven_extra_count,
	'cash'=>$cash,
	'stat_strength'=>$stat_strength,
	'stat_intellect'=>$stat_intellect,
	'stat_agility'=>$stat_agility,
	'stat_wisdom'=>$stat_wisdom,
	'stat_health'=>$stat_health,
	'skill_slot_0'=>$skill_slot_0,
	'skill_slot_1'=>$skill_slot_1,
	'skill_slot_2'=>$skill_slot_2,
	'skill_slot_3'=>$skill_slot_3,
	'stat_point'=>$stat_point,
	'opened_zone_id'=>$opened_zone_id));
}

function LoginQuery($account_id,$login_key, $char_uid, $zone_id){
	$dbhandle = DB_Connect();
	
	//Select DB
	$db_selected = mysqli_select_db($dbhandle, DB_NAME)
	or die("Could not select db");
	
	
	
	
	

	$strQuery = "select count(*),cash from account where user_id='".$account_id."' and login_key='".$login_key."'"; 
    
	
	$error = "";
	//Query Result
	if($query_result = mysqli_query($dbhandle, $strQuery))
	{
		
		$data = mysqli_fetch_row($query_result);	

		if( count($data) > 0 )
		{
			if($data[0] > 0)
			{	
				$lang = GetLang($dbhandle,$account_id);
		
				SubUpdateZoneID($dbhandle,$char_uid,$zone_id, $lang);
				
				$opened_zone_id = GetOpenedZoneID($dbhandle, $char_uid);
				if($opened_zone_id < $zone_id)
				{
					SubUpdateOpenedZoneID($dbhandle, $char_uid, $zone_id);					
				}
				
				$cash = $data[1];
				SubGetCharacterLevel($dbhandle,$char_uid, $zone_id, $cash);					
		
				$response = "LOGIN_OK";
				
				if(Available_PotionDailyEvent($dbhandle,$account_id, $char_uid))
				{
					UpdatePotionAndLog($dbhandle,$account_id, $char_uid, 30000,500,20);
				}
				
			}		
			else 
			{
				$response = "LOGIN_FAILED";
				$error = "ERROR : 021";
			}					
		}
		else 
		{
			$response = "LOGIN_FAILED";
			$error = "ERROR : 020";
		}
		
		mysqli_free_result($query_result);
	}
	

    mysqli_close($dbhandle);
 


}

$json = json_decode(file_get_contents('php://input'));
$account_id = $json->account_id;
$login_key = $json->login_key;
$char_uid = $json->char_uid;
$zone_id = $json->zone_id;

//if(CheckValidatedServerIP())
//{
	LoginQuery($account_id, $login_key, $char_uid, $zone_id);
//}
//else
//{
//	$response = "INVALIDATED_SERVER";
//	$error = "CheckValidatedServerIP ERROR";
//	$isXmlHttpRequest = (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) ?
//	(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') ? true : false: false;
//	($isXmlHttpRequest) ? header('Content-type: application/json') : header('Content-type: text/plain'); 
 
//	echo json_encode(array(	'result'=>$response,'error'=>$error	));
//}



?>