<?php
include("common.php");
$API_VERSION = 0.1;

function quit()
{
	$ret = new stdClass;
	$ret->success = false;
	$ret->version = $GLOBALS["API_VERSION"];
	echo(json_encode($ret));
	exit();
}

$ret = new stdClass;
$ret->success = true;
$ret->version = $API_VERSION;

if (isset($_POST["action"]) && $_POST["action"] != "")
{
	$action = $_POST["action"];
}
else
{
	quit();
}

$con = new mysqli(getenv("SQL_HOST"), getenv("SQL_USER"), getenv("SQL_PASSWORD"), getenv("SQL_DATABASE"), getenv("SQL_PORT"));
if ($con->connect_error)
{
	quit();
}

if ($action == "send-report")
{
	if (isset($_POST["aircraft-id"]) && $_POST["aircraft-id"] != "" && isset($_POST["report"]) && $_POST["report"] != "")
	{
		$acID = $_POST["aircraft-id"];
		$report = $_POST["report"];
	}
	else
	{
		quit();
	}

	$stmt = $con->prepare("SELECT user FROM `aircraft-devs` WHERE acid = ?");
	$stmt->bind_param("s", $acID);
	$stmt->execute();
	$result = $stmt->get_result();
	$res = $result->fetch_assoc();
	$stmt->close();
	if ($res == Null)
	{
		$ret->success = false;
		$ret->error = "No dev in db";
	}
	else
	{
		while ($res != Null)
		{
			$msg = $report . "


You're receiving this email cause you have signed up to the Aircraft Developer Registry.
You can always sign off of receiving mails for the " . $acID . " using this link
" . getenv("BASE_URL") . "/signoff.php?aircraft-id=" . $acID . "&email=" . $res["user"] . "
Or sign off from receiving any mails using this link;
" . getenv("BASE_URL") . "/signoff.php?aircraft-id=all&email=" . $res["user"];
			send_mail($res, "Issue Report: " . $acID, $msg);
			$res = $result->fetch_assoc();
		}
	}

}

$con->close();
echo(json_encode($ret));
?>