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

include('_global.php'); 

$SaleID=$_REQUEST['SaleID'];

$opt_con_off = $_REQUEST['OptConOff'];

$original_values_returned = isset( $_REQUEST['Original_SaleDate'], $_REQUEST['Original_AgentKey'], $_REQUEST['Original_Amount'], $_REQUEST['Original_DestinationKey'] );

if( $SaleID > 0 && ( $opt_con_off == 1 || $original_values_returned ) )
{
	$updated = ''; $set = '';

	if(isset($_REQUEST['SaleDate']))
	{
		$updated .= ', Date';
		$set .= ", SaleDate = '".$_REQUEST['SaleDate']."'";
	}
	if(isset($_REQUEST['AgentKey']))
	{
		$updated .= ', Agent';
		$set .= ", AgentKey = '".$_REQUEST['AgentKey']."'";
	}
	if(isset($_REQUEST['Amount']))
	{
		$updated .= ', Amount';
		$set .= ", Amount = '".$_REQUEST['Amount']."'";
	}
	if(isset($_REQUEST['DestinationKey']))
	{
		$updated .= ', Destination';
		$set .= ", DestinationKey = '".$_REQUEST['DestinationKey']."'";
	}

	if($set>'')
	{
		$updated = substr($updated,2);
		$set = substr($set,2);
		$sql = "UPDATE SALE SET $set WHERE SaleID='$SaleID'";

		if( $opt_con_off == 0 ) 
		{
			$sql .= " AND SaleDate='".$_REQUEST['Original_SaleDate']."'";
			$sql .= " AND AgentKey='".$_REQUEST['Original_AgentKey']."'";
			$sql .= " AND Amount='".$_REQUEST['Original_Amount']."'";
			$sql .= " AND DestinationKey='".$_REQUEST['Original_DestinationKey']."'";
		}
		$sqlExecute = mysql_query($sql, $conn) or die("Couldn't perform query $sql (".__LINE__."): " . mysql_error() . '.');

		if( mysql_affected_rows() == 0 )
		{
			$message = "Record SaleID $SaleID was not updated.";
			if( $opt_con_off == 0 ) $message .= " Optimistic Concurrency Violation.";
			$status = -1;
		}
		else
		{
			$message = "Update $updated in SaleID $SaleID record successful.";
			$status = 1;
		}

	}
	else
	{
		$message = "Nothing changed. Sale record was not updated.";
		$status=0;
	}

	$sql = "SELECT SaleID, AgentKey, AgentName, SaleDate, UNIX_TIMESTAMP(SaleDate)*1000 AS SaleTime, Amount, DestinationKey, DestinationName FROM SALE INNER JOIN AGENT ON AgentKey=AgentID INNER JOIN DESTINATION ON DestinationKey=DestinationID WHERE SaleID=$SaleID";

	$sqlTable = mysql_query($sql, $conn) or die("Couldn't perform query $sql (".__LINE__."): " . mysql_error() . '.');
	$sqlRecord = mysql_fetch_assoc($sqlTable);
}
else
{
	$message = "SaleID or Original Values not defined";
	$status = -1;
}

$json = json_encode([
		"status" => $status,
		"message" => $message,
		"OptConOff" => $opt_con_off,
		"SaleID" => $SaleID,
		"SaleDate" => $_REQUEST['SaleDate'],
		"AgentKey" => $_REQUEST['AgentKey'],
		"Amount" => $_REQUEST['Amount'],
		"DestinationKey" => $_REQUEST['DestinationKey'],
		"Original_SaleDate" => $_REQUEST['Original_SaleDate'],
		"Original_AgentKey" => $_REQUEST['Original_AgentKey'],
		"Original_Amount" => $_REQUEST['Original_Amount'],
		"Original_DestinationKey" => $_REQUEST['Original_DestinationKey'],
		"SaleRecord" => $sqlRecord
], JSON_PRETTY_PRINT);

echo $json;

?>