<?php
	header('Access-Control-Allow-Origin: *');

	include('_global.php');

	$datetime = date('Y-m-d H:i:s');

	$AgentName=$_REQUEST['AgentName'];

	$OfficeKey=$_REQUEST['OfficeKey'];

	$AgentName_as=addslashes($AgentName);

	$AgentID = 0;

	$OfficeLocation = '';

	$inserted = 0;

	$message='';

	if( strlen($AgentName) > 5 && $OfficeKey > 0 )
	{
		$sql = "SELECT AgentName, OfficeKey FROM AGENT WHERE AgentName='$AgentName_as' AND OfficeKey='$OfficeKey'";

		$sqlTable = mysql_query($sql, $conn) or die("Couldn't perform query $sql (".__LINE__."): " . mysql_error() . '.');

		if($sqlRecord = mysql_fetch_assoc($sqlTable))
		{
			$message = "already added";
		}
		else
		{
			$sql="INSERT INTO AGENT (AgentName,OfficeKey) VALUES ('$AgentName_as',$OfficeKey)";
			$sqlExecute = mysql_query($sql, $conn) or die("Couldn't perform query $sql (".__LINE__."): " . mysql_error() . '.');
			$message = "added";
			$inserted = 1;
		}

		$sql = "SELECT * FROM AGENT INNER JOIN OFFICE ON OfficeKey=OfficeID WHERE AgentName='$AgentName_as' AND OfficeKey='$OfficeKey'";

		$sqlTable = mysql_query($sql, $conn) or die("Couldn't perform query $sql (".__LINE__."): " . mysql_error() . '.');

		if($sqlRecord = mysql_fetch_assoc($sqlTable))
		{
			$message = $sqlRecord['AgentName'] . " $message at " . $sqlRecord['OfficeLocation'] . " location.";
			$AgentID = $sqlRecord['AgentID'];
			$OfficeLocation = $sqlRecord['OfficeLocation'];
		}
	}
	else
	{
		$message = "AgentName or OfficeKey wasn't specified correctly.";
	}

	$json = json_encode([		"datetime" => $datetime,
								"inserted" => $inserted,
								"message" => $message,
								"AgentID" => $AgentID,
								"AgentName" => $AgentName,
								"OfficeKey" => $OfficeKey,
								"OfficeLocation" => $OfficeLocation
						], JSON_PRETTY_PRINT);

	echo $json;

?>