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

include('_global.php'); 

$SaleID=$_REQUEST['SaleID']*1;

$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 ) )
{
	$sql = "SELECT SaleID, AgentKey, AgentName, SaleDate, UNIX_TIMESTAMP(SaleDate)*1000 AS SaleTime, Amount, DestinationKey, DestinationName";
	$sql .= " FROM SALE INNER JOIN AGENT ON AgentKey=AgentID INNER JOIN DESTINATION ON DestinationKey=DestinationID WHERE SaleID=$SaleID";

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

	if( $SaleRecord = mysql_fetch_assoc($sqlSales) )
	{
		$sql = "DELETE FROM SALE 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 deleted.";
			if( $opt_con_off == 0 ) $message .= " Optimistic Concurrency Violation.";
			$status = -1;
		}
		else
		{
			$message = "Delete SaleID $SaleID record successful.";
			$status = 1;
		}
	}
	else
	{
		$message = "SaleID $SaleID was not found.";
		$status = -1;
	}
}
else
{
	$message = "SaleID or Original Values not defined";
	$status = -1;
}

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

echo $json;

?>