<?php
include 'common.php';

function Log_IP_Time($dbhandle, $seq, $ip)
{
    $now = new DateTime();
    //$now = new DateTime('now', new DateTimeZone('Asia/Seoul'));
	$strTime =  date_format($now, "Y-m-d H:i:s");

	$stmt = $dbhandle->prepare("UPDATE gm_account SET ip=?, latest_login_time=? WHERE seq=?");
	$stmt->bind_param("ssi", $ip, $strTime, $seq);
	$result = $stmt->execute();
	$stmt->close();
	if($result)
	{
		return true;
	}
	else
	{
		return false;
	}
}

function GMLoginCheck($gm_id, $pwd, $ip){

	$dbhandle = DB_Connect();
	//Select DB
	$db_selected = mysqli_select_db($dbhandle, DB_NAME)
	or die("Could not select db");

    $response = "";
    $error = "";

    $stmt = $dbhandle->prepare("SELECT * FROM gm_account WHERE id=? AND pwd=?");
	$stmt->bind_param("ss", $gm_id, $pwd);
	$stmt->execute();
	$result = $stmt->get_result();
    if ($result)
    {
        if ($row = $result->fetch_assoc())
        {
            mysqli_stmt_free_result($stmt);
            $ip_list = explode(',', $row["allowed_ip_list"]);

            $result_ip_allow = false;
            for ($i=0; $i<sizeof($ip_list); $i++)
            {
                if ($ip == $ip_list[$i])
                {
                    $result_ip_allow = true;
                    break;
                }
            }

            if ($result_ip_allow)
            {
                Log_IP_Time($dbhandle, $row["seq"], $ip);
                $response = "GMLOGIN_OK";
                $error = "";
            }
            else
            {
                $response = "GMLOGIN_NOT_ALLOW_IP";
                $error = "Not Allow IP : ".$ip;
            }
        }
        else
        {
            //empty
            $response = "GMLOGIN_LOGIN_FAIL";
            $error = "No Exist ID or Wrong Password";
        }
    }
    else
    {
        //DB ERROR
        $response = "GMLOGIN_DB_ERROR";
        $error = mysqli_error($dbhandle);
    }

  
	
	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, 'error'=>$error));

}

$json = json_decode(file_get_contents('php://input'));
$gm_id = $json->gm_id;
$pwd = $json->pwd;


GMLoginCheck($gm_id, $pwd, $_SERVER['REMOTE_ADDR']);

?>