<?php
include 'common.php';


function IsAlreadyConnected($dbhandle, $wallet_id)
{
	$stmt = $dbhandle->prepare("select count(*) as cnt from account where wallet_id=?");
	$stmt->bind_param("s", $wallet_id);
	$stmt->execute();
	$result = $stmt->get_result();
	$row = $result->fetch_assoc();
	
	mysqli_stmt_free_result($stmt);
	if( !$result )
	{
		return true;
	}
	
	if($row["cnt"] > 0 )
		return true;   //yes already connected
	else
		return false;
}

function GetUserIdByWalletId($dbhandle, $wallet_id)
{
	$stmt = $dbhandle->prepare("select user_id from account where wallet_id=?");
	$stmt->bind_param("s", $wallet_id);
	$stmt->execute();
	$result = $stmt->get_result();
	$row = $result->fetch_assoc();
	
	mysqli_stmt_free_result($stmt);
	if( !$result )
	{
		return null;
	}
	
	return $row["user_id"];		
}


function ConnectWalletIdCheck($wallet_id, $wallet_pwd_hash)
{
	$dbhandle = DB_Connect();
	//Select DB
	$db_selected = mysqli_select_db($dbhandle, DB_NAME)
	or die("Could not select db");
	
	
	
	$response = "WALLET_ID_CONNECTION_CHECK_FAILED";	
	$error = "";
	$user_id = null;
	if(IsAlreadyConnected($dbhandle, $wallet_id))
	{
		$user_id = GetUserIdByWalletId($dbhandle, $wallet_id);
		
		
		$response = "WALLET_ID_ALREADY_CONNECTED";	
		
		
	}
	else
	{
		$user_id = $wallet_id;
		$response = "WALLET_ID_NOT_CONNECTED";	
	}
	
	
	
	
	 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, 'user_id'=>$user_id));
}

$json = json_decode(file_get_contents('php://input'));
$wallet_id = $json->wallet_id;
$wallet_pwd_hash = $json->wallet_pwd_hash;
$checksum = $json->checksum;
		

if(CheckSum($wallet_id,$wallet_pwd_hash,$checksum))
{
	ConnectWalletIdCheck($wallet_id, $wallet_pwd_hash);
}



	

?>