<?php
include 'common.php';


function PrintDebug($response, $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));
	exit; 
}



function IsBlockAccount($dbhandle, $account_id)
{

	$stmt = $dbhandle->prepare("select count(*) as cnt from block_account_log where user_id=? and is_account_block=1");	
	$stmt->bind_param("s", $account_id);
	$stmt->execute();
	$result = $stmt->get_result();
	$num = $result->fetch_assoc();
	
	mysqli_stmt_free_result($stmt);
	
	if($num["cnt"] > 0)
	{
		return true;
	}
	else
	{
		return false;
	}
}


        
function Available_CrystalDailyEvent($dbhandle, $account_id, $version, $event_id)
{
	$now = new DateTime();
	//$now->setTimezone(new DateTimeZone('Asia/Seoul'));
	$login_time =  date_format($now, "Y-m-d");
	
	//버전 체크
	if($version != '0.22.30' || $version != '0.22.31')
	{
		return false;
	}
	
	//기간체크
	$time_now = strtotime($login_time);
	$event_start = strtotime('2020-11-20 00:00:00');
	$event_end = strtotime('2020-11-27 23:59:59');
	if($time_now >= $event_start &&  $time_now <= $event_end)
	{
		
		
		$stmt = $dbhandle->prepare("select count(*) as cnt from crystal_event_log where event_id=? and user_id=? and DATE_FORMAT(log_time,'%Y-%m-%d') =?");	
		$stmt->bind_param("iss",$event_id, $account_id, $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 UpdateCrystalAndLog($dbhandle,$account_id, $version, $event_id)
{
	$amount =50;
	
	$stmt = $dbhandle->prepare("update account set cash=cash+? where user_id=?");
	$stmt->bind_param("ss", $amount,$account_id);
	$result = $stmt->execute();
	//$stmt->close();
	
	$now = new DateTime();
	//$now->setTimezone(new DateTimeZone('Asia/Seoul'));
	$login_time =  date_format($now, "Y-m-d H:i:s");
	
	
	
	$stmt = $dbhandle->prepare("insert into crystal_event_log (user_id, amount, log_time, event_id) values(?,?,?,?)");
	$stmt->bind_param("sisi", $account_id, $amount, $login_time, $event_id);
	
	$result = $stmt->execute();
	$stmt->close();
	
	
}


function CrystalDailyEvent($dbhandle,$account_id,$version, $event_id)
{
	$stmt = $dbhandle->prepare("select count(*) as cnt from account where user_id=?");	
	$stmt->bind_param("s", $account_id);
	$stmt->execute();
	$result = $stmt->get_result();
	$num = $result->fetch_assoc();
	
	mysqli_stmt_free_result($stmt);
	
	if($num["cnt"] > 0)
	{		
         
		//기간체크 & 이미 지급됬는지 체크해서 가능한지
		if(Available_CrystalDailyEvent($dbhandle,$account_id,$version, $event_id))
		{			
			UpdateCrystalAndLog($dbhandle,$account_id, $version, $event_id);
		}
	}
	else
	{
		
	}
	
}

function CharacterListCheck($dbhandle, $account_id)
{


	$stmt = $dbhandle->prepare("select count(*) as cnt from character_list where user_id=? and deleted=false");	
	$stmt->bind_param("s", $account_id);
	$stmt->execute();
	$result = $stmt->get_result();
	$num = $result->fetch_assoc();
	
	mysqli_stmt_free_result($stmt);
	
	if($num["cnt"] > 0)
	{
		return "LOGIN_OK";
	}
	else
	{
		return "LOGIN_OK_CHAR_NOT_EXIST";
	}
	

}

function UpdateLoginKey($dbhandle, $account_id, $ip, $version, $lang)
{
	
	$login_key = rand();

	$login_time = date('Y-m-d H:i:s');
	
	$now = new DateTime();
	//$now->setTimezone(new DateTimeZone('Asia/Seoul'));
	$login_time =  date_format($now, "Y-m-d H:i:s");
	
	$stmt = $dbhandle->prepare("update account set login_key=?, ip=? , login_time=? , version=? , lang=? where user_id=?");
	$stmt->bind_param("ssssss", $login_key, $ip, $login_time,$version, $lang, $account_id);
	$result = $stmt->execute();
	$stmt->close();
	
	
	if($result)
	{
		return $login_key;
	}
	else
	{
		$login_key = "";
		
	}
		
	
	
	
	
	
	
   
	
	return $login_key;
}

function CreateAccountID($dbhandle, $user_id,$ip, $version, $lang, $platform)
{

	//Select DB
	$db_selected = mysqli_select_db($dbhandle, DB_NAME)
	or die("Could not select db");

	// check character count limit
	$select_query = "select count(*) from account";
	$result_set = @mysqli_query($dbhandle, $select_query);
	$row = @mysqli_fetch_row($result_set);
	
	
	$login_key = rand();
	
	$now = new DateTime();
	//$now->setTimezone(new DateTimeZone('Asia/Seoul'));
	$login_time =  date_format($now, "Y-m-d H:i:s");

	$stmt = $dbhandle->prepare("insert into account (user_id,user_pwd,platform,login_key, ip, is_guest, login_time, version, lang) values(?,'null',?,?,?,0,?,?,?)");
	$stmt->bind_param("sssssss", $user_id, $platform, $login_key, $ip, $login_time,$version,$lang);
	$result = $stmt->execute();
	$stmt->close();
	
	if($result)
	{
		$db_success = "yes";
	}
	else
	{
		$db_success = "no";
		
	}
	


	/* $insert_query = "insert into account (user_id,user_pwd,platform,login_key, ip, is_guest, login_time) values('".$user_id."','null','google','".$login_key."','".$ip."',0,'null')";




	//Query Result
	$result = @mysqli_query($dbhandle,$insert_query);
	if($result == 1)
	{
		$db_success = "yes";
	}
	else
	{
		$db_success = "no";
	} */
	
	
    return array($user_id, $login_key, $db_success);
}



function LoginQuery($account_id, $ip, $version,$lang, $platform){
	$dbhandle = DB_Connect();
	
	//Select DB
	$db_selected = mysqli_select_db($dbhandle, DB_NAME)
	or die("Could not select db");
	
	
	
	
	if(IsBlockAccount($dbhandle,$account_id))
	{
		
		$response = "LOGIN_FAILED";
		$new_login_key = "";
		$error = "Blocked";
	
		$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');
		 
		 $notice = "Blocked";
		 
		echo json_encode(array('result'=>$response,'account_id'=>$account_id, 'login_key'=>$new_login_key,'error'=>$error, 'notice'=>$notice));
		exit;
	}
	


    $stmt = $dbhandle->prepare("select count(*) as cnt,user_id,login_key from account where user_id=?");	
	$stmt->bind_param("s", $account_id);
	$stmt->execute();
	$result = $stmt->get_result();


	$new_login_key = "";
	$error = "";
	
	//
	$CRYSTAL_EVENT_ID = 1;
	
	if($row = $result->fetch_assoc())
	{
		if($row["cnt"] > 0)
		{
			$response = CharacterListCheck($dbhandle, $account_id);	
			//임시로 주석 처리 
			if($response != "LOGIN_FAILED")
			{
				$new_login_key = UpdateLoginKey($dbhandle, $account_id, $ip, $version, $lang);
				if($new_login_key == "")
				{
					$response = "LOGIN_FAILED";
					$error = "ERROR : 042";
				}
				
				CrystalDailyEvent($dbhandle,$account_id, $version, $CRYSTAL_EVENT_ID);
			}
		}
		else	// 계정이없다. 생성 필요  /* 구글 토큰 검증 필요 */		
		{
			
			list($account_id,$login_key,$db_success) = CreateAccountID($dbhandle, $account_id,$ip, $version, $lang, $platform);
			if($db_success == "yes")
			{
				$new_login_key = $login_key;
				$response = "LOGIN_OK";
				$error = "";
				
				CrystalDailyEvent($dbhandle,$account_id, $version, $CRYSTAL_EVENT_ID);
				
			}
			else
			{
				$response = "LOGIN_FAILED";
				$error = "ERROR : Failed to create id ";
			}
			
			
		}		
	}
	
	mysqli_stmt_free_result($stmt);
	
	
	$now = new DateTime();
	//$now->setTimezone(new DateTimeZone('Asia/Seoul'));
	$login_log_time =  date_format($now, "Y-m-d H:i:s");

	$stmt = $dbhandle->prepare("insert into login_log (user_id,log_time, lang) values(?,?,?)");
	$stmt->bind_param("sss", $account_id, $login_log_time,$lang);
	$result = $stmt->execute();
	$stmt->close();
	
	
	
	
	
	
	$error=$version;
	

    mysqli_close($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');
 
    echo json_encode(array('result'=>$response,'account_id'=>$account_id,'login_key'=>$new_login_key,'iap_url'=>IAP_URL,'error'=>$error));

}
$json = json_decode(file_get_contents('php://input'));
$account_id = $json->account_id;
$version = $json->version;
$lang = $json->lang;
$check_sum = $json->check_sum;
$platform = $json->platform;

if(!CheckSum($account_id,$version,$check_sum))
{	
	$response = "LOGIN_FAILED";
	$new_login_key = "";
	$error = "login error(108)";
	$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,'account_id'=>$account_id, 'login_key'=>$new_login_key,'error'=>$error));
	return;
}







if ($account_id == 'a_5288843277264847275' ||
$account_id == 'g17996893341400698406' ||
$account_id == 'a_6361116018492116957' ||
$account_id == 'g17777363609468649255' ||
$account_id == 'g05708447530224277349' ||
$account_id == 'g17286077756811295332')
{
	
	
	
	LoginQuery($account_id, $_SERVER['REMOTE_ADDR'], $version, $lang, $platform);
}
else
{
	if (CheckServerMaintenance())
	{
		if (CheckServerVersion($version))
		{
			LoginQuery($account_id, $_SERVER['REMOTE_ADDR'], $version, $lang, $platform);
		}
	}
}



?>