<?php
// replen.php
// VIMS RDT Replen Process
// ----------------------------------------------------------------------------------------
// Modified 2019-07-27 - Created.
// ----------------------------------------------------------------------------------------
header('Cache-Control: no-cache, no-store, must-revalidate');   
header('Expires: 0');
set_time_limit(0);

// error_reporting(E_ALL);
// ini_set('display_errors', 1);

// postScreen - Transaction Processing
// echo "FAIL-test";
function getServerReplenPlt($mUserId,$mConnect)
{
	$mReturn = "";
// Get Server Data from URL
	$mJsonArray = array();
	$mJsonArray['userId'] = $mUserId;
// 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",":8095/pick",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8095/pick/";
    }
	$ch = curl_init();
	try
	{
		curl_setopt($ch, CURLOPT_URL, $mConnectp."createPallet?userId=".$mUserId);
		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")
			$mErrMsg =("FAIL-Unexpected System Error -".$mResult.":".$mResponse.":".$mErrors.":".$mJsonObject);
		else
		{
			$mErrMsg = "OK  - Post Complete";
		}
	}
	catch (Exception $e)
	{
		$mErrMsg =("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
	}			
	if ($mResult == "")
		$mResult = "FAIL-Server Error";
	
	return ($mResult);
}

// Get Next Replen Serial
function getServerReplen($mUserId,$mReplenGroup,$mAisle,$mConnect,$mToPlt="")
{
//	http://172.16.1.70:8095/pick/findReplenTask?replenGroupCode=ORDR1
	$mReturn = "";
	if ($mAisle == "NONE")
	{
		return "OK  -";
	}
//	if (($mReplenGroup != null) && ($mReplenGroup != ""))
//	{
// Get Server Data from URL
		$mJsonArray = array();
		$mJsonArray['replenGroupCode'] = $mReplenGroup;
		$mJsonArray['userId'] = $mUserId;
// 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",":8095/pick",$mConnect);
        if ($mConnectp == $mConnect)
        {
            $e = strpos($mConnect,":8081");
            $mConnectp = substr($mConnect,0,$e).":8095/pick/";
        }
		$ch = curl_init();
		try
		{
			curl_setopt($ch, CURLOPT_URL, $mConnectp."findReplenTask?replenGroupCode=".$mReplenGroup."&userId=".$mUserId);
			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")
				$mErrMsg =("FAIL-Unexpected System Error -".$mResult.":".$mResponse.":".$mErrors.":".$mJsonObject);
			else
			{
				$mErrMsg = "OK  - Post Complete";
			}
		}
		catch (Exception $e)
		{
			$mErrMsg = ("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
		}
//		print_r("FAIL-TEST-".$mConnectp."-".$mReplenGroup."-".$mResult);
//	}
	return($mResult);
}

function getReplen($mUserId,$mReplenGroup,$mAisle,$mConnect,$mHost,$mUser,$mPwd,$mDbName,$mTransactionTypeId)
{
	$mReturn = "";
// mysql connection
	$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
	if (!$mConnection)
		return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
	$mDataQuery = "SELECT replen_task.id AS id, replen_task.part_id AS part_id, replen_task.to_location_code AS to_location_code, location.id AS loc_id FROM replen_task";
	$mDataQuery .= " JOIN pick_group ON replen_task.pick_group_id=pick_group.id";
	$mDataQuery .= " JOIN location ON replen_task.location_code=location.location_code";
	$mdataQuery .= " WHERE pick_group.pick_group_code='".$mReplenGroup."'"; 
	$mDataQuery .= " AND (replen_task.processed=0 OR replen_task.processed IS null) AND (replen_task.in_use IS null OR replen_task.in_use='' OR replen_task.in_use='".$mCurrentUser."' OR (replen_task.last_updated_date < DATE_SUB(NOW(), INTERVAL 10 MINUTE)))";
	$mDataQuery .= "ORDER BY replen_task.priority, replen_task.date_created LIMIT 1";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
	$mPartId = "";
	$mToLoc = "";
	$mData = mysqli_query($mConnection,$mDataQuery);
//	return("FAIL-TEST1-".$mDataQuery."-".mysqli_num_rows($mData));
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
		$mPartId = $mRow['part_id'];
		$mToLoc = $mRow['to_location_code'];
		$mLocId = $mRow['loc_id'];
	}
	if ($mPartId != "")
	{
		$i = 0;
		$mInvQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_qty AS inventory_qty, inventory_master.allocated_qty AS allocated_qty, part.part_number AS part_number, inventory_master.serial_reference AS serial_reference, inventory_master.ran_or_order AS ran_order, location.location_code AS location_code,location_column.filling_priority AS pick_priority FROM inventory_master JOIN location ON inventory_master.current_location_id=location.id JOIN part ON inventory_master.part_id=part.id JOIN pick_group ON location.pick_group_id=pick_group.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id LEFT JOIN location_column ON location.column_code=location_column.column_code LEFT JOIN location_type ON location.location_type_id=location_type.id WHERE inventory_master.part_id=".$mPartId." AND inventory_master.inventory_qty >0 AND inventory_master.inventory_qty>inventory_master.allocated_qty AND inventory_master.requires_inspection=0 AND lower(location_type.location_area)<>'work' AND inventory_status.non_pickable<>1 AND (inventory_master.inventory_status_id IS null OR lower(inventory_status.inventory_status_code) IN('ok','ok'))";
		$mInvQuery .= "AND inventory_master.current_location_id <> ".$mLocId;
		$mInvQuery .= " AND NOT EXISTS(SELECT id FROM replen_task WHERE replen_task.inventory_master_id=inventory_master.id)";			
		$mInvQuery .= " ORDER BY inventory_master.date_created, location.location_code,inventory_master.inventory_qty LIMIT 1";
		if (!mysqli_query($mConnection,$mInvQuery))
			return "FAIL-".mysqli_error($mConnection)."-".$mInvQuery;
		$mInvData = mysqli_query($mConnection,$mInvQuery);
		$mTest = "_PICKFACE";
		if (mysqli_num_rows($mInvData) == 0)
		{
			$mInvQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_qty AS inventory_qty, inventory_master.allocated_qty AS allocated_qty, part.part_number AS part_number, inventory_master.serial_reference AS serial_reference, inventory_master.ran_or_order AS ran_order, location.location_code AS location_code,location_column.filling_priority AS pick_priority FROM inventory_master JOIN location ON inventory_master.current_location_id=location.id JOIN part ON inventory_master.part_id=part.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id LEFT JOIN location_column ON location.column_code=location_column.column_code LEFT JOIN location_type ON location.location_type_id=location_type.id WHERE inventory_master.part_id=".$mPartId." AND inventory_master.inventory_qty >0 AND inventory_master.inventory_qty>inventory_master.allocated_qty AND inventory_master.requires_inspection=0 AND lower(location_type.location_area)<>'work' AND inventory_status.non_pickable<>1 AND (inventory_master.inventory_status_id IS null OR lower(inventory_status.inventory_status_code) IN('ok','ok'))";
			$mInvQuery .= "AND inventory_master.current_location_id <> ".$mLocId;
			$mInvQuery .= " AND NOT EXISTS(SELECT id FROM replen_task WHERE replen_task.inventory_master_id=inventory_master.id)";
			$mInvQuery .= " ORDER BY inventory_master.date_created, location.location_code,inventory_master.inventory_qty LIMIT 1";
			if (!mysqli_query($mConnection,$mInvQuery))
				return "FAIL-".mysqli_error($mConnection)."-".$mInvQuery;
			$mInvData = mysqli_query($mConnection,$mInvQuery);
			$mTest="_NOTPICKFACE";
		}
		if (mysqli_num_rows($mInvData) > 0)
		{
			$mInvRow = mysqli_fetch_assoc($mInvData);
			$mReturn = "DATA:fromlocationCode:".$mInvRow['location_code'].",partNumber:".$mInvRow['part_number'].",serialReference:".$mInvRow['serial_reference'];
		}
		else
		{
			$mReturn = "FAIL-No Replen Tasks";
		}		
	}
	else
	{
		$mReturn = "FAIL-No Replen Tasks";
	}
	if ($mReturn == "")
		$mReturn = "OK  -getReplen";
//	return ("FAIL-TEST1-".$mReturn);
	return ($mReturn);
}

// Validate Replen
function validateReplen($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName)
{
	$mParms = json_decode($mJsonObject, true);
	$mErrMsg = "";
	$mPartNumber = "";
	
	if ($mParms['partnumber'])
		$mPartNumber = $mParms['partnumber'];
	
// mysql connection
	$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
		exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
	
	if (($mParms['fromlocationhashcode'] != "") || ($mParms['vldlocation'] != ""))
	{
		$mDataQuery = "SELECT location.location_code AS location_code FROM location WHERE location.location_hash = '".$mParms['fromlocationhashcode']."' LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
			return("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
		$mData = mysqli_query($mConnection,$mDataQuery);
		$i = 0;
		while($mRow = mysqli_fetch_assoc($mData)) 
		{
			$mDataStr = ($mRow['location_code']);
			$i++;
		}
		if (($i == 0) || (strtoupper($mDataStr) != strtoupper($mParms['vldlocation'])))
		{
			$mErrMsg = "FAIL-Location is Incorrect";
		}
	}

// Check Scanned Part
	if (($mErrMsg == "") && ($mParms['partnumber'] != ""))
	{
		if (trim($mParms['partnumber']) != trim($mParms['vldpartnumber']))
		{
			$mDataQuery = "SELECT id AS id, part_number AS part_number FROM part WHERE upper(part_number) = '".$mParms['partnumber']."' OR (upper(part_number)='".$mParms['vldpartnumber']."' AND upper(jis_supply_group)='".$mParms['partnumber']."') LIMIT 1";
			if (!mysqli_query($mConnection,$mDataQuery))
				exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
			$mData = mysqli_query($mConnection,$mDataQuery);
			$i = 0;
			while($mRow = mysqli_fetch_assoc($mData)) 
			{
				$mPartNumber = $mRow['part_number'];
				$i++;
			}
			
			if (($i == 0) || (strtoupper($mPartNumber) != $mVldPartNumber))
				$mErrMsg = "FAIL-Incorrect Part Number";
		}
	}

// Validate Entered Serial	
	if (($mErrMsg == "") && ($mParms['serialreference'] != ""))
	{
		if ($mPartNumber == "")
			$mDataQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_qty AS inventory_qty, inventory_master.requires_inspection AS inspect, location.location_code, part.part_number AS part_number, part.conversion_factor AS conversion_factor, tag.tag_reference AS tag_reference FROM inventory_master JOIN part ON inventory_master.part_id=part.id JOIN location on inventory_master.current_location_id=location.id 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 UPPER(inventory_master.serial_reference)='".$mParms['serialreference']."' AND inventory_master.inventory_qty > 0 AND (inventory_master.inventory_status_id IS null OR LOWER(inventory_status.inventory_status_code) IN('ok','qtine')) LIMIT 2";
		else
			$mDataQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_qty AS inventory_qty, inventory_master.requires_inspection AS inspect, location.location_code,part.part_number AS part_number, part.conversion_factor AS conversion_factor, tag.tag_reference AS tag_reference FROM inventory_master JOIN part ON inventory_master.part_id=part.id JOIN location on inventory_master.current_location_id=location.id 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 UPPER(inventory_master.serial_reference)='".$mParms['serialreference']."' AND (part.part_number='".$mPartNumber."' OR part.jis_supply_group ='".$mPartNumber."') AND inventory_master.inventory_qty > 0 AND (inventory_master.inventory_status_id IS null OR LOWER(inventory_status.inventory_status_code) IN('ok','qtine')) LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
			exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
		$mData = mysqli_query($mConnection,$mDataQuery);
		$i = 0;
		$mInvId = "";
		$mInvQty = 0;
		$mPartConvFactor = 1;
		$mTagRef = "";
		while($mRow = mysqli_fetch_assoc($mData)) 
		{
			$mInvLoc = ($mRow['location_code']);
			$mInspect = ($mRow['inspect']);
			$mInvId = ($mRow['id']);
			$mInvQty = ($mRow['inventory_qty']);
			$mPartConvFactor = ($mRow['conversion_factor']);
			$mPartNumber = ($mRow['part_number']);
			$mTagRef = ($mRow['tag_reference']);
			$i++;
		}
		if ($i == 0)
		{
			$mErrMsg = "FAIL-Serial is Incorrect";
			return($mErrMsg);
		}
		if ($i == 1)
		{
			if ($mInspect == "1")
			{
				$mErrMsg = "FAIL-Serial is flagged for inspection";
			}
			elseif (strtoupper($mDataStr) != strtoupper($mInvLoc))
			{
				$mErrMsg = "FAIL-Scanned Serial is in a different Location ".$mPartNumber."-".strtoupper($mInvLoc)."-".strtoupper($mDataStr);
			}
			elseif ($mPartNumber != $mParms['vldpartnumber'])
			{
				$mErrMsg = "FAIL-Incorrect Part for this Task".$mPartNumber."-".$mParms['vldpartnumber'];
			}
			elseif (substr($mTagRef,0,3) == "REP")
			{
				$mErrMsg = "FAIL-Serial is already located to pallet ".$mTagRef;
			}
            if (empty($mErrMsg))
            {
                $mDataQuery = "SELECT id FROM chgpno_task WHERE part_number='".$mPartNumber."' AND processed=0 LIMIT 1";
                if (!$mData = mysqli_query($mConnection,$mDataQuery))
                    exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
                if (mysqli_num_rows($mData) > 0)
                {
                    $mErrMsg = "FAIL-cannot locate - change part number task is open";
                }
            }
		}
// Multiple Serials - Prompt for Part Number
		if ($i > 1)
		{
			$mErrMsg = "DATA:serialReference:".$mParms['serialreference']."::skip,partNumber::I";
			return($mErrMsg);
		}
		if ($mErrMsg == "")
		{
// Apply Conversion Factor
			if ($mPartConvFactor > 0)
				$mInvQty = $mInvQty / $mPartConvFactor;
		}
//		return("FAIL-TEST1-".$i);
	}

//		exit("FAIL-TEST1".$mDataQuery."-".mysqli_num_rows($mData)."-".$mStrictSerial);

	mysqli_close($mConnection);
	
	if ($mErrMsg == "")
	{
		$mErrMsg = "OK  -Valid Replen";
	}
	
	return($mErrMsg);
}

// Process Replen
function processServerReplen($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName)
{
	$mParms = json_decode($mJsonObject, true);
	$mErrMsg = "";
	
//	http://172.16.1.70:8095/pick/scanReplen
//              "tagReference":"REP195714",
//                "pickGroupId":1,
//                "replenTaskId":1,
//                "scannedSerial":"AA001A",
//                "suggestedSerial":"PARTA",
//                "locationCode":"AA001A",
//                "userId":"userId"
//	print_r("FAIL-TEST1-".$mJsonObject);
//	return ("FAIL-TEST1-".$mJsonObject);
	
// Prepare Server Data
// Replace default Server Tomcat Service
	$mConnectp = str_replace(":8081/vantec",":8095/pick",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8095/pick/";
    }
	$ch = curl_init();
	try
	{
		curl_setopt($ch, CURLOPT_URL, $mConnectp."scanReplen");
		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")
			$mErrMsg = ("FAIL-Unexpected System Error -".$mResult.":".$mResponse.":".$mErrors.":".$mJsonObject);
		else
		{
			$mErrMsg = "OK  - Post Complete";
		}
	}
	catch (Exception $e)
	{
		$mErrMsg = ("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
	}
/*
	if (strtolower($mResult) == "true")
		return("FAIL-Text true");
	elseif (strtolower($mResult) == "false")
		return("FAIL-Text false");
	elseif ($mResult == 1)
		return("FAIL-1");
	elseif ($mResult == 0)
		return("FAIL=0");
	elseif ($mResult == true)
		return("FAIL-Boolean true");
	elseif ($mResult == false)
		return("FAIL-Boolean false");
	else
		return("???-".$mResult);
*/
// if result is true the pallet full
	if ((strtolower($mResult) == "true") || ($mResult == 1)) 
	{
// mysql connection
		$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
			exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
		$mDataQuery = "SELECT id AS id, pallet AS pallet FROM pick_group WHERE id='".$mParms['pickGroupId']."' LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
			exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
		$mData = mysqli_query($mConnection,$mDataQuery);
		if (mysqli_num_rows($mData) ==0)
			return("FAIL-Incorrect Pick Group".$mDataQuery);
		$mPallet = 0;
		while($mRow = mysqli_fetch_assoc($mData))
		{
			$mPallet = $mRow['pallet'];	
		}
		if ($mPallet == 0)
		{
			$mDataQuery = "SELECT to_location_code AS to_location_code FROM replen_task WHERE id=".$mParms['replenTaskId']." LIMIT 1";
			if (!mysqli_query($mConnection,$mDataQuery))
				exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
			$mData = mysqli_query($mConnection,$mDataQuery);
			$mToLoc = "";
			while($mRow = mysqli_fetch_assoc($mData))
			{
				$mToLoc = $mRow['to_location_code'];	
			}
			return "DATA:toLocationHashCode:".$mToLoc.":HHHHHIH:skip6";
		}
		else
			return ("OKMS-Pallet is Full,REPLOC?DATA:replenGroup:".$mParms['replenGroup']);
	}
	return ("OK  -Replen Task");
}

function validateServerReplenLocate($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName)
{
	$mParms = json_decode($mJsonObject, true);
	$mErrMsg = "";
	$mPartNumber = "";	
	$mToLocationHashCode = "";
	if ($mParms['partnumber'])
		$mPartNumber = $mParms['partnumber'];
	if ($mParms['tolocationhashcode'])
		$mToLocationHashCode = $mParms['tolocationhashcode'];
	
// mysql connection
	$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
		exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Validate Entered Location
	if (($mErrMsg == "") && ($mToLocationHashCode != ""))
	{
		$mDataQuery = "SELECT location_code AS location_code FROM location WHERE location_hash = '".$mToLocationHashCode."' LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
			exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
		$mData = mysqli_query($mConnection,$mDataQuery);
		if (mysqli_num_rows($mData) ==0)
			return("FAIL-Incorrect Location");
		$mLocationCode == "";
		while($mRow = mysqli_fetch_assoc($mData)) 
		{
			$mLocationCode = $mRow['location_code'];
		}
		if ($mLocationCode != $mParms['vldLocationCode'])
		{	
			$mErrMsg = "FAIL-Incorrect Location";
			return($mErrMsg);
		}
// Process Replen
		if ($mErrMsg == "")
		{
//			http://172.16.1.70:8095/pick/processedReplen?serial=1&partnumber=PARTA&userId=tan
// Get Server Data from URL
			$mJsonArray = array();
			$mJsonArray['serial'] = $mParms['serialreference'];
			$mJsonArray['partNumber'] = $mPartNumber;
			$mJsonArray['userId'] = $mParms['currentUser'];
			$mJsonArray['locationCode'] = $mLocationCode;
// Convert Array to Json Object
			try
			{
				$mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
			}
			catch(Exception $e)
			{
				exit("FAIL-Json Error");
			}
//			return ("FAIL-TEST1-".$mJsonObject);
// Prepare Server Data
// Replace default Server Tomcat Service
			$mConnectp = str_replace(":8081/vantec",":8095/pick",$mConnect);
            if ($mConnectp == $mConnect)
            {
                $e = strpos($mConnect,":8081");
                $mConnectp = substr($mConnect,0,$e).":8095/pick/";
            }
			$ch = curl_init();
			try
			{
				curl_setopt($ch, CURLOPT_URL, $mConnectp."processedReplen?serial=".$mParms['serialreference']."&partNumber=".$mPartNumber."&userId=".$mParms['currentUser'].",&locationCode=".$mLocationCode);
				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")
					$mErrMsg = ("FAIL-Unexpected System Error -".$mResult.":".$mResponse.":".$mErrors.":".$mJsonObject);
				else
				{
					$mErrMsg = "OK  - Post Complete";
				}
			}
			catch (Exception $e)
			{
				$mErrMsg = ("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
			}
			return ("OK  -REPLOC complete");
		}
	}
// Validate Entered Serial	
	if (($mErrMsg == "") && ($mParms['serialreference'] != ""))
	{
		if (($mPartNumber == "") || ($mPartNumber == null))
			$mDataQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_qty AS inventory_qty, inventory_master.requires_inspection AS inspect, location.location_code, part.part_number AS part_number, part.conversion_factor AS conversion_factor FROM inventory_master JOIN part ON inventory_master.part_id=part.id JOIN location on inventory_master.current_location_id=location.id WHERE UPPER(inventory_master.serial_reference)='".$mParms['serialreference']."' AND inventory_master.inventory_qty > 0 LIMIT 2";
		else
			$mDataQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_qty AS inventory_qty, inventory_master.requires_inspection AS inspect, location.location_code,part.part_number AS part_number, part.conversion_factor AS conversion_factor FROM inventory_master JOIN part ON inventory_master.part_id=part.id JOIN location on inventory_master.current_location_id=location.id WHERE UPPER(inventory_master.serial_reference)='".$mParms['serialreference']."' AND (part.part_number='".$mPartNumber."' OR part.jis_supply_group ='".$mPartNumber."') AND inventory_master.inventory_qty > 0 LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
			exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
		$mData = mysqli_query($mConnection,$mDataQuery);
		$i = 0;
		$mInvId = "";
		$mInvQty = 0;
		$mPartConvFactor = 1;
		while($mRow = mysqli_fetch_assoc($mData)) 
		{
			$mDataStr = ($mRow['location_code']);
			$mInspect = ($mRow['inspect']);
			$mInvId = ($mRow['id']);
			$mInvQty = ($mRow['inventory_qty']);
			$mPartConvFactor = ($mRow['conversion_factor']);
			$mPartNumber = ($mRow['part_number']);
			$i++;
		}
		if ($i == 0)
		{
			$mErrMsg = "FAIL-Serial is Incorrect-";
			return($mErrMsg);
		}
		if ($i == 1)
		{
			if ($mInspect == "1")
			{
				$mErrMsg = "FAIL-Serial is flagged for inspection";
			}
		}
// Multiple Serials - Prompt for Part Number
		if ($i > 1)
		{
			if ($mErrMsg == "")			
			{
				$mErrMsg = "DATA:serialReference:".$mParms['serialreference']."::skippartNumber,partNumber::I";
				return($mErrMsg);
			}
		}
	}
// Prompt for To-Loc
//		http://172.16.1.70:8095/pick/getToLocationCodeForSerial?serial=repelnme&&partNumber=928320301
	if ($mErrMsg == "")
	{
// Get Server Data from URL
		$mJsonArray = array();
		$mJsonArray['serial'] = $mParms['serialreference'];
		$mJsonArray['partNumber'] = $mPartNumber;
// Convert Array to Json Object
		try
		{
			$mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
		}
		catch(Exception $e)
		{
			exit("FAIL-Json Error");
		}
// Prepare Server Data
// Replace default Server Tomcat Service
		$mConnectp = str_replace(":8081/vantec",":8095/pick",$mConnect);
        if ($mConnectp == $mConnect)
        {
            $e = strpos($mConnect,":8081");
            $mConnectp = substr($mConnect,0,$e).":8095/pick/";
        }
		$ch = curl_init();
		try
		{
			curl_setopt($ch, CURLOPT_URL, $mConnectp."getToLocationCodeForSerial?serial=".$mParms['serialreference']."&partNumber=".$mPartNumber);
			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")
				$mErrMKsg = ("FAIL-Unexpected System Error -".$mResult.":".$mResponse.":".$mErrors.":".$mJsonObject);
			else
			{
				$mErrMsg = "OK  - Post Complete";
			}
		}
		catch (Exception $e)
		{
			$mErrMsg =("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
		}
	}
	if (($mResult == "") or ($mResult == null))
	{
		$mResult = "No Available Location";
		return "DATA:partNumber:".$mPartNumber.":P,toLocationHashCodeContent:".$mResult;
	}
	else
		return "DATA:partNumber:".$mPartNumber.":P,toLocationHashCodeContent:".$mResult;
}

function createReplen($mPartNumber, $mLocationCode, $mCurrentUser, $mConnect)
{
	$mReturn = "";
	
	$mJsonArray = array();
	$mJsonArray['partNumber'] = $mPartNumber;
	$mJsonArray['locationCode'] = $mLocationCode;
	$mJsonArray['userId'] = $mCurrentUser;
	
// Convert Array to Json Object
	try
	{
		$mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
	}
	catch(Exception $e)
	{
		return("FAIL-Json Error");
	}
// Replace default Server Tomcat Service
	$mConnectp = str_replace(":8081/vantec",":8095/pick",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8095/pick/";
    }
	$ch = curl_init();
	try
	{
		curl_setopt($ch, CURLOPT_URL, $mConnectp."createReplen");
		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")
			$mErrMsg =("FAIL-Unexpected System Error -".$mResult.":".$mResponse.":".$mErrors.":".$mJsonObject);
		else
		{
			return("OK  - createReplen");
		}
	}
	catch (Exception $e)
	{
		$mErrMsg =("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
	}
	if ($mReturn == "")
		$mReturn = "OK  -createReplen";
	return($mReturn);
}

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

// mysql connection
	$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
	if (!$mConnection)
		return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
	$mDataQuery = "SELECT id AS id, location_code AS location_code, max_pick_face_qty AS max_qty FROM location WHERE location.location_hash='".$mParms['tolocationhashcode']."' LIMIT 1";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	$mLocId = 0;
	$mMaxQty = 0;
	while($mRow = mysqli_fetch_assoc($mData))
	{
		$mLocId = $mRow['id'];
		$mLocCode = $mRow['location_code'];
		$mMaxQty = $mRow['max_qty'];
	}
	$mDataQuery = "SELECT count(id) AS count FROM inventory_master WHERE current_location_id=".$mLocId." AND inventory_qty > 0 ORDER BY current_location_id";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	$mData = (mysqli_query($mConnection,$mDataQuery));
	$mInvCount = 0;
	while($mRow = mysqli_fetch_assoc($mData))
	{
		$mInvCount = $mRow['count'];
	}
	if ($mInvCount >= $mMaxQty)
	{
		$mDataQuery = "UPDATE replen_task SET processed=1, last_updated_date=now(),last_updated_by='".$mParms['currentuser']."' WHERE to_location_code='".$mLocCode."' AND processed=0";
		if (!mysqli_query($mConnection,$mDataQuery))
			return "FAIL-".mysqli_error($mConnection).$mDataQuery;
	}
//	print_r("FAIL-TEST1-".$mDataQuery."-".$mInvCount."-".$mMaxQty."-".$mLocCode."-".$mJsonObject);
	return ("OK  -closeReplen");
}

function clearReplen($mCurrentUser,$mConnect,$mHost,$mUser,$mPwd,$mDbName)
{
	$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
	if (!$mConnection)
		return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
	$mDataQuery = "UPDATE replen_task SET replen_task.in_use='' WHERE replen_task.processed=0 AND (replen_task.in_use='".$mCurrentUser."' OR (replen_task.in_use <> '' AND replen_task.last_updated_date < DATE_SUB(NOW(), INTERVAL 10 MINUTE)))";
	if (!mysqli_query($mConnection,$mDataQuery))
		return "FAIL-".mysqli_error($mConnection).$mDataQuery;
//	return("FAIL-TEST1".$mDataQuery);
	return("OK  -clearReplen");
}

function transferReplen($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName)
{
	$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
	if (!$mConnection)
		return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
	
	$mParms = json_decode($mJsonObject, true);
	$mErrMsg = "";
/*	
	$mJsonArray = array();
	$mJsonArray['replenTaskId'] = $mParms['sequencingrequestid'];
	$mJsonArray['userId'] = $mParms['currentuser'];
	
// Convert Array to Json Object
	try
	{
		$mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
	}
	catch(Exception $e)
	{
		return("FAIL-Json Error");
	}
*/
// http://172.16.1.70:8095/pick/transferReplen?replenTaskId=1&&userId=ta
// Replace default Server Tomcat Service
	$mConnectp = str_replace(":8081/vantec",":8095/pick",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8095/pick/";
    }
	$ch = curl_init();
	try
	{
		curl_setopt($ch, CURLOPT_URL, $mConnectp."transferReplen?replenTaskId=".$mParms['sequencingrequestid']."&userId=".$mParms['currentuser']);
		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")
			$mErrMsg =("FAIL-Unexpected System Error -".$mResult.":".$mResponse.":".$mErrors.":".$mJsonObject);
		else
		{
			$mReturn = "OK  - Post Complete";
		}
	}
	catch (Exception $e)
	{
		$mErrMsg =("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
	}
//	print_r("FAIL-TEST1-".$mResult."-".$mJsonObject);
	if ($mResult == "true")
		$mReturn = "OK  -transferReplen";
	else
		$mReturn = "FAIL-Replen Transfer Error - ".$mResult;

	if ($mReturn == "")
		$mReturn = "OK  -transferReplen";
	
	return($mReturn);
	
}
?>