<?php

// 
// VIMS RDT transaction Processing
// ----------------------------------------------------------------------------------------

// ----------------------------------------------------------------------------------------
header('Cache-Control: no-cache, no-store, must-revalidate');   
header('Expires: 0');
// Header to allow Cross-Server AJAX Connection
header('Access-Control-Allow-Origin: *');

set_time_limit(0);


function postPtm($mPltNumber,$mToLocHash,$mCurrentUser,$mHost,$mUser,$mPwd=,$mDbName)
{
// mysql connection - Use Passed values...
		$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
			exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
	
	$mDataQuery = "SELECT id AS id, location_code AS location_code FROM location WHERE location.location_hash='".$mToLocHash."' LIMIT 1";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	if (mysqli_num_rows($mData) == 0)
		return "FAIL-Invalid Location Code.";
	$mRow = mysqli_fetch_assoc($mData);
	$mToLocId = ($mRow['id']);
	$mToLocCode = ($mRow['location_code']);
// Get id for inventory status 'ok'
	$mInvStsId = 0;
	$mDataQuery = "SELECT id AS id FROM inventory_status WHERE lower(inventory_status_code) = 'ok' LIMIT 1";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	$mRow = mysqli_fetch_assoc($mData);
	$mInvStsId = ($mRow['id']);
// Get id for document status
	$mDocStsId = 0;
	$mDocCmpId = 0;
	$mDataQuery = "SELECT id AS id, document_status_code AS document_status_code FROM document_status";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	while($mRow = mysqli_fetch_assoc($mData))
	{
		if (strtolower($mRow['document_status_code']) == "open")
			$mDocStsId=($mRow['id']);
		if (strtolower($mRow['document_status_code']) == "complete")
			$mDocCmpId=($mRow['id']);
	}
	if ($mDocCmpId == null)
		$mDocCmpId = 1;
// Get Existing Inventory
	$mDataQuery = "SELECT inventory_master.id AS id, part.part_number AS part_number, CASE WHEN inventory_master.serial_reference IS NULL THEN pick_detail.serial_reference ELSE inventory_master.serial_reference END AS serial_reference, inventory_master.ran_or_order AS ran_order, inventory_master.inventory_qty AS inventory_qty, tag.tag_reference AS plt_number, location.location_code AS location_code FROM inventory_master JOIN part ON inventory_master.part_id=part.id JOIN location ON inventory_master.current_location_id=location.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id LEFT JOIN pick_detail ON pick_detail.inventory_master_id=inventory_master.id WHERE (tag.tag_reference='".$mPltNumber."' OR inventory_master.serial_reference = '".$mPltNumber."') AND inventory_qty>0";  
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	if (mysqli_num_rows($mData) == 0)
		return "FAIL-No inventory exists for this pallet or serial reference.";
	$mPlt = "";
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
// Update Tables
		$mInvId = ($mRow['id']);
		$mPlt = ($mRow['plt_number']);
		$mTranQuery = "INSERT INTO transaction_history (id,short_code,part_number,serial_reference,ran_or_order,txn_qty,source_tag,from_location_code,to_location_code,date_created,last_updated,last_updated_by,transaction_reference_code,from_plt) VALUES(DEFAULT,'PTM','".($mRow['part_number'])."','".($mRow['serial_reference'])."','".($mRow['ran_order'])."',".($mRow['inventory_qty']).",'".($mRow['plt_number'])."','".($mRow['location_code'])."','".$mToLocCode."',now(),now(),'".$mCurrentUser."','PTM','".$mRow['plt_number']."')";	
		if (!mysqli_query($mConnection,$mTranQuery))
			return "FAIL-".mysqli_error($mConnection)."-".$mTranQuery;	
		
		if ($mInvId != "")
		{
			$mInvQuery = "UPDATE inventory_master SET current_location_id=".$mToLocId.",location_id=".$mToLocId.",location_code='".$mToLocCode."',last_updated=now(),last_updated_by='".$mParms['currentuser']."' WHERE id=".$mInvId." LIMIT 1";
//			$mInvQuery = "UPDATE inventory_master SET current_location_id=".$mToLocId.",location_id=".$mToLocId.",location_code='".$mToLocCode."',parent_tag_id=null, tag_reference='',last_updated=now(),last_updated_by='".$mParms['currentuser']."' WHERE id=".$mInvId." LIMIT 1";
			if (!mysqli_query($mConnection,$mInvQuery))
				return "FAIL-".mysqli_error($mConnection).$mInvQuery;
		}		
	}
	return("OK  -locate Complete");
}

// Set Location Filling Status
function locationFillingSts($mFromLocationId,$mFromLocationCode,$mToLocationId,$mToLocationCode,$mHost,$mUser,$mPwd,$mDbName)
{
	$mInvCount = 0;
// mysql connection
	$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
		die("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error()."-".$mHost."-".$mUser."-".$mPwd."-".$mDbName);
	$mDataQuery = "";
// Check for Inventory in Location	
	if ($mFromLocationId != "")
	{
		$mDataQuery = "SELECT inventory_master.id AS inv_count FROM inventory_master LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE inventory_master.current_location_id=".$mFromLocationId." AND inventory_qty > 0 AND (inventory_master.inventory_status_id IS null OR lower(inventory_status.inventory_status_code) NOT IN('pkd','plt')) LIMIT 1";
	}
	elseif ($mFromLocationCode != "")
	{
		$mDataQuery = "SELECT inventory_master.id AS inv_count FROM inventory_master JOIN location ON inventory_master.current_location_id=location.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE (location.location_code='".$mFromLocationCode."' OR location.location_hash='".$mFromLocationCode."') AND inventory_master.inventory_qty > 0 AND (inventory_master.inventory_status_id IS null OR lower(inventory_status.inventory_status_code) NOT IN('pkd','plt')) LIMIT 1";
	}
	if ($mDataQuery != "")
	{
		if (!mysqli_query($mConnection,$mDataQuery))
			return("FAIL-1".mysqli_error($mConnection)."-".$mDataQuery);
		$mData = mysqli_query($mConnection,$mDataQuery);
		$i = 0;
		while($mRow = mysqli_fetch_assoc($mData)) 
		{
			$mInvCount = ($mRow['inv_count']);
			$i++;
		}
		if ($i == 0)
		{
			if (($mFromLocationId == "") && ($mFromLocationCode != ""))
			{
				$mDataQuery = "SELECT location.id AS id FROM location WHERE (location_hash ='".$mFromLocationCode."' OR location_code = '".$mFromLocationCode."') LIMIT 1";
				if (!$mData = mysqli_query($mConnection,$mDataQuery))
					return("FAIL-2".mysqli_error($mConnection)."-".$mDataQuery);
				$i=0;
				while($mRow = mysqli_fetch_assoc($mData)) 
				{
					$mFromLocationId = ($mRow['id']);
					$i++;
				}
			}

			if ($mFromLocationId != "")
			{
				$mDataQuery = "UPDATE location SET location.filling_status_id=(SELECT id FROM location_filling_status WHERE lower(filling_code) = 'empty') WHERE location.id=".$mFromLocationId." LIMIT 1";
				if (!mysqli_query($mConnection,$mDataQuery))
					return ("FAIL-3".mysqli_error($mConnection)."-".$mDataQuery);
			}
		}
	}
// To Location
	if (($mToLocationId != "") || ($mToLocationCode != ""))
	{
// Check for Inventory in Location
		$mDataQuery = "";
		if ($mToLocationId != "")
		{
			$mdataQuery = "SELECT inventory_master.id AS inv_count FROM inventory_master LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE inventory_master.current_location_id=".$mToLocationId." AND inventory_qty > 0 AND (inventory_master.inventory_status_id IS null OR lower(inventory_status.inventory_status_code) NOT IN('pkd','plt')) LIMIT 1";
		}
		elseif ($mToLocationCode != "")
		{
			$mDataQuery = "SELECT inventory_master.id AS inv_count FROM inventory_master JOIN location ON inventory_master.current_location_id=location.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE (location.location_code='".$mToLocationCode."' OR location.location_hash='".$mToLocationCode."') AND inventory_master.inventory_qty > 0 AND (inventory_master.inventory_status_id IS null OR lower(inventory_status.inventory_status_code) NOT IN('pkd','plt')) LIMIT 1";
		}
		if ($mDataQuery != "")
		{
			if (!$mData = mysqli_query($mConnection,$mDataQuery))
				return("FAIL-4".mysqli_error($mConnection)."-".$mDataQuery);
		
			$i = 0;
			while($mRow = mysqli_fetch_assoc($mData)) 
			{
				$mInvCount = ($mRow['inv_count']);
				$i++;
			}
			if ($i > 0)
			{
				if (($mToLocationId == "") && ($mToLocationCode != ""))
				{
					$mDataQuery = "SELECT location.id AS id FROM location WHERE (location_hash ='".$mToLocationCode."' OR location_code = '".$mToLocationCode."') LIMIT 1";
					if (!$mData = mysqli_query($mConnection,$mDataQuery))
						return("FAIL-5".mysqli_error($mConnection)."-".$mDataQuery);
					$i=0;
					while($mRow = mysqli_fetch_assoc($mData)) 
					{
						$mToLocationId = ($mRow['id']);
						$i++;
					}
				}

				if ($mToLocationId != "")
				{
					$mDataQuery = "SELECT id, filling_code FROM location_filling_status";
					if (!$mData = mysqli_query($mConnection,$mDataQuery))
						return("FAIL-6".mysqli_error($mConnection)."-".$mDataQuery);
					$i=0;
					$mFillId = 0;
					$mFullId = 0;
					$mClosedId = 0;
					$mQtineId = 0;
					$mNotIn = "";
					while($mRow = mysqli_fetch_assoc($mData)) 
					{
						if (strtolower($mRow['filling_code']) == "filling")
							$mFillId = ($mRow['id']);
						if (strtolower($mRow['filling_code']) == "full")
							$mFullId = ($mRow['id']);
						if (strtolower($mRow['filling_code']) == "closed")
							$mClosedId = ($mRow['id']);
						if (strtolower($mRow['filling_code']) == "qtine")
							$mQtineId = ($mRow['id']);
						$i++;
					}
					$mDataQuery = "UPDATE location SET location.filling_status_id=".$mFillId." WHERE location.id=".$mToLocationId;					
					if ($mFullId != 0)
						$mdataQuery .= " AND COALESCE(location.filling_status_id,0) <> ".$mFullId;
					if ($mClosedId != 0)
						$mdataQuery .= " COALESCE(AND location.filling_status_id,0) <> ".$mClosedId;
					if ($mQtineId != 0)
						$mdataQuery .= " AND COALESCE(location.filling_status_id,0) <> ".$mQtineId;
					$mDataQuery .= " LIMIT 1";
					if (!mysqli_query($mConnection,$mDataQuery))
						return ("FAIL-7".mysqli_error($mConnection)."-".$mDataQuery);
				}		
			}
		}
	}
//	return ("FAIL-TEST1-".$mDataQuery."-".$mToLocationId."-".$mToLocationCode);
	return("OK  -Location Filling Status");
}

// Create / Return Pallet Tag
function processPlt($mPlt,$mVirtualPalletLbl,$mTransactionTypeId,$mPltSts,$mCurrentUser,$mHost,$mUser,$mPwd,$mDbName)
{
//	$mParms = json_decode($mJsonObject, true);
// Blank Pallet
	if (($mVirtualPalletLbl == "0") && ($mPlt == ""))
		return("FAIL-Invalid Pallet");
// Check Pallet Type
	if ((substr($mPlt,0,3) == "PCK" && substr($mTransactionTypeId,0,2) != "PB"))
		return("FAIL-Invalid Pallet Type");
	elseif ((substr($mPlt,0,3) == "RCV" && substr($mTransactionTypeId,0,2) != "RB"))
		return("FAIL-Invalid Pallet Type");
	elseif ((substr($mPlt,0,3) == "RXD" && substr($mTransactionTypeId,0,3) != "JRB"))
		return("FAIL-Invalid Pallet Type");
	elseif ((substr($mPlt,0,3) == "REP" && substr($mTransactionTypeId,0,3) != "REPLEN"))
		return("FAIL-Invalid Pallet Type");
	
// mysql connection - Use Passed values...
		$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
			exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
	
// Check Pallet Status
	if ($mPlt != "" && $mPltSts != "")
	{
		$mDataQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_status_id AS inventory_status_id, inventory_status.inventory_status_code AS inventory_status_code FROM inventory_master LEFT JOIN tag on inventory_master.parent_tag_id=tag.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE tag.tag_reference='".$mPlt."' LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
			return "FAIL-1".mysqli_error($mConnection)."-".$mDataQuery;
				
		$mData = mysqli_query($mConnection,$mDataQuery);
		$mInvId = "";
		$mInvStsId = "";
		$mInvStsCode = "";
		$mRow = mysqli_fetch_assoc($mData);
		if (mysqli_num_rows($mData) > 0)
		{
			$mInvStsId = ($mRow['inventory_status_id']);
			$mInvStsCode = ($mRow['inventory_status_code']);
// Check Inventory Status of the Pallet
			if (strtolower($mInvStsCode) != strtolower($mPltSts))
			{
				return("FAIL-This Pallet is in Use.");
			}
		}		
	}

// Test for Existing Pallet / Tag
	if ($mPlt != "")
	{
// Select by Serial
		$mDataQuery = "SELECT inventory_master.parent_tag_id AS parent_tag_id, tag.tag_reference AS tag_reference FROM inventory_master LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE (inventory_master.serial_reference='".$mPlt."' OR inventory_master.serial_reference='".substr($mPlt,1)."') LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
			return "FAIL-2".mysqli_error($mConnection)."-".$mDataQuery;
				
		$mData = mysqli_query($mConnection,$mDataQuery);
		$mTagRef = "";
		$mRow = mysqli_fetch_assoc($mData); 
		$mTagRef = ($mRow['tag_reference']);
		if ($mTagRef != "")
		{
			return($mTagRef);
		}
		
		$mDataQuery = "SELECT id FROM tag WHERE tag_reference='".$mPlt."' AND (active IS null OR active = '1') LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
			return "FAIL-3".mysqli_error($mConnection)."-".$mDataQuery;
				
		$mData = mysqli_query($mConnection,$mDataQuery);
		$mTagId = "";
		$mRow = mysqli_fetch_assoc($mData); 
		$mTagId = ($mRow['id']);
		if ($mTagId == "")
		{
			$mDataQuery = "INSERT INTO tag (id,version,auto_generated,current_location_id,date_created,document_header_id,last_updated,last_updated_by,tag_reference,validated,active,picked) VALUES(DEFAULT,0,0,null,now(),null,now(),'".$mCurrentUser."','".$mPlt."',1,1,0)";
			if (!mysqli_query($mConnection,$mDataQuery))
				return "FAIL-4".mysqli_error($mConnection).$mDataQuery;
		}
		return($mPlt);
	}
// Create Virtual Pallet / Tag
	else
	{
		$mDataQuery = "INSERT INTO tag (id,version,auto_generated,current_location_id,date_created,document_header_id,last_updated,last_updated_by,tag_reference,validated,active,picked) VALUES(DEFAULT,0,0,null,now(),null,now(),'".$mCurrentUser."','PLT000000',1,1,0)";
		if (!mysqli_query($mConnection,$mDataQuery))
			return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
		$mTagId=mysqli_insert_id($mConnection);
		$mTagReference = "000000".round($mTagId);
		if (substr($mTransactionTypeId,0,2) == "PB")
			$mTagReference = "PCK".substr($mTagReference,-6);
		elseIf (substr($mTransactionTypeId,0,2) == "RB")
			$mTagReference = "RCV".substr($mTagReference,-6);
		elseIf (substr($mTransactionTypeId,0,3) == "JRB")
			$mTagReference = "RXD".substr($mTagReference,-6);
		elseIf (substr($mTransactionTypeId,0,3) == "REP")
			$mTagReference = "REP".substr($mTagReference,-6);
		else
			$mTagReference = "PLT".substr($mTagReference,-6);
		$mDataQuery = "UPDATE tag SET tag_reference='".$mTagReference."' WHERE id=".$mTagId." LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
				return "FAIL-5".mysqli_error($mConnection).$mDataQuery;
		return($mTagReference);
	}
}

// Create Receipt Header for unadvised Items
function addReceiptHeader($mHaulierRef,$mDelNote,$mTransactionTypeId,$mCurrentUser,$mHost,$mUser,$mPwd,$mDbName)
{
	if (($mHaulierRef == "") || ($mDelNote == ""))
		Return ("FAIL-Invalid Haulier or Delivery Note");
// mysql connection - Use Passed values...
	if (($mDbHost != null) && ($mDbHost != ""))
		$mConnection=mysqli_connect($mDbHost,$mDbUser,$mDbPwd,$mDbName) or
			exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// ... or get defaults from function defaultDbConnection
	else
		$mConnection =defaultDbConnection();

// Get id for inventory status 'ok'
	$mInvStsId = 0;
	$mInvRcvId = 0;

	$mDataQuery = "SELECT id AS id, inventory_status_code AS inventory_status_code FROM inventory_status";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
		if (strtolower($mRow['inventory_status_code']) == "ok")
			$mInvStsId = ($mRow['id']);
		elseif (strtolower($mRow['inventory_status_code']) == "rcv")
			$mInvRcvId = ($mRow['id']);
	}

// Get id for document status
	$mDocStsId = 0;
	$mDocCmpId = 0;
	$mDataQuery = "SELECT id AS id, document_status_code AS document_status_code FROM document_status";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	while($mRow = mysqli_fetch_assoc($mData))
	{
		if (strtolower($mRow['document_status_code']) == "open")
			$mDocStsId=($mRow['id']);
		if (strtolower($mRow['document_status_code']) == "complete")
			$mDocCmpId=($mRow['id']);
	}
	if ($mDocCmpId == null)
		$mDocCmpId = 1;
	
// check for invalid haulier / Del.note
	$mDocHdrId = "";
	$mDataQuery = "SELECT id AS id, vendor_id AS vendor_id, customer_reference AS customer_reference, expected_delivery_date AS expected_delivery_date FROM receipt_header WHERE haulier_reference = '".$mHaulierRef."' AND COALESCE(document_status_id,0) IN(0,".$mDocStsId.",".$mDocCmpId.") LIMIT 1";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	if (mysqli_num_rows($mData) == 0)
		return("FAIL-Invalid Haulier Reference.");

	$mRow = mysqli_fetch_assoc($mData);
	$mVendorId=($mRow['vendor_id']);
	$mExpectedDelivery = ($mRow['expected_delivery_date']);
	$mCustomerRef = ($mRow['customer_reference']);
	
// Create Receipt Header
	$mDataQuery = "INSERT INTO receipt_header (id,document_reference,haulier_reference,delivery_note,vendor_id,customer_reference,expected_delivery_date,document_status_id,date_created,created_by,last_updated_date,last_updated_by)";
	$mDataQuery .= " VALUES(DEFAULT,'RCP000000','".$mHaulierRef."','".$mDelNote."',".$mVendorId.",'','".$mExpectedDelivery."',".$mDocStsId.",now(),'".$mCurrentUser."',now(),'".$mCurrentUser."')";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mDocHdrId=mysqli_insert_id($mConnection);
	$mDocReference = "000000".round($mDocHdrId);
	$mDocReference = "RCP".substr($mDocReference,-6);
	$mDataQuery = "UPDATE receipt_header SET document_reference='".$mDocReference."' WHERE id=".$mDocHdrId." LIMIT 1";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;

	return("OK  -");
}

function postRcts($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName)
{
	$mParms = json_decode($mJsonObject, true);

// mysql connection - Use Passed values...
		$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
			exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());

// Get id for document status
	$mDocStsId = 0;
	$mDocCmpId = 0;
	$mDataQuery = "SELECT id AS id, document_status_code AS document_status_code FROM document_status";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	while($mRow = mysqli_fetch_assoc($mData))
	{
		if (strtolower($mRow['document_status_code']) == "open")
			$mDocStsId=($mRow['id']);
		if (strtolower($mRow['document_status_code']) == "complete")
			$mDocCmpId=($mRow['id']);
	}
	if ($mDocCmpId == null)
		$mDocCmpId = 1;
	
// Get id for inventory status 'ok'
	$mInvStsId = 0;
	$mDataQuery = "SELECT id AS id FROM inventory_status WHERE lower(inventory_status_code) = 'ok' LIMIT 1";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	$mRow = mysqli_fetch_assoc($mData);
	$mInvStsId = ($mRow['id']);
	
	$mDataQuery = "SELECT id AS id, location_code AS location_code FROM location WHERE location.location_hash='".$mParms['tolocationhashcode']."' OR location.location_code='".$mParms['tolocationhashcode']."' LIMIT 1";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-1".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	if (mysqli_num_rows($mData) == 0)
	{
		return "FAIL-Invalid Location Code".$mDataQuery;
	}
	$mRow = mysqli_fetch_assoc($mData);
	$mToLocId = ($mRow['id']);
	$mToLocCode = ($mRow['location_code']);
	$mRctDtlId = "";
	$mRctCtsQty = 0;
	$mRctHdrId = "";
	$mTxnQty = 0;
	$mPartId = "";
	if (($mParms['quantity']) && ($mParms['quantity'] != null) && ($mParms['quantity'] != ""))
	{
// Get Part Conversion Factor
		$mConvFactor = 1;
		$mDataQuery = "SELECT id AS id, conversion_factor AS conversion_factor FROM part WHERE part_number = '".$mParms['partnumber']."' LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
			return "FAIL-2".mysqli_error($mConnection).$mDataQuery;	
		$mData = (mysqli_query($mConnection,$mDataQuery));
		if (mysqli_num_rows($mData) == 0)
		{
			return("FAIL-Invalid Part Number");
		}
		while($mRow = mysqli_fetch_assoc($mData))
		{
			$mPartId = ($mRow['id']);
			$mConvFactor = ($mRow['conversion_factor']);
		}
		
// Validate Scanned Qty against Rec.Qty.
		$mRctDtlQty = "";
		$mHaulierRef = "";
		$mDataQuery = "SELECT receipt_header.id AS hdr_id, receipt_header.document_reference AS document_reference, receipt_header.haulier_reference AS haulier_reference, receipt_header.jis_ind AS jis_ind, receipt_detail.id AS id, receipt_detail.received_qty AS received_qty FROM receipt_detail JOIN receipt_body ON receipt_detail.receipt_body_id=receipt_body.id JOIN receipt_header ON receipt_body.receipt_header_id=receipt_header.id WHERE receipt_detail.part_number='".$mParms['partnumber']."' AND receipt_detail.serial_reference='".$mParms['serialreference']."' LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
			return "FAIL-3".mysqli_error($mConnection).$mDataQuery;
		$mData = (mysqli_query($mConnection,$mDataQuery));
		$mRow = mysqli_fetch_assoc($mData);
		$mRctDtlId = ($mRow['id']);
		$mRctDtlQty = ($mRow['received_qty']);
		$mHaulierRef = ($mRow['haulier_reference']);
		$mRctHdrId = ($mRow['hdr_id']);
		$mRctDocRef = ($mRow['document_reference']);
		$mRctJisInd = ($mRow['jis_ind']);
		
		if (($mRctDtlQty != "") && ($mParms['quantity']*$mConvFactor != $mRctDtlQty))
		{
			return "FAIL-Scanned Qty does not match Receipt Qty.";
		}
// Store Converted Qty.		
		$mRctCtsQty = ($mParms['quantity']*$mConvFactor);
		$mTxnQty = ($mParms['quantity']*$mConvFactor);
	}
// Check for valid Inventory
	$mDataQuery = "SELECT inventory_master.id AS id, part.part_number AS part_number, inventory_master.serial_reference AS serial_reference, inventory_master.ran_or_order AS ran_order, inventory_master.inventory_qty AS inventory_qty, tag.tag_reference AS plt_number, location.location_code AS location_code FROM inventory_master JOIN part ON inventory_master.part_id=part.id LEFT JOIN location ON inventory_master.current_location_id=location.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE part.part_number='".$mParms['partnumber']."' AND inventory_master.serial_reference='".$mParms['serialreference']."' AND inventory_qty>0 LIMIT 1";  
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	if (mysqli_num_rows($mData) == 0)
		return "FAIL-No inventory exists for this serial reference.";
	$mInvId = "";
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
		if ($mRctCtsQty == 0)
			$mRctCtsQty = ($mRow['inventory_qty']);
		$mTxnQty = $mRctCtsQty;
		$mInvId = ($mRow['id']);
		if ($mConvFactor > 0)
			$mTranQuery = "INSERT INTO transaction_history (id,short_code,part_number,serial_reference,ran_or_order,txn_qty,source_tag,from_location_code,to_location_code,date_created,last_updated,last_updated_by,transaction_reference_code,conversion_factor) VALUES(DEFAULT,'".$mParms['transactiontypeid']."','".($mRow['part_number'])."','".($mRow['serial_reference'])."','".($mRow['ran_order'])."',".$mTxnQty.",'".($mRow['plt_number'])."','".($mRow['location_code'])."','".$mToLocCode."',now(),now(),'".$mParms['currentuser']."','".$mParms['transactiontypeid']."',".$mConvFactor.")";	
		else
			$mTranQuery = "INSERT INTO transaction_history (id,short_code,part_number,serial_reference,ran_or_order,txn_qty,source_tag,from_location_code,to_location_code,date_created,last_updated,last_updated_by,transaction_reference_code,conversion_factor) VALUES(DEFAULT,'".$mParms['transactiontypeid']."','".($mRow['part_number'])."','".($mRow['serial_reference'])."','".($mRow['ran_order'])."',".$mTxnQty.",'".($mRow['plt_number'])."','".($mRow['location_code'])."','".$mToLocCode."',now(),now(),'".$mParms['currentuser']."','".$mParms['transactiontypeid']."',1)";	
		if (!mysqli_query($mConnection,$mTranQuery))
			return "FAIL-".mysqli_error($mConnection)."-".$mTranQuery;
	}
// Full Box Pick
	if ($mInvId != "")
	{
		if ($mParms['transactiontypeid'] == "FQA")
			$mDataQuery = "UPDATE inventory_master SET current_location_id=".$mToLocId.",location_id=".$mToLocId.",location_code='".$mToLocCode."',last_updated=now(),last_updated_by='".$mParms['currentuser']."', inventory_status_id=".$mInvStsId.", requires_inspection=0 WHERE id=".$mInvId." LIMIT 1";
		elseif ($mParms['transactiontypeid'] == "TQA")
			$mDataQuery = "UPDATE inventory_master SET current_location_id=".$mToLocId.",location_id=".$mToLocId.",location_code='".$mToLocCode."',last_updated=now(),last_updated_by='".$mParms['currentuser']."', inventory_status_id=".$mInvStsId.", requires_inspection=1 WHERE id=".$mInvId." LIMIT 1";
		else
			$mDataQuery = "UPDATE inventory_master SET current_location_id=".$mToLocId.",location_id=".$mToLocId.",location_code='".$mToLocCode."',last_updated=now(),last_updated_by='".$mParms['currentuser']."', inventory_status_id=".$mInvStsId." WHERE id=".$mInvId." LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
			return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	}
	if ($mRctDtlId != "")
	{
		try
		{
			$mDataQuery = "UPDATE receipt_detail SET cts_qty=".$mRctCtsQty.",last_updated_date=now(),last_updated_by='".$mParms['currentuser']."' WHERE id=".$mRctDtlId." LIMIT 1";
			if (!mysqli_query($mConnection,$mDataQuery))
				return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
		}
		catch(Exception $e)
		{
			return("FAIL-CTS Qty.");
		}
	}
// Flag Receipt if All CTS is complete
//	$mDataQuery = "SELECT receipt_header.id AS id FROM receipt_header JOIN receipt_body ON receipt_body.receipt_header_id=receipt_header.id JOIN receipt_detail ON receipt_detail.receipt_body_id=receipt_body.id WHERE receipt_header.haulier_reference='".$mHaulierRef."' AND (receipt_body.received_qty<receipt_body.advised_qty OR (receipt_detail.received_qty=0 OR receipt_detail.received_qty<>receipt_detail.cts_qty)) LIMIT 1";
	if ($mRctHdrId != "")
	{
		$mDataQuery = "SELECT receipt_header.id AS id FROM receipt_header JOIN receipt_body ON receipt_body.receipt_header_id=receipt_header.id LEFT JOIN receipt_detail ON receipt_detail.receipt_body_id=receipt_body.id WHERE receipt_header.id=".$mRctHdrId." AND (receipt_body.received_qty<receipt_body.advised_qty OR (receipt_detail.received_qty IS null OR receipt_detail.received_qty=0 OR receipt_detail.received_qty<>receipt_detail.cts_qty)) LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
			return "FAIL-".mysqli_error($mConnection).$mDataQuery;
		$mData = (mysqli_query($mConnection,$mDataQuery));
		if (mysqli_num_rows($mData) == 0)
		{
// Get id for document status 'closed'		
			$mDataQuery = "SELECT id AS id FROM document_status WHERE lower(document_status_code) = 'closed' LIMIT 1";
			if (!mysqli_query($mConnection,$mDataQuery))
				return "FAIL-".mysqli_error($mConnection).$mDataQuery;
			$mData = (mysqli_query($mConnection,$mDataQuery));
			$mRow = mysqli_fetch_assoc($mData);
			$mDocStsId = ($mRow['id']);
			$mDataQuery = "UPDATE receipt_header SET document_status_id=".$mDocStsId.",last_updated_date=now(),last_updated_by='".$mParms['currentuser']."' WHERE id=".$mRctHdrId." LIMIT 1";
			if (!mysqli_query($mConnection,$mDataQuery))
				return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
			
// Send IDOC Trigger for Confirm Receipt
//			http://172.16.1.70:8092/screen/writeCompleteJisReceiptMessage?documentReference=RCP000193
//			http://172.16.1.70:8092/screen/writeCompleteReceiptMessage?documentReference=RCP000193

// Get Server Data from URL
			$mJsonArray = array();
			$mJsonArray['documentReference'] = $mRctDocRef;
// Convert Array to Json Object
			try
			{
				$mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
			}
			catch(Exception $e)
			{
				exit("FAIL-Json Error");
			}
// Replace default Server Tomcat Service
			$mConnectp = str_replace(":8081/vantec",":8092/screen",$mConnect);		
			$ch = curl_init();
			try
			{
				if ($mJisInd != "")
					curl_setopt($ch, CURLOPT_URL, $mConnectp."writeCompleteJisReceiptMessage?documentReference=".$mRctDocRef);
				else
					curl_setopt($ch, CURLOPT_URL, $mConnectp."writeCompleteReceiptMessage?documentReference=".$mRctDocRef);
				curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $mJsonObject);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				$mResult = curl_exec($ch);
				$mErrors = curl_error($ch);
				$mResponse = curl_getinfo($ch, CURLINFO_HTTP_CODE);

				curl_close($ch);
				if ($mResponse != "200")
					print_r("FAIL-Unexpected System Error -".$mResult.":".$mResponse.":".$mErrors.":".$mJsonObject);
				else
				{
					$mErrMsg = "OK  - Post Complete";
				}
			}
			catch (Exception $e)
			{
				exit("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
			}			
		}
	}	
	return("OK  -locate Complete");
}
/*
function postPiecePick($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName)
{
	$mParms = json_decode($mJsonObject, true);

// mysql connection - Use Passed values...
		$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
			exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());

// Get id for document status
	$mDocStsId = 0;
	$mDocCmpId = 0;
	$mDataQuery = "SELECT id AS id, document_status_code AS document_status_code FROM document_status";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	while($mRow = mysqli_fetch_assoc($mData))
	{
		if (strtolower($mRow['document_status_code']) == "open")
			$mDocStsId=($mRow['id']);
		if (strtolower($mRow['document_status_code']) == "complete")
			$mDocCmpId=($mRow['id']);
	}
	if ($mDocCmpId == null)
		$mDocCmpId = 1;
	
// Get id for inventory status
	$mInvStsId = 0;
	$mInvRcvId = 0;
	$mDataQuery = "SELECT id AS id, inventory_status_code AS inventory_status_code FROM inventory_status";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
		if (strtolower($mRow['inventory_status_code']) == "ok")
			$mInvStsId = ($mRow['id']);
		elseif (strtolower($mRow['inventory_status_code']) == "rcv")
			$mInvRcvId = ($mRow['id']);
		elseif (strtolower($mRow['inventory_status_code']) == "gi")
			$mInvRcvId = ($mRow['id']);
	}
	if ($mInvStsId == null)
		$mInvStsId = 0;
	if ($mInvRcvId == null)
		$mInvRcvId = 0;
	
	$mDataQuery = "SELECT id AS id, location_code AS location_code FROM location WHERE location.location_hash='".$mParms['tolocationhashcode']."' OR location.location_code='".$mParms['tolocationhashcode']."' LIMIT 1";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-1".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	if (mysqli_num_rows($mData) == 0)
	{
		return "FAIL-Invalid Location Code".$mDataQuery;
	}
	$mRow = mysqli_fetch_assoc($mData);
	$mToLocId = ($mRow['id']);
	$mToLocCode = ($mRow['location_code']);
	$mRctDtlId = "";
	$mRctCtsQty = 0;
	$mRctHdrId = "";
	$mTxnQty = 0;
	$mPartId = "";
	if (($mParms['quantity']) && ($mParms['quantity'] != null) && ($mParms['quantity'] != ""))
	{
// Get Part Conversion Factor
		$mConvFactor = 1;
		$mDataQuery = "SELECT id AS id, conversion_factor AS conversion_factor FROM part WHERE part_number = '".$mParms['partnumber']."' LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
			return "FAIL-2".mysqli_error($mConnection).$mDataQuery;	
		$mData = (mysqli_query($mConnection,$mDataQuery));
		if (mysqli_num_rows($mData) == 0)
		{
			return("FAIL-Invalid Part Number");
		}
		while($mRow = mysqli_fetch_assoc($mData))
		{
			$mPartId = ($mRow['id']);
			$mConvFactor = ($mRow['conversion_factor']);
		}
		
// Validate Scanned Qty against Rec.Qty.
		$mRctDtlQty = "";
		$mHaulierRef = "";
		$mDataQuery = "SELECT receipt_header.id AS hdr_id, receipt_header.document_reference AS document_reference, receipt_header.haulier_reference AS haulier_reference, receipt_header.jis_ind AS jis_ind, receipt_detail.id AS id, receipt_detail.received_qty AS received_qty FROM receipt_detail JOIN receipt_body ON receipt_detail.receipt_body_id=receipt_body.id JOIN receipt_header ON receipt_body.receipt_header_id=receipt_header.id WHERE receipt_detail.part_number='".$mParms['partnumber']."' AND receipt_detail.serial_reference='".$mParms['serialreference']."' LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
			return "FAIL-3".mysqli_error($mConnection).$mDataQuery;
		$mData = (mysqli_query($mConnection,$mDataQuery));
		$mRow = mysqli_fetch_assoc($mData);
		$mRctDtlId = ($mRow['id']);
		$mRctDtlQty = ($mRow['received_qty']);
		$mHaulierRef = ($mRow['haulier_reference']);
		$mRctHdrId = ($mRow['hdr_id']);
		$mRctDocRef = ($mRow['document_reference']);
		$mRctJisInd = ($mRow['jis_ind']);
		
		if (($mRctDtlQty != "") && ($mParms['quantity']*$mConvFactor > $mRctDtlQty))
		{
			return "FAIL-Scanned Qty does not match Receipt Qty.";
		}
// Store Converted Qty.		
		$mQty = ($mParms['quantity']*$mConvFactor);
		$mTxnQty = ($mParms['quantity']*$mConvFactor);
	}
// Check for valid Inventory
	$mDataQuery = "SELECT inventory_master.id AS id, part.part_number AS part_number, inventory_master.serial_reference AS serial_reference, inventory_master.ran_or_order AS ran_order, inventory_master.inventory_qty AS inventory_qty,inventory_master.product_type_id AS product_type_id, inventory_master.pruf_cube AS pruf_cube, tag.tag_reference AS plt_number, location.location_code AS location_code FROM inventory_master JOIN part ON inventory_master.part_id=part.id LEFT JOIN location ON inventory_master.current_location_id=location.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE part.part_number='".$mParms['partnumber']."' AND inventory_master.serial_reference='".$mParms['serialreference']."' AND inventory_master.inventory_status_id IN(0,$mInvStsId) AND inventory_qty>0 LIMIT 1";  
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	if (mysqli_num_rows($mData) == 0)
		return "FAIL-No inventory exists for this serial reference.";
	$mInvId = "";
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
		$mInvQty = ($mRow['inventory_qty']);
		if ($mQty == 0)
			$mQty = ($mRow['inventory_qty']);
		$mTxnQty = $mQty;
		$mInvId = ($mRow['id']);
		$mInvPrdId = $mRow['product_type_id'];
		$mInvPruf = $mRow['pruf_cube'];
		$mRanOrOrder = $mRow['ran_order'];
		if ($mConvFactor > 0)
			$mTranQuery = "INSERT INTO transaction_history (id,short_code,part_number,serial_reference,ran_or_order,txn_qty,source_tag,from_location_code,to_location_code,date_created,last_updated,last_updated_by,transaction_reference_code,conversion_factor) VALUES(DEFAULT,'".$mParms['transactiontypeid']."','".($mRow['part_number'])."','".($mRow['serial_reference'])."','".($mRow['ran_order'])."',".$mTxnQty.",'".($mRow['plt_number'])."','".($mRow['location_code'])."','".$mToLocCode."',now(),now(),'".$mParms['currentuser']."','".$mParms['transactiontypeid']."',".$mConvFactor.")";	
		else
			$mTranQuery = "INSERT INTO transaction_history (id,short_code,part_number,serial_reference,ran_or_order,txn_qty,source_tag,from_location_code,to_location_code,date_created,last_updated,last_updated_by,transaction_reference_code,conversion_factor) VALUES(DEFAULT,'".$mParms['transactiontypeid']."','".($mRow['part_number'])."','".($mRow['serial_reference'])."','".($mRow['ran_order'])."',".$mTxnQty.",'".($mRow['plt_number'])."','".($mRow['location_code'])."','".$mToLocCode."',now(),now(),'".$mParms['currentuser']."','".$mParms['transactiontypeid']."',1)";	
		if (!mysqli_query($mConnection,$mTranQuery))
			return "FAIL-".mysqli_error($mConnection)."-".$mTranQuery;
	}
	if ($mInvId != "")
	{
// full box transaction
		if ($mInvQty <= $mQty)
		{
			$mDataQuery = "UPDATE inventory_master SET current_location_id=".$mToLocId.",location_id=".$mToLocId.",location_code='".$mToLocCode."',last_updated=now(),last_updated_by='".$mParms['currentuser']."', inventory_status_id=".$mInvStsId." WHERE id=".$mInvId." LIMIT 1";
			if (!mysqli_query($mConnection,$mDataQuery))
				return "FAIL-".mysqli_error($mConnection).$mDataQuery;
		}
		else
		{
			if ($mInvPrdId != null)
				$mDataQuery = "INSERT INTO inventory_master (id,version,allocated_qty,current_disposition_id,current_inventory_status_id,current_location_id,location_id,location_code,date_created,created_by,expiry_date,inventory_qty,available_qty,last_updated,last_updated_by,parent_tag_id,part_id,part_number,ran_or_order,recorded_missing,requires_decant,requires_inspection,serial_reference,originating_detail_id,conversion_factor,stock_date,active,inventory_status_id,product_type_id,pruf_cube) VALUES(DEFAULT,0,0,null,null,".$mToLocId.",".$mToLocId.",'".$mToLocCode."',now(),'".$mParms['currentuser']."',null,".$mQty.",".$mQty.",now(),'".$mParms['currentuser']."',null,".$mPartId.",'".$mParms['partnumber']."','".$mRanOrOrder."',0,0,0,null,null,".$mConvFactor.",now(),1,".$mInvPrdId.",null,".$mInvPruf.")";
			else
				$mDataQuery = "INSERT INTO inventory_master (id,version,allocated_qty,current_disposition_id,current_inventory_status_id,current_location_id,location_id,location_code,date_created,created_by,expiry_date,inventory_qty,available_qty,last_updated,last_updated_by,parent_tag_id,part_id,part_number,ran_or_order,recorded_missing,requires_decant,requires_inspection,serial_reference,originating_detail_id,conversion_factor,stock_date,active,inventory_status_id,product_type_id,pruf_cube) VALUES(DEFAULT,0,0,null,null,".$mToLocId.",".$mToLocId.",'".$mToLocCode."',now(),'".$mParms['currentuser']."',null,".$mQty.",".$mQty.",now(),'".$mParms['currentuser']."',null,".$mPartId.",'".$mParms['partnumber']."','".$mRanOrOrder."',0,0,0,null,null,".$mConvFactor.",now(),1,null,null,".$mInvPruf.")";
			if (!mysqli_query($mConnection,$mDataQuery))
				return "FAIL-".mysqli_error($mConnection).$mDataQuery;
			$mDataQuery = "UPDATE inventory_master SET inventory_qty=inventory_qty-".$mTxnQty.",last_updated=now(),last_updated_by='".$mParms['currentuser']."', inventory_status_id=".$mInvStsId." WHERE id=".$mInvId." LIMIT 1";
			if (!mysqli_query($mConnection,$mDataQuery))
				return "FAIL-".mysqli_error($mConnection).$mDataQuery;
		}
	}
	if ($mRctDtlId != "")
	{
		try
		{
			$mDataQuery = "UPDATE receipt_detail SET cts_qty=".$mQty.",last_updated_date=now(),last_updated_by='".$mParms['currentuser']."' WHERE id=".$mRctDtlId." LIMIT 1";
			if (!mysqli_query($mConnection,$mDataQuery))
				return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
		}
		catch(Exception $e)
		{
			return("FAIL-Receipt Qty.");
		}
	}
// Flag Receipt if All CTS is complete
//	$mDataQuery = "SELECT receipt_header.id AS id FROM receipt_header JOIN receipt_body ON receipt_body.receipt_header_id=receipt_header.id JOIN receipt_detail ON receipt_detail.receipt_body_id=receipt_body.id WHERE receipt_header.haulier_reference='".$mHaulierRef."' AND (receipt_body.received_qty<receipt_body.advised_qty OR (receipt_detail.received_qty=0 OR receipt_detail.received_qty<>receipt_detail.cts_qty)) LIMIT 1";
	if ($mRctHdrId != "")
	{
		$mDataQuery = "SELECT receipt_header.id AS id FROM receipt_header JOIN receipt_body ON receipt_body.receipt_header_id=receipt_header.id LEFT JOIN receipt_detail ON receipt_detail.receipt_body_id=receipt_body.id WHERE receipt_header.id=".$mRctHdrId." AND (receipt_body.received_qty<receipt_body.advised_qty OR (receipt_detail.received_qty IS null OR receipt_detail.received_qty=0 OR receipt_detail.received_qty<>receipt_detail.cts_qty)) LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
			return "FAIL-".mysqli_error($mConnection).$mDataQuery;
		$mData = (mysqli_query($mConnection,$mDataQuery));
		if (mysqli_num_rows($mData) == 0)
		{
// Get id for document status 'closed'		
			$mDataQuery = "SELECT id AS id FROM document_status WHERE lower(document_status_code) = 'closed' LIMIT 1";
			if (!mysqli_query($mConnection,$mDataQuery))
				return "FAIL-".mysqli_error($mConnection).$mDataQuery;
			$mData = (mysqli_query($mConnection,$mDataQuery));
			$mRow = mysqli_fetch_assoc($mData);
			$mDocStsId = ($mRow['id']);
			$mDataQuery = "UPDATE receipt_header SET document_status_id=".$mDocStsId.",last_updated_date=now(),last_updated_by='".$mParms['currentuser']."' WHERE id=".$mRctHdrId." LIMIT 1";
			if (!mysqli_query($mConnection,$mDataQuery))
				return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
			
// Send IDOC Trigger for Confirm Receipt
//			http://172.16.1.70:8092/screen/writeCompleteJisReceiptMessage?documentReference=RCP000193
//			http://172.16.1.70:8092/screen/writeCompleteReceiptMessage?documentReference=RCP000193

// Get Server Data from URL
			$mJsonArray = array();
			$mJsonArray['documentReference'] = $mRctDocRef;
// Convert Array to Json Object
			try
			{
				$mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
			}
			catch(Exception $e)
			{
				exit("FAIL-Json Error");
			}
// Replace default Server Tomcat Service
			$mConnectp = str_replace(":8081/vantec",":8092/screen",$mConnect);		
			$ch = curl_init();
			try
			{
				if ($mJisInd != "")
					curl_setopt($ch, CURLOPT_URL, $mConnectp."writeCompleteJisReceiptMessage?documentReference=".$mRctDocRef);
				else
					curl_setopt($ch, CURLOPT_URL, $mConnectp."writeCompleteReceiptMessage?documentReference=".$mRctDocRef);
				curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $mJsonObject);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				$mResult = curl_exec($ch);
				$mErrors = curl_error($ch);
				$mResponse = curl_getinfo($ch, CURLINFO_HTTP_CODE);

				curl_close($ch);
				if ($mResponse != "200")
					print_r("FAIL-Unexpected System Error -".$mResult.":".$mResponse.":".$mErrors.":".$mJsonObject);
				else
				{
					$mErrMsg = "OK  - Post Complete";
				}
			}
			catch (Exception $e)
			{
				exit("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
			}			
		}
	}
	
	return("OK  -locate Complete");
}
*/
function postPts($mPltNumber,$mPartNumber,$mToLocHash,$mCurrentUser,$mHost,$mUser,$mPwd,$mDbName)
{
// mysql connection - Use Passed values...
	$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
		exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
	
	$mDataQuery = "SELECT id AS id, location_code AS location_code FROM location WHERE location.location_hash='".$mToLocHash."' LIMIT 1";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	if (mysqli_num_rows($mData) == 0)
		return "FAIL-Invalid Location Code.";
	$mRow = mysqli_fetch_assoc($mData);
	$mToLocId = ($mRow['id']);
	$mToLocCode = ($mRow['location_code']);
// Get id for inventory status 'ok'
	$mInvStsId = 0;
	$mDataQuery = "SELECT id AS id FROM inventory_status WHERE lower(inventory_status_code) = 'ok' LIMIT 1";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	$mRow = mysqli_fetch_assoc($mData);
	$mInvStsId = ($mRow['id']);
// Get id for document status
	$mDocStsId = null;
	$mDocCmpId = null;
	$mDataQuery = "SELECT id AS id, document_status_code AS document_status_code FROM document_status";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	while($mRow = mysqli_fetch_assoc($mData))
	{
		if (strtolower($mRow['document_status_code']) == "open")
			$mDocStsId=($mRow['id']);
		if (strtolower($mRow['document_status_code']) == "complete")
			$mDocCmpId=($mRow['id']);
	}
	if ($mDocCmpId == null)
		$mDocCmpId = 1;
// Get Existing Inventory
	$mDataQuery = "SELECT inventory_master.id AS id, part.part_number AS part_number, inventory_master.serial_reference AS serial_reference, inventory_master.ran_or_order AS ran_order, inventory_master.inventory_qty AS inventory_qty, tag.tag_reference AS plt_number, location.location_code AS location_code FROM inventory_master JOIN part ON inventory_master.part_id=part.id JOIN location ON inventory_master.current_location_id=location.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE part.part_number='".$mPartNumber."' AND (tag.tag_reference='".$mPltNumber."' OR inventory_master.serial_reference = '".$mPltNumber."') AND inventory_qty>0";  
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	if (mysqli_num_rows($mData) == 0)
		return "FAIL-No inventory exists for this pallet or serial reference.";
	$mPlt = "";
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
// Check That Receipt is closed
		$mJisInd = "";
		$mRctQuery = "SELECT receipt_header.id AS id, receipt_header.document_status_id AS document_status_id, receipt_header.jis_ind AS jis_ind FROM receipt_header JOIN receipt_body ON receipt_body.receipt_header_id=receipt_header.id JOIN receipt_detail ON receipt_detail.receipt_body_id=receipt_body.id WHERE receipt_detail.part_number='".$mPartNumber."' AND receipt_detail.serial_reference='".$mRow['serial_reference']."' LIMIT 1";
		if (!mysqli_query($mConnection,$mRctQuery))
			return "FAIL-".mysqli_error($mConnection).$mRctQuery;
		$mRctData = (mysqli_query($mConnection,$mRctQuery));
		if (mysqli_num_rows($mRctData) > 0)
		{
			$mRctRow = mysqli_fetch_assoc($mRctData);
			if (($mRctRow['document_status_id'] == $mDocStsId) || ($mRctRow['document_status_id'] == $mDocCmpId))
				return "FAIL-Receipt is not closed";
//				return "FAIL-Receipt is not closed".$mRctRow['document_status_id']."-".$mDocStsId."-".$mRctQuery."-".$mRctRow['id'];
			$mJisInd = $mRctRow['jis_ind'];
		}
// Update Tables
		$mInvId = ($mRow['id']);
		$mPlt = ($mRow['plt_number']);
		$mTranQuery = "INSERT INTO transaction_history (id,short_code,part_number,serial_reference,ran_or_order,txn_qty,source_tag,from_location_code,to_location_code,date_created,last_updated,last_updated_by,transaction_reference_code,from_plt) VALUES(DEFAULT,'PTS','".($mRow['part_number'])."','".($mRow['serial_reference'])."','".($mRow['ran_order'])."',".($mRow['inventory_qty']).",'".($mRow['plt_number'])."','".($mRow['location_code'])."','".$mToLocCode."',now(),now(),'".$mCurrentUser."','PTS','".$mRow['plt_number']."')";	
		if (!mysqli_query($mConnection,$mTranQuery))
			return "FAIL-".mysqli_error($mConnection)."-".$mTranQuery;	
		
		if ($mInvId != "")
		{
			if ((substr($mPlt,0,3) == "RXD") || ($mJis_Ind == "1"))
				$mInvQuery = "UPDATE inventory_master SET current_location_id=".$mToLocId.",location_id=".$mToLocId.",location_code='".$mToLocCode."',last_updated=now(),last_updated_by='".$mParms['currentuser']."' WHERE id=".$mInvId." LIMIT 1";
			else
				$mInvQuery = "UPDATE inventory_master SET current_location_id=".$mToLocId.",location_id=".$mToLocId.",location_code='".$mToLocCode."',last_updated=now(),last_updated_by='".$mParms['currentuser']."' WHERE id=".$mInvId." LIMIT 1";
			if (!mysqli_query($mConnection,$mInvQuery))
				return "FAIL-".mysqli_error($mConnection).$mInvQuery;
		}		
	}
	return("OK  -locate Complete");
}

// General Transaction Processing
function postTransaction($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName)
{
	$mReturn = "";
	$mParms = json_decode($mJsonObject, true);
	$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
		exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
	if ($mParms['transactiontypeid'])
	{
// Get id for inventory status 'ok'
		$mInvStsId = 0;
		$mInvRcvId = 0;
		$mDataQuery = "SELECT id AS id, inventory_status_code AS inventory_status_code FROM inventory_status";
		if (!mysqli_query($mConnection,$mDataQuery))
			return "FAIL-".mysqli_error($mConnection).$mDataQuery;
		$mData = (mysqli_query($mConnection,$mDataQuery));
		while($mRow = mysqli_fetch_assoc($mData)) 
		{
			if (strtolower($mRow['inventory_status_code']) == "ok")
				$mInvStsId = ($mRow['id']);
			elseif (strtolower($mRow['inventory_status_code']) == "rcv")
				$mInvRcvId = ($mRow['id']);
			elseif (strtolower($mRow['inventory_status_code']) == "gi")
				$mInvRcvId = ($mRow['id']);
		}
		if ($mInvStsId == null)
			$mInvStsId = 0;
		if ($mInvRcvId == null)
			$mInvRcvId = 0;
// Get id for document status
		$mDocStsId = 0;
		$mDocCmpId = 0;
		$mDataQuery = "SELECT id AS id, document_status_code AS document_status_code FROM document_status";
		if (!mysqli_query($mConnection,$mDataQuery))
			return "FAIL-".mysqli_error($mConnection).$mDataQuery;
		$mData = (mysqli_query($mConnection,$mDataQuery));
		while($mRow = mysqli_fetch_assoc($mData))
		{
			if (strtolower($mRow['document_status_code']) == "open")
				$mDocStsId=($mRow['id']);
			if (strtolower($mRow['document_status_code']) == "complete")
				$mDocCmpId=($mRow['id']);
		}
		if ($mDocStsId == null)
			$mDocStsId = 0;
		if ($mDocCmpId == null)
			$mDocCmpId = 0;
		
// Get id for product type
		$mPrufId = 0;
		$mProdId = 0;
		$mDataQuery = "SELECT id AS id, product_type_code AS product_type_code FROM product_type";
		if (!mysqli_query($mConnection,$mDataQuery))
			return "FAIL-".mysqli_error($mConnection).$mDataQuery;
		$mData = (mysqli_query($mConnection,$mDataQuery));
		while($mRow = mysqli_fetch_assoc($mData)) 
		{
			if (strtolower($mRow['product_type_code']) == "prod")
				$mProdId = ($mRow['id']);
			elseif (strtolower($mRow['product_type_code']) == "prufcube")
				$mPrufId = ($mRow['id']);
		}
		if ($mProdId == null)
			$mProdId = 0;
		if ($mPrufId == null)
			$mPrufId = 0;
// Validate Haulier Reference
		$mDocumentHdrId = "";
		$mDocumentReference = "";
		if ($mParms['haulierreference'])
		{
			if (($mParms['deliverynote']) && ($mParms['deliverynote'] != ""))
			{
//				$mDataQuery = "SELECT receipt_header.id AS id, receipt_header.document_reference AS document_reference FROM receipt_header WHERE haulier_reference='".($mParms['haulierreference'])."' AND delivery_note='".($mParms['deliverynote'])."' AND EXISTS(SELECT id FROM document_status WHERE receipt_header.document_status_id=document_status.id AND lower(document_status.document_status_code)='open') LIMIT 1";
				$mDataQuery = "SELECT receipt_header.id AS id, receipt_header.document_reference AS document_reference, receipt_header.delivery_note AS delivery_note FROM receipt_header WHERE haulier_reference='".($mParms['haulierreference'])."' AND delivery_note='".($mParms['deliverynote'])."' AND COALESCE(receipt_header.document_status_id,0) IN(0,".$mDocStsId.",".$mDocCmpId.") LIMIT 1";
			}
			else
			{
//				$mDataQuery = "SELECT receipt_header.id AS id, receipt_header.document_reference AS document_reference FROM receipt_header WHERE haulier_reference='".($mParms['haulierreference'])."' AND EXISTS(SELECT id FROM document_status WHERE receipt_header.document_status_id=document_status.id AND lower(document_status.document_status_code)='open') LIMIT 1";
				$mDataQuery = "SELECT receipt_header.id AS id, receipt_header.document_reference AS document_reference, receipt_header.delivery_note AS delivery_note FROM receipt_header JOIN receipt_body ON receipt_body.receipt_header_id=receipt_header.id WHERE receipt_header.haulier_reference='".($mParms['haulierreference'])."' AND receipt_body.part_number = '".($mParms['partnumber'])."' AND COALESCE(receipt_header.document_status_id,0) IN(0".$mDocStsId.",".$mDocCmpId.") LIMIT 1";
			}
			if (!mysqli_query($mConnection,$mDataQuery))
				return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
			$mData = mysqli_query($mConnection,$mDataQuery);
			if (mysqli_num_rows($mData) == 0)
			{
				$mDataQuery = "SELECT receipt_header.id AS id, receipt_header.document_reference AS document_reference, receipt_header.delivery_note AS delivery_note FROM receipt_header WHERE receipt_header.haulier_reference='".($mParms['haulierreference'])."' AND COALESCE(receipt_header.document_status_id,0) IN(0".$mDocStsId.",".$mDocCmpId.") LIMIT 1";
				if (!mysqli_query($mConnection,$mDataQuery))
				return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
				$mData = mysqli_query($mConnection,$mDataQuery);
			}
			while($mRow = mysqli_fetch_assoc($mData)) 
			{
				$mDocumentHdrId = ($mRow['id']);
				$mDocumentReference = ($mRow['document_reference']);
				$mDeliveryNote = ($mRow['delivery_note']);
			}
			if ($mDocumentHdrId == "")
			{
				$mReturn = "FAIL-Invalid Haulier Reference.".$mDataQuery;
				return($mReturn);
			}
		}
		if ($mReturn == "")
		{
// Validate Part Number
			$mPartId = 0;
			$mPartConvFactor = 1;
			$mInspection = 0;
			if ($mParms['partnumber'])
			{
				$mDataQuery = "SELECT id AS id, conversion_factor AS conversion_factor,requires_inspection AS requires_inspection FROM part WHERE part_number = '".($mParms['partnumber'])."' LIMIT 1";
				if (!mysqli_query($mConnection,$mDataQuery))
					return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
			
				$mData = mysqli_query($mConnection,$mDataQuery);
				while($mRow = mysqli_fetch_assoc($mData)) 
				{
					$mPartId = ($mRow['id']);
					$mPartConvFactor = ($mRow['conversion_factor']);
					$mInspection = ($mRow['requires_inspection']);
				}
				if ($mPartId == "")
				{
					$mReturn = "FAIL-Wrong Part Number";
					return($mReturn);
				}
			}
		}
		if ($mReturn == "")
		{
			$mInvId = "";
			$mInvQty = 0;
			if (($mParms['serialreference']) && ($mPartId != ""))
			{
// Check if Part / Serial already exists
				$mDataQuery = "SELECT id AS id, inventory_qty AS inventory_qty FROM inventory_master WHERE part_id = ".$mPartId." AND serial_reference='".$mParms['serialreference']."' LIMIT 1";
				if (!mysqli_query($mConnection,$mDataQuery))
					return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
				
				$mData = mysqli_query($mConnection,$mDataQuery);
				while($mRow = mysqli_fetch_assoc($mData)) 
				{
					$mInvId = ($mRow['id']);
					$mInvQty = ($mRow['inventory_qty']);
				}
				if (($mInvId != "") && (intval($mInvQty) != 0))
				{
//						$mReturn = "FAIL-Duplicate Serial.";
				}
			}
		}
		if ($mReturn == "")
		{
// Validate Location Code
			$mLocId = "";
			if (($mParms['tolocationcode']) || ($mParms['tolocationhashcode']))
			{
				if ($mParms['tolocationcode'])
					$mDataQuery = "SELECT id AS id, location_code AS location_code FROM location WHERE location_code = '".$mParms['tolocationcode']."' OR location_hash = '".$mParms['tolocationcode']."' LIMIT 1";
				if ($mParms['tolocationhashcode'])
					$mDataQuery = "SELECT id AS id, location_code AS location_code FROM location WHERE location_code = '".$mParms['tolocationhashcode']."' OR location_hash = '".$mParms['tolocationhashcode']."' LIMIT 1";
				if (!mysqli_query($mConnection,$mDataQuery))
					return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
				
				$mData = mysqli_query($mConnection,$mDataQuery);
				while($mRow = mysqli_fetch_assoc($mData)) 
				{
					$mLocId = ($mRow['id']);
					$mToLocationCode = ($mRow['location_code']);
				}
				if ($mLocId == "")
				{
					$mReturn = "FAIL-Wrong Location";
					return($mReturn);
				}
			}
		}
		if ($mReturn == "")
		{
			$mToTagId = "";

// Create / Retrieve Pallet Tag
			if ($mParms['toplt'])
			{
				$mDataQuery = "SELECT id AS id FROM tag WHERE tag_reference='".$mParms['toplt']."' AND (active IS null OR active = '1') LIMIT 1";
				if (!mysqli_query($mConnection,$mDataQuery))
					return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
				
				$mData = mysqli_query($mConnection,$mDataQuery);
				while($mRow = mysqli_fetch_assoc($mData)) 
				{
					$mToTagId = ($mRow['id']);
				}
/*
				if ($mToTagId == "")
				{
					$mDataQuery = "INSERT INTO tag (id,version,auto_generated,current_location_id,date_created,document_header_id,last_updated,last_updated_by,tag_reference,validated,active) VALUES(DEFAULT,0,0,null,now(),null,now(),'".$mCurrentUser."','".$mParms['toplt']."',1,1)";
					if (!mysqli_query($mConnection,$mDataQuery))
						return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
					$mToTagId=mysqli_insert_id($mConnection);
				}
*/
			}

// Create Inventory
//			if (($mRanOrOrder == "") || ($mRanOrOrder == null))
//				$mRanOrOrder = $mDocumentReferenceCode;
			if (($mInvId != "") && (intval($mInvQty)==0))
			{
				$mDataQuery = "DELETE FROM inventory_master WHERE id=".$mInvId;
				if (!mysqli_query($mConnection,$mDataQuery))
					return "FAIL-".mysqli_error($mConnection).$mDataQuery;
				$mInvId = "";
			}
			$mInvUpdate = "";
// Apply Conversion Factor
			if (($mParms['quantity']) && ($mParms['quantity'] != ""))
			{
				$mQty = 0;
				$mTxnQty = 0;
				$mQty = $mParms['quantity']*$mPartConvFactor;
				$mTxnQty = $mParms['quantity']*$mPartConvFactor;
			}
// Receiving
			if ((strtolower($mParms['transactiontypeid'])=="rbtd") || (strtolower($mParms['transactiontypeid'])=="rbtp") || (strtolower($mParms['transactiontypeid'])=="testtran") || (strtolower($mParms['transactiontypeid'])=="jrbtp") || ($mParms['transactiontypeid']=="RBTP")) 
			{
				if ((!$mParms['quantity']) || ($mParms['quantity'] <= 0))
				{
					$mReturn = "FAIL-Wrong quantity";
					return($mReturn);
				}
				$mQty = 0;
				$mTxnQty = 0;
				if ($mParms['quantity'])
				{
					$mQty = $mParms['quantity']*$mPartConvFactor;
					$mTxnQty = $mParms['quantity']*$mPartConvFactor;
				}
/*
// Inventory Master
				if ($mInvId == "")
				{
					if ($mToTagId == "")
						$mDataQuery = "INSERT INTO inventory_master (id,version,allocated_qty,current_disposition_id,current_inventory_status_id,current_location_id,location_id,location_code,date_created,created_by,expiry_date,inventory_qty,available_qty,last_updated,last_updated_by,parent_tag_id,part_id,part_number,ran_or_order,recorded_missing,requires_decant,requires_inspection,serial_reference,originating_detail_id,conversion_factor,stock_date,active,inventory_status_id) VALUES(DEFAULT,0,0,null,null,".$mLocId.",".$mLocId.",'".$mToLocationCode."',now(),'".$mParms['currentuser']."',null,".$mQty.",".$mQty.",now(),'".$mParms['currentuser']."',null,".$mPartId.",'".$mParms['partnumber']."','".$mParms['ranorder']."',0,0,0,'".$mParms['serialreference']."',null,".$mPartConvFactor.",now(),1,".$mInvRcvId.")";
					else	
						$mDataQuery = "INSERT INTO inventory_master (id,version,allocated_qty,current_disposition_id,current_inventory_status_id,current_location_id,location_id,location_code,date_created,created_by,expiry_date,inventory_qty,available_qty,last_updated,last_updated_by,parent_tag_id,part_id,part_number,ran_or_order,recorded_missing,requires_decant,requires_inspection,serial_reference,originating_detail_id,conversion_factor,stock_date,active,inventory_status_id,tag_reference) VALUES(DEFAULT,0,0,null,null,".$mLocId.",".$mLocId.",'".$mToLocationCode."',now(),'".$mParms['currentuser']."',null,".$mQty.",".$mQty.",now(),'".$mParms['currentuser']."',".$mToTagId.",".$mPartId.",'".$mParms['partnumber']."','".$mParms['ranorder']."',0,0,0,'".$mParms['serialreference']."',null,".$mPartConvFactor.",now(),1,".$mInvRcvId.",'".$mParms['toplt']."')";
					if (!mysqli_query($mConnection,$mDataQuery))
						return "FAIL-".mysqli_error($mConnection).$mDataQuery;
					$mInvUpdate = "1";
					$mInvId=mysqli_insert_id($mConnection);
				}
*/
// Receipt Body
				$mDataQuery = "SELECT id AS id,received_qty AS received_qty, product_type_id AS product_type_id FROM receipt_body WHERE receipt_header_id=".$mDocumentHdrId." AND (part_id=".$mPartId." OR part_number='".$mParms['partnumber']."') LIMIT 1";
				if (!mysqli_query($mConnection,$mDataQuery))
					return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
				
				$mData = mysqli_query($mConnection,$mDataQuery);
				$mRctBdyId = "";
				$mRctBdyQty = 0;
				$mRctBdyProdId = null;
				while($mRow = mysqli_fetch_assoc($mData)) 
				{
					$mRctBdyId = ($mRow['id']);
					$mRctBdyQty = ($mRow['received_qty']);
					$mRctBdyProdId = ($mRow['product_type_id']);
				}
// No Receipt Body - Add One
				if ($mRctBdyId == "")
				{
					$mDataQuery = "INSERT INTO receipt_body (id,document_reference,product_type_id,part_number,advised_qty,received_qty,difference,part_id,receipt_header_id,document_status_id,date_created,created_by,last_updated_date,last_updated_by) VALUES(DEFAULT,'".$mDocumentReference."',null,'".$mParms['partnumber']."',0,".$mQty.",".$mQty.",".$mPartId.",".$mDocumentHdrId.",".$mDocStsId.",now(),'".$mParms['currentuser']."',now(),'".$mParms['currentuser']."')";
					if (!mysqli_query($mConnection,$mDataQuery))
						return "FAIL-".mysqli_error($mConnection).$mDataQuery;
					$mRctBdyId=mysqli_insert_id($mConnection);				
				}
				else
				{
					$mRctBdyQty=$mRctBdyQty+$mQty;
					$mDataQuery = "UPDATE receipt_body SET part_id=".$mPartId.", received_qty=".$mRctBdyQty.",difference=received_qty-advised_qty,last_updated_date=now(),last_updated_by='".$mParms['currentuser']."' WHERE id=".$mRctBdyId." LIMIT 1";
					if (!mysqli_query($mConnection,$mDataQuery))
						return "FAIL-".mysqli_error($mConnection).$mDataQuery;
				}
// Receipt Detail
				$mDataQuery = "SELECT id AS id,received_qty AS received_qty FROM receipt_detail WHERE receipt_body_id=".$mRctBdyId." AND part_id=".$mPartId." AND serial_reference='".$mParms['serialreference']."' LIMIT 1";
				if (!mysqli_query($mConnection,$mDataQuery))
					return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
				
				$mData = mysqli_query($mConnection,$mDataQuery);
				$mRctDtlId = "";
				$mRctDtlQty = 0;
				while($mRow = mysqli_fetch_assoc($mData)) 
				{
					$mRctDtlId = ($mRow['id']);
					$mRctDtlQty = ($mRow['received_qty']);
				}
				if ($mRctDtlId == "")
				{
					if (strtolower($mParms['transactiontypeid'])== "jrbtp")
						$mDataQuery = "INSERT INTO receipt_detail (id,document_reference,product_type_id,part_number,part_id,serial_reference,ran_order,advised_qty,received_qty,cts_qty,difference,receipt_body_id,document_status_id,date_created,created_by,last_updated_date,last_updated_by) VALUES(DEFAULT,'".$mDocumentReference."',null,'".$mParms['partnumber']."',".$mPartId.",'".$mParms['serialreference']."','".$mParms['ranorder']."',0,".$mQty.",".$mQty.",".$mQty.",".$mRctBdyId.",".$mDocStsId.",now(),'".$mParms['currentuser']."',now(),'".$mParms['currentuser']."')";
					else
						$mDataQuery = "INSERT INTO receipt_detail (id,document_reference,product_type_id,part_number,part_id,serial_reference,ran_order,advised_qty,received_qty,cts_qty,difference,receipt_body_id,document_status_id,date_created,created_by,last_updated_date,last_updated_by) VALUES(DEFAULT,'".$mDocumentReference."',null,'".$mParms['partnumber']."',".$mPartId.",'".$mParms['serialreference']."','".$mParms['ranorder']."',0,".$mQty.",0,".$mQty.",".$mRctBdyId.",".$mDocStsId.",now(),'".$mParms['currentuser']."',now(),'".$mParms['currentuser']."')";
					if (!mysqli_query($mConnection,$mDataQuery))
						return "FAIL-".mysqli_error($mConnection).$mDataQuery;
					$mRctDtlId=mysqli_insert_id($mConnection);
				}
				else
				{
					$mRctDtlQty=$mRctDtlQty+$mQty;
					if (strtolower($mParms['transactiontypeid'])== "jrbtp")
						$mDataQuery = "UPDATE receipt_detail SET received_qty=".$mQty.",cts_qty=".$mQty.",difference=received_qty-advised_qty,last_updated_date=now(),last_updated_by='".$mParms['currentuser']."' WHERE id=".$mRctDtlId." LIMIT 1";
					else
						$mDataQuery = "UPDATE receipt_detail SET received_qty=".$mRctDtlQty.",difference=received_qty-advised_qty,last_updated_date=now(),last_updated_by='".$mParms['currentuser']."' WHERE id=".$mRctDtlId." LIMIT 1";
					if (!mysqli_query($mConnection,$mDataQuery))
						return "FAIL-".mysqli_error($mConnection).$mDataQuery;
				}
			}
// Inventory Master
			if ($mInvId == "")
			{
				$mInvPruf = 0;
				if (strtolower($mParms['prufconfirm'])=="y")
					$mInvPruf = 1;
				if ($mToTagId == "")
					$mDataQuery = "INSERT INTO inventory_master (id,version,allocated_qty,current_disposition_id,current_inventory_status_id,current_location_id,location_id,location_code,date_created,created_by,expiry_date,inventory_qty,available_qty,last_updated,last_updated_by,parent_tag_id,part_id,part_number,ran_or_order,recorded_missing,requires_decant,requires_inspection,serial_reference,originating_detail_id,conversion_factor,stock_date,active,inventory_status_id,product_type_id,pruf_cube) VALUES(DEFAULT,0,0,null,null,".$mLocId.",".$mLocId.",'".$mToLocationCode."',now(),'".$mParms['currentuser']."',null,".$mQty.",".$mQty.",now(),'".$mParms['currentuser']."',null,".$mPartId.",'".$mParms['partnumber']."','".$mParms['ranorder']."',0,0,".$mInspection.",'".$mParms['serialreference']."',null,".$mPartConvFactor.",now(),1,".$mInvRcvId.",null,".$mInvPruf.")";
				else	
					$mDataQuery = "INSERT INTO inventory_master (id,version,allocated_qty,current_disposition_id,current_inventory_status_id,current_location_id,location_id,location_code,date_created,created_by,expiry_date,inventory_qty,available_qty,last_updated,last_updated_by,parent_tag_id,part_id,part_number,ran_or_order,recorded_missing,requires_decant,requires_inspection,serial_reference,originating_detail_id,conversion_factor,stock_date,active,inventory_status_id,tag_reference,product_type_id,pruf_cube) VALUES(DEFAULT,0,0,null,null,".$mLocId.",".$mLocId.",'".$mToLocationCode."',now(),'".$mParms['currentuser']."',null,".$mQty.",".$mQty.",now(),'".$mParms['currentuser']."',".$mToTagId.",".$mPartId.",'".$mParms['partnumber']."','".$mParms['ranorder']."',0,0,".$mInspection.",'".$mParms['serialreference']."',null,".$mPartConvFactor.",now(),1,".$mInvRcvId.",'".$mParms['toplt']."',null,".$mInvPruf.")";
				if (!mysqli_query($mConnection,$mDataQuery))
					return "FAIL-".mysqli_error($mConnection).$mDataQuery;
				$mInvUpdate = "1";
				$mInvId=mysqli_insert_id($mConnection);
			}
// Transaction History
			$mTxnQty = $mQty;
			if (($mTxnQty == "") || ($mTxnQty == null) || (!$mTxnQty))
				$mTxnQty = 0;
			if ($mInvUpdate != "")
			{
				$mTranRefCode = $mParms['transactiontypeid'];
				if ($mParms['toplt'] == "")
					$mDataQuery = "INSERT INTO transaction_history (id,associated_document_reference,date_created,created_by,from_location_code,last_updated,last_updated_by,parent_tag,part_number,ran_or_order,serial_reference,short_code,to_location_code,transaction_reference_code,txn_qty,comment,active,conversion_factor,customer_reference,requires_inspection) VALUES(DEFAULT,'".$mDocumentReference."',now(),'".$mParms['currentuser']."','".$mFromLocationCode."',now(),'".$mParms['currentuser']."',null,'".$mParms['partnumber']."','".$mParms['ranorder']."','".$mParms['serialreference']."','".$mParms['transactiontypeid']."','".$mToLocationCode."','".$mTranRefCode."',".$mTxnQty.",'',1,".$mPartConvFactor.",'".$mDeliveryNote."',".$mInspection.")";
				else
					$mDataQuery = "INSERT INTO transaction_history (id,associated_document_reference,date_created,created_by,from_location_code,last_updated,last_updated_by,parent_tag,part_number,ran_or_order,serial_reference,short_code,to_location_code,transaction_reference_code,txn_qty,comment,active,conversion_factor,customer_reference,requires_inspection,to_plt) VALUES(DEFAULT,'".$mDocumentReference."',now(),'".$mParms['currentuser']."','".$mFromLocationCode."',now(),'".$mParms['currentuser']."','".$mParms['toplt']."','".$mParms['partnumber']."','".$mParms['ranorder']."','".$mParms['serialreference']."','".$mParms['transactiontypeid']."','".$mToLocationCode."','".$mTranRefCode."',".$mTxnQty.",'',1,".$mPartConvFactor.",'".$mDeliveryNote."',".$mInspection.",'".$mParms['toplt']."')";
				if (!mysqli_query($mConnection,$mDataQuery))
					return "FAIL-".mysqli_error($mConnection).$mDataQuery;
			}
		}
// JIS Receipt
		if (strtolower($mParms['transactiontypeid'])== "jrbtp")
		{
			if ($mDocumentHdrId != "")
			{
				$mDataQuery = "SELECT receipt_header.id AS id FROM receipt_header JOIN receipt_body ON receipt_body.receipt_header_id=receipt_header.id JOIN receipt_detail ON receipt_detail.receipt_body_id=receipt_body.id WHERE receipt_header.id=".$mDocumentHdrId." AND (receipt_body.received_qty<receipt_body.advised_qty OR receipt_detail.received_qty=0) LIMIT 1";
				if (!mysqli_query($mConnection,$mDataQuery))
					return "FAIL-".mysqli_error($mConnection).$mDataQuery;
				$mData = (mysqli_query($mConnection,$mDataQuery));
				if (mysqli_num_rows($mData) == 0)
				{
// Get id for document status 'closed'		
					$mDataQuery = "SELECT id AS id FROM document_status WHERE lower(document_status_code) = 'closed' LIMIT 1";
					if (!mysqli_query($mConnection,$mDataQuery))
						return "FAIL-".mysqli_error($mConnection).$mDataQuery;
					$mData = (mysqli_query($mConnection,$mDataQuery));
					$mRow = mysqli_fetch_assoc($mData);
					$mDocStsId = ($mRow['id']);
// Update Receipt & Inventory Status
					$mDataQuery = "UPDATE receipt_header SET document_status_id=".$mDocStsId.",last_updated_date=now(),last_updated_by='".$mParms['currentuser']."' WHERE id=".$mDocumentHdrId." LIMIT 1";
					if (!mysqli_query($mConnection,$mDataQuery))
						return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
					$mDataQuery = "SELECT receipt_body.part_id AS part_id, receipt_detail.serial_reference AS serial_reference FROM receipt_body JOIN receipt_detail ON receipt_detail.receipt_body_id=receipt_body.id WHERE receipt_body.receipt_header_id=".$mDocumentHdrId;
					if (!mysqli_query($mConnection,$mDataQuery))
						return "FAIL-".mysqli_error($mConnection).$mDataQuery;
					$mData = (mysqli_query($mConnection,$mDataQuery));
					while($mRow = mysqli_fetch_assoc($mData)) 
					{
						$mInvQuery = "UPDATE inventory_master SET inventory_status_id = ".$mInvStsId." WHERE part_id=".$mRow['part_id']." AND serial_reference = '".$mRow['serial_reference']."' AND inventory_status_id=".$mInvRcvId." LIMIT 1";
						if (!mysqli_query($mConnection,$mInvQuery))
							return "FAIL-".mysqli_error($mConnection)."-".$mInvQuery;
					}
				}
			}		
		}

// Post Documents - TEMPORARY
		try
		{
			include_once ('postdocument.php');
			$mStatus = postdocument($mJsonObject,'Customer Receipt','RCP',$mHost,$mUser,$mPwd,$mDbName);
		}
		catch (Exception $e)
		{
		}
		
// Return Status
		if ($mReturn == "")
		{
			$mReturn = "OK  -";
		}
	}
	if ($mReturn == "")
		$mReturn = "OKMS-".strtolower($mParms['transactiontypeid']."-".$mInvUpdate);
	return $mReturn;
}

?>