<html>
	<head>
		<title>Sign Off</title>
	</head>
	<body>
<?php
include("common.php");
if (isset($_GET["aircraft-id"]) && $_GET["aircraft-id"] != "" && isset($_GET["email"]) && $_GET["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();
	}
	if ($_GET["aircraft-id"] == "all")
	{
		$stmt = $con->prepare("SELECT id FROM `aircraft-devs` WHERE user = ?");
		$stmt->bind_param("s", $_GET["email"]);
	}
	else
	{
		$stmt = $con->prepare("SELECT id FROM `aircraft-devs` WHERE acid = ? AND user = ?");
		$stmt->bind_param("ss", $_GET["aircraft-id"], $_GET["email"]);
	}
	$stmt->execute();
	$result = $stmt->get_result();
	$res = $result->fetch_assoc();
	$stmt->close();
	if ($res == Null)
	{
		echo("You're not signed up to receive emails for " . $_GET["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 = "signoff";
		$action->acid = $_GET["aircraft-id"];
		$action->email = $_GET["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 off of 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($_GET["email"], "Sign Off " . $_GET["aircraft-id"], $msg);
		echo("We've sent you an email. Please confirm your sign off with the link");
	}
	$con->close();
}
else
{
	echo("Invalid request.");
}
?>
	</body>
</html>