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


$AgentKey = $_REQUEST['AgentKey'];
$Amount = $_REQUEST['Amount'];
$DestinationKey = $_REQUEST['DestinationKey'];
$SaleDate = $_REQUEST['SaleDate'];

$datetime = time() * 1000;

if(!$SaleDate) $SaleDate = $datetime;

if(ctype_digit($SaleDate)) 
{
	$SaleDate = date('Y-m-d',$SaleDate/1000);
}
else
{
	$SaleDate=date('Y-m-d',strtotime($SaleDate));
}

if($SaleDate > '' && $AgentKey > 0 && $Amount > 0 && $DestinationKey > 0)
{

// php equivalent of JavaScript var isnum = /^\d+$/.test(val);
	$set .= ", SaleDate = '$SaleDate'";
	$message .= ", Date ".date('M j, Y',strtotime($SaleDate));

	$sql = "SELECT AgentName FROM AGENT WHERE AgentID='$AgentKey'";
	$sqlExecute = mysql_query($sql, $conn) or die("Couldn't perform query $sql (".__LINE__."): " . mysql_error() . '.');
	$sqlAgent = mysql_fetch_assoc($sqlExecute);

	$message .= ", Agent ".$sqlAgent['AgentName'];

	$set .= ", AgentKey = '$AgentKey'";

	$message .= ', ' . money_format('$%i',$Amount);
	$set .= ", Amount = '$Amount'";

	$sql = "SELECT DestinationName FROM DESTINATION WHERE DestinationID='$DestinationKey'";
	$sqlExecute = mysql_query($sql, $conn) or die("Couldn't perform query $sql (".__LINE__."): " . mysql_error() . '.');
	$sqlDestination = mysql_fetch_assoc($sqlExecute);
	$message .= ", to ".$sqlDestination['DestinationName'];
	$set .= ", DestinationKey = '$DestinationKey'";

	$set = substr($set,2);
	$message = substr($message,2);
	$sql = "INSERT INTO SALE SET $set";
	$sqlExecute = mysql_query($sql, $conn) or die("Couldn't perform query $sql (".__LINE__."): " . mysql_error() . '.');

	$sql = "SELECT *, UNIX_TIMESTAMP(SaleDate)*1000 AS SaleTime FROM SALE INNER JOIN AGENT ON AgentKey=AgentID INNER JOIN DESTINATION ON DestinationKey=DestinationID WHERE AgentKey=$AgentKey AND DestinationKey='$DestinationKey' ORDER BY SaleID DESC LIMIT 1";

	$sqlTable = mysql_query($sql, $conn) or die("Couldn't perform query $sql (".__LINE__."): " . mysql_error() . '.');
	$sqlRecord = mysql_fetch_assoc($sqlTable);
}
else
{
	$message = "Agent, Destination and Amount were not all specified.";
}

$json = json_encode([
		"datetime" => $datetime,
		"SaleDate" => $SaleDate,
		"AgentKey" => $AgentKey,
		"Amount" => $Amount,
		"DestinationKey" => $DestinationKey,
		"sale" => $sqlRecord,
		"message" => $message
], JSON_PRETTY_PRINT);

echo $json;

?>