<html>
	<head>
		<title>Sign Up</title>
	</head>
	<body>
<?php
include("common.php");
// We expect name to be empty cause it's hidden -> only bots will fill it out
if (isset($_POST["aircraft-id"]) && $_POST["aircraft-id"] != "" && isset($_POST["email"]) && $_POST["email"] != "")
{
	$con = new mysqli(getenv("SQL_HOST"), getenv("SQL_USER"), getenv("SQL_PASSWORD"), getenv("SQL_DATABASE"), getenv("SQL_PORT"));
	if ($con->connect_error)
	{
		echo("An error occured, please try later</body></html>");
		exit();
	}
	$stmt = $con->prepare("SELECT id FROM `aircraft-devs` WHERE acid = ? AND user = ?");
	$stmt->bind_param("ss", $_POST["aircraft-id"], $_POST["email"]);
	$stmt->execute();
	$result = $stmt->get_result();
	$res = $result->fetch_assoc();
	$stmt->close();
	if ($res != Null)
	{
		echo("You've already signed up to receive emails for " . $_POST["aircraft-id"]);
	}
	else
	{
		$hash_unique = false;
		while (!$hash_unique)
		{
			$hash = bin2hex(random_bytes(16));
			$sql = "SELECT id FROM `confirmation-pending` WHERE id = '" . $hash . "';";
			$result = $con->query($sql);
			$res = $result->fetch_assoc();
			if ($res == Null)
			{
				$hash_unique = true;
			}
		}
		$action = new stdClass;
		$action->action = "signup";
		$action->acid = $_POST["aircraft-id"];
		$action->email = $_POST["email"];

		$stmt = $con->prepare("INSERT INTO `confirmation-pending` (id, action, ts) VALUES (?, ?, NOW())");
		$stmt->bind_param("ss", $hash, json_encode($action));
		$stmt->execute();
		$stmt->close();

		$msg = "You've received this email cause someone requested to sign this
email up for the Aircraft Developer Registry at
" . getenv("BASE_URL") . "
If you have requested this please use the following link to confirm
" . getenv("BASE_URL") . "/confirm.php?id=" . $hash . "
If you haven't requested to be signed up, please ignore this email.";

		send_mail($_POST["email"], "Sign Up " . $_POST["aircraft-id"], $msg);
		echo("We've sent you an email. Please confirm your sign up with the link");
	}
	$con->close();
}
else
{
	echo("Invalid request.");
}
?>
	</body>
</html>