<?php
include 'core/init.php';
include 'core/query/MinecraftVotifier.php';
include 'includes/overall/header.php';
include 'core/functions/recaptchalib.php';


$server_id  = (INT)$_GET['id'];
$user_id	= id_to_user_id($server_id);
$addedBy 	= username_from_user_id($user_id);

if(empty($_GET['id']) == true || $addedBy == false){echo "<h2>Server not found.</h2>";include 'includes/overall/footer.php';die();}

$result  = mysql_query("SELECT `ip`, `name`, `votifier_key`, `votifier_ip`, `votifier_port` FROM `servers` WHERE `id` = '$server_id'");
$server_data = mysql_fetch_array($result, MYSQL_ASSOC);

if(!empty($_POST)) {
	$captcha = recaptcha_check_answer ($settings['recaptcha_private'], $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
	$ip = $_SERVER['REMOTE_ADDR'];
	$currentTime = time();

	$result = mysql_query("SELECT `timestamp` FROM `votes` WHERE `server_id` = '{$server_id}' AND `ip` = '{$ip}' ORDER BY `id` DESC LIMIT 1");
	$dbTime = @mysql_result($result, 0);

	if($captcha->is_valid == false) {
		$errors[] = "Captcha is not correct !";
	}
	if($currentTime - $dbTime <= 86400) {
		$errors[] = "You already voted today";
	}

	if(!empty($errors)) echo output_errors($errors);
	
	if(empty($errors)) {
		if($server_data['votifier_key'] !== "false"){

			$votifier_ip = (empty($server_data['votifier_ip']) == true) ? $server_data['ip'] : $server_data['votifier_ip'];
			$username = htmlspecialchars($_POST['username'], ENT_QUOTES);

			if(Votifier($server_data['votifier_key'], $votifier_ip, $server_data['votifier_port'], $username) !== false) {

				mysql_query("INSERT INTO `votes` (`ip`, `server_id`, `timestamp`) VALUES ('".$ip."', {$server_id}, {$currentTime})");
				mysql_query("UPDATE `servers` SET `votes` = votes+1 WHERE `id` = {$server_id}");

				echo output_success("Your vote was successfully added !");

			} else {
				echo "<p>We had some problems sending the vote to the server..</p>";
			}

		} else {

			mysql_query("INSERT INTO `votes` (`ip`, `server_id`, `timestamp`) VALUES ('".$ip."', {$server_id}, {$currentTime})");
			mysql_query("UPDATE `servers` SET `votes` = votes+1 WHERE `id` = {$server_id}");

			echo output_success("Your vote was successfully added !");

		}
	}

}
?>

<h3>Vote for <?php echo $server_data['name']; ?></h3>

<form action="" method="POST" role="form">
	<?php if ($server_data['votifier_key'] !== "false") { ?>
	<label>InGame Username</label>
	<input class="form-control" type="text" name="username" class="span3"/><br />
	<?php } ?>
	
	<?php $error = null; echo recaptcha_get_html($settings['recaptcha_public'], $error); ?><br />
	
	<input class="btn btn-primary span3" type="submit" value="Vote" />
</form>


<?php include 'includes/overall/footer.php'; ?>