<?php
// validaterdt.php
// VIMS RDT validation Processing
// ----------------------------------------------------------------------------------------
// Modified 2019-04-26 - Over Allocation Correction.
//          2019-05-01 - Check Inspection Flag for Location Moves
//          2019-05-08 - processreceipt - Added function call
//          2019-05-24 - Store Serial in setFillingStatus to display on return to cts screen.
//          2019-05-28 - dupdelnote - prompt for delivery_note during receipt - called from RBTD & RBTP transactions.
//          2019-06-03 - validatedelnote - Validate Delivery Note entry
//          2019-06-04 - Validation for JIS-Receipt Processing (JRBTP)
//          2019-06-06 - dupdelnote - Prompt for Del.Note if Part is not advised
//          2019-06-12 - Added processing for PRUFCUBE parts
//          2019-06-18 - Prompt for delivery note for over-receipts
//          2019-06-24 - fieldlength - Ensure that quantity is numeric
//          2019-06-24 - validatedelnote - Check Delivery Note Prefix
//          2019-07-09 - Cross-Dock Pick Processing (XPTM)
//          2019-12-09 - delDelNote - Additional Validation for JIS receipt.
//          2019-12-17 - inventoryserial - Change TQA to stop movement of RCV Serials.
//          2019-12-19 - validatedelnote - Add validation for haulier-reference & delivery-note.
//          2019-12-19 - inventoryserial - Change CTM to stop movement of RCV Serials.
//          2020-01-06 - validateboxcount - Check for 3 wrong counts (rdtvims.html & jrbtp)
//          2020-02-28 - validatehaulierpart - Add check for valid part
//          2020-03-20 - getNextLoc - Test for 'qtine' inventory_status_code
//          2020-03-20 - inventoryserial - add test foe qtine
//          2020-04-29 - getNetxLocation - added serial_ref to param.list
//          2020-05-21 - validatercts - added chech in mysql to only select open/complete receipts.
//          2020-05-21 - inventoryserial - changed qa validation to only check if not duplicate serial.
//          2020-06-03 - getreplen - Get REPLEN Task To-Loc.
//          2020-06-12 - postxptm - delete clearlocation call.
//          2020-06-26 - inventoryserial - Change CTM to stop movement of QA serials.
//          2020-07-08 - validatepickplt - Check for closed TO.
//          2020-07-14 - inventoryserial - prompt for QA reference if Stock to QA.
//          2020-07-16 - validateexpirydate - nonprod receiving expiry date prompt
//          2020-07-16 - posttransaction - add expiry_date
//          2020-10-26 - checkrecsts - Test receipt status
//          2020-10-27 - validateshortlocation - check that scanned location is Shortage Type.
//          2020-10-27 - validatemts - Validation for Pick Shortage.
//          2020-10-27 - postmts - Process Pick Shortage.
//          2020-11-10 - validategoodinserial - test for modular part
//          2020-12-13 - getNextLocation check for requires_decant
//          2021-02-22 - getNextLocation - populate $mProductType
//          2021-03-19 - various - 'nonran' inventory_status
//          2021-04-06 - tqa & fqa processing corrections.
//          2021-04-27 - inventoryserial - add overbooking to allowed inventory_status
//          2021-05-18 - getputawayloc - extra validation.
//          2021-05-26 - validatecustomerreference - correct validation of receipt_header.id
//          2021-05-26 - validategoodinserial - check inventory_status.
//          2021-08-12 - validatemarshallocation - check for fixed location.
//          2021-08-20 - validateunknownserial - prompt confirm of unknown serial
//          2021-12-16 - validatetraintrolleyloc - get train trolley from zone destination
//          2022-01-25 - validatetrain - check if train exists.
// ----------------------------------------------------------------------------------------


// ----------------------------------------------------------------------------------------
// Init Config
// ----------------------------------------------------------------------------------------
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);
date_default_timezone_set('Europe/London');

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


// ----------------------------------------------------------------------------------------
// Includes and Requires
// ----------------------------------------------------------------------------------------
require_once __DIR__ . '/./helpers.php';
include_once 'connect.php';


// ----------------------------------------------------------------------------------------
// Global Variables
// ----------------------------------------------------------------------------------------

$conn = dbConnection();
// validaterdt - VIMS Server Validation
$mFilter = "";
$mFunction = $_GET['function'] ?? '';
$mConnect = $_GET['connection'] ?? '';
$mUser = $_GET['user'] ?? '';
$mPwd = $_GET['pword'] ?? '';
$mHost = $_GET['host'] ?? '';
$mDbName = $_GET['dbase'] ?? '';
$mTableName = $_GET['table'] ?? '';
$mReturnFields = $_GET['returnfields'] ?? '';
if(isset($_GET['filter'])) {
    $mFilter =   $_GET['filter'];
}

if (!empty($conn['host']))
    $mHost = $conn['host'];
if (!empty($conn['user']))
    $mUser = $conn['user'];
if (!empty($conn['pwd']))
    $mPwd = $conn['pwd'];
if (!empty($conn['dbase']))
    $mDbName = $conn['dbase'];
if (!empty($conn['path']))
    $mConnect = $conn['path'];


// Get Input Parameters from POST or GET
if (!empty($_POST))
{
    $mFilter = "";
    foreach($_POST as $k1=>$v1)
    {
        if ($mFilter != "")
            $mFilter .= "|AND|";
        $mFilter .= $k1."=".$v1;
    }
}
if ($mFilter == "")
{
    $mFilter = file_get_contents("php://input");
    $mArray1 = json_decode($mFilter, true);
    $mFilter = "";
    foreach($mArray1 as $k1=>$v1)
    {
        if ($mFilter != "")
            $mFilter .= "|AND|";
        $mFilter .= $k1."=".$v1;
    }
}

$mFilter = str_replace("&","|AMPERSAND|",$mFilter);
$mFilter = str_replace("|AND|","&",$mFilter);
$mFilter = str_replace("|COLON|",":",$mFilter);
$mFilter = str_replace("/dbase/",$mDbName,$mFilter);
// Replace Chars in Input String to emulate a JSON format instead of GET format
$mFilter = str_replace("=",":",$mFilter);
$mFilter = str_replace("&",",",$mFilter);


$mSQLData = array();

$mErrMsg = "OK  -";
$mDataStr = "";


// ----------------------------------------------------------------------------------------
// Function Routers
// ----------------------------------------------------------------------------------------

// Test
if (($mFunction != null) && ($mFunction == "test"))
{
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }

    echo $mStatus;
    return;
}

// Basic call / response
if (($mFunction != null) && ($mFunction == "ajax"))
{
    $mResponse = "";
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "response")
            $mResponse = $v2;
        if ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }
    if ($mResponse == "" || $mResponse == null)
        $mResponse = "OK  -".$mResponse;
    $mResponse = str_replace("comma",",",$mResponse);
    exit ($mResponse);
}

// Check for Session Time-Out
if (($mFunction != null) && ($mFunction == "sessiontimeout"))
{
    $mTimeOut = 10;
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "timeout")
            $mTimeOut = $v2;
//          $mTimeOut = $v2*3600;
    }
    $mTimeOut = $mTimeOut*60;
    session_start();
//  if(time() - $_SESSION['userData']['timestamp'] > 900)
    if(time() - $_SESSION['userData']['timestamp'] > $mTimeOut)  
    { 
// subtract new timestamp from the old one
//      echo"<script>alert('15 Minutes over!');</script>";
        echo("FALO-Session Timed-out");
        unset($_SESSION['userData']);
//      exit;
        return;
    } 
    else 
    {
        $_SESSION['userData']['timestamp'] = time(); //set new timestamp
    }
}

// Basic Field Validation - format is - http://172.16.1.70:8081/vantec/validateRDTField?fieldName=partNumber&fieldValue=PARTA&transactionType=RBTD

if (($mFunction != null) && ($mFunction == "validateRDTField"))
{
// Replace Server Connection with validation Service
    $mConnectv = str_replace(":8081/vantec",":8084/validation",$mConnect);

    $mStatus = "OK  -";
    $mDataStr = "";
// Strip out User
    $mCurrentUser="";
    $s = strpos(strtolower($mFilter),"currentuser=");
    if ($s > 0)
    {
        $s = $s+12;
        $e = strpos($mFilter,"&",$s);
        if ($e <= $s)
            $e = strlen($mFilter);
        $mCurrentUser = substr($mFilter,$s,$e-$s);
        $mFilter = substr($mFilter,0,$s-13);
    }
// Get Server Data from URL
    try
    {
        $mFilter = $mFunction."?".$mFilter;
        $mDataStr = file_get_contents($mConnectv.$mFilter);
        if ($mDataStr === false) 
            {
                $mStatus = "FAIL-";
                $mDataStr = '{"status":"FAIL"}';
            }
    } 
    catch (Exception $e) 
    {
        exit("FAIL-Connection Error at - ".$mConnectv.$mFilter.":".$e);
    }

// Convert JSON String to Array
    $mSQLData = json_decode($mDataStr, true);
    $mDataStr = str_replace("{","",$mDataStr);
    $mDataStr = str_replace("}","",$mDataStr);
    $mDataStr = str_replace("[","",$mDataStr);
    $mDataStr = str_replace("]","",$mDataStr);
    $mDataStr = str_replace('"',"",$mDataStr);
    
    $mStatus = $mSQLData['status'];
    if (substr($mStatus,0,2) == "OK")
    {
        $mStatus = "OK  -";
        $mDataStr = substr($mDataStr,9);
    }
    else
    {
        $mStatus = "FAIL-";
        $mDataStr = substr($mDataStr,11);
    }
}

// Validate Field Min / Max Length
elseif (($mFunction != null) && ($mFunction=="validatelength"))
{
// Set default error message
    $mErrMsg = "OK  -";
// Strip out User
    $mCurrentUser="";
    $s = strpos(strtolower($mFilter),"currentuser=");
    if ($s > 0)
    {
        $s = $s+12;
        $e = strpos($mFilter,"&",$s);
        if ($e <= $s)
            $e = strlen($mFilter);
        $mCurrentUser = substr($mFilter,$s,$e-$s);
        $mFilter = substr($mFilter,0,$s-13);
    }   
// Parse-out Field, min, max
    $s = strpos($mFilter,"field=");
    $s = $s + 6;
    $e = strpos($mFilter,"&min=");
    if ($e <= $s)
        $e = strlen($mFilter);
    $mField = substr($mFilter,$s,$e-$s);
    $s = strpos($mFilter,"min=");
    $s = $s + 4;
    $e = strpos($mFilter,"&max=");
    if ($e <= $s)
        $e = strlen($mFilter);
    $mMin = substr($mFilter,$s,$e-$s);
    $s = strpos($mFilter,"max=");
    $s = $s + 4;
    $e = strpos($mFilter,"&min=");
    if ($e <= $s)
        $e = strlen($mFilter);
    $mMax = substr($mFilter,$s,$e-$s);
//  exit("FAIL-".$mField.":".$mMin.":".$mMax.":".strlen($mField));
// Check Min Length
    if (strlen($mField) < intval($mMin))
    {
        $mErrMsg = "FAIL-Scanned Field too short";
    }
    if (strlen($mField) > intval($mMax))
    {
        $mErrMsg = "FAIL-Scanned Field too long";
    }
}

// Validate Field Min / Max Length
elseif (($mFunction != null) && (strtolower($mFunction) == "validatefieldlength"))
{   
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mMin = "";
    $mMax = "";
    $mTrim = "";
    $mErrMsg = "OK  -";
//  exit("FAIL-TEST-".$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "fieldname")
            $mFieldName = $v2;
        elseif ($k2 == "field")
            $mField = trim(strtoupper($v2));
        elseif ($k2 == "min")
            $mMin = $v2;
        elseif ($k2 == "max")
            $mMax = $v2;
        elseif ($k2 == "trim")
            $mTrim = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
    }
// Test for non-numeric Quantity
    if (($mFieldName == "quantity") || ($mFieldName=="number"))
        if(is_numeric($mField))
        {
        }
        else
        {
            echo "FAIL-This must be a number only";
            return;
        }
// Test for Company Defaults
    if (($mErrMsg == "OK  -") && ($mMax == ""))
    {
        if ($mCurrentUser != "")
        {
// mysql connection
            $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
                exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// get company default Min .. Max
            $mDataQuery = "SELECT company.id AS id";
            if (strtolower($mFieldName) == "partnumber")
                $mDataQuery .=  ",min_part_number_length AS min, max_part_number_length AS max";
            elseif (strtolower($mFieldName) == "ranorder")
                $mDataQuery .= ",min_ran_number_length AS min, max_ran_number_length AS max";
            elseif (strtolower($mFieldName) == "serialreference")
                $mDataQuery .= ",min_serial_number_length AS min, max_serial_number_length AS max";
            elseif (strtolower($mFieldName) == "quantity")
                $mDataQuery .= ",min_box_qty AS min, max_box_piece_qty AS max";
            $i = 0;
//          $mMin = "";
//          $mMax = "";
            try
            {
//              $mDataQuery .= " FROM company JOIN user ON company.id=user.company_id WHERE user.username = '".$mCurrentUser."' LIMIT 1";
                $mDataQuery .= " FROM company LIMIT 1";
                if (!mysqli_query($mConnection,$mDataQuery))
                    exit("FAIL-".mysqli_error($mConnection).":".$mDataQuery);
                $mData = mysqli_query($mConnection,$mDataQuery);
                while($mRow = mysqli_fetch_assoc($mData)) 
                {
                    $mMin = ($mRow['min']);
                    $mMax = ($mRow['max']);
                    $i++;
                }
            }
            catch (Exception $e) 
            {
//              $mMin = "";
//              $mMax = "";
            }
//          mysqli_close($mConnection);
        }
    }
// part number replacement chars
    $i = 0;
    if ((strtolower($mFieldName) == "partnumber") || (strtolower($mFieldName) == "vendorpartcode"))
    {
        $mReplace = array("-","#","/","'","_");
        foreach($mReplace as $mChar)
        {
            if (strpos($mField,$mChar) !== false)
            {
                $mField = str_replace($mChar,"",$mField);
                $i++;
            }
//          exit("FAIL-TEST1 ".$mField." ".$i);
        }
    }
    if (($mMax != "") && ($mMax != "0"))
    {
        if (($mFieldName == "quantity") || ($mFieldName=="number"))
        {
// Numeric Field outside Limits
            if (($mField < $mMin) || ($mField > $mMax))
                $mErrMsg = "FAIL-Value Error";
        }
        else
        {
// Return Trimmed Field if required
            if (($mTrim != "") && (strlen($mField) > $mMax))
            {
                $mDataStr = "DATA-".$mFieldName.":".substr($mField,0,$mMax);
                echo $mDataStr;
                return;
            }
// String Field outside limits                  
            if ((strlen($mField) < $mMin) || (strlen($mField) > $mMax))
                $mErrMsg = "FAIL-Field Length Error";
        }
    }
    if ($i > 0)
    {
        $mDataStr = "DATA:".$mFieldName.":".$mField;
        echo $mDataStr;
        return;
    }
    
    echo $mErrMsg;
    return;
}

// Get Part Details from Server
elseif (($mFunction != null) && ($mFunction == "findPartDetails"))
{
// Replace Server Connection with validation Service
    $mConnectv = str_replace(":8081/vantec",":8084/validation",$mConnect);

// Strip out User
    $mCurrentUser="";
    $s = strpos(strtolower($mFilter),"currentuser=");
    if ($s > 0)
    {
        $s = $s+12;
        $e = strpos($mFilter,"&",$s);
        if ($e <= $s)
            $e = strlen($mFilter);
        $mCurrentUser = substr($mFilter,$s,$e-$s);
        $mFilter = substr($mFilter,0,$s-13);
    }
// Get Server Data from URL
    try
    {
        $mFilter = $mFunction."?".$mFilter;
        $mDataStr = file_get_contents($mConnectv.$mFilter);
        if ($mDataStr === false) 
            {
                $mStatus = "FAIL-";
                $mDataStr = '{"status":"FAIL"}';
            }
    } 
    catch (Exception $e) 
    {
        exit("FAIL-Connection Error at - ".$mConnectv.$mFilter.":".$e);
    }
    
//  echo ("FAIL-TEST:".$mConnect.$mFilter.":".$mDataStr);
//  exit;
// Parse XML to XML Object Array
//  $xml = simplexml_load_string($mData, 'SimpleXMLElement', LIBXML_NOCDATA);
//  $mStatus = "".$xml->status."";

// Convert JSON String to Array
    $mSQLData = json_decode($mDataStr, true);
    
    $mDataStr = "";
    $c = 0;
    foreach ($mSQLData as $key => $val) 
    {
        if ($c > 0)
            $mDataStr = $mDataStr.",";
        $mDataStr = $mDataStr.$key.":".$val;
        $c++;   
    }

    $mDataStr = str_replace("{","",$mDataStr);
    $mDataStr = str_replace("}","",$mDataStr);
    $mDataStr = str_replace("[","",$mDataStr);
    $mDataStr = str_replace("]","",$mDataStr);
    $mDataStr = str_replace('"',"",$mDataStr);
//  echo ("FAIL-TEST:".$mConnect.$mFilter.":".$mDataStr);
//  exit;
//  $mStatus = $mSQLData['status'];
    if ($mDataStr != "")
    {
        $mStatus = "DATA-";
//      $mDataStr = substr($mDataStr,9);
    }
    else
    {
        $mStatus = "FAIL-";
//      $mDataStr = substr($mDataStr,11);
    }
}

// Validate Location
elseif (($mFunction != null) && ($mFunction=="validatelocation"))
{
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Set default error message
    $mErrMsg = "FAIL-Invalid Location";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mLocationHash = "";
    $mLocationCode = "";
    $mVldLocationCode = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "tolocationhashcode")
            $mLocationHash = ($v2);
        elseif ($k2 == "locationcode")
            $mLocationCode = ($v2);
        elseif ($k2 == "vldlocationcode")
            $mVldLocationCode = ($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = ($v2);
    }
    
//  exit("FAIL-".$mFilter);
    if (($mLocationHash == "") && ($mLocationCode == ""))
        exit("FAIL-Location cannot be blank");
// Test for existence of location Code
    if ($mLocationHash != "")
        $mDataQuery = "SELECT location.id AS id, location.location_code AS location_code, location.location_hash AS hash_code FROM location LEFT JOIN location_type ON location.location_type_id=location_type.id WHERE (location.location_hash='".$mLocationHash."') LIMIT 1";
    elseif ($mLocationCode != "")
        $mDataQuery = "SELECT location.id AS id, location.location_code AS location_code, location.location_hash AS hash_code FROM location LEFT JOIN location_type ON location.location_type_id=location_type.id WHERE (location.location_code='".$mLocationCode."') LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection));
    $mData = mysqli_query($mConnection,$mDataQuery);
    $i = 0;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
//      $mSQLData[] =($mRow);
        $mLocationCode = ($mRow['location_code']);
        $i++;
    }
//  mysqli_close($mConnection);
    $mDataStr = "";
    If ($i > 0)
    {
        if (($mVldLocationCode != "") && ($mVldLocationCode != $mLocationCode))
        {
            $mStatus = "FAIL-Incorrect Location - ".$mLocationCode;
        }
        else
            $mStatus = "OK  -";
    }
    else
    {
        if ($mLocationCode != "")
            $mStatus = $mErrMsg."- ".$mLocationCode;
        else    
            $mStatus = $mErrMsg."- ".$mLocationHash;
    }
    if ($mStatus == "")
        $mStatus = "OK  -validatelocation";
    exit ($mStatus);
}

// Validate Location
elseif (($mFunction != null) && ($mFunction=="validatelocationtype"))
{
    $mLocation = "";
    $mErrMsg = "";
    
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;

// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    $mFromLocation = "";
    $mToLocation = "";
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "location")
            $mLocation = $v2;
        if ($k2 == "partnumber")
            $mPartNumber = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error()); 
// Validate From Location / Pallet
    $mDataQuery = "SELECT location.id AS location_id, location_code, multi_part_location AS multi_part FROM location WHERE location_hash ='".$mLocation."' LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    $mData = mysqli_query($mConnection,$mDataQuery);
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mLocationId = ($mRow['location_id']);
        $mLocationCode = ($mRow['location_code']);
        $mMultiPart = ($mRow['multi_part']);
    }
// Check for Mixed Parts
    if ($mMultiPart == 0)
    {
        $mDataQuery = "SELECT inventory_master.part_id AS part_id, part.part_number AS part_number FROM inventory_master JOIN part ON inventory_master.part_id=part.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE current_location_id=".$mLocationId." AND (inventory_master.inventory_status_id IS null OR LOWER(inventory_status.inventory_status_code) NOT IN('pkd','plt')) LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $mPartId = "";
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mPartId = ($mRow['part_id']);
            $mInvPartNumber = ($mRow['part_number']);
        }
        if ($mPartId != "")
        {
            if (strtoupper($mPartNumber) != strtoupper($mInvPartNumber))
            {
//              exit("FAIL-Location is Single Part Only");
                echo "FAIL-Single Part Location";
                return;
            }
        }
    }
//  exit("OK  -validatelocationtype");
    echo "OK  -validatelocationtype";
    return;
//  exit("FAIL-validatelocationtype".$mDataQuery."-".mysqli_num_rows($mData));
}

// Validate Receiving Location
elseif (($mFunction != null) && ($mFunction=="validatereceiptlocation"))
{
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Set default error message
    $mErrMsg = "FAIL-Wrong Location Type for Receiving";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "tolocation")
            $mLocation = ($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = ($v2);
    }
// Test for existence of Receiving Location Type
//  $mDataQuery = "SELECT location.id AS id FROM location JOIN location_type ON location.location_type_id=location_type.id WHERE (location.location_hash='".$mLocation."' OR location.location_code='".$mLocation."') AND location_type.location_type_code='RCV' LIMIT 1";
    $mDataQuery = "SELECT location.id AS id FROM location JOIN location_type ON location.location_type_id=location_type.id WHERE (location.location_hash='".$mLocation."') AND lower(location_type.location_type_code)='rcv' LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);   
    $i = 0;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
//      $mSQLData[] =($mRow);
        $i++;
    }   
    $mDataStr = "";
    If ($i > 0)
    {
        $mStatus = "OK  -";
    }
    else
    {
        $mStatus = $mErrMsg;
    }
//    mysqli_close($mConnection);
    echo($mStatus);
    return;
}

// Validate Marshall Location
elseif (($mFunction != null) && ($mFunction=="validatemarshalllocation"))
{
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Set default error message
    $mErrMsg = "";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "tolocation")
            $mLocation = ($v2);
        elseif ($k2 == "vldtolocation")
            $mVldLocation = ($v2);    
        elseif ($k2 == "currentUser")
            $mCurrentUser = ($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = ($v2);
    }
// Test for existence of Receiving Location Type
    $mDataQuery = "SELECT location.id AS id,location.location_code AS location_code, location.location_hash AS location_hash FROM location JOIN location_type ON location.location_type_id=location_type.id WHERE (location.location_hash='".$mLocation."') AND lower(location_type.location_type_code) IN('ma','ml','mar','trl','maxdpt') LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    $i = 0;
    if (mysqli_num_rows($mData) == 0)
    {
       $mErrMsg = "FAIL-Wrong Location Type for Marshalling-".$mLocation; 
    }
    if ($mErrMsg == "")
    {
        $mLocCode = "";
        $mLocHash = "";
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mLocCode = $mRow['location_code'];
            $mLocHash = $mRow['location_hash'];
            $i++;
        }
//        mysqli_close($mConnection);
        if ($mVldLocation && $mVldLocation != null && $mVldLocation != "")
        {
            if (strtolower($mVldLocation) != strtolower($mLocHash) && strtolower($mVldLocation) != strtolower($mLocCode))
            {
                $mErrMsg = "FAIL-Scanned Location is not Fixed Location ".$mVldLocation." ".$mLocHash;
            }
        }
    }
    if ($mErrMsg == "")
    {
        $mErrMsg = "OK  -";
    }
    echo ($mErrMsg);
    return;
}

// Validate Trailer Location
elseif (($mFunction != null) && ($mFunction=="validatetrailerlocation"))
{
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Set default error message
    $mErrMsg = "FAIL-Wrong Location Type for Trailer";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "tolocation")
            $mLocation = ($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = ($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = ($v2);
    }
// Test for existence of Receiving Location Type
    $mDataQuery = "SELECT location.id AS id FROM location JOIN location_type ON location.location_type_id=location_type.id WHERE (location.location_hash='".$mLocation."' OR location.Location_code='".$mLocation."') AND lower(location_type.location_type_code)='trl' LIMIT 1";
    $mData = mysqli_query($mConnection,$mDataQuery);
    $i = 0;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
//      $mSQLData[] =($mRow);
        $i++;
    }
//  mysqli_close($mConnection);
    $mDataStr = "";
    If ($i > 0)
    {
        $mStatus = "OK  -";
    }
    else
    {
        $mStatus = $mErrMsg;
    }
}

// Validate Shortage Location
elseif (($mFunction != null) && ($mFunction=="validateshortlocation"))
{
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Set default error message
    $mErrMsg = "FAIL-Wrong Location Type for Shortage";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "tolocation")
            $mLocation = ($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = ($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = ($v2);
    }
// Test for existence of Shortage Location Type
    $mDataQuery = "SELECT location.id AS id FROM location JOIN location_type ON location.location_type_id=location_type.id WHERE (location.location_hash='".$mLocation."') AND lower(location_type.location_type_code) IN('shtg','shtg') LIMIT 1";
    $mData = mysqli_query($mConnection,$mDataQuery);
    $i = 0;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $i++;
    }
//  mysqli_close($mConnection);
    $mDataStr = "";
    If ($i > 0)
    {
        $mStatus = "OK  -";
    }
    else
    {
        $mStatus = $mErrMsg;
    }
}

// Validate Goods-In Serial
elseif (($mFunction != null) && ($mFunction=="validategoodinserial"))
{
    $mStatus = validateGoodsInSerial($mHost,$mUser,$mPwd,$mDbName,$mFilter);
    echo($mStatus);
    return;
}

// Validate Haulier Vendor / Part
elseif (($mFunction != null) && ($mFunction=="validatehaulierpart" || $mFunction == "validatecustomerpart"))
{   
    $mStatus = validateCustomerPart($mHost,$mUser,$mPwd,$mDbName,$mFilter);
    
    if ($mStatus == "")
        $mStatus = "OK  -HaulierPart";
/*  
    try
    {
        mysqli_close($mConnection);
    }
    catch(Exception $e)
    {
    }
*/
//  exit($mStatus);
    echo $mStatus;
    return;
}

// Validate Goods-In Serial
elseif (($mFunction != null) && ($mFunction=="validatepartserial"))
{
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Set default error message
    $mErrMsg = "FAIL-Invalid Serial or Part";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mMin = "";
    $mMax = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "partnumber")
            $mPartNumber = strtoupper($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = strtoupper($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = strtoupper($v2);
    }
    
    $mDataQuery = "SELECT inventory_master.id AS id FROM inventory_master JOIN part ON inventory_master.part_id=part.id WHERE (part.part_number='".$mPartNumber."') AND inventory_master.serial_reference='".$mSerialReference."' AND inventory_master.inventory_qty > 0 LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    if (mysqli_num_rows($mData)==0)
    {
        $mDataQuery = "SELECT inventory_master.id AS id FROM inventory_master LEFT JOIN part ON inventory_master.part_id=part.id WHERE (inventory_master.part_number='".$mPartNumber."') AND inventory_master.serial_reference='".$mSerialReference."' AND inventory_master.inventory_qty > 0 LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    }
    $i = mysqli_num_rows($mData);
    if ($i == 0)
    {
//      mysqli_close($mConnection);
//      exit("FAIL-Invalid Serial");
        echo "FAIL-Invalid Serial ".$mDataQuery;
        return;
    }
    if ($mTransactionTypeId == "CTS")
    {
//      $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.part_id AS part_id, 0 AS product_type_id, part.part_number AS part_number FROM inventory_master JOIN part ON inventory_master.part_id=part.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE (part.part_number = '".$mPartNumber."' OR part.vendor_part_code='".$mPartNumber."') AND inventory_master.serial_reference = '".$mSerialReference."' AND (inventory_master.inventory_qty-inventory_master.hold_qty) > 0 AND (inventory_master.inventory_status_id IS null or lower(inventory_status.inventory_status_code) in('ok','rcv','qa','qtine','noran')) LIMIT 1";
        $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.part_id AS part_id, 0 AS product_type_id, part.part_number AS part_number FROM inventory_master JOIN part ON inventory_master.part_id=part.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE (part.part_number = '".$mPartNumber."') AND inventory_master.serial_reference = '".$mSerialReference."' AND inventory_master.inventory_qty > 0 AND (inventory_master.inventory_status_id IS null or lower(inventory_status.inventory_status_code) in('ok','rcv','qa','qtine','noran')) LIMIT 1";
        $mData = mysqli_query($mConnection,$mDataQuery);
        $i = mysqli_num_rows($mData);
        if ($i == 0)
        {
//          mysqli_close($mConnection);
//          exit("FAIL-This Serial is not available");
            echo "FAIL-This Serial is not available";
            return;
        }
    }
    if ($mTransactionTypeId == "AFTP")
    {
//      $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.part_id AS part_id, 0 AS product_type_id, part.part_number AS part_number FROM inventory_master JOIN part ON inventory_master.part_id=part.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE (part.part_number = '".$mPartNumber."' OR part.vendor_part_code='".$mPartNumber."') AND inventory_master.serial_reference = '".$mSerialReference."' AND (inventory_master.inventory_qty-inventory_master.hold_qty) > 0 AND inventory_master.requires_inspection <> 1 AND (inventory_master.inventory_status_id IS null or lower(inventory_status.inventory_status_code) in('ok','rcv','missing','qa','qtine','noran')) LIMIT 1";
        $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.part_id AS part_id, 0 AS product_type_id, part.part_number AS part_number FROM inventory_master JOIN part ON inventory_master.part_id=part.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE (part.part_number = '".$mPartNumber."') AND inventory_master.serial_reference = '".$mSerialReference."' AND inventory_master.inventory_qty > 0 AND inventory_master.requires_inspection <> 1 AND (inventory_master.inventory_status_id IS null or lower(inventory_status.inventory_status_code) in('ok','rcv','missing','qa','qtine','noran')) LIMIT 1";
        $mData = mysqli_query($mConnection,$mDataQuery);
        $i = mysqli_num_rows($mData);
        if ($i == 0)
        {
//          mysqli_close($mConnection);
//          exit("FAIL-This Serial is not available");
            echo "FAIL-This Serial is not available";
            return;
        }
    }
    $i = 0;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mSQLData[] =($mRow);
        $i++;
    }
//  mysqli_close($mConnection);
    $mDataStr = "";
    If ($i == 1)
    {
        $mStatus = "OK  -";
    }
    else
    {
        $mStatus = $mErrMsg;
    }
}

// Validate Inventory Status Flag
elseif (($mFunction != null) && ($mFunction=="validateinventorystatus"))
{
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mMin = "";
    $mMax = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "statusflag")
            $mStatusFlag = strtoupper($v2);
        elseif ($k2 == "allowedcodes")
            $mAllowedCodes = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = strtoupper($v2);
    }
    $s = strpos($mAllowedCodes,$mStatusFlag);
    if (($s === false) || ($mStatusFlag == ","))
    {
//      exit("FAIL-Invalid Status Flag. ".$mStatusFlag.":".$mAllowedCodes.":".$s);
        echo "FAIL-Invalid Status Flag. ".$mStatusFlag.":".$mAllowedCodes.":".$s;
        return;
    }
    else
    {
//      exit("OK  -");
        echo "OK  -";
        return;
    }
}

// Check for duplicate Ran
elseif (($mFunction != null) && ($mFunction == "validateranpart"))
{
    $mErrMsg = "";
    $i = 0;
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "partnumber")
            $mPartNumber = $v2;
        elseif ($k2 == "ranorder")
            $mRanOrder = strtolower($v2);
    }
// ignore for NO-RAN
    if ((strtolower($mRanOrder) == "no-ran") || ($mRanOrder == ""))
    {
//      exit("OK  -");
        echo "OK  -";
        return;
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
//  $mDataQuery = "SELECT inventory_master.ran_or_order AS ran_or_order, inventory_master.part_id AS part_id, part.part_number as part_number FROM inventory_master JOIN part ON inventory_master.part_id=part.id WHERE inventory_master.ran_or_order='".$mRanOrder."' AND (inventory_master.inventory_qty-inventory_master.hold_qty) <> 0 AND (part.part_number <> '".$mPartNumber."' AND part.vendor_part_code <> '".$mPartNumber."') LIMIT 1";
    $mDataQuery = "SELECT inventory_master.ran_or_order AS ran_or_order, inventory_master.part_id AS part_id, part.part_number as part_number FROM inventory_master JOIN part ON inventory_master.part_id=part.id WHERE inventory_master.ran_or_order='".$mRanOrder."' AND inventory_master.inventory_qty <> 0 AND (part.part_number <> '".$mPartNumber."') LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection));
    $mData = mysqli_query($mConnection,$mDataQuery);
    $i = 0;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mErrMsg = "FAIL-RAN already exists for Part -".($mRow['part_number']);
        $i++;
    }
    if ($mErrMsg == "")
    {
        $mDataQuery = "SELECT part_number as part_number FROM scan_data WHERE ran_order='".$mRanOrder."' AND part_number <> '".$mPartNumber."' LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection));
        $mData = mysqli_query($mConnection,$mDataQuery);
        $i = 0;
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mErrMsg = "FAIL-RAN already exists for Part -".($mRow['part_number']);
            $i++;
        }
    }
//  mysqli_close($mConnection);
    if ($i > 0)
    {
//      exit($mErrMsg);
        echo $mErrMsg;
        return;
    }
//  exit("OK  -");
    echo "OK  -";
    return;
}

// Update Inventory Decant / QA flag.
elseif (($mFunction != null) && (strtolower($mFunction) == "updateinventorystatus"))
{
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $s=0;
    $e=0;
    $mJsonArray = array();
    $mDataQuery = "UPDATE inventory_master SET last_updated=now(), last_updated_by=, statusFlag= CASE WHEN statusFlag=0 THEN 1 ELSE 0 END WHERE part_number= AND serial_reference= LIMIT 1";
    $mPartNumber = "";
    $mSerialReference = "";
    $mInspect = "";
    $mDecant = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "statusFlag")
        {
            if ($v2 == "D")
                $mDataQuery=str_replace("statusFlag=","requires_decant=",$mDataQuery);
            elseif ($v2 == "I")
                $mDataQuery=str_replace("statusFlag=","requires_inspection=",$mDataQuery);
            else
            {
//              exit("FAIL-Invalid Inventory Status Flag - ".$v2);
                echo "FAIL-Invalid Inventory Status Flag - ".$v2;
                return;
            }
        }
        if ($k2 == "currentUser")
        {
            $mFilter = "last_updated_by='".$v2."'";
            $mDataQuery = str_replace("last_updated_by=",$mFilter,$mDataQuery);
        }
        if ($k2 == "partNumber")
        {
            $mFilter = "part_number='".$v2."'";
            $mDataQuery = str_replace("part_number=",$mFilter,$mDataQuery);
            $mPartNumber = $v2;
        }
        if ($k2 == "serialReference")
        {
            $mFilter = "serial_reference='".$v2."'";
            $mDataQuery = str_replace("serial_reference=",$mFilter,$mDataQuery);
            $mSerialReference = $v2;
        }
        $mJsonArray[$k2] = $v2;
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    if (!mysqli_query($mConnection,$mDataQuery))
    {
        exit("FAIL-".mysqli_error($mConnection));
    }
// Get Upsdated Status
    $mDataQuery = "SELECT inventory_master.requires_decant AS decant, inventory_master.requires_inspection AS inspect FROM inventory_master JOIN part ON inventory_master.psrt_id=part.id WHERE (part.part_number='".$mPartNumber."') AND serial_reference='".$mSerialReference."' AND inventory_master.inventory_qty > 0 LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
    {
        exit("FAIL-".mysqli_error($mConnection));
    }
    $mData = mysqli_query($mConnection,$mDataQuery);
    $i = 0;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mDecant=($mRow['decant']);
        $mInspect=($mRow['inspect']);
        $i++;
    }
//  mysqli_close($mConnection);
    if ($i = 0)
    {
//      exit("OKMS-Inventory Status Changed");
        echo "OKMS-Inventory Status Changed";
        return;
    }
    else
        if ($mDecant=="1")
            $mDecant = "ON";
        else
            $mDecant = "OFF";
        if ($mInspect=="1")
            $mInspect = "ON";
        else
            $mInspect = "OFF";
//      exit("OKMS-Inventory Status Changed - Decant is ".$mDecant." and Inspect is ".$mInspect);
        echo "OKMS-Inventory Status Changed - Decant is ".$mDecant." and Inspect is ".$mInspect;
        return;
}

// Update Inventory Inspection flag.
elseif (($mFunction != null) && (strtolower($mFunction) == "changeinspstatus"))
{
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mJsonArray = array();
// Set SQL string with placeholder fields
    $mDataQuery = "UPDATE inventory_master SET last_updated=now(), last_updated_by=, statusFlag= WHERE part_number= AND serial_reference= LIMIT 1";
    $mPartNumber = "";
    $mSerialReference = "";
    $mInspect = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "statusflag")
        {
            if (strtolower($v2) == "y")
                $mDataQuery=str_replace("statusFlag=","requires_inspection=1",$mDataQuery);
            elseif (strtolower($v2) == "n")
                $mDataQuery=str_replace("statusFlag=","requires_inspection=0",$mDataQuery);
            else
            {
//              exit("FAIL-Invalid Inventory Status Flag - ".$v2);
                echo "FAIL-Invalid Inventory Status Flag - ".$v2;
                return;
            }
        }
        if ($k2 == "currentUser")
        {
            $mFilter = "last_updated_by='".$v2."'";
            $mDataQuery = str_replace("last_updated_by=",$mFilter,$mDataQuery);
        }
        if (strtolower($k2) == "partnumber")
        {
            $mFilter = "part_number='".$v2."'";
            $mDataQuery = str_replace("part_number=",$mFilter,$mDataQuery);
            $mPartNumber = $v2;
        }
        if (strtolower($k2) == "serialreference")
        {
            $mFilter = "serial_reference='".$v2."'";
            $mDataQuery = str_replace("serial_reference=",$mFilter,$mDataQuery);
            $mSerialReference = $v2;
        }
        $mJsonArray[strtolower($k2)] = $v2;
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    if (!mysqli_query($mConnection,$mDataQuery))
    {
        exit("FAIL-".mysqli_error($mConnection));
    }
// Get Upsdated Status
    $mDataQuery = "SELECT inventory_master.requires_inspection AS inspect FROM inventory_master JOIN part ON inventory_master.part_id=part.id WHERE (part.part_number='".$mPartNumber."') AND serial_reference='".$mSerialReference."' AND inventory_master.inventory_qty > 0 LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
    {
        exit("FAIL-".mysqli_error($mConnection));
    }
    $mData = mysqli_query($mConnection,$mDataQuery);
    $i = 0;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mInspect=($mRow['inspect']);
        $i++;
    }
//  mysqli_close($mConnection);
    if ($i = 0)
    {
//      exit("OKMS-Inventory Status Changed");
        echo "OKMS-Inventory Status Changed";
        return;
    }
    else
        if ($mInspect=="1")
            $mInspect = "ON";
        else
            $mInspect = "OFF";
//      exit("OKMS-Inventory Status Changed - Inspect is ".$mInspect);
        echo "OKMS-Inventory Status Changed - Inspect is ".$mInspect;
        return;
}

// Return Inventory / Part Details
elseif (($mFunction != null) && (strtolower($mFunction) == "getpart"))
{
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;

// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);

// Create Associative Array by Exploding Array Elements on :
    $mPartNumber = "";
    $mSerialReference = "";
    $mVendorPartCode = "";
    $mLocationCode = "";
    $mPlt = "";
    $mShowMsg = "";
    $mSkip = "";
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "partnumber")
            $mPartNumber = strtoupper($v2);
        elseif ($k2 == "vendorpartcode")
            $mVendorPartCode = strtoupper($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = strtoupper($v2);
        elseif ($k2 == "tolocationhashcode")
            $mLocationCode = strtoupper($v2);
        elseif ($k2 == "plt")
            $mPlt = strtoupper($v2);
        elseif ($k2 == "showmessage")
            $mShowMsg = strtoupper($v2);
        elseif (strtolower($k2) == "skip")
            $mSkip = strtolower($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }

// blank input parameters - ignore
    if (($mPartNumber == "") && ($mVendorPartCode == "") && ($mSerialReference == "") && ($mPlt == ""))
    {
        exit("OK  -getPart");
    }

    // mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Set default error message
    $mErrMsg = "FAIL-No Matching Records";

// Find Part Number from Serial Reference
    if (($mSerialReference != "") && ($mPartNumber == "") && ($mVendorPartCode == ""))
    {
        $mDataQuery = "SELECT
                inventory_master.id AS id,
                part.part_number AS part_number,
                location.location_code AS location_code,
                part.weight AS part_weight
            FROM inventory_master
                LEFT JOIN part ON inventory_master.part_id = part.id
                LEFT JOIN location ON inventory_master.current_location_id = location.id
            WHERE 
                inventory_master.serial_reference='{$mSerialReference}'
                AND inventory_master.inventory_qty > 0 
            LIMIT 2";

        $mData = mysqli_query($mConnection,$mDataQuery);
        if (mysqli_num_rows($mData) > 1)
        {
            // mysqli_close($mConnection);

            if ($mTransactionTypeId == "CTS")
            {
                exit( "DATA:partNumber:::skippartNumber");
            }
            elseif ($mSkip != "")
            {
                exit ("DATA:serialReference:".$mSerialReference."::".$mSkip.",partNumber::I");
            }   
            else
            {
                exit( "DATA:partNumber::I:skippartNumber");
            }
        }
        elseif (mysqli_num_rows($mData) == 1)
        {
            while($mRow = mysqli_fetch_assoc($mData)) 
            {
                $mPartNumber = ($mRow['part_number']);
                $mLocationCode = ($mRow['location_code']);
                $mPartWeight = ($mRow['part_weight']);
            }
        }
        elseif (mysqli_num_rows($mData) == 0)
        {
            if ($mPlt != "")
            {
                $mDataQuery = "SELECT
                        inventory_master.id AS id,
                        inventory_master.serial_reference AS serial_reference,
                        part.part_number AS part_number,
                        part.weight AS part_weight
                    FROM inventory_master
                        LEFT JOIN part ON inventory_master.part_id = part.id
                        LEFT JOIN location ON inventory_master.current_location_id = location.id
                        LEFT JOIN tag ON inventory_master.parent_tag_id = tag.id
                    WHERE 
                        inventory_master.tag_reference='{$mPlt}'
                        AND inventory_master.inventory_qty > 0 LIMIT 1";

                $mData = mysqli_query($mConnection,$mDataQuery);

    // No Inventory Check for decant
                if (mysqli_num_rows($mData) == 0)
                {
                    $mDataQuery = "SELECT
                            decant_body.id AS id,
                            part.part_number AS part_number,
                            '' AS location_code
                        FROM decant_body 
                            JOIN decant_header ON decant_body.decant_header_id = decant_header.id
                            JOIN part ON decant_header.part_id=part.id
                        WHERE decant_body.serial_reference='{$mSerialReference}'
                    LIMIT 1";

                    if (!mysqli_query($mConnection,$mDataQuery))
                        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);

                    $mData = mysqli_query($mConnection,$mDataQuery);
                }
            }
            if (mysqli_num_rows($mData) == 0)
            {
                $mErrMsg = "FAIL-Serial not found ".$mSerialReference;
//              mysqli_close($mConnection);
                exit($mErrMsg);
            }
            else
            {
                while($mRow = mysqli_fetch_assoc($mData)) 
                {
                    $mPartNumber = $mRow['part_number'];
                    $mLocationCode = $mRow['location_code'];
                    $mPartWeight = $mRow['part_weight'];
                }
            }
        }
    }

    if ($mPartNumber != "")
    {
        $mDataQuery = "SELECT
                part_number AS partNumber,
                rdt_prompt AS rdtMessage,
                requires_count AS countonrcpt,
                effective_from AS effective_from,
                effective_to AS effective_to,
                part.modular AS modular,
                part.weight AS part_weight
            FROM part
            WHERE (part_number='{$mPartNumber}')
            LIMIT 1";
    }

    if ($mVendorPartCode != "")
    {
        $mDataQuery = "SELECT
                part_number AS partNumber,
                rdt_prompt AS rdtMessage,
                requires_count AS countonrcpt,
                effective_from AS effective_from,
                effective_to AS effective_to,
                part.modular AS modular,
                part.weight AS part_weight
            FROM part
            WHERE 
                (jis_supply_group='{$mVendorPartCode}'
                OR vendor_part_code='{$mVendorPartCode}')
            LIMIT 1";
    }

    if (!mysqli_query($mConnection,$mDataQuery))
    {
        exit("FAIL-".mysqli_error($mConnection));
    }

    $mData = mysqli_query($mConnection,$mDataQuery);
    $i = 0;
    $mRdtMessage = "";
    $mCountOnRcpt = "";
    $mEffFrom = "";
    $mEffTo = "";

    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mPartNumber = ($mRow['partNumber']);
        $mRdtMessage=($mRow['rdtMessage']);
        $mCountOnRcpt=($mRow['countonrcpt']);
        $mEffFrom=($mRow['effective_from']);
        $mEffTo=($mRow['effective_to']);
        $mModular = ($mRow['modular']);
        $mPartWeight = ($mRow['part_weight']);
        $i++;
    }
//  mysqli_close($mConnection);
    $mDataStr = "";
    if ($i > 0)
    {
        $mStartDate = date("Y-m-d H:i:s");
        if (($mStartDate < $mEffFrom) || ($mStartDate > $mEffTo))
        {
            $mTransactionTypes = ['PBTP','PBTTP'];
            if (in_array($mTransactionTypeId,$mTransactionTypes))
//            if (($mTransactionTypeId == "PBTP") || ($mTransactionTypeId == "PBTM"))
            {
                $mRdtMessage .= " Warning - ".$mPartNumber." is not active today";
            }
            else
            {
                exit ("FAIL- ".$mPartNumber." is not active today");
            }
        }
// Test for modular part
        if (($mTransactionTypeId == "CTS") || ($mTransactionTypeId == "CTS"))
        {
            if ($mModular == 1)
            {
                exit ("FAIL-Modular Part - use PTS ");
            }
        }
    }
    if ($i > 0)
    {
        if ($mShowMsg != 'Y')
        {
            $mRdtMessage = '';
        }
        if ($mTransactionTypeId == 'JRBTP')
        {
            $mDataStr = "DATA-PartNumber:{$mPartNumber},quantity:1,partWeight:{$mPartWeight},rdtMessage:{$mRdtMessage},countonrcpt:{$mCountOnRcpt}";
        }
        elseif ($mTransactionTypeId == 'CTM')
        {
            $mDataStr = "DATA-PartNumber:{$mPartNumber},partWeight:{$mPartWeight},rdtMessage:{$mRdtMessage},countonrcpt:{$mCountOnRcpt}";
        }
        elseif ($mTransactionTypeId == 'CTS')
        {
            $mDataStr = "DATA-PartNumber:{$mPartNumber},partWeight:{$mPartWeight},rdtMessage:{$mRdtMessage},countonrcpt:{$mCountOnRcpt}";
        }
        elseif ($mLocationCode != '')
        {
            $mDataStr = "DATA-PartNumber:{$mPartNumber},partWeight:{$mPartWeight},rdtMessage:{$mRdtMessage},countonrcpt:{$mCountOnRcpt},toLocationHashCode:{$mLocationCode}";
        }
        else
        {
            $mDataStr = "DATA-PartNumber:{$mPartNumber},partWeight:{$mPartWeight},rdtMessage:{$mRdtMessage},countonrcpt:{$mCountOnRcpt}";
        }
        
        $mErrMsg = "";
//      exit($mDataStr);
        echo $mDataStr;
        return;
    }
    else
    {
        exit ("FAIL-Invalid Part Number");
    }
}

// Get Location Hash Code
elseif (($mFunction != null) && ($mFunction=="getlocationhashcode"))
{
    $mErrMsg = "";
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mLocation = "";
    
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "locationcode")
            $mLocation = strtoupper(trim($v2));
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    if (($mFromLocation != ""))
    {
        $mDataQuery = "SELECT location.location_hash AS hash_code FROM location WHERE location.location_code = '".$mLocation."' 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)) 
        {
            $mDataStr = ($mRow['hash_code']);
            $i++;
        }
        if ($i == 0)
        {
            $mErrMsg = "FAIL-Location is Incorrect";
        }
        else
        {
            $mErrMsg = "DATA:fromLocationHashCode:".$mDataStr;
        }
    }
}

// execute SQL command to test for existance of specified data - (eg. SELECT id FROM /dbase/.part WHERE part_number='/partNumber/') 
elseif (($mFunction != null) && ($mFunction == "getdata"))
{
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Set default error message
    $mErrMsg = "FAIL-No Matching Records";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "select")
            $mFilter = $v2;
        elseif ($k2 == "table")
            $mTableName = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }   
// Test for input override Error Message    
    $s = strpos($mFilter,"FAIL-");
    if ($s > 0)
    {
        $mErrMsg = substr($mFilter,$s);
        $mFilter = substr($mFilter,0,$s);
    }
// ; with ,
    $mFilter = str_replace(";",",",$mFilter);
// If Input table does not start with SELECT assume it's just a table name
    if (strtolower(substr($mTableName,0,6)) != "select")
        $mTableName = "SELECT * FROM ".$mTableName;
// Check for Filter / selection
    if (strtolower(substr($mFilter,0,5)) != "where")
        $mFilter = "WHERE ".$mFilter;
    $mDataQuery=$mTableName." ".$mFilter;
    $s = strpos(strtolower($mDataQuery),"limit");
    if ($mDataQuery = "")
    {
//      exit("FAIL-Unexpected Error");
        echo "FAIL-Unexpected Error";
        return;
    }
    if ($s == 0)
        $mDataQuery = $mDataQuery." LIMIT 1";
//  exit("FAIL-".$mDataQuery);
// mysql query construct
    $mData = mysqli_query($mConnection,$mDataQuery);
    $i = 0;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mSQLData[] =($mRow);
        $i++;
    }
//  mysqli_close($mConnection);
    $mDataStr = "";
    If ($i > 0)
    {
//      $mStatus = "OK  -"; 
        $mDataStr = json_encode($mSQLData);
        $mDataStr = str_replace("{","",$mDataStr);
        $mDataStr = str_replace("}","",$mDataStr);
        $mDataStr = str_replace("[","",$mDataStr);
        $mDataStr = str_replace("]","",$mDataStr);
        $mDataStr = str_replace('"',"",$mDataStr);
        $mDataStr = str_replace('_',"",$mDataStr);
        $mStatus = "DATA-";
        $mErrMsg = "";
    }
    else
    {
        $mStatus = $mErrMsg;
        $mDataStr = "";
    }
//  exit("FAIL-".$mDataStr);
}

// Qty Validation - format - value(condition)
elseif (($mFunction != null) && ($mFunction == "qty"))
{
    $mQty = "";
    $mFrom = "";
    $mTo = "";
    $mErrMsg = "OK  -";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "quantity")
            $mFilter = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
// Test for condition
    $e = strpos($mFilter,"(");
    if ($e > 0)
        $mQty = substr($mFilter,0,$e);
    else
        $mQty = $mFilter;
// Qty Range        
    $s = strpos($mFilter,"..");
    if ($s > 0)
    {
        $mFrom = substr($mFilter,$e+1,$s-($e+1));
        $e = strpos($mFilter,")");
        $mTo = substr($mFilter,$s+2,$e-($s+2));
        if (($mQty < $mFrom) || ($mQty > $mTo))
            $mErrMsg = "FAIL-Quantity Range Error";
    }
    $s = strpos($mFilter,"(NE");
    if ($s > 0)
    {
        $e = strpos($mFilter,")");
        $mTo = substr($mFilter,$s+3,$e-($s+3));
        if ($mQty == $mTo)
            $mErrMsg = "FAIL-Quantity Error";
    }
    $s = strpos($mFilter,"(EQ");
    if ($s > 0)
    {
        $e = strpos($mFilter,")");
        $mTo = substr($mFilter,$s+3,$e-($s+3));
        if ($mQty != $mTo)
            $mErrMsg = "FAIL-Quantity Error";
    }
    if ($mErrMsg == "OK  -")
    {
// Test for zero
        if ($mFilter == 0)
            $mErrMsg = "FAIL-zero quantity.";
    }
// Qty Validation - format - value(condition)
}

// validate scanned Qty against Counted Qty.
elseif (($mFunction != null) && ($mFunction == "countqty"))
{
    $mQty = "";
    $mCountQty = "";
    
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "qty")
            $mQty = trim(strtoupper($v2));
        elseif ($k2 == "countqty")
            $mCountQty = trim(strtoupper($v2));
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
    if(is_numeric($mQty))
    {
    }
    else
    {
        echo "FAIL-This must be a number only";
        return;
    }
    if(is_numeric($mCountQty))
    {
    }
    else
    {
        echo "FAIL-This must be a number only";
        return;
    }
// Test for matching qty.
    if ($mQty == $mCountQty)
        $mStatus = "OK  -checkcountqty";
    else
    {
        $mTxtValue = "Is this count correct?:YES:NO";
        $mTxtValue = str_replace(":","|COLON|",$mTxtValue);
        $mTxtValue = str_replace(",","|COMMA|",$mTxtValue);
        $mStatus = "OKCC-".$mTxtValue;
    }
    echo $mStatus;
    return;
}

// Get Virtual Pallet Id
elseif (($mFunction != null) && ($mFunction == "getplt"))
{

// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mPlt = "";
    $mPltSts = "";
    $mCustomerRef = "";
    $mReplenGroup = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "plt")
            $mPlt = strtoupper($v2);
        elseif ($k2 == "pltsts")
            $mPltSts = $v2;
        elseif ($k2 == "customerreference")
            $mCustomerRef = strtoupper($v2);
        elseif ($k2 == "replengroup")
            $mReplenGroup = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
        
// pick
    if ($mCustomerRef != "")
    {
        $mDataQuery = "SELECT order_header.id AS id FROM order_header JOIN pick_header ON order_header.pick_header_id=pick_header.id LEFT JOIN order_type ON order_header.order_type=order_type.order_type_code WHERE pick_header.document_reference='".$mCustomerRef."' LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection));
        $mData = mysqli_query($mConnection,$mDataQuery);
        if (mysqli_num_rows($mData) > 0)
        {
// Get Pallet Tag
            include_once ('transaction.php');
            $mDataStr = processPlt($mCustomerRef,$mVirtualPalletLbl,$mTransactionTypeId,$mPltSts,$mCurrentUser,$mHost,$mUser,$mPwd,$mDbName);
            if (substr($mDataStr,0,2) == "FA")
                $mStatus = $mDataStr;
            elseif ($mTransactionTypeId == "RBTC")
                $mStatus = "DATA:toPlt:".$mCustomerRef.":PPPPPPI:skip7";
            elseif ($mTransactionTypeId == "PBTP")
                $mStatus = "DATA:toPlt:".$mCustomerRef."::skiptoPlt";
            elseif ($mTransactionTypeId == "PBTTP")
                $mStatus = "DATA:toPlt:".$mCustomerRef."::skiptoPlt";
            else
                $mStatus = "DATA:toPlt:".$mCustomerRef;
            echo $mStatus;
            return;
        }
        echo "OK  -getPlt";
        return;
    }

// replen pick
    if ($mReplenGroup != "")
    {
        $mDataQuery = "SELECT pick_group.id AS id FROM pick_group WHERE pick_group.pick_group_code='".$mReplenGroup."' LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection));
        $mData = mysqli_query($mConnection,$mDataQuery);

        if (mysqli_num_rows($mData) > 0)
        {
// Get Pallet Tag
            include_once ('transaction.php');
            $mDataStr = processPlt($mReplenGroup,$mVirtualPalletLbl,$mTransactionTypeId,$mPltSts,$mCurrentUser,$mHost,$mUser,$mPwd,$mDbName);
            if (substr($mDataStr,0,2) == "FA")
                $mStatus = $mDataStr;
            elseif ($mTransactionTypeId == "JRBTP")
                $mStatus = "DATA:toPlt:".$mCustomerRef.":PPPPPPP:skip3";
            elseif ($mTransactionTypeId == "RBTC")
                $mStatus = "DATA:toPlt:".$mCustomerRef.":PPPPPPI:skip7";
            elseif ($mTransactionTypeId == "PBTP")
                $mStatus = "DATA:toPlt:".$mCustomerRef.":HHHPPPPIPP:skiptoPlt";
            elseif ($mTransactionTypeId == "PBTTP")
                $mStatus = "DATA:toPlt:".$mCustomerRef.":HHHPPPPIPP:skiptoPlt"; 
            else
                $mStatus = "DATA:toPlt:".$mCustomerRef.":PPPPPPP:skip3";
            echo $mStatus;
            return;
        }
        echo "OK  -getPlt";
        return;
    }
// Check Virtual Pallet Flag    
//  $mDataQuery = "SELECT company.virtual_pallet_lbl AS virtual_pallet_lbl FROM company JOIN user ON company.id=user.company_id WHERE user.username='".$mCurrentUser."' LIMIT 1";
    $mDataQuery = "SELECT company.virtual_pallet_lbl AS virtual_pallet_lbl FROM company LIMIT 1";

    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection));
    $mData = mysqli_query($mConnection,$mDataQuery);
    $i = mysqli_num_rows($mData);
    if ($i == 0)
    {
        $mDataQuery = "SELECT company.virtual_pallet_lbl AS virtual_pallet_lbl FROM company LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection));
        $mData = mysqli_query($mConnection,$mDataQuery);
    }
    $i = 0;
    $mVirtualPalletLbl = "";
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mVirtualPalletLbl = ($mRow['virtual_pallet_lbl']);
        $i++;
    }
//  mysqli_close($mConnection);
// Blank Pallet
    if (($mVirtualPalletLbl == "0") && ($mPlt == ""))
    {
        if ($mTransactionTypeId == "PBTP")
            echo "DATA:toPlt:::skiptoPlt";
        elseif ($mTransactionTypeId == "PBTTP")
            echo "DATA:toPlt:::skiptoPlt";
        else
            echo "FAIL-Invalid Pallet";
        return;
    }
// Get Pallet Tag
    include_once ('transaction.php');
    $mDataStr = processPlt($mPlt,$mVirtualPalletLbl,$mTransactionTypeId,$mPltSts,$mCurrentUser,$mHost,$mUser,$mPwd,$mDbName);
    if (substr($mDataStr,0,2) == "FA")
        $mStatus = $mDataStr;
    elseif ($mTransactionTypeId == "JRBTP")
        $mStatus = "DATA:toPlt:".$mDataStr.":PPPPPPP:skip3";
    elseif ($mTransactionTypeId == "RBTC")
        $mStatus = "DATA:toPlt:".$mDataStr.":PPPPPPI:skip7";    
    elseif ((substr($mTransactionTypeId,0,4) == "PBTP") && ($mDataStr != ""))
        $mStatus = "DATA:toPlt:".$mDataStr;
    elseif ((substr($mTransactionTypeId,0,4) == "PBTTP") && ($mDataStr != ""))
        $mStatus = "DATA:toPlt:".$mDataStr;
    else
        $mStatus = "DATA:toPlt:".$mDataStr.":PPPPPPP";

    echo $mStatus;
    return;
}

// Get Pallet from Serial Ref.
elseif (($mFunction != null) && ($mFunction == "getserialplt"))
{
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    $mErrMsg = "";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;

// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    $mPartNumber = "";
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "pltnumber")
            $mFilter = $v2;
        elseif (strtolower($k2) == "partnumber")
            $mPartNumber = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }
    $mPrefix = "";
// get plt from inventory_master
    if ($mTransactionTypeId == "PTS")
    {
        $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.part_id AS part_id, inventory_master.tag_reference AS plt_number, inventory_master.product_type_id AS product_type_id, inventory_master.pruf_cube AS pruf_cube, inventory_master.requires_inspection AS requires_inspection, part.part_number AS part_number,inventory_status.inventory_status_code AS inventory_status_code FROM inventory_master LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id JOIN part ON inventory_master.part_id=part.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE tag.tag_reference = '".$mFilter."' AND inventory_master.inventory_qty > 0 AND ((inventory_master.inventory_status_id IS null) or (lower(inventory_status.inventory_status_code) IN('ok','pck','rcv','pi','qa','qtine','noran'))) LIMIT 50";
    }
    else
    {
        $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.part_id AS part_id, inventory_master.tag_reference AS plt_number, inventory_master.product_type_id AS product_type_id, inventory_master.pruf_cube AS pruf_cube, inventory_master.requires_inspection AS requires_inspection, part.part_number AS part_number,inventory_status.inventory_status_code AS nventory_status_code FROM inventory_master LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id JOIN part ON inventory_master.part_id=part.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE inventory_master.tag_reference = '".$mFilter."' AND inventory_master.inventory_qty > 0 LIMIT 1";
    }
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
//  $mData = mysqli_query($mConnection,$mDataQuery);
//  exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
    $i = 0;
    $mInvId = "";
    $mInvPartId = "";
    $mInvPlt = "";
    $mInvPartNumber = "";
    $mProductType = "";
    $mPrufCube = "";
    $mReqInsp = "0";
    $mInvStsCode = "";
// Store details of 1st Serial on the Pallet - apart from Pruf-Cube flag.
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        if ($i == 0)
        {
            $mInvId = ($mRow['id']);
            $mInvPartId = ($mRow['part_id']);
            $mInvPlt = ($mRow['plt_number']);
            $mInvPartNumber = ($mRow['part_number']);
            $mProductType = ($mRow['product_type_id']);
            $mInvStsCode = $mRow['inventory_status_code'];
            $i++;
        }
        if ($mRow['pruf_cube'] == "1")
            $mPrufCube = "1";
        if ($mRow['requires_inspection'] == "1")
            $mReqInsp = "1";
    }
// If no Matching Pallet - Try Serial.
    if ($i == 0)
    {
        if ($mTransactionTypeId == "PTS")
        {
            if ($mPartNumber != "")
                $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.part_id AS part_id, inventory_master.tag_reference AS plt_number, inventory_master.product_type_id AS product_type_id, inventory_master.pruf_cube AS pruf_cube, inventory_master.requires_inspection AS requires_inspection
                , part.part_number AS part_number
                ,inventory_status.inventory_status_code AS inventory_status_code 
                FROM inventory_master 
                LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id 
                JOIN part ON inventory_master.part_id=part.id 
                LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id 
                WHERE inventory_master.serial_reference = '".$mFilter."'
                AND inventory_master.inventory_qty > 0 
                AND (part.part_number = '".$mPartNumber."') 
                AND (inventory_master.inventory_status_id IS null OR LOWER(inventory_status.inventory_status_code) in('ok','rcv','pi','qa','qtine','noran')) 
                LIMIT 1";
            else
                $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.part_id AS part_id, inventory_master.tag_reference AS plt_number, inventory_master.product_type_id AS product_type_id, inventory_master.pruf_cube AS pruf_cube, inventory_master.requires_inspection AS requires_inspection 
                ,part.part_number AS part_number
                ,inventory_status.inventory_status_code AS inventory_status_code 
                FROM inventory_master 
                LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id 
                JOIN part ON inventory_master.part_id=part.id 
                LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id 
                WHERE inventory_master.serial_reference = '".$mFilter."' 
                AND inventory_master.inventory_qty > 0 AND (inventory_master.inventory_status_id IS null OR LOWER(inventory_status.inventory_status_code) IN('ok','pkd','rcv','plt','pi','qa','qtine','noran')) 
                LIMIT 2";
        }
        else
        {
            if ($mPartNumber != "")
                $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.part_id AS part_id, inventory_master.tag_reference AS plt_number, inventory_master.product_type_id AS product_type_id, inventory_master.pruf_cube AS pruf_cube, inventory_master.requires_inspection AS requires_inspection
                , part.part_number AS part_number
                ,inventory_status.inventory_status_code AS inventory_status_code
                FROM inventory_master 
                LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id 
                JOIN part ON inventory_master.part_id=part.id
                LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id
                WHERE inventory_master.serial_reference = '".$mFilter."' 
                AND inventory_master.inventory_qty > 0 AND (part.part_number = '".$mPartNumber."' OR part.vendor_part_code='".$mPartNumber."') 
                LIMIT 1";
            else
                $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.part_id AS part_id, inventory_master.tag_reference AS plt_number, inventory_master.product_type_id AS product_type_id, inventory_master.pruf_cube AS pruf_cube, inventory_master.requires_inspection AS requires_inspection
                , part.part_number AS part_number 
                ,inventory_status.inventory_status_code AS inventory_status_code 
                FROM inventory_master 
                LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id 
                JOIN part ON inventory_master.part_id=part.id 
                LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id
                WHERE inventory_master.serial_reference = '".$mFilter."' 
                AND inventory_master.inventory_qty > 0 
                LIMIT 2";
        }
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
//      exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
//      $mData = mysqli_query($mConnection,$mDataQuery);
        $i = 0;
        $mInvId = "";
        $mInvPartId = "";
        $mInvPlt = "";
        $mInvPartNumber = "";
        $mProductType = "";
        $mPrufCube = "";
        $mReqInsp = "0";
        $mInvStsCode = "";
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mInvId = ($mRow['id']);
            $mInvPartId = ($mRow['part_id']);
            $mInvPlt = ($mRow['plt_number']);
            $mInvPartNumber = ($mRow['part_number']);
            $mProductType = ($mRow['product_type_id']);
            $mInvStsCode = $mRow['inventory_status_code'];
            if ($mRow['pruf_cube'] == "1")
                $mPrufCube = "1";
            if ($mRow['requires_inspection'] == "1")
                $mReqInsp = "1";
            $i++;
        }
    }
    if ($i > 1)
    {
        if ($mTransactionTypeId == "XPTM")
//          exit("DATA:partNumber::HHHHIHH");
            $mStatus = "DATA:partNumber::HHHHIHH"; 
        else
//          exit("DATA:partNumber::HI");
            $mStatus = "DATA:partNumber::HI";
        echo $mStatus;
        return;
    }
    if ($i == 0)
    {
//      exit("FAIL-Invalid Pallet or Serial");
        echo "FAIL-Invalid Pallet or Serial";
        return;
    }
    elseif ($mInvPlt == "")
    {
//      exit("FAIL-This Serial is not on a pallet");
        echo "FAIL-This Serial is not on a pallet";
        return;
    }
    if ($i == 1)
    {
// Read Pallet Contents
// validate Inventory Status
        if ($mTransactionTypeId == "PTS")
        {
//          $mDataQuery = "SELECT inventory_master.id AS id FROM inventory_master JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE inventory_master.plt_number='".$mInvPlt."' AND LOWER(inventory_status.inventory_status_code) NOT IN('ok','noran') LIMIT 1";
            $mDataQuery = "SELECT inventory_master.id AS id 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 inventory_master.tag_reference='".$mInvPlt."' AND ((inventory_master.inventory_status_id IS NOT null) AND (LOWER(inventory_status.inventory_status_code) NOT IN('ok','rcv','pck','pi','noran'))) LIMIT 1";
            if (!mysqli_query($mConnection,$mDataQuery))
                exit("FAIL-".mysqli_error($mConnection));
            $mData = mysqli_query($mConnection,$mDataQuery);
            $i = 0;
            while($mRow = mysqli_fetch_assoc($mData)) 
            {
                $i++;
            }
            if ($i > 0)
            {
//              exit("FAIL-Incorrect Inventory Status on Pallet");
                echo "FAIL-Incorrect Inventory Status on Pallet";
                return;
            }
        }
//      $mDataQuery = "SELECT inventory_master.part_id AS part_id, inventory_master.product_type_id AS product_type_id, inventory_master.pruf_cube AS pruf_cube, inventory_master.requires_inspection AS requires_inspection, part.fixed_location_type_id AS location_type_id, part.fixed_sub_type_id AS zone_type_id FROM inventory_master JOIN part ON inventory_master.part_id=part.id JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE tag.tag_reference = '".$mInvPlt."' LIMIT 50";
        $mDataQuery = "SELECT inventory_master.part_id AS part_id, inventory_master.product_type_id AS product_type_id, inventory_master.pruf_cube AS pruf_cube, inventory_master.requires_inspection AS requires_inspection, inventory_master.requires_decant AS requires_decant
        ,part.fixed_location_type_id AS location_type_id, part.fixed_sub_type_id AS zone_type_id
        , inventory_status.inventory_status_code AS inventory_status_code 
        FROM inventory_master 
        JOIN part ON inventory_master.part_id=part.id 
        LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id 
        JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id 
        WHERE inventory_master.tag_reference = '".$mInvPlt."' 
        LIMIT 50";
        if (!mysqli_query($mConnection,$mDataQuery))
        {
            exit("FAIL-".mysqli_error($mConnection).":".$mDataQuery);
        }
        $mData = mysqli_query($mConnection,$mDataQuery);
        $mInvPartId = "";
        $mLocationType = "";
        $mZoneType = "";
        $mProductType = "";
        $mMultiPart = "";
        $mPrufCube = "";
        $mReqInsp = "0";
        $mReqDecant = "";
        $mInvStatusCode = "";
        $mReqQr = "0";
        $i = 0;
        while(($mRow = mysqli_fetch_assoc($mData)) && ($mMultiPart == ""))
        {
            if ($i == 0)
            {
                $mInvPartId = ($mRow['part_id']);
                $mLocationType = ($mRow['location_type_id']);
                $mZoneType = ($mRow['zone_type_id']);
                $mProductType = ($mRow['product_type_id']);
                $mInvStatusCode = $mRow['inventory_status_code'];
            }
            else
            {
                if ($mInvPartId != ($mRow['part_id']))
                    $mMultiPart = "1";
            }
            if ($mRow['pruf_cube'] == "1")
                $mPrufCube = "1";
            if ($mRow['requires_inspection'] == "1")
                $mReqInsp = "1";
            if ($mRow['requires_decant'] == "1")
                $mReqDecant = "1";
            if (strtolower($mRow['inventory_status_code']) == "qtine")
                $mReqQr = "1";
            $i++;
        }
        if ($mReqQr == "1")
        {
            if (strlen($mReqInsp)>0)
                $mReqInsp .= "1";
            else
                $mReqInsp = "01";
//            exit("FAIL-TEST1-".$mReqInsp);
        }
        if ($i == 0)
        {
//          exit("FAIL-Incorrect Pallet");
            echo "FAIL-Incorrect Pallet";
            return;
        }
        if ($mTransactionTypeId == "PTS")
        {
            if ($mProductType != "")
//              $mDataQuery = "SELECT inventory_master.id AS id FROM inventory_master JOIN part ON inventory_master.part_id=part.id JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE tag.tag_reference='".$mInvPlt."' AND (part.fixed_location_type_id<>".$mLocationType." OR part.fixed_sub_type_id<>".$mZoneType." OR inventory_master.product_type_id<>".$mProductType.") LIMIT 1";
                $mDataQuery = "SELECT inventory_master.id AS id FROM inventory_master JOIN part ON inventory_master.part_id=part.id LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE inventory_master.tag_reference='".$mInvPlt."' AND (part.fixed_location_type_id<>".$mLocationType." OR part.fixed_sub_type_id<>".$mZoneType.") LIMIT 1";
            else
                $mDataQuery = "SELECT inventory_master.id AS id FROM inventory_master JOIN part ON inventory_master.part_id=part.id LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE inventory_master.tag_reference='".$mInvPlt."' AND (part.fixed_location_type_id<>".$mLocationType." OR part.fixed_sub_type_id<>".$mZoneType.") 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))
            {
                $i++;
            }
            if ($i > 0)
            {
//              exit("FACS-Mixed Location / Product Types on Pallet");
                echo "FACS-Mixed Location / Product Types on Pallet";
                return;
            }
        }
    }
//  mysqli_close($mConnection);
    if ($mErrMsg == "")
    {
        $mRtn = $mInvPlt;
        if ($mReqDecant == "1")
            $mReqInsp = "2";
        if ($mReqQr =="1")
        {
            if (strlen($mReqInsp)>0)
                $mReqInsp .= "1";
            else
                $mReqInsp = "01";
//            exit("FAIL-TEST1-".$mReqInsp);
        }
        if ($mTransactionTypeId == "PTS")
        {       
            include_once ('location.php');
            $mConnectp = str_replace(":8081/vantec",":8083/putaway",$mConnect);
            if ($mConnectp == $mConnect)
            {
                $e = strpos($mConnect,":8081");
                $mConnectp = substr($mConnect,0,$e).":8083/putaway/";
            }
            $mLocation = getNextLocation($mInvPartId,$mProductType,$mMultiPart,"PLT",$mPrufCube,$mReqInsp,$mHost,$mUser,$mPwd,$mDbName,$mTransactionTypeId,'');
            if ($mLocation != "")
            {
                $mStatus = "DATA:pltNumber:".$mRtn.":IP".",partNumber:".$mInvPartNumber.":HH,toLocationHashCode:".$mLocation.":**"; 
                $mDataStr = "DATA:pltNumber:".$mRtn.":IP".",partNumber:".$mInvPartNumber.":HH,toLocationHashCode:".$mLocation.":**";
            }
            else
            {
                $mStatus = "DATA:pltNumber:".$mRtn.":IP".",partNumber:".$mInvPartNumber.":HH";  
                $mDataStr = "DATA:pltNumber:".$mRtn.":IP".",partNumber:".$mInvPartNumber.":HH";
            }
        }
        elseif ($mTransactionTypeId == "PTM")
        {
            $mStatus = "DATA:plt:".$mRtn.":IPP".",partNumber:".$mInvPartNumber.":HHH";  
            $mDataStr = "DATA:plt:".$mRtn.":IPP".",partNumber:".$mInvPartNumber.":HHH";
        }
        elseif ($mTransactionTypeId == "XPTM")
        {
            $mStatus = "DATA:plt:".$mRtn.",partNumber:".$mInvPartNumber.":HHHHHHH"; 
            $mDataStr = "DATA:plt:".$mRtn.",partNumber:".$mInvPartNumber.":HHHHHHH";
        }
        else
        {
            $mStatus = "DATA:pltNumber:".$mRtn.":IP".",partNumber:".$mInvPartNumber.":HH";  
            $mDataStr = "DATA:pltNumber:".$mRtn.":IP".",partNumber:".$mInvPartNumber.":HH";
        }
//      exit($mDataStr);

        if (substr($mLocation,0,2)=="FA")
            exit($mLocation);
        
        echo $mDataStr;
        return;
    }
//  exit("OK  -");
    echo "OK  -";
    return;
}

// check for duplicate Inventory Serials
elseif (($mFunction != null) && ($mFunction == "inventoryserial"))
{
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    $mErrMsg = "";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mPartNumber = "";
    $mReference = "";
    $mVldSerialReference = null;
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "serialreference")
            $mSerialReference = $v2;
        elseif (strtolower($k2) == "vldserialreference")
            $mVldSerialReference = $v2;
        elseif (strtolower($k2) == "partnumber")
            $mPartNumber = $v2;
        elseif (strtolower($k2) == "reference")
            $mReference = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }

// validate serial against prompted serial
    if (!empty($mVldSerialReference) && strtoupper($mVldSerialReference) != strtoupper($mSerialReference))
        exit ("FAIL-Incorrect Serial");
        
// Get id for inventory status
    $mInvStsId = 0;
    $mInvRcvId = 0;
    $mInvPkdId = 0;
    $mInvPltId = 0;
    $mInvMisId = 0;
    $mInvOvrId = 0;
    $mInvRanId = 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']) == "pkd")
            $mInvPkdId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "plt")
            $mInvPltId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "missing")
            $mInvMisId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "overbooking")
            $mInvOvrId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "noran")
            $mInvRanId = ($mRow['id']);
    }
    if ($mInvPkdId == null && $mInvPltId != null)
        $mInvPkdId = $mInvPltId;
    
    $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.part_id AS part_id, inventory_master.product_type_id AS product_type_id, inventory_master.pruf_cube AS pruf_cube, inventory_master.requires_inspection AS requires_inspection, inventory_master.requires_decant AS requires_decant";
        $mDataQuery .=",part.part_number AS part_number";
        $mDataQuery .=",location.location_type_id AS location_type";
        $mDataQuery .=",location_type.location_area AS location_area, location_type.location_type_code AS location_type_code";
        $mDataQuery .=",inventory_status.inventory_status_code AS inventory_status_code";
        $mDataQuery .= " FROM inventory_master JOIN part ON inventory_master.part_id=part.id";
        $mDataQuery .=" JOIN location ON inventory_master.current_location_id=location.id";
        $mDataQuery .=" LEFT JOIN location_type ON location.location_type_id=location_type.id";
        $mDataQuery .=" LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id";
    $mDataQuery .=" WHERE inventory_master.serial_reference = '".$mSerialReference."' AND inventory_master.inventory_qty > 0";
    if ($mTransactionTypeId == "CTS")
        $mDataQuery .= " AND inventory_master.inventory_status_id NOT IN(".$mInvRcvId.",".$mInvRcvId.")";
    if ($mPartNumber != "")
        $mDataQuery .= " AND (inventory_master.part_number='".$mPartNumber."') LIMIT 1";
    else
        $mDataQuery .= " LIMIT 2";
    if(!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    $mData = mysqli_query($mConnection,$mDataQuery);
//  exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
    $i = mysqli_num_rows($mData);
    if ($i == 0)
    {
        echo "FAIL-No available inventory for Serial";
        return;
    }
    if (($mTransactionTypeId == "CTS") || ($mTransactionTypeId == "AFTP"))
    {
        $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.part_id AS part_id, inventory_master.product_type_id AS product_type_id, inventory_master.pruf_cube AS pruf_cube, inventory_master.requires_inspection AS requires_inspection, inventory_master.requires_decant AS requires_decant";
        $mDataQuery .=",part.part_number AS part_number";
        $mDataQuery .=",location.location_type_id AS location_type";
        $mDataQuery .=",location_type.location_area AS location_area, location_type.location_type_code AS location_type_code";
        $mDataQuery .=",inventory_status.inventory_status_code AS inventory_status_code";
        $mDataQuery .= " FROM inventory_master JOIN part ON inventory_master.part_id=part.id";
        $mDataQuery .=" JOIN location ON inventory_master.current_location_id=location.id";
        $mDataQuery .=" LEFT JOIN location_type ON location.location_type_id=location_type.id";
        $mDataQuery .=" LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id";
        $mDataQuery .=" WHERE inventory_master.serial_reference = '".$mSerialReference."' AND inventory_master.inventory_qty > 0 AND (inventory_master.inventory_status_id IS null OR lower(inventory_status.inventory_status_code) in('ok','rcv','qa','qtine','noran','overbooking'))";
        if ($mPartNumber != "")
            $mDataQuery .= " AND (part.part_number='".$mPartNumber."') LIMIT 1";
        else
            $mDataQuery .= " LIMIT 2";
        if(!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $mData = mysqli_query($mConnection,$mDataQuery);
        $i = mysqli_num_rows($mData);
        if ($i == 0)
        {
            echo "FAIL-This Serial is not available";
            return;
        }
    }
    elseif ($mTransactionTypeId == "FQA")
    {
        $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.part_id AS part_id, inventory_master.product_type_id AS product_type_id, inventory_master.pruf_cube AS pruf_cube, inventory_master.requires_inspection AS requires_inspection, inventory_master.requires_decant AS requires_decant";
        $mDataQuery .=",part.part_number AS part_number";
        $mDataQuery .=",location.location_type_id AS location_type";
        $mDataQuery .=",location_type.location_area AS location_area, location_type.location_type_code AS location_type_code";
        $mDataQuery .=",inventory_status.inventory_status_code AS inventory_status_code";
        $mDataQuery .= " FROM inventory_master JOIN part ON inventory_master.part_id=part.id";
        $mDataQuery .=" JOIN location ON inventory_master.current_location_id=location.id";
        $mDataQuery .=" LEFT JOIN location_type ON location.location_type_id=location_type.id";
        $mDataQuery .=" LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id";
        $mDataQuery .=" WHERE inventory_master.serial_reference = '".$mSerialReference."' AND inventory_master.inventory_qty > 0";
//      $mDataQuery .=" AND (inventory_master.inventory_status_id IS null OR lower(inventory_status.inventory_status_code) in('ok','qa','qtine','noran'))";

        if ($mPartNumber != "")
            $mDataQuery .= " AND (part.part_number='".$mPartNumber."') LIMIT 1";
        else
            $mDataQuery .= " LIMIT 2";
        if(!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $mData = mysqli_query($mConnection,$mDataQuery);
        $i = mysqli_num_rows($mData);
        if ($i == 0)
        {
            echo "FAIL-This QA Serial is not available";
            return;
        }
    }
    if ($i == 1)
    {
        $i = 0;
        $mInvId = "";
        $mInvPartId = "";
        $mInvPart = "";
        $mProductType = "";
        $mPrufCube = "";
        $mReqInsp = "0";
        $mReqDecant = "0";
        $mLocArea = "";
        $mLocTypeCode = "";
        $mInvStsCode = "";

        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mInvId = ($mRow['id']);
            $mInvPart = ($mRow['part_number']);
            $mInvPartId = ($mRow['part_id']);
            $mPartNumber = ($mRow['part_number']);
            $mProductType = ($mRow['product_type_id']);
            $mLocArea = ($mRow['location_area']);
            $mLocTypeCode = ($mRow['location_type_code']);
            $mInvStsCode = ($mRow['inventory_status_code']);
            if (($mRow['pruf_cube']) == "1")
                $mPrufCube = "1";
            if (($mRow['requires_inspection']) == "1")
                $mReqInsp = "1";
            if (($mRow['requires_decant']) == "1")
                $mReqDecant = "1";
            $i++;
        }

        $mPartWeight = getPartNumberWeight($mPartNumber, $mConnection);

// FQA - Ignore 'requires inspection'
        if ($mTransactionTypeId == "FQA")
            $mReqInsp = "0";
// TQA - Force 'requires inspection'
        if ($mTransactionTypeId == "TQA")
        {
// From Location cannot be work
            if (strtolower($mLocArea) == "work")
            {
                echo "FAIL-Invalid Location Type ".$mLocArea;
                return;
            }
            else
                $mReqInsp = "1";
        }
// CTM - Location Type Validation
        if ($mTransactionTypeId == "CTM")
        {
// From Location cannot be work
//          if (strtolower($mLocArea) == "work")
            if (strtolower($mLocTypeCode) == "rcv")
            {
                echo "FAIL-Box on receiving – use CTS";
                return;
            }
            if (strtolower($mLocTypeCode) == "qtine")
            {
                echo "FAIL-Box in inspection – use FQA";
                return;
            }
            if (strtolower($mLocTypeCode) == "qa")
            {
                echo "FAIL-Box in inspection – use FQA";
                return;
            }
        }
        if ($mTransactionTypeId == "CTL" || $mTransactionTypeId == "CTS")
        {
            if (strtolower($mLocTypeCode) == "qa")
            {
                echo "FAIL-Box in inspection – use FQA";
                return;
            }
        }
//  exit("FAIL-Test".$mPrufCube."-".($mRow['pruf_cube'])."-".$i);
//      mysqli_close($mConnection);
    }
// No serial found
    if ($i == 0)
    {
        $mErrMsg = "FAIL-Invalid Serial scanned";   
    }
// single serial - return Part Number & putaway location
    elseif ($i == 1)
    {
// If decant Serial - set inspection flag
        if ($mReqDecant == "1")
            $mReqInsp = "2";
// If Inventory_status = 'qtine' add to inspection flag
        if (strtolower($mInvStsCode)=="qtine")
        {
            if (strlen($mReqInsp)>0)
                $mReqInsp .= "1";
            else
                $mReqInsp = "01";
//            exit("FAIL-TEST11-".$mReqInsp);
        }
        $mRtn = $mInvPart;
        if (($mTransactionTypeId != "CTM") && ($mTransactionTypeId != "STKMV") && ($mTransactionTypeId != "FQA"))
        {
            include_once ('location.php');
            $mLocation = getNextLocation($mInvPartId,$mProductType,"","",$mPrufCube,$mReqInsp,$mHost,$mUser,$mPwd,$mDbName,$mTransactionTypeId);
        }
        if ($mTransactionTypeId == "CTM")
        {   
            $mDataStr = "DATA:partNumber:{$mRtn}:PP,partWeight:{$mPartWeight}:PP,toLocationHashCode::*";
        }
        elseif ($mTransactionTypeId == "TQA")
        {
/*
            if ($mReference == "")
            {
                $mDataStr = "DATA:partNumber:".$mPartNumber.":PP,reference::PI,toLocationHashCode:".$mLocation.":PP:skip2";
            }
            else
            {
                $mDataStr = "DATA:partNumber:".$mPartNumber.":PP,reference:".$mReference.":PP,toLocationHashCode:".$mLocation.":P*:skip2";
            }     
*/
            if ($mSerialReference == "")
            {
                $mDataStr = "DATA:partNumber:{$mPartNumber}:PP,serialReference::PI,toLocationHashCode:{$mLocation}:PP,partWeight:{$mPartWeight}:PP:skip2";
            }
            else
            {
                $mDataStr = "DATA:partNumber:{$mPartNumber}:PP,serialReference:{$mSerialReference}:PP,partWeight:{$mPartWeight}:PP,toLocationHashCode:{$mLocation}:P*:skip2";
            }
        }
        elseif ($mLocation == "No Available Locations")
        {   
            $mDataStr = "DATA:partNumber:{$mRtn},partWeight:{$mPartWeight},toLocationHashCode::*";
        }
        elseif ($mLocation == "FAIL-No Available Locations")
        {
            $mLocSubStr = substr($mLocation,5);
            $mDataStr = "DATA:partNumber:{$mRtn},partWeight:{$mPartWeight},toLocationHashCode:{$mLocSubStr}:*";
        }
        elseif ($mLocation != "")
        {   
            $mDataStr = "DATA:partNumber:{$mRtn},partWeight:{$mPartWeight},toLocationHashCode:{$mLocation}";
        }
        elseif ($mTransactionTypeId == "STKMV")
        {
            $mDataStr = "DATA:partNumber:{$mRtn},partWeight:{$mPartWeight}";
        }
        else
        {
            $mDataStr = "DATA:partNumber:{$mRtn},partWeight:{$mPartWeight}";
        }
    }
// multiple Serials - Prompt for Part Number Entry
    elseif ($i > 1)
    {
        $mRtn = "";
        if ($mTransactionTypeId == "TQA")
        {   
            $mDataStr = "DATA:partNumber::PI:skippartNumber";
        }
        elseif ($mTransactionTypeId == "STKMV")
        {   
            $mDataStr = "DATA:serialReference:".$mSerialReference."::skippartNumber,partNumber::I";
        }
        else
        {   
            $mDataStr = "DATA:partNumber:::skippartNumber";
        }
    }
    else
    {
        $mErrMsg = "FAIL-Invalid Serial ";  
//      $mErrMsg = "FAIL-Invalid Serial ".$mDataQuery."-".mysqli_num_rows($mData);  
        $mStatus = $mErrMsg;
        $mDataStr = $mErrMsg;
    }
//  exit($mDataStr);

//  if (substr($mLocation,0,4)=="FAIL")
//          exit("FAIL-".substr($mLocation,-500));

    echo $mDataStr;
    return;
}

// Confirm Haulier Receipt Complete
elseif (($mFunction != null) && (strtolower($mFunction) == "completereceipt"))
{
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mHaulierReference = "";
    $mCustomerReference = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "haulierreference")
            $mHaulierReference = $v2;
        elseif (strtolower($k2) == "customerreference")
            $mCustomerReference = $v2;    
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    $mErrMsg = "FAIL-No Matching Haulierer";
    if ($mHaulierReference != "")
        $mDataQuery = "SELECT id AS id,document_reference AS document_reference FROM receipt_header WHERE upper(haulier_reference)='".$mHaulierReference."'";
    else
        $mDataQuery = "SELECT id AS id,document_reference AS document_reference FROM receipt_header WHERE upper(customer_reference)='".$mCustomerReference."'";
    $mData = mysqli_query($mConnection,$mDataQuery);
    $i = 0;
    $mDocId = "";
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mDocId = ($mRow['id']);
        $mRctDocRef = ($mRow['document_reference']);
        $i++;
    }
    if ($i == 0)
    {
        $mErrMsg = "FAIL-No Matching Receipt Reference";
    }
    else
    {
// Get Document status code for open
        $mDataQuery = "SELECT id FROM document_status WHERE lower(document_status_code)='open' LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $mDocOpnId = null;
        $mRow = mysqli_fetch_assoc($mData);
        $mDocOpnId = ($mRow['id']);
// Get Document status code for complete
        $mDataQuery = "SELECT id FROM document_status WHERE lower(document_status_code)='complete' LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $mData = mysqli_query($mConnection,$mDataQuery);
        $mDocClsId = null;
        $mRow = mysqli_fetch_assoc($mData);
        $mDocClsId = ($mRow['id']);
        if ($mHaulierReference != "")
            $mDataQuery = "UPDATE receipt_header SET receipt_header.document_status_id=".$mDocClsId.",receipt_header.last_updated_date=now(), receipt_header.last_updated_by='".$mCurrentUser."' WHERE receipt_header.haulier_reference = '".$mHaulierReference."' AND receipt_header.document_status_id=".$mDocOpnId;
        else
            $mDataQuery = "UPDATE receipt_header SET receipt_header.document_status_id=".$mDocClsId.",receipt_header.last_updated_date=now(), receipt_header.last_updated_by='".$mCurrentUser."' WHERE receipt_header.customer_reference = '".$mCustomerReference."' AND receipt_header.document_status_id=".$mDocOpnId;
        if(!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $mErrMsg = "OKMS- Receipt Complete";
    }
    
    if ($mDocId != "")
    {
// Close receipt_body 
        $mDataQuery = "SELECT receipt_body.id AS id FROM receipt_body WHERE receipt_body.receipt_header_id=".$mDocId;
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mBdyId = $mRow['id'];
            
            $mUpdQuery = "UPDATE receipt_body SET document_status_id=".$mDocClsId.",receipt_body.last_updated_date=now(), receipt_body.last_updated_by='".$mCurrentUser."' WHERE id=".$mBdyId." LIMIT 1";
            if (!mysqli_query($mConnection,$mUpdQuery))
                exit ("FAIL-".mysqli_error($mConnection)."-".$mUpdQuery);
// Flag inventory_master & receipt_detail
            $mDtlQuery = "SELECT receipt_detail.id AS id FROM receipt_detail WHERE receipt_detail.receipt_body_id=".$mBdyId;
            if (!$mDtlData = mysqli_query($mConnection,$mDtlQuery))
                exit ("FAIL-".mysqli_error($mConnection)."-".$mDtlQuery);
            while($mDtlRow = mysqli_fetch_assoc($mDtlData)) 
            {
                $mDtlId = $mDtlRow['id'];
                $mUpdQuery = "UPDATE receipt_detail SET document_status_id=".$mDocClsId.",receipt_detail.last_updated_date=now(), receipt_detail.last_updated_by='".$mCurrentUser."' WHERE id=".$mDtlId." LIMIT 1";
                if (!mysqli_query($mConnection,$mUpdQuery))
                    exit ("FAIL-".mysqli_error($mConnection)."-".$mUpdQuery);
            }
        }
// Check if Receipt is fully received.
        $mDataQuery = "SELECT receipt_header.id AS id,receipt_header.document_reference AS document_reference FROM receipt_header JOIN receipt_body ON receipt_body.receipt_header_id=receipt_header.id WHERE receipt_header.id=".$mDocId." AND ((receipt_body.received_qty<>receipt_body.advised_qty OR receipt_body.advised_qty=0)) LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit ("FAIL-".mysqli_error($mConnection).$mDataQuery);
        if (mysqli_num_rows($mData) == 0)
        {
// Send IDOC Trigger for Confirm Receipt
//          http://van-kuk-test:8093/vantec/writeCompleteReceiptMessage Input - {"documentReference":"RCP000001","userId":"admin"}
// Get Server Data from URL
            $mJsonArray = array();
            $mJsonArray['documentReference'] = $mRctDocRef;
            $mJsonArray['userId'] = $mCurrentUser;
// 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",":8093/vantec",$mConnect);
            if ($mConnectp == $mConnect)
            {
                $e = strpos($mConnect,":8081");
                $mConnectp = substr($mConnect,0,$e).":8093/vantec/";
            }
            $ch = curl_init();
            try
            {
                curl_setopt($ch, CURLOPT_URL, $mConnectp."writeCompleteReceiptMessage?documentReference=".$mRctDocRef."&userId=".$mCurrentUser);
                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);
            }
        }
    }    
    
//  mysqli_close($mConnection);
    if ($mErrMsg == "")
        $mErrMsg = "OK  -completereceipt";
    echo $mErrMsg;
    return;
}

// Confirm Haulier Receipt Complete
elseif (($mFunction != null) && (strtolower($mFunction) == "closereceipt"))
{
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mHaulierReference = "";
    $mCustomerReference = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        if (strtolower($k2) == "haulierreference")
            $mHaulierReference = $v2;
        elseif (strtolower($k2) == "customerreference")
            $mCustomerReference = $v2;    
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
    
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    $mErrMsg = "FAIL-No Matching Haulierer";
// Get Document status code for complete
        $mDataQuery = "SELECT id FROM document_status WHERE lower(document_status_code)='closed' LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $mData = mysqli_query($mConnection,$mDataQuery);
        $mDocClsId = null;
        $mRow = mysqli_fetch_assoc($mData);
        $mDocClsId = ($mRow['id']);
// Get Inventory status code for ok
        $mDataQuery = "SELECT id FROM inventory_status WHERE lower(inventory_status_code)='ok' LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $mData = mysqli_query($mConnection,$mDataQuery);
        $mInvStsId = null;
        $mRow = mysqli_fetch_assoc($mData);
        $mInvStsId = ($mRow['id']);

    if ($mHaulierReference != "")
        $mDataQuery = "SELECT id AS id,document_reference AS document_reference,product_type_id AS product_type_id FROM receipt_header WHERE upper(haulier_reference)='".$mHaulierReference."' ORDER BY haulier_reference, product_type_id DESC, document_reference";
    else
        $mDataQuery = "SELECT id AS id,document_reference AS document_reference,product_type_id AS product_type_id FROM receipt_header WHERE upper(customer_reference)='".$mCustomerReference."' ORDER BY customer_reference, product_type_id DESC, document_reference";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection));
    $mData = mysqli_query($mConnection,$mDataQuery);
    $i = 0;
    $mDocId = "";
    $mDocumentReference = array();
    $mProductType = array();
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mDocId = ($mRow['id']);
        $mDocumentReference[$i] = ($mRow['document_reference']);
        $mProductType[$i] = ($mRow['product_type_id']);
        $i++;
    }
    if ($i == 0)
    {
        $mErrMsg = "FAIL-No Matching Receipt Reference";
//      exit($mErrMsg);
        echo $mErrMsg;
        return;
    }
    else
    {
// Test for Scan Data
        if ($mHaulierReference != "")
            $mDataQuery = "SELECT id FROM scan_data WHERE upper(haulier_reference)='".$mHaulierReference."' LIMIT 1";
        else
            $mDataQuery = "SELECT id FROM scan_data WHERE upper(customer_reference)='".$mCustomerReference."' LIMIT 1";
        if(!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection).":".$mDataQuery);
        $mData = mysqli_query($mConnection,$mDataQuery);
        if (mysqli_num_rows($mData) > 0)
        {
//          exit("FAIL-This Receipt is not Counted");
            echo "FAIL-This Receipt is not Counted";
            return;
        }
        else
        {
            if ($mHaulierReference != "")
                $mDataQuery = "UPDATE receipt_header SET receipt_header.document_status_id=(SELECT id FROM document_status WHERE lower(document_status.document_status_code)='closed'),receipt_header.last_updated_date=now(), receipt_header.last_updated_by='".$mCurrentUser."' WHERE upper(receipt_header.haulier_reference) = '".$mHaulierReference."'";
            else
                $mDataQuery = "UPDATE receipt_header SET receipt_header.document_status_id=(SELECT id FROM document_status WHERE lower(document_status.document_status_code)='closed'),receipt_header.last_updated_date=now(), receipt_header.last_updated_by='".$mCurrentUser."' WHERE upper(receipt_header.customer_reference) = '".$mCustomerReference."'";
            if(!mysqli_query($mConnection,$mDataQuery))
                exit("FAIL-".mysqli_error($mConnection).":".$mDataQuery);
            $mErrMsg = "";
        }
    }
    if ($errMsg == "")
    {
// Test for Customer Interface
        for ($i=0;$i<count($mDocumentReference);++$i)
        {
            $mDataQuery = "SELECT receipt_detail.part_id AS part_id, receipt_detail.serial_reference AS serial_reference FROM receipt_detail JOIN inventory_master ON receipt_detail.part_id=inventory_master.part_id AND receipt_detail.serial_reference=inventory_master.serial_reference LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE upper(receipt_detail.document_reference) = '".$mDocumentReference[$i]."' AND lower(inventory_status.inventory_status_code)='rcv'";
            if (!mysqli_query($mConnection,$mDataQuery))
                exit("FAIL-".mysqli_error($mConnection));
            $mData = mysqli_query($mConnection,$mDataQuery);
            while($mRow = mysqli_fetch_assoc($mData)) 
            {
                $mPartId = ($mRow['part_id']);
                $mSerialReference = ($mRow['serial_reference']);
                $mInvQuery = "UPDATE inventory_master SET inventory_master.inventory_status_id=".$mInvStsId.",inventory_master.inventory_status_id=".$mInvStsId.",inventory_master.last_updated=now(), inventory_master.last_updated_by='".$mCurrentUser."' WHERE inventory_master.part_id = ".$mPartId." AND inventory_master.serial_reference='".$mSerialReference."' AND EXISTS(SELECT id FROM inventory_status WHERE inventory_master.inventory_status_id=inventory_status.id AND lower(inventory_status.inventory_status_code)='rcv') LIMIT 1";
                if(!mysqli_query($mConnection,$mInvQuery))
                exit("FAIL-".mysqli_error($mConnection).":".$mDataQuery);
            }
// Server Call to Update TT-RAN - http://172.16.1.70:8081/vantec/closeReceipt
//                "documentReference" : "RCP000005",
//                "userId"  :"TA"

            try
            {
                $mFilter = "documentReference=".$mDocumentReference[$i]."&userId=".$mCurrentUser;
                $mJsonStr = '{"documentReference":"'.$mDocumentReference[$i].'","userId":"'.$mCurrentUser.'"}';
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $mConnect."closeReceipt");
                curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $mJsonStr);
                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 - TT.RAN".$mResult.":".$mResponse.":".$mErrors);
                else
                {
//                  print_r("FAIL-Message Code=".$mJsonObject.":".$mResult.":".$mResponse.":".$mErrors);
                }
            }
            catch(Exception $e)
            {
                $mErrMsg = "FAIL-Unexpected System Error - TT.RAN -".$e;
            }
// Generate Interface Message
            if ($mProductType[$i] == 2)
            {
                require_once "../reports/receiptinterfaceout.php";
                mainProcessRan($mHost, $mUser, $mPwd, $mDbName,$mDocumentReference[$i],"M");
            }
            if ($mProductType[$i] == 1)
            {
                require_once "../reports/receiptinterfaceout.php";
//              mainProcessPdf($mHost, $mUser, $mPwd, $mDbName,$mDocumentReference[$i],"M");
                if ($mHaulierReference != "")
                    mainProcessPdf($mHost, $mUser, $mPwd, $mDbName,$mHaulierReference,"M");
                else
                    mainProcessPdf($mHost, $mUser, $mPwd, $mDbName,$mCustomerReference,"M");
            }
        }
    }
//  mysqli_close($mConnection);
    if ($mErrMsg == "")
        $mErrMsg = "OKMS- Receipt Closed";
//  exit($mErrMsg);
    echo $mErrMsg;
    return;
}

// Set Location Filling Status
elseif (($mFunction != null) && (strtolower($mFunction) == "setfillingstatus"))
{
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;

// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    $mSerialReference = "";
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "tolocationhashcode")
            $mLocationHash = $v2;
        elseif ($k2 == "fillingstatus")
            $mFillingStatus = $v2;
        elseif (strtolower($k2) == "serialreference")
            $mSerialReference = $v2;
        elseif (strtolower($k2) == "partnumber")
            $mPartNumber = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    $mErrMsg = "FAIL-No Matching Location";
    $mDataQuery = "SELECT id AS id FROM location_filling_status WHERE filling_code ='".$mFillingStatus."' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection));
    $mData = mysqli_query($mConnection,$mDataQuery);
    $i = 0;
    $mFillId = "";
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mFillId = ($mRow['id']);
        $i++;
    }
    if ($i == 0)
    {
        $mErrMsg = "FAIL-No Matching Status";
    }
    else
    {
        $mDataQuery = "UPDATE location SET filling_status_id=".$mFillId.",last_updated=now(), last_updated_by='".$mCurrentUser."' WHERE location_hash = '".$mLocationHash."' LIMIT 1";
        if(!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection).":".$mDataQuery);
    }
    
// Prompt Next Location
    if ((($mTransactionTypeId == "CTS") || ($mTransactionTypeId == "RCTS") || ($mTransactionTypeId == "FQA") || ($mTransactionTypeId == "CTL")) && ($mSerialReference != ""))
    {
        $mInvPartId = "";
        $mDataQuery = "SELECT id AS id FROM part WHERE (part_number='".$mPartNumber."') LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        $mData = (mysqli_query($mConnection,$mDataQuery));
        $mLocation = "";
        while($mRow = mysqli_fetch_assoc($mData))
        {
            $mInvPartId = $mRow['id'];
        }
        if ($mInvPartId != "")
        {
            include_once('location.php');
            $mLocation = getNextLocation($mInvPartId,"","1","","","",$mHost,$mUser,$mPwd,$mDbName,$mTransactionTypeId,$mSerialReference);
        }
        if ($mLocation != "")
            $mErrMsg = "CHGTRAN-".$mTransactionTypeId."?DATA:serialReference:".$mSerialReference.",partNumber:".$mPartNumber.",toLocationHashCode:".$mLocation."::skip2";
        else
            $mErrMsg = "CHGTRAN-".$mTransactionTypeId."?DATA:serialReference:".$mSerialReference;
    }
    else
        $mErrMsg = "OK  - Location ".$mFillingStatus;
//  mysqli_close($mConnection);
//  exit($mErrMsg);
    echo $mErrMsg;
    return;
}

// Post Transaction
elseif (($mFunction != null) && (strtolower($mFunction) == "processtransaction"))
{
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $s=0;
    $e=0;
    $mJsonArray = array();
// Test for blank input
    if (($mFilter == "") || ($mFilter == null))
    {
//      exit("OK  -");
        echo "OK  -";
        return;
    }
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    $i = 0;
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "jserialReference")
            $mJsonArray['serialReference'] = $v2;
        elseif (($k2 == "quantity") || ($k2 == "countQty"))
            $mJsonArray[$k2] = floatval($v2);
        else
            $mJsonArray[$k2] = $v2;
        if (($v2 != "") && ($v2 != 0))
            $i++;
    }

// All Values are blank
    if ($i == 0)
    {
//      exit("OK  -");
        echo "OK  -";
        return;
    }
// Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
    }
    catch(Exception $e)
    {
//      exit("FAIL-Json Error");
        echo "FAIL-Json Error";
        return;
    }
    
// POST Operation
    try
    {
        $mConnectp = str_replace(":8081/vantec",":8093/vantec",$mConnect);
        if ($mConnectp == $mConnect)
        {
            $e = strpos($mConnect,":8081");
            $mConnectp = substr($mConnect,0,$e).":8093/vantec/";
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $mConnectp."processTransaction");
        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  - Update Complete";
//          exit($mErrMsg);
            echo $mErrMsg;
            return;
//          print_r("FAIL-Message Code=".$mJsonObject.":".$mResult.":".$mResponse.":".$mErrors);
        }
    }
    catch (Exception $e)
    {
        $mErrMsg = ("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
    }
    return;
}

elseif (($mFunction != null) && ($mFunction == "completedocument"))
{
// Strip out User
    $mCurrentUser="";
    $s = strpos(strtolower($mFilter),"currentuser=");
    if ($s > 0)
    {
        $s = $s+12;
        $e = strpos($mFilter,"&",$s);
        if ($e <= $s)
            $e = strlen($mFilter);
        $mCurrentUser = substr($mFilter,$s,$e-$s);
        $mFilter = substr($mFilter,0,$s-13);
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    $mErrMsg = "FAIL-No Matching Haulierer";
    $mDataQuery = "SELECT id AS id FROM receipt_header WHERE haulier_reference_code='".$mFilter."'";
    $mData = mysqli_query($mConnection,$mDataQuery);
    $i = 0;
    $mDocId = "";
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mDocId = ($mRow['id']);
        $i++;
    }
    if ($i == 0)
    {
        $mErrMsg = "FAIL-No Matching Document";
    }
    else
    {
        $mDataQuery = "UPDATE receipt_header SET status=1,last_updated_date=now() WHERE haulier_reference = '".$mFilter."'";
        mysqli_query($mConnection,$mDataQuery);
        $mErrMsg = "OKMS- Doc.".$mFilter." Complete";
    }
//  mysqli_close($mConnection);
//  exit($mErrMsg);
    echo $mErrMsg;
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "addhaulierreferencetomultiplereceipt"))
{
//  $mJsonObject = '{"haulierReference": "TRL10145","documentReference": ["RCP000001","RCP000002"]}';
// Strip out User
    $mCurrentUser="";
    $s = strpos(strtolower($mFilter),"currentuser=");
    if ($s > 0)
    {
        $s = $s+12;
        $e = strpos($mFilter,"&",$s);
        if ($e <= $s)
            $e = strlen($mFilter);
        $mCurrentUser = substr($mFilter,$s,$e-$s);
        $mFilter = substr($mFilter,0,$s-13);
    }
    $mJsonObject = $mFilter;
// POST Operation
    try
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $mConnect."addHaulierReferenceToMultipleReceipt");
        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")
        {
//          exit("FAIL-Message Error Code=".$mResult.":".$mResponse.":".$mErrors);
            echo "FAIL-Message Error Code=".$mResult.":".$mResponse.":".$mErrors;
            return;
        }
//      else
//          print_r("FAIL-Message Code=".$mResult.":".$mResponse.":".$mErrors);
            echo("OK  -");
    }
    catch (Exception $e)
    {
        exit("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
    }
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "createreceiptdoc"))
{
//  $mJsonObject = '{"haulierReference": "TRL10145","documentReference": ["RCP000001","RCP000002"]}';
// Strip out User
    $mCurrentUser="";
    $s = strpos(strtolower($mFilter),"currentuser=");
    if ($s > 0)
    {
        $s = $s+12;
        $e = strpos($mFilter,"&",$s);
        if ($e <= $s)
            $e = strlen($mFilter);
        $mCurrentUser = substr($mFilter,$s,$e-$s);
        $mFilter = substr($mFilter,0,$s-13);
    }
    $mJsonObject = $mFilter;
// POST Operation
    try
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $mConnect."createReceiptDoc");
        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")
        {
//          exit("FAIL-Message Error Code=".$mResult.":".$mResponse.":".$mErrors);
            echo "FAIL-Message Error Code=".$mResult.":".$mResponse.":".$mErrors;
        }
//      else
//          print_r("FAIL-Message Code=".$mResult.":".$mResponse.":".$mErrors);
            echo "OK  -";
    }
    catch (Exception $e)
    {
        exit("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
    }
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "updateplt"))
{   
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mHaulierReference = "";
    $mCustomerReference = "";
$mCountQty = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "haulierreference")
            $mHaulierReference = strtoupper($v2);
        elseif ($k2 == "customerreference")
            $mCustomerReference = strtoupper($v2);
        elseif ($k2 == "tolocationhashcode")
            $mLocation = strtoupper($v2);
        elseif ($k2 == "toplt")
            $mPltReference = strtoupper($v2);
        elseif ($k2 == "ranorder")
            $mRanOrder = strtoupper($v2);
        elseif ($k2 == "partnumber")
            $mPartNumber = strtoupper($v2);
        elseif ($k2 == "deliverynote")
            $mDeliveryNote = strtoupper($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = strtoupper($v2);
        elseif ($k2 == "qty")
            $mQty = trim($v2);
        elseif ($k2 == "countqty")
            $mCountQty = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
    if ($mCountQty == "")
        $mCountQty = $mQty;
    if(is_numeric($mQty))
    {
    }
    else
    {
        echo "FAIL-This must be a number only";
        return;
    }
    if(is_numeric($mCountQty))
    {
    }
    else
    {
        echo "FAIL-This must be a number only";
        return;
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Create / Update Pallet Table
//  $mDataQuery = "CREATE TABLE IF NOT EXISTS scan_data (id int(11) NOT NULL auto_increment,date_created datetime NULL, created_by varchar(255) NULL, last_updated_date datetime NULL, last_updated_by varchar(255) NULL,plt_reference varchar(45) NULL,ran_or_order varchar(45) NULL,part_number varchar(255) NULL, serial_reference varchar(255) NULL, haulier_reference varchar(255) NULL, location_code varchar(255) NULL,scan_qty float(7,4) NULL,count_qty float(7,4) NULL, validated int(6) NULL default 0, active int(6) NULL default 1, delivery_note varchar(255) NULL, PRIMARY Key (id))";
//  mysqli_query($mConnection,$mDataQuery);
//  if (!mysqli_query($mConnection,$mDataQuery))
//  {
//      exit("FAIL-".mysqli_error($mConnection));
//  }
// Get part id
    $mDataQuery = "SELECT part.id AS id, part.part_number AS part_number FROM part WHERE (part.part_number = '".$mPartNumber."') LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
    {
        exit("FAIL-".mysqli_error($mConnection).":".$mDataQuery);
    }
    $mData = mysqli_query($mConnection,$mDataQuery);
    $mPartId = "";
    while($mRow = mysqli_fetch_assoc($mData))
    {
        $mPartId = $mRow['id'];
        $mPartNumber = $mRow['part_number'];
    }
// Add / Update Pallet
    $mDataQuery = "SELECT id FROM scan_data WHERE upper(plt_reference)='".$mPltReference."' AND upper(part_number) = '".$mPartNumber."' AND upper(serial_reference) = '".$mSerialReference."' LIMIT 2";
    $mResults = mysqli_query($mConnection,$mDataQuery);
    $i = mysqli_num_rows($mResults);
    if ($i > 1)
    {
        mysqli_query($mConnection,"DELETE FROM scan_data WHERE upper(plt_reference)='".$mPltReference."' AND upper(part_number) = '".$mPartNumber."' AND upper(serial_reference) = '".$mSerialReference."'");
        if (!mysqli_query($mConnection,$mDataQuery))
        {
            exit("FAIL-".mysqli_error($mConnection));
        }
    }
    if ($i == 1)
    {
        $mDataQuery = "Update scan_data SET last_updated_date=now(), last_updated_by='".$mCurrentUser."', scan_qty=".$mQty.", count_qty=".$mCountQty." WHERE plt_reference='".$mPltReference."' AND part_number = '".$mPartNumber."' AND serial_reference = '".$mSerialReference."'";
    }
    else
    {
        if ($mPartId == "")
            if ($mHaulierReference != "")
                $mDataQuery = "INSERT INTO scan_data(id,date_created,created_by,last_updated_date,last_updated_by,plt_reference,ran_order,part_number,serial_reference,haulier_reference,location_code,scan_qty,count_qty,validated,active,delivery_note) VALUES(DEFAULT,now(),'".$mCurrentUser."',now(),'".$mCurrentUser."','".$mPltReference."','".$mRanOrder."','".$mPartNumber."','".$mSerialReference."','".$mHaulierReference."','".$mLocation."',".$mQty.",".$mCountQty.",0,1,'".$mDeliveryNote."')";
            else
                $mDataQuery = "INSERT INTO scan_data(id,date_created,created_by,last_updated_date,last_updated_by,plt_reference,ran_order,part_number,serial_reference,customer_reference,location_code,scan_qty,count_qty,validated,active,delivery_note) VALUES(DEFAULT,now(),'".$mCurrentUser."',now(),'".$mCurrentUser."','".$mPltReference."','".$mRanOrder."','".$mPartNumber."','".$mSerialReference."','".$mCustomerReference."','".$mLocation."',".$mQty.",".$mCountQty.",0,1,'".$mDeliveryNote."')";
        else
            if ($mHaulierReference != "")
                $mDataQuery = "INSERT INTO scan_data(id,date_created,created_by,last_updated_date,last_updated_by,plt_reference,ran_order,part_number,serial_reference,haulier_reference,location_code,scan_qty,count_qty,validated,active,delivery_note,part_id) VALUES(DEFAULT,now(),'".$mCurrentUser."',now(),'".$mCurrentUser."','".$mPltReference."','".$mRanOrder."','".$mPartNumber."','".$mSerialReference."','".$mHaulierReference."','".$mLocation."',".$mQty.",".$mCountQty.",0,1,'".$mDeliveryNote."',".$mPartId.")";
            else    
                $mDataQuery = "INSERT INTO scan_data(id,date_created,created_by,last_updated_date,last_updated_by,plt_reference,ran_order,part_number,serial_reference,customer_reference,location_code,scan_qty,count_qty,validated,active,delivery_note,part_id) VALUES(DEFAULT,now(),'".$mCurrentUser."',now(),'".$mCurrentUser."','".$mPltReference."','".$mRanOrder."','".$mPartNumber."','".$mSerialReference."','".$mCustomerReference."','".$mLocation."',".$mQty.",".$mCountQty.",0,1,'".$mDeliveryNote."',".$mPartId.")";
    }
    if (!mysqli_query($mConnection,$mDataQuery))
    {
        exit("FAIL-".mysqli_error($mConnection).":".$mDataQuery);
    }
//  mysqli_close($mConnection);
    echo "OK  - updateplt";
    return;
}

// Receipt Pallet Box Count
elseif (($mFunction != null) && ($mFunction == "validateboxcount"))
{
    $mQty = "";
    $mReference = "";
    $mPlt = "";
    $mTrys = "0";
    $mErrMsg = "";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mHaulierReference = "";
    $mCustomerReference = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "haulierreference")
            $mHaulierReference = $v2;
        if ($k2 == "customerreference")
            $mCustomerReference = $v2;
        elseif ($k2 == "toplt")
            $mPlt = strtoupper($v2);
        elseif ($k2 == "trys")
            $mTrys = $v2;
        elseif ($k2 == "qty")
            $mQty = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
//  if ($mTrys > 3)
//      $mTrys = 3;
// get Pallet / box count
    if (($mErrMsg == "") && ($mHaulierReference != "" || $mCustomerReference != ""))
    {
// mysql connection
        $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
            exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// get Pallet Inventory Count
        $i = 0;
        $mInvCount = 0;
        $mInvCount1 = 0;
// Count Inventory
        if ($mHaulierReference != "")
            $mDataQuery = "SELECT count(*) as invcount FROM inventory_master JOIN receipt_detail ON inventory_master.part_id=receipt_detail.part_id AND inventory_master.serial_reference=receipt_detail.serial_reference JOIN receipt_body ON receipt_body.id=receipt_detail.receipt_body_id JOIN receipt_header ON receipt_header.id=receipt_body.receipt_header_id LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE inventory_master.tag_reference = '".$mPlt."' AND receipt_header.haulier_reference='".$mHaulierReference."' AND inventory_master.inventory_qty <> 0 LIMIT 1";
        else
            $mDataQuery = "SELECT count(*) as invcount FROM inventory_master JOIN receipt_detail ON inventory_master.part_id=receipt_detail.part_id AND inventory_master.serial_reference=receipt_detail.serial_reference JOIN receipt_body ON receipt_body.id=receipt_detail.receipt_body_id JOIN receipt_header ON receipt_header.id=receipt_body.receipt_header_id LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE inventory_master.tag_reference = '".$mPlt."' AND receipt_header.customer_reference='".$mCustomerReference."' AND inventory_master.inventory_qty <> 0 LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error);
        $mData = mysqli_query($mConnection,$mDataQuery);        
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mInvCount = (int)($mRow['invcount']);
            $i++;
        }
//      exit("FAIL-".$mDataQuery.":".$mFilter);
        if ($mHaulierReference != "")
            $mDataQuery = "SELECT count(*) AS invcount FROM scan_data WHERE haulier_reference='".$mHaulierReference."' AND plt_reference='".$mPlt."' LIMIT 1";
        else
            $mDataQuery = "SELECT count(*) AS invcount FROM scan_data WHERE customer_reference='".$mCustomerReference."' AND plt_reference='".$mPlt."' LIMIT 1";
        $mData = mysqli_query($mConnection,$mDataQuery);        
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mInvCount1 = (int)($mRow['invcount']);
            $i++;
        }
        $mInvCount=$mInvCount+$mInvCount1;
//      exit("FAIL-".$mInvCount."-".$mQty);
        if ($mQty != $mInvCount)
        {
            $mErrMsg = "FAIL-Wrong Box Count Quantity.";
        }
//      mysqli_close($mConnection);
//      $mtrys = $mtrys-1;
        if ($mErrMsg == "")
            $mErrMsg = "OK  -";                          
    }
    else
        $mErrMsg = "FAIL-Invalid Reference";
    echo $mErrMsg;
    return;
}

// Check for outstanding Scan-data
elseif (($mFunction != null) && (strtolower($mFunction) == "checkscandata"))
{
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $mHaulierReference = "";
    $mCustomerReference = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "haulierreference")
            $mHaulierReference = strtoupper($v2);
        if ($k2 == "customerreference")
            $mCustomerReference = strtoupper($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }   
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    if ($mHaulierReference != "")
        $mDataQuery = "SELECT id FROM scan_data WHERE haulier_reference = '".$mHaulierReference."' LIMIT 1";
    else
        $mDataQuery = "SELECT id FROM scan_data WHERE customer_reference = '".$mCustomerReference."' LIMIT 1";
    $mData = mysqli_query($mConnection,$mDataQuery);
    if (mysqli_num_rows($mData) > 0)
        $mErrMsg = "FAIL-Receipt not Complete";
    else
        $mErrMsg = "OK  -";
//  mysqli_close($mConnection);
    exit($mErrMsg);
}

// Post Pallet Contents
elseif (($mFunction != null) && (strtolower($mFunction) == "processplt"))
{
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $s=0;
    $e=0;
    $mJsonArray = array();
    $mHaulierReference = "";
    $mCustomerReference = "";

// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "haulierreference")
            $mHaulierReference = strtoupper($v2);
        elseif ($k2 == "customerreference")
            $mCustomerReference = strtoupper($v2);
        elseif ($k2 == "toplt")
            $mPltReference = strtoupper($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
    if (($mHaulierReference == "" && $mCustomerReference == "") || ($mPltReference == ""))
        exit("FAIL-Invalid Reference");
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Read Pallet Contents
    if ($mHaulierReference != "")
        $mPltQuery = "SELECT id AS id, haulier_reference AS haulierreference, customer_reference AS customerreference,location_code AS tolocationhashcode, plt_reference AS toplt, ran_order AS ranorder, part_number AS partnumber, serial_reference AS serialreference, scan_qty AS quantity, count_qty AS countqty, last_updated_by AS currentuser, delivery_note AS deliverynote FROM scan_data WHERE upper(haulier_reference)='".trim($mHaulierReference)."' AND upper(plt_reference)='".trim($mPltReference)."'";
    else
        $mPltQuery = "SELECT id AS id, haulier_reference AS haulierreference, customer_reference AS customerreference, location_code AS tolocationhashcode, plt_reference AS toplt, ran_order AS ranorder, part_number AS partnumber, serial_reference AS serialreference, scan_qty AS quantity, count_qty AS countqty, last_updated_by AS currentuser, delivery_note AS deliverynote FROM scan_data WHERE upper(customer_reference)='".trim($mCustomerReference)."' AND upper(plt_reference)='".trim($mPltReference)."'";
    if (!mysqli_query($mConnection,$mPltQuery))
        exit("FAIL-".mysqli_error($mConnection).":".$mPltQuery);
    
    include_once ('transaction.php');   
    $mPltData = mysqli_query($mConnection,$mPltQuery);
    while($mPltRow = mysqli_fetch_assoc($mPltData))
    {
// Convert Array to Json Object
        try
        {
            $mJsonObject = json_encode(array_merge(array("transactiontypeid"=>$mTransactionTypeId),$mPltRow), JSON_FORCE_OBJECT);
        }
        catch(Exception $e)
        {
            exit("FAIL-Json Error");
        }
// POST Operation
        try
        {
            $mStatus = postTransaction($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
            if (substr($mStatus,0,2) == "FA")
                exit("FAIL-".$mStatus);
            $mDataQuery = "DELETE FROM scan_data WHERE id = ".$mPltRow['id']." LIMIT 1";
            if(!mysqli_query($mConnection,$mDataQuery))
                exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        }
        catch (Exception $e)
        {
            exit("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
        }
    }
//  mysqli_close($mConnection);
    echo "OK  -";
    return;
}

// Check for mixed pallet - location type
elseif (($mFunction != null) && (strtolower($mFunction) == "getpltloctype"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "pltnumber")
            $mPltNumber = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Read Pallet Contents
    $mDataQuery = "SELECT part.fixed_location_type_id AS location_type_id, part.fixed_sub_type_id AS zone_type_id FROM inventory_master JOIN part ON inventory_master.part_id=part.id LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE inventory_master.tag_reference = '".$mPltNumber."' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
    {
        exit("FAIL-".mysqli_error($mConnection).":".$mDataQuery);
    }
    $mData = mysqli_query($mConnection,$mDataQuery);
    $mLocationType = "";
    $mZoneType = "";
    $i = 0;
    while($mRow = mysqli_fetch_assoc($mData))
    {
        $mLocationType = ($mRow['location_type_id']);
        $mZoneType = ($mRow['zone_type_id']);
        $i++;
    }
    if ($i == 0)
    {
        exit("FAIL-Incorrect Pallet");
    }
    $mDataQuery = "SELECT inventory_master.id AS id FROM inventory_master JOIN part ON inventory_master.part_id=part.id LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE inventory_master.tag_referenec='".$mPltNumber."' AND (part.fixed_location_type_id<>".$mLocationType." OR part.fixed_sub_type_id<>".$mZoneType.") 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))
    {
        $i++;
    }
    if ($i > 0)
    {
        exit("FACS-Mixed Location Types on Pallet");
    }
    exit("OK  -");
}

// Validate Putaway Location
elseif (($mFunction != null) && ($mFunction=="validateputawaylocation"))
{
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Set default error message
    $mErrMsg = "FAIL-Wrong Location Type for Put Away";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "tolocationhashcode")
            $mLocation = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = strtoupper($v2);
    }
// Test for existence of Location Type
    $mDataQuery = "SELECT location.id AS id, location_type.location_type_code AS location_type_code FROM location JOIN location_type ON location.location_type_id=location_type.id WHERE (location.location_hash='".$mLocation."') LIMIT 1";
    $mData = mysqli_query($mConnection,$mDataQuery);
    $i = 0;
    $mLocationType = "";
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
//      $mSQLData[] =($mRow);
        $mLocationType = ($mRow['location_type_code']);
        $i++;
    }
//  mysqli_close($mConnection);
    $mDataStr = "";
    if ($i == 0)
        exit("FAIL-Location Not Found");
    if (strtolower($mLocationType) == "rcv")
        exit("FAIL-Incorrect Location for PutAway");
    If ($i > 0)
    {
        exit("OK  -");
    }
    else
    {
        exit($mErrMsg);
    }
}

// Return Next Putaway Location for part
elseif (($mFunction != null) && (strtolower($mFunction) == "getputawayloc"))
{
    $mErrMsg = "";
    $mPartNumber = "";
    $mSerialReference = "";
    $mPltNumber = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "partnumber")
            $mPartNumber = strtoupper($v2);
        elseif ($k2 == "pltnumber")
            $mPltNumber = strtoupper($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = strtoupper($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);  
    }
    
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    
// Part Number Only
    if ($mPartNumber != "" && $mPltNumber == "" && $mSerialReference == "")
    {
        $mInvPartId = "";
        $mDataQuery = "SELECT id AS id FROM part WHERE (part_number='".$mPartNumber."') LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        $mData = (mysqli_query($mConnection,$mDataQuery));

        while($mRow = mysqli_fetch_assoc($mData))
        {
            $mInvPartId = $mRow['id'];
        }
        if ($mInvPartId != "")
        {
            $mRequiresInspection = "";
// Test for outstanding RELOC
            $mDataQuery = "SELECT reloc_body.id AS id,reloc_header.to_location AS to_location";
            $mDataQuery .=" FROM reloc_header";
            $mDataQuery .=" JOIN reloc_body ON reloc_header.id=reloc_body.reloc_header_id";
            $mDataQuery .=" WHERE reloc_body.serial_reference=?";
            $mDataQuery .=" AND reloc_body.processed=0";
            $mDataQuery .=" AND reloc_header.to_location='stock'";
            $mDataQuery .=" LIMIT 1";
            try
            {
                $mStmt = $mConnection->prepare($mDataQuery);
                $mStmt->bind_param("s", $mSerialReference);
                $mStmt->execute();
                $mData = $mStmt->get_result();
                $mRows = $mData->fetch_all(MYSQLI_ASSOC);
            }
            catch (Exception $e)
            {
                exit("FAIL-".$e." ".mysqli_error($mConnection)." ".$mDataQuery);
            }
            $mStmt->close();
            if (mysqli_num_rows($mData)>0)
            {
                $mRequiresInspection = "00";
                $mDataQuery = "UPDATE inventory_master SET hold_qty=0, requires_inspection=0";
                $mDataQuery .=",inventory_status_id=(SELECT id FROM inventory_status WHERE inventory_status_code='ok' LIMIT 1)";
                $mDataQuery .=" WHERE serial_reference=?";
                $mDataQuery .=" LIMIT 1";
                try
                {
                    $mStmt = $mConnection->prepare($mDataQuery);
                    $mStmt->bind_param("s", $mSerialReference);
                    $mStmt->execute();
                }
                catch (Exception $e)
                {
                    exit("FAIL-".$e." ".mysqli_error($mConnection)." ".$mDataQuery);
                }
                $mStmt->close();
            }
// Get sugessted location
            include_once('location.php');
            $mLocation = getNextLocation($mInvPartId,"","1","","",$mRequiresInspection,$mHost,$mUser,$mPwd,$mDbName,$mTransactionTypeId);
//          exit("FAIL-TEST1-".$mLocation);
            if(strpos($mLocation,",") !== false)
            {
                $i = strpos($mLocation,",");
                $mRdtMsg = substr($location,$i+1);
                $mLocation = substr($mLocation,0,$i-1);
            }
            if ($mLocation != "")
            {
                $mStatus = "DATA:toLocationHashCode:".$mLocation.":*,rdtmessage:".$mRdtMsg;
            }
            else
            {
                $mStatus = "DATA:toLocationHashCode: :*,rdtmessage:".$mRdtMsg;
            }
            exit($mStatus);
        }
        else
        {
            exit("FAIL-Invalid Part Number");
        }
    }
    if ($mPartNumber == "")
    {
        if ($mTransactionTypeId == "PTS" && $mSerialReference != "")
        {
            $mDataQuery = "SELECT tag_reference FROM inventory_master WHERE (serial_reference='".$mSerialReference."' OR tag_reference='".$mSerialReference."') AND (inventory_master.inventory_qty) > 0 LIMIT 2";
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                exit("FAIL-".mysqli_error($mConnection).":".$mDataQuery);
            if (mysqli_num_rows($mData) == 0)
                exit("FAIL-Invalid Pallet");
            if (mysqli_num_rows($mData) == 2)
                exit("DATA:partNumber::I");
            else
                list($mPltNumber) = mysqli_fetch_row($mData);
        }
        if ($mTransactionTypeId != "PTS")
        {
            $mDataQuery = "SELECT part_number FROM inventory_master WHERE (serial_reference='".$mSerialReference."' OR tag_reference='".$mSerialReference."') AND (inventory_master.inventory_qty) > 0 LIMIT 2";
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                exit("FAIL-".mysqli_error($mConnection).":".$mDataQuery);
            if (mysqli_num_rows($mData) == 0)
                exit("FAIL-Invalid Serial");
            if (mysqli_num_rows($mData) == 2)
                return "DATA:partNumber::I";
            else
            {
                list($mPartNumber) = mysqli_fetch_row($mData);
            }
        }
//        exit("FAIL-TEST".$mDataQuery."-".$mTransactionTypeId."-".$mSerialReference);
    }
//      exit("FAIL-TEST".$mDataQuery."-".$mPartNumber);
    $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.part_id AS part_id
    , part.part_number AS part_number
    , inventory_master.product_type_id AS product_type_id, inventory_master.pruf_cube AS pruf_cube, inventory_master.requires_inspection AS requires_inspection, inventory_master.requires_decant AS requires_decant
    ,inventory_status.inventory_status_code AS inventory_status_code 
    ,location_type.to_qr AS to_qr
    FROM inventory_master 
    JOIN part ON inventory_master.part_id=part.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
    LEFT JOIN location ON inventory_master.location_id=location.id
    LEFT JOIN location_type ON location.location_type_id=location_type.id
    WHERE ";
// Get Inventory Record based on Pallet 
    if ($mTransactionTypeId == "PTS")
    {
        $mDataQuery .= " (inventory_master.tag_reference = '".$mPltNumber."' OR inventory_master.serial_reference='".$mPltNumber."') AND (inventory_master.inventory_qty) > 0 LIMIT 500";
    }
// Get Inventory Record based on Part & Serial
    else
    {
        $mDataQuery .= " (part.part_number = '".$mPartNumber."') AND inventory_master.serial_reference = '".$mSerialReference."' AND (inventory_master.inventory_qty) > 0 LIMIT 1";
    }
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
    {
        exit("FAIL-".mysqli_error($mConnection).":".$mDataQuery);
    }
    if ($mTransactionTypeId=="PTS" && mysqli_num_rows($mData)==0)
    {
//    exit("FAIL-TEST".$mDataQuery."-".mysqli_num_rows($mData)."-".$mPartNumber."-".$mPltNumber);
        $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.part_id AS part_id
        , part.part_number AS part_number
        , inventory_master.product_type_id AS product_type_id, inventory_master.pruf_cube AS pruf_cube, inventory_master.requires_inspection AS requires_inspection, inventory_master.requires_decant AS requires_decant
        ,inventory_status.inventory_status_code AS inventory_status_code
        ,location_type.to_qr AS to_qr, location_type.to_inspect AS to_inspect
        FROM inventory_master 
        JOIN part ON inventory_master.part_id=part.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
        LEFT JOIN location ON inventory_master.location_id=location.id
        LEFT JOIN location_type ON location.location_type_id=location_type.id
        WHERE ";
// Get Inventory Record based on Pallet 
        if ($mPartNumber=="")
        {
            $mDataQuery .= " (inventory_master.tag_reference = '".$mPltNumber."' OR inventory_master.serial_reference='".$mPltNumber."') AND (inventory_master.inventory_qty) > 0 LIMIT 2";
        }
    // Get Inventory Record based on Part & Serial
        else
        {
            $mDataQuery .= " (part.part_number = '".$mPartNumber."') AND inventory_master.serial_reference = '".$mPltNumber."' AND (inventory_master.inventory_qty) > 0 LIMIT 1";
        }            
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection).":".$mDataQuery);
//        exit("FAIL-TEST1".mysqli_error($mConnection).":".$mDataQuery."-".mysqli_num_rows($mData));
        if (mysqli_num_rows($mData) == 0)
        {
            exit("FAIL-Invalid Pallet / Serial");
        }
        if (mysqli_num_rows($mData) == 2)
            return "DATA:partNumber:::skippartNumber";
    }
    
    $mInvId = null;
    $mProductType = "";
    $mInvPartId = "";
    $mMultiPart = "";
    $mPrufCube = "";
    $mReqInsp = "0";
    $mReqDecant = "";
    $mReqQr = "";
    $mToQr = 0;
    $mToInsp = 0;
    $i = 0;
    
    if (mysqli_num_rows($mData) == 0)
    {
 //       mysqli_close($mConnection);
        if ($mPltNumber != null && $mPltNumber != "")
            echo("FAIL-Invalid Pallet");
        else
            echo("FAIL-Invalid Serial");
        return;
    }
    
//  while(($mRow = mysqli_fetch_assoc($mData)) && ($mMultiPart==""))
    while($mRow = mysqli_fetch_assoc($mData))
    {
        if ($i == 0)
        {
            $mInvId = ($mRow['id']);
            $mProductType = ($mRow['product_type_id']);
            $mInvPartId = ($mRow['part_id']);
            $mToQr = $mRow['to_qr'];
            $mToInsp = $mRow['to_inspect'];
        }
// Check for multi-part Pallet
        else
        {
            if ($mInvPartId != ($mRow['part_id']))
                $mMultiPart = "1";
        }
        if ($mRow['pruf_cube'] == "1")
            $mPrufCube = "1";
        if ($mRow['requires_inspection'] == "1")
            $mReqInsp = "1";
        if ($mRow['requires_decant'] == "1")
            $mReqDecant = "1";
        if (strtolower($mRow['inventory_status_code']) == "qtine")
        {
            $mReqInsp = "0";
            $mReqQr = "1";
        }
        if (strtolower($mRow['inventory_status_code']) == "overbooking")
            $mInvId = ($mRow['id']);
        $i++;
    }
    if ($mReqDecant == "1")
        $mReqInsp = "2";
// If Inventory_status = 'qtine' add to inspection flag
    if ($mReqQr == "1")
    {
        if ($mToQr == 1)
        {
            if (strlen($mReqInsp)>0)
                $mReqInsp .= "1";
            else    
                $mReqInsp = "01";
        }
//      exit("FAIL-TEST-".$mReqInsp." ".$mDataQuery."-".$mToQr);
    }
    
    $mRequiresInspection = "";
// Test for outstanding RELOC
    $mDataQuery = "SELECT reloc_body.id AS id,reloc_header.to_location AS to_location";
    $mDataQuery .=" FROM reloc_header";
    $mDataQuery .=" JOIN reloc_body ON reloc_header.id=reloc_body.reloc_header_id";
    $mDataQuery .=" WHERE reloc_body.serial_reference=?";
    $mDataQuery .=" AND reloc_body.processed=0";
    $mDataQuery .=" AND reloc_header.to_location='stock'";
    $mDataQuery .=" LIMIT 1";
    try
    {
        $mStmt = $mConnection->prepare($mDataQuery);
        $mStmt->bind_param("s", $mSerialReference);
        $mStmt->execute();
        $mData = $mStmt->get_result();
        $mRows = $mData->fetch_all(MYSQLI_ASSOC);
    }
    catch (Exception $e)
    {
        exit("FAIL-".$e." ".mysqli_error($mConnection)." ".$mDataQuery);
    }
    $mStmt->close();
    if (mysqli_num_rows($mData)>0)
    {
        $mReqInsp = "00";
        $mDataQuery = "UPDATE inventory_master SET hold_qty=0, requires_inspection=0";
        $mDataQuery .=",inventory_status_id=(SELECT id FROM inventory_status WHERE inventory_status_code='ok' LIMIT 1)";
        $mDataQuery .=" WHERE serial_reference=?";
        $mDataQuery .=" LIMIT 1";
        try
        {
            $mStmt = $mConnection->prepare($mDataQuery);
            $mStmt->bind_param("s", $mSerialReference);
            $mStmt->execute();
        }
        catch (Exception $e)
        {
            exit("FAIL-".$e." ".mysqli_error($mConnection)." ".$mDataQuery);
        }
        $mStmt->close();
    }
    error_log("validaterdt.php-".$mDataQuery." INSP-".$mReqInsp);
//  exit("FAIL-TEST1".$mDataQuery."/".$mInvPartId."/".$mProductType."/".$mMultiPart."/".$mInvId."/".$i);
    include_once ('location.php');
    $mConnectp = str_replace(":8081/vantec",":8083/putaway",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8093/putaway/";
    }
    if ($mTransactionTypeId == "PTS")
        $mLocation = getNextLocation($mInvPartId,$mProductType,$mMultiPart,"PTS",$mPrufCube,$mReqInsp,$mHost,$mUser,$mPwd,$mDbName,$mTransactionTypeId,'',$mInvId);
    else
        $mLocation = getNextLocation($mInvPartId,$mProductType,$mMultiPart,"",$mPrufCube,$mReqInsp,$mHost,$mUser,$mPwd,$mDbName,$mTransactionTypeId,$mSerialReference,$mInvId);
    if (substr($mLocation,0,2)=="FA")
        exit($mLocation);
    if ($mTransactionTypeId == "CTS")
    {
//      $mDataStr = "DATA:toLocationHashCode:$mLocation";
        if ($mLocation != "")
        {
            $mStatus = "DATA:toLocationHashCode:".$mLocation;
            $mDataStr = "DATA:toLocationHashCode:".$mLocation;
        }
        else
        {
            $mStatus = "DATA:toLocationHashCode:";
            $mDataStr = "DATA:toLocationHashCode:";
        }
    }
    elseif ($mLocation != "")
    {
        $mStatus = "DATA:toLocationHashCode:".$mLocation;
        $mDataStr = "DATA:toLocationHashCode:".$mLocation;
    }
    else
    {
        $mStatus = "DATA:toLocationHashCode:";
        $mDataStr = "DATA:toLocationHashCode:";
    }
    exit($mDataStr);
}

// validate prompted location
// http://172.16.1.70:8083/putaway/validateLocation?locationHashCode=GY2Q&locationCode=DOCK2
elseif (($mFunction != null) && (strtolower($mFunction) == "validatepromptedlocation"))
{
    $mDataStr = "OK  -";
// Replace default Server Tomcat Service
    $mConnectp = str_replace(":8081/vantec",":8083/putaway",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8083/putaway/";
    }
// Get Server Data from URL
    try
    {
        $mFilter = "validateLocation?".$mFilter;
        $mDataStr = file_get_contents($mConnectp.$mFilter);
        if (($mDataStr == false) || ($mDataStr == "false"))
        {
            $mStatus = "FAIL-";
            $mDataStr = "FAIL-Wrong Location Scanned";
        }
        else
        {
            $mStatus = "OK  -";
            $mDataStr = "OK  -";
        }
    } 
    catch (Exception $e) 
    {
        $mErrMsg = ("FAIL-Unexpected System Error - ".$mConnectp.$mFilter."/".$e);
    }
    exit($mDataStr);
}

elseif (($mFunction != null) && (strtolower($mFunction) == "validatecompanypromptedlocation"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "partnumber")
            $mPartNumber = strtoupper($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = strtoupper($v2);
        elseif ($k2 == "hashcode")
            $mLocationHash = strtoupper($v2);
        elseif ($k2 == "locationcode")
            $mLocation = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = strtoupper($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }
    if ($mTransactionTypeId == "PTS")
        $mPlt = "PTS";
    else
        $mPlt = "";
    
    include_once ('location.php');
    $mDataStr = validateCompanyPutawayLocation($mCurrentUser,$mPartNumber,$mLocationHash,$mLocation,$mSerialReference,$mPlt,$mHost,$mUser,$mPwd,$mDbName,$mTransactionTypeId,"n");
    exit($mDataStr);
}

// Validate Haulier Reference
elseif (($mFunction != null) && (strtolower($mFunction) == "validatehaulierreference" || strtolower($mFunction) == "validatecustomerreference"))
{
    $mErrMsg = "";
    $mHaulierReference = "";
    $mCustomerReference = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "haulierreference")
            $mHaulierReference = strtoupper($v2);
        elseif ($k2 == "customerreference")
            $mCustomerReference = strtoupper($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }

// mysql connection
    $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;
    $mDocQaId = 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 (strtolower($mRow['document_status_code']) == "closed")
            $mDocClsId=($mRow['id']);
        if (strtolower($mRow['document_status_code']) == "quarantine")
            $mDocQaId=($mRow['id']);
    }
    if ($mDocStsId == null)
        $mDocStsId = 0;
    if ($mDocCmpId == null)
        $mDocCmpId = 0;
    if ($mDocClsId == null)
        $mDocClsId = 0;
    if ($mDocQaId == null)
        $mDocQaId = 0;
        
// Read Pallet Contents
    if ($mHaulierReference != "")
        $mDataQuery = "SELECT receipt_header.id AS id, receipt_header.document_status_id AS document_status_id, receipt_header.jis_ind AS jis_ind, vendor.ran_scan AS ran_scan FROM receipt_header LEFT JOIN vendor ON receipt_header.vendor_id=vendor.id WHERE upper(receipt_header.haulier_reference) = '".$mHaulierReference."' AND receipt_header.document_status_id IN(0,".$mDocStsId.",".$mDocCmpId.",".$mDocQaId.") LIMIT 1";
    else
        $mDataQuery = "SELECT receipt_header.id AS id, receipt_header.document_status_id AS document_status_id, receipt_header.jis_ind AS jis_ind, vendor.ran_scan AS ran_scan FROM receipt_header LEFT JOIN vendor ON receipt_header.vendor_id=vendor.id WHERE upper(receipt_header.customer_reference) = '".$mCustomerReference."' AND receipt_header.document_status_id IN(0,".$mDocStsId.",".$mDocCmpId.",".$mDocQaId.") LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
    {
        exit("FAIL-".mysqli_error($mConnection).":".$mDataQuery);
    }
    else
    {
        $mData = mysqli_query($mConnection,$mDataQuery);
        $mRanScan = "";
        $mJisInd = "";
        $mRctStsId = "";
        $i = 0;
        while($mRow = mysqli_fetch_assoc($mData))
        {
            $mHdrId = ($mRow['id']);
            $mRanScan = ($mRow['ran_scan']);
            $mJisInd = ($mRow['jis_ind']);
            $mRctStsId = ($mRow['document_status_id']);
            $i++;
        }
        if ($i == 0)
        {
            exit("FAIL-Incorrect Reference");
        }
        if ($mRctStsId == $mDocClsId)
        {
            echo("FAIL-Receipt is Closed");
            return;
        }
        if ($mRctStsId == $mDocQaId)
        {
            echo("FAIL-No open orders for this ASN – report to supervisor");
            return;
        }
        if (($mRctStsId != $mDocStsId) && ($mRctStsId != $mDocCmpId))
        {
            exit("FAIL-Receipt is not available");
        }
        if ($mTransactionTypeId == "RBTC")
        {
            $mDataQuery = "SELECT
                    id FROM receipt_body
                WHERE
                    receipt_header_id = {$mHdrId}
                    AND (case_reference IS NOT NULL AND case_reference <> '')
                LIMIT 1";

            $mData = mysqli_query($mConnection,$mDataQuery);
            if (mysqli_num_rows($mData) == 0)
            {
                echo("FAIL-Incorrect Receipt Type");
                return;
            }
//          $mDataQuery = "SELECT id FROM receipt_body WHERE receipt_header_id=".$mHdrId." AND (case_reference IS NOT null OR case_reference <> '') LIMIT 1";
//          $mData = mysqli_query($mConnection,$mDataQuery);
//          if (mysqli_num_rows($mData) == 0)
//          {
//              echo("FAIL-Incorrect Receipt Type");
//              return;
//          }
        }
        
        if ((substr($mTransactionTypeId,0,3) == "JRB" && $mJisInd == "") || (substr($mTransactionTypeId,0,3) != "JRB" && $mJisInd != ""))
        {
            exit("FAIL-Incorrect Receipt Type");
        }
    }
    if (($mRanScan == "0") || (!mysqli_query($mConnection,$mDataQuery)))
    {
        if (($mTransactionTypeId == "RBTP") || ($mTransactionTypeId == "JRBTP") || ($mTransactionTypeId == "RBTD"))
        {
            $mStatus = "DATA:ranOrder:NO-RAN:HHHHHHH";  
            $mDataStr = "DATA:ranOrder:NO-RAN:HHHHHHH";
        }
        else
        {
            $mStatus = "DATA:ranOrder:NO-RAN:HHHH"; 
            $mDataStr = "DATA:ranOrder:NO-RAN:HHHH";
        }
    }
    else
    {
        if (($mTransactionTypeId == "RBTP") || ($mTransactionTypeId == "JRBTP") || ($mTransactionTypeId == "RBTD"))
        {
            $mStatus = "DATA:ranOrder:NO-RAN:PIPPPPH";  
            $mDataStr = "DATA:ranOrder:NO-RAN:PIPPPPH";
        }
        else
        {
            $mStatus = "DATA:ranOrder:NO-RAN:PIPP"; 
            $mDataStr = "DATA:ranOrder:NO-RAN:PIPP";
        }
    }
    exit($mDataStr);
}

// Clear Pick Flag
elseif (($mFunction != null) && (strtolower($mFunction) == "clearpickflag"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        if ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    $mConnectp = str_replace(":8081/vantec",":8095/pick",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8095/pick/";
    }
    include_once ('allocation.php');
    $mStatus = clearPickDetail($mCurrentUser,$mHost,$mUser,$mPwd,$mDbName);
    exit("OK  -");
}

// Server Call to Post Pick Transaction
elseif (($mFunction != null) && (strtolower($mFunction) == "pickserverprocessed"))
{
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $s=0;
    $e=0;
    $mJsonArray = array();

// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (($k2 == "quantity") || ($k2 == "countQty") || ($k2 == "pickQty"))
            $mJsonArray[$k2] = floatval($v2);
        else
            $mJsonArray[$k2] = $v2;
    }
// Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
    }
    catch(Exception $e)
    {
        exit("FAIL-Json Error");
    }
// POST Operation
    try
    {
// 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();
        curl_setopt($ch, CURLOPT_URL, $mConnectp."processTransaction");
        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  - Update Complete";
            exit($mErrMsg);
//          print_r("FAIL-Message Code=".$mJsonObject.":".$mResult.":".$mResponse.":".$mErrors);
        }
    }
    catch (Exception $e)
    {
        $mErrMsg = ("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
    }
    return;
}

// Flag Pick Detail as Processed
elseif (($mFunction != null) && (strtolower($mFunction) == "pickprocessed"))
{
    $mErrMsg = "";
    $mToPlt = "";
    $mToLocHash = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "pickdetailid")
            $mPickDtlId = trim($v2);
        elseif (strtolower($k2) == "inventorymasterid")
            $mPickInvId = trim($v2);
        elseif (strtolower($k2) == "plt")
            $mToPlt = trim($v2);
        elseif (strtolower($k2) == "serialreference")
            $mSerialReference = trim($v2);
        elseif (($k2 == "quantity") || ($k2 == "countqty") || ($k2 == "pickqty"))   
            $mPickQty = floatval($v2);
        elseif (strtolower($k2) == "tolocationhashcode")
            $mToLocHash = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    include_once ('allocation.php');
    $mStatus = updatePickDetail($mHost,$mUser,$mPwd,$mDbName,$mPickDtlId,$mPickInvId,$mSerialReference,$mPickQty,$mCurrentUser,$mTransactionTypeId,$mToPlt,$mToLocHash,$mConnect);
    exit($mStatus);
}

// Validate Pick Serial
elseif (($mFunction != null) && ($mFunction=="validatepickserial"))
{
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Set default error message
    $mErrMsg = "FAIL-Serial does not exist";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mPartNumber = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "partnumber")
            $mPartNumber = ($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = ($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = (trim($v2));
    }
// Test for existence of multi Serials on Inventory
    if ($mPartNumber == "")
    {
        $mDataQuery = "SELECT
                inventory_master.id AS id,
                inventory_master.requires_inspection AS inspect,
                part.part_number AS part_number
            FROM inventory_master
                JOIN part ON inventory_master.part_id=part.id
                LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id
            WHERE
                inventory_master.serial_reference='{$mSerialReference}'
                AND (inventory_master.inventory_qty) > 0
                AND (
                    inventory_master.inventory_status_id IS null
                    OR (
                            inventory_status.non_pickable<>1
                            OR lower(inventory_status.inventory_status_code) IN('ok','lost','noran','qtine')
                        )
                    )
            LIMIT 2";

        if (!mysqli_query($mConnection,$mDataQuery))
        {
            exit("FAIL-" . mysqli_error($mConnection) . "-" . $mDataQuery);
        }

        $mData = mysqli_query($mConnection,$mDataQuery);
        $i = 0;
        $mInspect = "";

        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $i++;
            $mInspect = ($mRow['inspect']);
            $mPartNumber = strtoupper(($mRow['part_number']));
        }

        $mPartWeight = getPartNumberWeight($mPartNumber, $mConnection);

        if ($i == 0)
        {
            $mDataStr = "FAIL-Serial is not Available";
        }

// Multiple Serials - Prompt for Part Number
        if ($i > 1)
        {
            if ($mTransactionTypeId == "PBTM")
            {
                $mDataStr = "DATA:serialReference:{$mSerialReference}::skippartNumber,partNumber:,partWeight:{$mPartWeight}";
            }
            else
            {
                $mDataStr = "DATA:serialReference:{$mSerialReference}::skip,partNumber:,partWeight:{$mPartWeight}";
            }
        }

        if ($i == 1)
        {
            if ($mInspect == "1")
            {
                $mDataStr = "FAIL-Serial is flagged for inspection";
            }
            else
            {
                $mDataStr = "DATA:serialReference:{$mSerialReference},partNumber:{$mPartNumber},partWeight:{$mPartWeight}";
            }
        }

//      mysqli_close($mConnection);
//      exit($mDataStr);
        echo $mDataStr;
        return;
    }
// Validate Part / Serial
    else
    {
        $mDataQuery = "SELECT
                inventory_master.id AS id,
                inventory_master.requires_inspection AS inspect,
                part.part_number AS part_number
            FROM inventory_master
                JOIN part ON inventory_master.part_id = part.id
                LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id
            WHERE
                inventory_master.serial_reference='{$mSerialReference}'
                AND (inventory_master.inventory_qty) > 0
                AND (part.part_number='{$mPartNumber}'
                OR part.jis_supply_group='{$mPartNumber}')
                AND (
                        inventory_master.inventory_status_id IS null
                        OR (
                                inventory_status.non_pickable<>1
                                OR lower(inventory_status.inventory_status_code) IN ('ok','lost','noran')
                            )
                    )
            LIMIT 1";

        $mData = mysqli_query($mConnection,$mDataQuery);
        $i = 0;
        $mInspect = "";

        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $i++;
            $mInspect = ($mRow['inspect']);
        }
    }
//  mysqli_close($mConnection);
    if ($i == 0)
    {
        if ($mPartNumber == "")
            $mDataStr = "FAIL-Serial is not Available";
        else
            $mDataStr = "FAIL-Serial or Part is not Available";
        exit($mDataStr);
    }
    if ($mInspect == "1")
    {
        $mDataStr = "FAIL-Serial is flagged for inspection";
        exit($mDataStr);
    }
//  mysqli_close($mConnection);
    $mDataStr = "";
    If ($i == 1)
    {
        $mStatus = "OK  -";
    }
    else
    {
        $mStatus = $mErrMsg." ".$mPartNumber;
    }
}

// Pick Aisle Summary
elseif (($mFunction != null) && (strtolower($mFunction) == "pickaislesummary"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "customerreference")
            $mCustomerReference = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
// Set path for Pick Service Call
    $mConnectp = str_replace(":8081/vantec",":8095/pick",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8095/pick/";
    }
    include_once ('allocation.php');
    $mStatus = pickAisleSummary($mHost,$mUser,$mPwd,$mDbName,$mCustomerReference,$mCurrentUser,$mTransactionTypeId,$mConnectp);
    exit($mStatus);
}

// Skip / Resequence Current Pick Task
elseif (($mFunction != null) && ($mFunction == "resequencepick"))
{
    $mReference = "";
    $mToPlt = "";
    $mTrys = "0";
    $mErrMsg = "";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    
//  exit("FAIL-TEST ".$mFilter);
    
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "reference")
            $mReference = $v2;
        elseif (strtolower($k2) == "pickdetailid")
            $mPickDtlId = strtoupper($v2);
        elseif (strtolower($k2) == "locationcode")
            $mLocationCode = strtoupper($v2);
        elseif (strtolower($k2) == "aislecode")
            $mAisle = $v2;
        elseif (strtolower($k2) == "toplt")
            $mToPlt = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
    if ($mReference == "")
    {
        exit("FAIL-Invalid Reference");
    }
    
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Update Pick Status
    $mDataQuery = "SELECT document_reference, inventory_master_id, qty_allocated FROM pick_detail WHERE id=".$mPickDtlId." LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    $mData = mysqli_query($mConnection,$mDataQuery);
    $mDocumentRef = "";
    $mInvId = "";
    $mAlcQty = 0;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mDocumentRef = $mRow['document_reference'];
        $mInvId = $mRow['inventory_master_id'];
        $mAlcQty = $mRow['qty_allocated'];
    }
    if ($mDocumentRef != "")
    {
        $mDataQuery = "UPDATE inventory_master SET allocated_qty=CASE WHEN allocated_qty>".$mAlcQty." THEN allocated_qty-".$mAlcQty." ELSE 0 END, available_qty=inventory_qty-(allocated_qty+hold_qty) WHERE id=".$mInvId." LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $mDataQuery = "UPDATE pick_detail SET in_use_by='SKIP',last_updated_date=now(),last_updated_by='".$mCurrentUser."-SKIP' WHERE document_reference='".$mDocumentRef."' AND processed=0";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        include_once ('allocation.php');
        $mErrMsg = getPick($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mReference,$mAisle,$mConnectp,$mToPlt);
        $mDataQuery = "UPDATE pick_detail SET in_use_by='',last_updated_date=now(),last_updated_by='".$mCurrentUser."' WHERE document_reference='".$mDocumentRef."' AND processed=0";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    }
// Get Highest Pick Sequence for this Pick
// ...
    $mPickPriority = 999;
    $mDataQuery = "SELECT max(pick_detail.pick_priority) AS pick_priority FROM pick_detail JOIN pick_body ON pick_detail.pick_body_id=pick_body.id JOIN pick_header ON pick_body.pick_header_id=pick_header.id WHERE pick_header.customer_reference ='".$mReference."' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    $mData = mysqli_query($mConnection,$mDataQuery);        
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mPickPriority = ($mRow['pick_priority']);
        $mPickPriority = (int)$mPickPriority+1;
        if ($mPickPriority < 50)
            $mPickPriority = (int)$mPickPriority+50;
    }
// Update Pick Priority
    $mDataQuery = "UPDATE pick_detail SET pick_priority = ".$mPickPriority.",in_use_by='',last_updated_date=now(),last_updated_by='".$mCurrentUser."-SKIP' WHERE id=".$mPickDtlId." LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    $mConnectp = str_replace(":8081/vantec",":8095/pick",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8095/pick/";
    }
//  include_once ('allocation.php');
    $mErrMsg = getPick($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mReference,$mAisle,$mConnectp,$mToPlt);
    if ($mErrMsg == "")
        exit("OK  -");
    else
        exit($mErrMsg);
}

// Skip / Resequence Current Pick Task
elseif (($mFunction != null) && ($mFunction == "lostserial"))
{
    $mInvId = "";
    $mToPlt = "";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    
//  exit("FAIL-TEST ".$mFilter);
    
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "reference")
            $mReference = $v2;
        elseif ($k2 == "invid")
            $mInvId = strtoupper($v2);
        elseif ($k2 == "aislecode")
            $mAisle = $v2;
        elseif ($k2 == "toplt")
            $mToPlt = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
    
    if ($mReference == "")
    {
        exit("FAIL-Invalid Reference");
    }
    
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());

// Update inventory Status
    $mDataQuery = "UPDATE inventory_master SET inventory_status_id = (SELECT id FROM inventory_status WHERE lower(inventory_status_code)='missing'),last_updated_date=now(),last_updated_by='".$mCurrentUser."-LOST' WHERE id=".$mInvId." LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
// Get Order Header Id & Pick Header Id for re-allocatuion
    $mDataQuery = "SELECT id FROM order_header WHERE customer_reference='".$mReference."' LIMIT 1";
//  $mDataQuery = "SELECT id FROM document_header WHERE document_type='RRM Order' AND customer_reference='".$mReference."' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    $mData = mysqli_query($mConnection,$mDataQuery);
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mOrderHdrId = ($mRow['id']);
    }
    $mDataQuery = "SELECT id FROM pick_header WHERE customer_reference='".$mReference."' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    $mData = mysqli_query($mConnection,$mDataQuery);
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mPickHdrId = ($mRow['id']);
    }
    $mConnectp = str_replace(":8081/vantec",":8095/pick",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8095/pick/";
    }
    include_once ('allocation.php');
    $mErrMsg = allocateOrderLines($mHost,$mUser,$mPwd,$mDbName,$mOrderId, $mPickHdrId, $mCurrentUser,"");
    $mErrMsg = getPick($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mReference,$mAisle,$mConnectp,$mToPlt);
    if ($mErrMsg == "")
        exit("OK  -");
    else
        exit($mErrMsg);
}

// Validate Pick Pallet
elseif (($mFunction != null) && ($mFunction == "validatepickplt"))
{
    $mPlt = "";
    $mErrMsg = "";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;

// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "toplt")
            $mPlt = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
    if (($mPlt == "") || ($mPlt == null))
    {
        exit("FAIL-Blank Pallet is not allowed");
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error()); 
// Check Inventory Status
    $mDataQuery = "SELECT inventory_master.id AS id FROM inventory_master JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE inventory_master.tag_reference='".$mPlt."' AND (inventory_master.inventory_status_id IS null OR lower(inventory_status.inventory_status_code) NOT IN('pkd','plt')) LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);       
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $i++;
    }
    if ($i > 0)
    {
        exit("FAIL-Non-Picked parts on this Pallet");
    }
// Check Pallet Location Type   
    $mDataQuery = "SELECT inventory_master.id AS id FROM inventory_master JOIN tag ON inventory_master.parent_tag_id=tag.id JOIN location ON inventory_master.current_location_id=location.id JOIN location_type ON location.location_type_id=location_type.id WHERE inventory_master.tag_reference='".$mPlt."' AND lower(location_type.location_area)='work' LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);       
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $i++;
    }
    if ($i > 0)
    {
//      exit("FAIL-Pallet is in a Work Area"); 
    }
    if ($mErrMsg == "")
        $mErrMsg = "OK  -validatePickPlt";
    exit ($mErrMsg);
}

// Validate Pick Pallet Status
elseif (($mFunction != null) && ($mFunction == "validatepickpltsts"))
{
    $mPlt = "";
    $mErrMsg = "";
    $mMarQry = "MARQRY";
    $mCount = "";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;

// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    $mVldLocation = "";
    $mLocationHash = "";
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "pltnumber")
            $mPlt = strtoupper($v2);
        elseif ($k2 == "locationhash")
            $mLocationHash = $v2;
        elseif ($k2 == "vldlocation")
            $mVldLocation = $v2;
        elseif ($k2 == "count")
            $mCount = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }
    if (($mPlt == "") || ($mPlt == null))
    {
        exit("FAIL-Blank Pallet is not allowed");
    }
// Check for count not required
    if (strtolower($mCount) != "n")
        $mCount = "";
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error()); 
//  $mDataQuery = "SELECT pallet.id AS id, pallet.created_by AS status FROM pallet WHERE pallet.plt_number='".$mPlt."' LIMIT 1";
    $mDataQuery = "SELECT tag.id AS id, tag.created_by AS status FROM tag WHERE tag.tag_reference='".$mPlt."' LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    $mPltSts = "";
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mPltSts = ($mRow['status']);
        $i++;
    }
    if ($i == 0)
    {
//      exit("FAIL-Invalid Pallet");
    }
    if (($mCount == "") && ($mPltSts != "PI") && ($mPltSts != "OK") && (substr($mPltSts,0,2) != "20"))
    {
//      exit("FAIL-Pallet has not been counted");
    }
// If Pick Pallet - Check TO is closed
/*
    $mDataQuery = "SELECT document_header.id AS id, document_status.document_status_code AS status FROM document_header JOIN document_status ON document_header.document_status_id=document_status.id WHERE document_header.customer_reference_code='".$mPlt."' LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    $mDocSts = "";
    while($mRow = mysqli_fetch_assoc($mData))
    {
        $mDocSts = ($mRow['status']);
        If ((strtolower($mDocSts) == "open") || (strtolower($mDocSts) == "allocated"))
        {
            echo ("FAIL- Pick is not closed");
            return;
        }
    }
*/
    if (($mPltSts == "PI") && ($mVldLocation == ""))
    {
        exit("DATA:toLocationHashCode:".$mMarQry);
    }
    if ($mLocationHash != "")
    {
        $mDataQuery = "SELECT location.id AS id, location.location_code AS location_code FROM location WHERE location.location_hash = '".$mLocationHash."' LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $mLocation = "";
        $i = 0;
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mLocation = ($mRow['location_code']);
            $i++;
        }
        if ($i == 0)
        {
            exit("FAIL-Invalid Location");
        }
        if (($mPltSts == "PI") && ($mLocation != $mMarQry))
        {
            exit("FAIL-Pallet must go to specified Location");
        }       
    }
    exit("OK  -");
}

// Validate Pick Serial
elseif (($mFunction != null) && ($mFunction=="validatemarshallserial"))
{
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Set default error message
    $mErrMsg = "FAIL-Serial does not exist";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mPartNumber = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "partnumber")
            $mPartNumber = strtoupper($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
// Test for existence of multi Serials on Inventory
    if ($mPartNumber == "")
    {
        $mDataQuery = "SELECT inventory_master.id AS id FROM inventory_master LEFT JOIN inventory_status ON inventory_inventory_status_id=inventory_status.id WHERE inventory_master.serial_reference='".$mSerialReference."' AND inventory_master.inventory_qty > 0 AND (lower(inventory_status.inventory_status_code) IN('pkd','lost','plt')) LIMIT 2";
        $mData = mysqli_query($mConnection,$mDataQuery);
        $i = 0;
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $i++;
        }
// Test for Tag_reference
        if ($i == 0)
        {
            if ($mTransactionTypeId == "MTT")
            {               
                $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.serial_reference AS serial_reference, part.part_number FROM inventory_master JOIN part on inventory_master.part_id=part.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 inventory_master.tag_reference='".$mSerialReference."' AND inventory_master.inventory_qty > 0 AND (lower(inventory_status.inventory_status_code) IN('pkd','lost','plt')) LIMIT 1";
                if (!$mData = mysqli_query($mConnection,$mDataQuery))
                    exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
                $i = 0;
                while($mRow = mysqli_fetch_assoc($mData)) 
                {
                    $mSerialReference = $mRow['serial_reference'];
                    $mPartNumber = $mRow['part_number'];
                    $i++;
                }
                if ($i > 0)
                {
                    $mDataStr = "DATA:serialReference:".$mSerialReference."::skiptoLocationHashCode,partNumber:".$mPartNumber.",toLocationHashCode:";
                    exit($mDataStr);
                }
            }
        }
// Multiple Serials - Prompt for Part Number
        if ($i > 1)
        {
            if ($mTransactionTypeId == "PBTM")
                $mDataStr = "DATA:serialReference:".$mSerialReference."::skippartNumber,partNumber:";
            else
                $mDataStr = "DATA:serialReference:".$mSerialReference."::skippartNumber,partNumber:";
            mysqli_close($mConnection);
            exit($mDataStr);
        }
    }
    else
    {
        $mDataQuery = "SELECT inventory_master.id AS id FROM inventory_master JOIN part ON inventory_master.part_id=part.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE inventory_master.serial_reference='".$mSerialReference."' AND inventory_master.inventory_qty > 0 AND (part.part_number='".$mPartNumber."') AND (lower(inventory_status.inventory_status_code) IN('pkd','lost','plt')) LIMIT 1";
        $mData = mysqli_query($mConnection,$mDataQuery);
        $i = 0;
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $i++;
        }
    }
    if ($i == 0)
    {
        if ($mPartNumber == "")
            $mDataStr = "FAIL-Serial is not available";
        else
            $mDataStr = "FAIL-Serial or Part is not available";
//      mysqli_close($mConnection);
        exit($mDataStr);
    }
//  mysqli_close($mConnection);
    $mDataStr = "";
    If ($i == 1)
    {
        $mStatus = "OK  -";
    }
    else
    {
        $mStatus = $mErrMsg." ".$mPartNumber;
    }
}

// Get Inventory By Serial
elseif (($mFunction != null) && ($mFunction == "getserialinventory"))
{
    $mSerialReference = "";
    $mErrMsg = "";

// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;

// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);

// Create Associative Array by Exploding Array Elements on :
    $mPartNumber="";
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "serialreference")
            $mSerialReference = strtoupper($v2);
        elseif ($k2 == "prvserial")
            $mPrvSerial = strtoupper($v2);
        elseif ($k2 == "partnumber")
            $mPartNumber = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }
//  if ($mSerialReference != $mPrvSerial)
//      $mPartNumber = "";

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

    if ($mPartNumber == "")
    {
        $mDataQuery = "SELECT
                inventory_master.*,
                part.part_number AS part_number,
                part.conversion_factor AS conversion_factor,
                location.location_code AS location_code,
                CASE 
                    WHEN inventory_status.inventory_status_code IS NULL THEN 'ok'
                    ELSE inventory_status.inventory_status_code
                END AS status_code,
                pick_header.customer_reference AS pick_customer_reference,
                inventory_master.tag_reference AS tag_reference
            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 pick_detail ON inventory_master.id=pick_detail.inventory_master_id
                LEFT JOIN pick_body ON pick_body.id=pick_detail.pick_body_id
                LEFT JOIN pick_header ON pick_header.id=pick_body.pick_header_id
                LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id
            WHERE inventory_master.serial_reference = '{$mSerialReference}'
            LIMIT 2";
    }
    else
    {
        $mDataQuery = "SELECT
                inventory_master.*,
                part.part_number AS part_number,
                part.conversion_factor AS conversion_factor,
                location.location_code AS location_code,
                CASE 
                    WHEN inventory_status.inventory_status_code IS NULL THEN 'ok'
                    ELSE inventory_status.inventory_status_code
                END AS status_code,
                pick_header.customer_reference AS pick_customer_reference,
                inventory_master.tag_reference AS tag_reference
            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 pick_detail ON inventory_master.id=pick_detail.inventory_master_id
                LEFT JOIN pick_body ON pick_body.id=pick_detail.pick_body_id
                LEFT JOIN pick_header ON pick_header.id=pick_body.pick_header_id
                LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id
            WHERE 
                inventory_master.serial_reference = '{$mSerialReference}'
                AND (part.part_number='{$mPartNumber}') LIMIT 1";
    }

    if (!$mData = mysqli_query($mConnection,$mDataQuery))
    {
        exit("FAIL-" . mysqli_error($mConnection) . "-" . $mDataQuery);
    }

    if ((mysqli_num_rows($mData) == 0) && ($mPartNumber == ""))
    {
        $mDataStr = "FAIL-Invalid Serial";
    }
    elseif ((mysqli_num_rows($mData) == 0) && ($mPartNumber != ""))
    {
        $mDataStr = "FAIL-Invalid Serial or Part";
    }
    elseif (mysqli_num_rows($mData) > 1)
    {
        $mPartWeight = getPartNumberWeight($mPartNumber, $mConnection);
        $mPartNumber = "";
        $mDataStr = "DATA:partNumber:{$mPartNumber},partWeight:{$mPartWeight}:I,locationCode: :,ranOrder: :";
    }
    else
    {
        $i = 0;
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mQty = $mRow['inventory_qty']-$mRow['hold_qty'];

            if ($mRow['conversion_factor'] > 0)
            {
                $mQty = $mQty / $mRow['conversion_factor'];
            }

            if (empty($mRow['tag_reference']))
            {
                $mRow['tag_reference'] = "-";
            }

            $mPartWeight = getPartNumberWeight($mRow['part_number'], $mConnection);

            $mDataStr = "DATA:serialReference:$mSerialReference::clear,partNumber:".$mRow['part_number'].":P,partWeight:".$mPartWeight.",locationCode:".($mRow['location_code'].",ranOrder:".$mRow['ran_or_order'].",quantity:".$mQty.",plt:".$mRow['tag_reference'].",createdDate:".substr($mRow['date_created'],0,10)." by ".$mRow['created_by'].",inventoryStatus:".$mRow['status_code'].",customerReference:".$mRow['pick_customer_reference']);
            $i++;
        }
    }
//  mysqli_close($mConnection);
    exit ($mDataStr);
}

// Validate Location Move
elseif (($mFunction != null) && ($mFunction == "validatelocationmove"))
{
    $mFromLocation = "";
    $mToLocation = "";
    $mErrMsg = "";
    
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;

// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    $mFromLocation = "";
    $mToLocation = "";
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "fromlocation")
            $mFromLocation = strtoupper($v2);
        elseif ($k2 == "tolocation")
            $mToLocation = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }
//    exit("FAIL-TEST1-".$mFilter." ".$mTransactionTypeId);
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error()); 
    if ($mFromLocation != "")
    {
// Validate From Location / Pallet
        $mDataQuery = "SELECT location.id AS location_id, location_code, multi_part_location AS multi_part FROM location WHERE location_hash ='".$mFromLocation."' LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
// No Location test for Pallet or Serial
        if (mysqli_num_rows($mData) == 0)
        {
            $mDataQuery = "SELECT field_name, prefix_name FROM default_setting";
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
            $i = 0;
            $mPalletPrefix = "";
            $mSerialPrefix = "";
            while($mRow = mysqli_fetch_assoc($mData)) 
            {
                if (strtolower($mRow['field_name']) == "pallet")
                    $mPalletPrefix=($mRow['prefix_name']);
                if (strtolower($mRow['field_name']) == "serialreference")
                    $mSerialPrefix=($mRow['prefix_name']);
            }
// Pallet
            if (strpos($mPalletPrefix,substr($mFromLocation,0,1)) !== false)
            {
                $mFromLocation=substr($mFromLocation,1);
                $mDataQuery = "SELECT tag.id AS id,inventory_master.current_location_id AS location_id,location.location_code AS location_code, location.multi_part_location AS multi_part FROM tag JOIN inventory_master ON tag.id=inventory_master.parent_tag_id JOIN location ON inventory_master.current_location_id=location.id WHERE tag.tag_reference='".$mFromLocation."' LIMIT 1";
                if (!$mData = mysqli_query($mConnection,$mDataQuery))
                    exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
                if (mysqli_num_rows($mData) == 0)
                {
                    exit("FAIL-pallet has no location");
                }
                $mFrom = "P";
            }
            else
            {       
// No Pallet test for Serial
                if (strpos($mSerialPrefix,substr($mFromLocation,0,1)) !== false)
                {
                    $mFromLocation=substr($mFromLocation,1);
                    $mDataQuery = "SELECT inventory_master.id AS id,inventory_master.current_location_id AS location_id, location.location_code, location.multi_part_location AS multi_part 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 inventory_master.serial_reference='".$mFromLocation."' AND (inventory_master.inventory_status_id IS null OR lower(inventory_status.inventory_status_code) NOT IN('pkd','plt')) LIMIT 1";
                    if (!$mData = mysqli_query($mConnection,$mDataQuery))
                        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
                    if (mysqli_num_rows($mData) == 0)
                    {
                        exit("FAIL-Serial has no location");
                    }
                    else
                    {
                        $mFrom = "S";
                    }
                }
                else
                {
                    exit("FAIL-Invalid From Location");
                }
            }
        }
        else
        {
            $mFrom = "L";
        }
        if ($mFrom == "")
            exit("FAIL-Invalid From Location");
// Get Location id & mixed_part
        $mFromMultiPart = "";
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mFromLocationId = ($mRow['location_id']);
            $mFromLocationCode = ($mRow['location_code']);
            $mFromMultiPart = ($mRow['multi_part']);
        }
    }
// check TTM location_type
    if ($mTransactionTypeId == "TTM")
    {
        $mLocationType="";
        $mDataQuery = "SELECT location_type_code FROM location_type JOIN location ON location.location_type_id=location_type.id WHERE location.location_code='$mFromLocationCode' LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        if (mysqli_num_rows($mData) > 0)
        {
            list($mLocationType)=mysqli_fetch_row($mData);
        }
        if($mLocationType != "TRL")
        {
            exit("FAIL-Invalid Location Type");
        }
    }
// To Location
    if ($mToLocation != "")
    {
// Validate To Location / Pallet
        $mDataQuery = "SELECT id AS location_id, location_code, multi_part_location AS multi_part FROM location WHERE location_hash ='".$mToLocation."' LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
// No Location test for Pallet
        if (mysqli_num_rows($mData) == 0)
        {
            $mDataQuery = "SELECT field_name, prefix_name FROM default_setting";
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
            $i = 0;
            $mPalletPrefix = "";
            $mSerialPrefix = "";
            while($mRow = mysqli_fetch_assoc($mData)) 
            {
                if (strtolower($mRow['field_name']) == "pallet")
                    $mPalletPrefix=($mRow['prefix_name']);
                if (strtolower($mRow['field_name']) == "serialreference")
                    $mSerialPrefix=($mRow['prefix_name']);
            }
// Pallet
            if (strpos($mPalletPrefix,substr($mToLocation,0,1)) !== false)
            {
                $mToLocation=substr($mToLocation,1);
                $mDataQuery = "SELECT tag.id AS id,inventory_master.current_location_id AS location_id FROM tag LEFT JOIN inventory_master ON tag.id=inventory_master.parent_tag_id WHERE tag.tag_reference='".$mToLocation."' LIMIT 1";
                if (!$mData = mysqli_query($mConnection,$mDataQuery))
                    exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
                if (mysqli_num_rows($mData) > 0)
                {
                    $i = 0;
                    while($mRow = mysqli_fetch_assoc($mData)) 
                    {
                        if($mRow['location_id'] != null)
                            $i++;
                    }
                    if ($i > 0)
                        exit("FAIL-pallet is in use");
                }
                else
                    exit("FAIL-Invalid To Pallet");
            
                $mTo = "P";
            }
            else
            {
                exit("FAIL-Invalid To Location");
            }
        }
        else
        {
            $mTo = "L";
        }
        if ($mTo == "")
            exit("FAIL-Invalid To Location");
    }
// Locate to Pallet
    if ($mTo == "P")
    {
//      include_once ('location.php');
//      $mErrMsg = processLocToPlt($mFromLocationId,$mToLocationId,$mFromLocationCode,$mToLOcationCode,$mCurrentUser);
        include_once ("transaction.php");
        $mErrMsg =  postLocToLoc($mFilter,$mHost,$mUser,$mPwd,$mDbName);
        exit($mErrMsg);
//      exit("FAIL-processPallet");
    }
// Locate to Location
    if ($mTo == "L")
    {
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $i = 0;
        $mToLocationId = "";
        $mToMultiPart = "";
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mToLocationId = ($mRow['location_id']);
            $mToLocationCode = ($mRow['location_code']);
            $mToMultiPart = ($mRow['multi_part']);
        }
        if ($mTransactionTypeId == "TTM")
        {
            include_once ('location.php');
            $mErrMsg = processTtm($mFromLocationId,$mToLocationId,$mFromLocationCode,$mToLocationCode,$mCurrentUser);
                exit($mErrMsg);
//            exit("OK  -validatelocationmove");
        }        
// Multi-Part To-Loc
        if ($mToMultiPart == 1)
        {
//          include_once ('location.php');
//          $mErrMsg = processLocToLoc($mFromLocationId,$mToLocationId,$mFromLocationCode,$mToLocationCode,$mCurrentUser);
            include_once ("transaction.php");
            $mErrMsg =  postLocToLoc($mFilter,$mHost,$mUser,$mPwd,$mDbName);
            exit($mErrMsg);
//          exit("FAIL-processLocLoc1");
        }
        else
        {
// Check for Mixed Parts in From
            $mDataQuery = "SELECT inventory_master.part_id FROM inventory_master LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE current_location_id=".$mFromLocationId." AND (inventory_master.inventory_status_id IS null OR LOWER(inventory_status.inventory_status_code) NOT IN('pkd','plt')) LIMIT 1";
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
            $mPartId = "";
            while($mRow = mysqli_fetch_assoc($mData)) 
            {
                $mPartId = ($mRow['part_id']);
            }
            if ($mPartId != "")
            {
                $mDataQuery = "SELECT inventory_master.id FROM inventory_master LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE current_location_id=".$mFromLocationId." AND part_id<>".$mPartId." AND (inventory_master.inventory_status_id IS null OR LOWER(inventory_status.inventory_status_code) NOT IN('pkd','plt')) LIMIT 1";
                if (!$mData = mysqli_query($mConnection,$mDataQuery))
                    exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
                if (mysqli_num_rows($mData) > 0)
                    exit("FAIL-Location Has Mixed Parts");

                $mDataQuery = "SELECT inventory_master.part_id FROM inventory_master LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE location_id=".$mToLocationId." AND part_id<>".$mPartId." AND (inventory_master.inventory_status_id IS null OR LOWER(inventory_status.inventory_status_code) NOT IN('pkd','plt')) LIMIT 1";
                if (!$mData = mysqli_query($mConnection,$mDataQuery))
                    exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
                if (mysqli_num_rows($mData) > 0)
                    exit("FAIL-Location already contains serials");
            }           
//          include_once ('location.php');
//          $mErrMsg = processLocToLoc($mFromLocationId,$mToLocationId,$mFromLocationCode,$mToLocationCode,$mCurrentUser);
            include_once ("transaction.php");
            $mErrMsg =  postLocToLoc($mFilter,$mHost,$mUser,$mPwd,$mDbName);
            exit($mErrMsg);
//          exit("FAIL-processLocLoc2");
        }           
    }
    if ($mErrMsg == "")
        $mErrMsg = "OK  -";
    exit ($mErrMsg);
}

// Flag Empty Location
elseif (($mFunction != null) && ($mFunction == "flagemptylocation"))
{
    $mLocationId = "";
    $mLocationCode = "";
    $mToLocationId = "";
    $mToLocationCode = "";
    $mErrMsg = "";
    $mInvCount = 0;
    
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;

// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "locationid")
            $mLocationId = $v2;
        elseif ($k2 == "locationcode")
            $mLocationCode = strtoupper($v2);
        elseif ($k2 == "tolocationid")
            $mToLocationId = $v2;
        elseif ($k2 == "tolocationcode")
            $mToLocationCode = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }

// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        die("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    $mDataQuery = "";
// Check for Inventory in Location  
    if ($mLocationId != "")
    {
        $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=".$mLocationId." 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";
    }
    elseif ($mLocationCode != "")
    {
        $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='".$mLocationCode."' OR location.location_hash='".$mLocationCode."') 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))
            exit("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 (($mLocationId == "") && ($mLocationCode != ""))
            {
                $mDataQuery = "SELECT location.id AS id FROM location WHERE (location_hash ='".$mLocationCode."' OR location_code = '".$mLocationCode."') LIMIT 1";
                if (!$mData = mysqli_query($mConnection,$mDataQuery))
                    exit("FAIL-2".mysqli_error($mConnection)."-".$mDataQuery);
                $i=0;
                while($mRow = mysqli_fetch_assoc($mData)) 
                {
                    $mLocationId = ($mRow['id']);
                    $i++;
                }
            }

            if ($mLocationId != "")
            {
                $mDataQuery = "UPDATE location SET location.filling_status_id=(SELECT id FROM location_filling_status WHERE lower(filling_code) = 'empty') WHERE location.id=".$mLocationId." LIMIT 1";
                if (!mysqli_query($mConnection,$mDataQuery))
                    exit ("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_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";
        }
        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))
                exit("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))
                        exit("FAIL-5".mysqli_error($mConnection)."-".$mDataQuery);
                    $i=0;
                    while($mRow = mysqli_fetch_assoc($mData)) 
                    {
                        $mToLocationId = ($mRow['id']);
                        $i++;
                    }
                }

                if ($mToLocationId != "")
                {
//                  $mDataQuery = "UPDATE location SET location.filling_status_id=(SELECT id FROM location_filling_status WHERE lower(filling_code) = 'filling') WHERE location.id=".$mToLocationId;
//                  $mDataQuery .= " AND location.filling_status_id<>(SELECT id FROM location_filling_status WHERE lower(filling_code) NOT IN('full','closed','qtine'))";
//                  $mDataQuery .= " LIMIT 1";
//                  if (!mysqli_query($mConnection,$mDataQuery))
//                      exit ("FAIL-6".mysqli_error($mConnection)."-".$mDataQuery);
                $mDataQuery = "SELECT id, filling_code FROM location_filling_status";
                if (!$mData = mysqli_query($mConnection,$mDataQuery))
                    return("FAIL-6".mysqli_error($mConnection)."-".$mDataQuery);
                $i=0;
                $mEmptyId = null;
                $mFillId = null;
                $mFullId = null;
                $mClosedId = null;
                $mQtineId = null;
                $mNotIn = "";
                while($mRow = mysqli_fetch_assoc($mData)) 
                {
                    if (strtolower($mRow['filling_code']) == "empty")
                        $mEmptyId = ($mRow['id']);
                    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 != null)
                    $mdataQuery .= " AND location.filling_status_id <> ".$mFullId;
                if ($mClosedId != null)
                    $mdataQuery .= " AND location.filling_status_id <> ".$mClosedId;
                if ($mQtineId != null)
                    $mdataQuery .= " AND location.filling_status_id <> ".$mQtineId;
                $mDataQuery .= " LIMIT 1";
                if (!mysqli_query($mConnection,$mDataQuery))
                    return ("FAIL-7".mysqli_error($mConnection)."-".$mDataQuery);
                }       
            }
        }
    }
    exit("OK  -Location Filling Status");
}
    
// PI Part Prompt
elseif (($mFunction != null) && (strtolower($mFunction) == "pipartprompt"))
{
    $mErrMsg = "";
    $mPiPartNumber="";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "pipartnumber")
            $mPiPartNumber = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
//  exit("FAIL-piPartPrompt");
    include_once ('picount.php');
    $mStatus = piPartPrompt($mHost,$mUser,$mPwd,$mDbName,$mPiPartNumber,$mCurrentUser);
    exit($mStatus);
}

// PI Next Location
elseif (($mFunction != null) && (strtolower($mFunction) == "pinextlocation"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "pipartnumber")
            $mPiPartNumber = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == 'fromlocation')
            $mFromLocation = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
//    exit("FAIL-".$mFilter);
    include_once ('picount.php');
    $mStatus = piNextLocation($mHost, $mUser, $mPwd, $mDbName, $mPiPartNumber, $mCurrentUser, $mFromLocation);
    if (substr($mStatus,0,4)=="FAIL")
        exit($mStatus);
    else
        exit("DATA:locationHashCode:".$mStatus);
}

// PI Part Update
elseif (($mFunction != null) && (strtolower($mFunction) == "pipartupdate"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "partnumber")
            $mPiPartNumber = trim($v2);
        elseif ($k2 == "locationcode")
            $mPiLocation = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    include_once ('picount.php');
    $mStatus = piPartUpdate($mHost, $mUser, $mPwd, $mDbName, $mPiPartNumber, $mPiLocation, $mCurrentUser);
    exit($mStatus);
}

// PI Part Serial Processing
elseif (($mFunction != null) && (strtolower($mFunction) == "pipartserial"))
{
    $mErrMsg = "";
// Set path for Pi Service Call
    $mConnectp = str_replace(":8081/vantec",":8091/pi",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8091/pi/";
    }
    
    include_once ('picount.php');
    $mStatus = piPartSerial($mHost, $mUser, $mPwd, $mDbName, $mFilter, $mCurrentUser, $mConnectp);
    exit($mStatus);
}

// PI Part Serial Processing
elseif (($mFunction != null) && (strtolower($mFunction) == "pipartloc"))
{
    $mErrMsg = "";
// Set path for Pi Service Call
    $mConnectp = str_replace(":8081/vantec",":8091/pi",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8091/pi/";
    }

    include_once ('picount.php');
    $mStatus = piPartSummary($mHost, $mUser, $mPwd, $mDbName, $mPiPartNumber, $mCurrentUser, $mTransactionTypeId, $mConnectp);
    exit($mStatus);
}

// PI Close PI Part Location
elseif (($mFunction != null) && (strtolower($mFunction) == "closepartpi"))
{
    $mErrMsg = "";
// Set path for Pi Service Call
    $mConnectp = str_replace(":8081/vantec",":8091/pi",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8091/pi/";
    }

    include_once ('picount.php');
    $mStatus = piPartLocClose($mHost, $mUser, $mPwd, $mDbName, $mFilter, $mCurrentUser, $mConnectp);
    if (empty($mStatus))
        $mStatus = "FAIL-PI Count Error";
    exit($mStatus);
}

// PI Location Box Count
elseif (($mFunction != null) && ($mFunction == "piloccount"))
{
    $mErrMsg = "";
// Set path for Pi Service Call
    $mConnectp = str_replace(":8081/vantec",":8091/pi",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8091/pi/";
    }

    $mCurrentUser = ''; // current user will be loaded from $mFilter inside piLocCount()
    include_once ('picount.php');
    $mStatus = piLocCount($mHost, $mUser, $mPwd, $mDbName, $mFilter, $mCurrentUser, $mConnectp);
    exit($mStatus);
}

// Validate Rec.Cts Quantity
elseif (($mFunction != null) && ($mFunction == "rctsqty"))
{   
    $mErrMsg = "";
    
    $mSerialReference = "";
    $mPartNumber = "";
    $mQuantity = "";
    
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;

// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "serialreference")
            $mSerialReference = strtoupper($v2);
        elseif (strtolower($k2) == "partnumber")
            $mPartNumber = strtoupper($v2);
        elseif ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty"))
            $mQty = floatval($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        die("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
        
// Get Document Id for Status 'open'    
    $mDataQuery = "SELECT id AS id FROM document_status WHERE lower(document_status_code) = 'open' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);   
    $mData = (mysqli_query($mConnection,$mDataQuery));
    $mRow = mysqli_fetch_assoc($mData);
    $mDocStsId = ($mRow['id']);

// Get Receipt Detail for scanned Serial / Part 
    $mRctDtlQty = "";
    $mRctStsId = "";
    $mDataQuery = "SELECT receipt_detail.id AS id, receipt_detail.received_qty AS received_qty, receipt_header.document_status_id AS document_status_id";
    $mDataQuery .= ",document_status.document_status_code AS document_status_code";
    $mDataQuery .= " FROM receipt_detail";
    $mDataQuery .= " JOIN receipt_body ON receipt_detail.receipt_body_id=receipt_body.id";
    $mDataQuery .= " JOIN receipt_header ON receipt_body.receipt_header_id=receipt_header.id";
    $mDataQuery .= " JOIN document_status ON receipt_header.document_status_id=document_status.id";
    $mDataQuery .= " WHERE receipt_detail.part_number='".$mPartNumber."' AND receipt_detail.serial_reference='".$mSerialReference."'";
//  $mDataQuery .= " AND lower(document_status.document_status_code) IN('open', 'complete')";
    $mDataQuery .= " ORDER BY receipt_header.date_created DESC";
    $mDataQuery .= " LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    $mData = (mysqli_query($mConnection,$mDataQuery));
// If No Receipt Check Inventory Qty.
    if (mysqli_num_rows($mData) == 0)
    {
        $mDataQuery = "SELECT (inventory_master.inventory_qty-inventory_master.hold_qty) AS received_qty FROM inventory_master JOIN part ON inventory_master.part_id=part.id WHERE part.part_number='".$mPartNumber."' AND inventory_master.serial_reference='".$mSerialReference."' LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $mData = (mysqli_query($mConnection,$mDataQuery));
    }
    $mRow = mysqli_fetch_assoc($mData);
    $mRctDtlQty = ($mRow['received_qty']);
    $mRctStsId = ($mRow['document_status_id']);

// Check Status 
    if ($mRctStsId != $mDocStsId)
    {
//      exit("FAIL-The Receipt is not Open.");
    }
    
// Get Part Conversion Factor
    $mConvFactor = 1;
    $mDataQuery = "SELECT conversion_factor AS conversion_factor FROM part WHERE (part.part_number = '".$mPartNumber."') LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);   
    $mData = (mysqli_query($mConnection,$mDataQuery));
    $mRow = mysqli_fetch_assoc($mData);
    $mConvFactor = ($mRow['conversion_factor']);
    
    if ($mRctDtlQty != "")
    {
//      if (intval($mQty*$mConvFactor) != $mRctDtlQty)
        $mConvQty = $mRctDtlQty / $mConvFactor;
        if ($mConvQty != $mQty)
        {
            exit("FAIL-Scanned Qty does not match Receipt Qty.".$mQty."-".$mConvQty."-".($mConvQty-$mQty));
        }
        else
        {
            exit("OK  -Qty. is ok.");
        }
    }
    else
    {
        exit("OK  -Qty. is ok.");
    }   
}

// RCTS Locate
elseif (($mFunction != null) && ($mFunction == "postrcts"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $s=0;
    $e=0;
    $mJsonArray = array();
// Test for blank input
    if (($mFilter == "") || ($mFilter == null))
        exit("OK  -");
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    $i = 0;
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty"))
            $mJsonArray[strtolower($k2)] = floatval($v2);
        elseif (strtolower($k2) == "jserialreference")
            $mJsonArray['serialreference'] = $v2;
        else
            $mJsonArray[strtolower($k2)] = $v2;
        if (($v2 != "") && ($v2 != 0))
            $i++;
    }

// All Values are blank
    if ($i == 0)
        exit("OK  -");
// Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
    }
    catch(Exception $e)
    {
        exit("FAIL-Json Error");
    }
// Set path for Service Call
    $mConnectp = str_replace(":8081/vantec",":8081/vantec",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8081/vantec/";
    }
    include_once ('transaction.php');
    $mStatus = postRcts($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
// Set Location Filling Status
    $mStatus = locationFillingSts("","","",$mJsonArray['tolocationhashcode'],$mHost,$mUser,$mPwd,$mDbName,$mJsonArray['currentUser']);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
// Close Replen Tasks
    include_once ('replen.php');
    $mStatus = closeReplen($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
    exit("OK  -rctcts");
}

// FQA Locate
elseif (($mFunction != null) && ($mFunction == "postfqa"))
{
    $mErrMsg = "";
    $mDocumentReference="";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $s=0;
    $e=0;
    $mJsonArray = array();
// Test for blank input
    if (($mFilter == "") || ($mFilter == null))
        exit("OK  -");
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    $i = 0;
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty"))
            $mJsonArray[strtolower($k2)] = floatval($v2);
        elseif (strtolower($k2) == "jserialreference")
            $mJsonArray['serialreference'] = $v2;
        else
            $mJsonArray[strtolower($k2)] = $v2;
        if (($v2 != "") && ($v2 != 0))
            $i++;
    }
    
// All Values are blank
    if ($i == 0)
        exit("OK  -");
// Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
    }
    catch(Exception $e)
    {
        exit("FAIL-Json Error");
    }

// Set path for Service Call
    $mConnectp = str_replace(":8081/vantec",":8081/vantec",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8081/vantec/";
    }
    include_once ('transaction.php');
    $mStatus = postRcts($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
// Set Location Filling Status
    $mStatus = locationFillingSts("","","",$mJsonArray['tolocationhashcode'],$mHost,$mUser,$mPwd,$mDbName,$mJsonArray['currentUser']);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
// Close Replen Tasks
    include_once ('replen.php');
    $mStatus = closeReplen($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
    
// Post fqa IDOC
//  http://172.16.1.70:8092/screen/writeQAINAndQAOUTMessage?serialNumber=PARTA&&partNumber=PARTA&&status=QAIN
// Replace default Server Tomcat Service
    $mConnectp = str_replace(":8081/vantec",":8092/screen",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8092/screen/";
    }
    $ch = curl_init();
    try
    {
        curl_setopt($ch, CURLOPT_URL, $mConnectp."writeQAINAndQAOUTMessage?serialNumber=".$mJsonArray['serialreference']."&partNumber=".$mJsonArray['partnumber']."&status=QOUT");
        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);
    }           
    
    exit("OK  -postfqa");
}

// TQA Locate
elseif (($mFunction != null) && ($mFunction == "posttqa"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $s=0;
    $e=0;
    $mJsonArray = array();
// Test for blank input
    if (($mFilter == "") || ($mFilter == null))
        exit("OK  -");
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    $i = 0;
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty"))
            $mJsonArray[strtolower($k2)] = floatval($v2);
        elseif (strtolower($k2) == "jserialreference")
            $mJsonArray['serialreference'] = $v2;
        else
            $mJsonArray[strtolower($k2)] = $v2;
        if (($v2 != "") && ($v2 != 0))
            $i++;
    }

// All Values are blank
    if ($i == 0)
        exit("OK  -");
// Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
    }
    catch(Exception $e)
    {
        exit("FAIL-Json Error");
    }
// Set path for Service Call
    $mConnectp = str_replace(":8081/vantec",":8081/vantec",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8081/vantec/";
    }
    include_once ('transaction.php');
    $mStatus = postRcts($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
// Set Location Filling Status
    $mStatus = locationFillingSts("","","",$mJsonArray['tolocationhashcode'],$mHost,$mUser,$mPwd,$mDbName,$mJsonArray['currentUser']);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
// Close Replen Tasks
    include_once ('replen.php');
    $mStatus = closeReplen($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
    exit("OK  -posttqa");
}

// AFTP Locate
elseif (($mFunction != null) && ($mFunction == "postaftp"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $s=0;
    $e=0;
    $mJsonArray = array();
// Test for blank input
    if (($mFilter == "") || ($mFilter == null))
        exit("OK  -");
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    $i = 0;
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty"))
            $mJsonArray[strtolower($k2)] = floatval($v2);
        elseif (strtolower($k2) == "jserialreference")
            $mJsonArray['serialreference'] = $v2;
        else
            $mJsonArray[strtolower($k2)] = $v2;
        if (($v2 != "") && ($v2 != 0))
            $i++;
    }
// Set To Location Code
    $mJsonArray['tolocationhashcode'] = "AFTMAR";
// All Values are blank
    if ($i == 0)
        exit("OK  -");
// Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
    }
    catch(Exception $e)
    {
        exit("FAIL-Json Error");
    }
// Set path for Service Call
    $mConnect = str_replace(":8081/vantec",":8081/vantec",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8081/vantec/";
    }
    include_once ('transaction.php');
    $mStatus = postPiecePick($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
// Set Location Filling Status
    $mStatus = locationFillingSts("","","",$mJsonArray['tolocationhashcode'],$mHost,$mUser,$mPwd,$mDbName,$mJsonArray['currentUser']);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
// Close Replen Tasks
    include_once ('replen.php');
    $mStatus = closeReplen($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
    exit("OK  -posttqa");
}

// RTND Locate
elseif (($mFunction != null) && ($mFunction == "postrtnd"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $mJsonArray = array();
// Test for blank input
    if (($mFilter == "") || ($mFilter == null))
        exit("OK  -");
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    $i = 0;
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty"))
            $mJsonArray[strtolower($k2)] = floatval($v2);
        elseif (strtolower($k2) == "jserialreference")
            $mJsonArray['serialreference'] = $v2;
        else
            $mJsonArray[strtolower($k2)] = $v2;
        if (($v2 != "") && ($v2 != 0))
            $i++;
    }
// All Values are blank
    if ($i == 0)
        exit("OK  -");
// Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
    }
    catch(Exception $e)
    {
        exit("FAIL-Json Error");
    }
// Set path for Service Call
    $mConnect = str_replace(":8081/vantec",":8081/vantec",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8081/vantec/";
    }
    include_once ('transaction.php');
    $mStatus = postTransaction($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
// Set Location Filling Status
    $mStatus = locationFillingSts("","","",$mJsonArray['tolocationhashcode'],$mHost,$mUser,$mPwd,$mDbName,$mJsonArray['currentUser']);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
// Close Replen Tasks
    include_once ('replen.php');
    $mStatus = closeReplen($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
    exit("OK  -posttqa");
}

// CTS Locate
elseif (($mFunction != null) && ($mFunction == "postcts"))
{
        $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $s=0;
    $e=0;
    $mJsonArray = array();
// Test for blank input
    if (($mFilter == "") || ($mFilter == null))
        exit("OK  -");
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    $i = 0;
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty"))
            $mJsonArray[strtolower($k2)] = floatval($v2);
        elseif (strtolower($k2) == "jserialreference")
            $mJsonArray['serialreference'] = $v2;
        else
            $mJsonArray[strtolower($k2)] = $v2;
        if (($v2 != "") && ($v2 != 0))
            $i++;
    }

// All Values are blank
    if ($i == 0)
        exit("OK  -");
// Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
    }
    catch(Exception $e)
    {
        exit("FAIL-Json Error");
    }
// Set path for Service Call
    $mConnect = str_replace(":8081/vantec",":8081/vantec",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8081/vantec/";
    }
    include_once ('transaction.php');
    if ($mArray1['transactionTypeId'] == "RCTS")
        $mStatus = postRcts($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
    else
        $mStatus = postRcts($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
// Set Location Filling Status
    $mStatus = locationFillingSts("","","",$mJsonArray['tolocationhashcode'],$mHost,$mUser,$mPwd,$mDbName,$mJsonArray['currentUser']);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
// Close Replen Tasks
    include_once ('replen.php');
    $mStatus = closeReplen($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
    exit("OK  -cts");   
}

// PTS Locate
elseif (($mFunction != null) && ($mFunction == "postpts"))
{
    $mErrMsg = "";
    $mPartNumber = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "pltnumber")
            $mPltNumber = trim($v2);
        elseif ($k2 == "partnumber")
            $mPartNumber = trim($v2);
        elseif ($k2 == "tolocationhash")
            $mToLocationHash = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
	error_log("validaterdt.php-".$mConnect);
    include_once('transaction.php');
    $mStatus = postPts($mPltNumber,$mPartNumber,$mToLocationHash,$mCurrentUser,$mHost,$mUser,$mPwd,$mDbName,$mConnect);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
// Set Location Filling Status
    $mStatus = locationFillingSts("","","",$mToLocationHash,$mHost,$mUser,$mPwd,$mDbName,$mJsonArray['currentUser']);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
    echo("OKMS-locate complete");
    return;
}

// Validate Delivery Note
elseif (($mFunction != null) && ($mFunction == "validatedelnote"))
{   
    $mErrMsg = "";
    $mHaulierReference = "";
    $mSerialReference = "";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mPartNumber = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "haulierreference")
            $mHaulierReference = strtoupper($v2);
        elseif (strtolower($k2) == "deliverynote")
            $mDeliveryNote = strtoupper($v2);
        elseif (strtolower($k2) == "partnumber")
            $mPartNumber = strtoupper($v2);
        elseif (strtolower($k2) == "serialreference")
            $mSerialReference = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        die("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());

// Delivery Note cannot start with 'Q','P','S'
    if ((substr($mDeliveryNote,0,1) == "Q") || (substr($mDeliveryNote,0,1) == "P") || (substr($mDeliveryNote,0,1) == "S"))
    {
        exit("FAIL-Incorrect Delivery Note Prefix");
    }
// 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 Receipt Detail for scanned Serial / Part 
    $mRctDtlQty = "";
    $mRctStsId = "";
// JIS Receipt Processing
    if ($mTransactionTypeId == "JRBTP")
    {
        $mDataQuery = "SELECT receipt_header.id AS id, receipt_header.haulier_reference AS haulier_reference, receipt_header.delivery_note AS delivery_note FROM receipt_header";
        $mDataQuery .= " JOIN receipt_body ON receipt_body.receipt_header_id=receipt_header.id";
        $mDataQuery .= " JOIN receipt_detail ON receipt_detail.receipt_body_id=receipt_body.id";
        $mDataQuery .= " JOIN part ON part.id = receipt_body.part_id";
        $mDataQuery .= " WHERE upper(receipt_header.delivery_note)='".$mDeliveryNote."' AND (part.part_number = '".$mPartNumber."')";
        if ($mSerialReference != "")
            $mDataQuery .= " AND receipt_detail.serial_reference = '".$mSerialReference."'";
        $mDataQuery .= " AND receipt_header.document_status_id IN(0,".$mDocStsId.",".$mDocCmpId.")";
        $mDataQuery .= " LIMIT 1";
    }
    elseif ($mPartNumber != "")
    {
        $mDataQuery = "SELECT receipt_header.id AS id, receipt_header.haulier_reference AS haulier_reference, receipt_header.delivery_note AS delivery_note FROM receipt_header";
        $mDataQuery .= " JOIN receipt_body ON receipt_body.receipt_header_id=receipt_header.id";
        $mDataQuery .= " JOIN part ON part.id = receipt_body.part_id";
        $mDataQuery .= " WHERE upper(receipt_header.delivery_note)='".$mDeliveryNote."' AND (part.part_number = '".$mPartNumber."')";
        $mDataQuery .= " AND receipt_header.document_status_id IN(0,".$mDocStsId.",".$mDocCmpId.")";
        $mDataQuery .= " LIMIT 1";
    }
    else
    {
        $mDataQuery = "SELECT receipt_header.id AS id, receipt_header.haulier_reference AS haulier_reference, receipt_header.delivery_note AS delivery_note FROM receipt_header WHERE upper(receipt_header.delivery_note)='".$mDeliveryNote."'";
        $mDataQuery .= " AND receipt_header.document_status_id IN(0,".$mDocStsId.",".$mDocCmpId.")";
        $mDataQuery .= " LIMIT 1";
    }
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);

    $mData = (mysqli_query($mConnection,$mDataQuery));
    if (mysqli_num_rows($mData) == 0)
    {
        if ($mTransactionTypeId == "JRBTP")
        {
            echo "FAIL-Invalid Delivery Note";
            return;
        }
        else
        {
            $mDataQuery = "SELECT receipt_header.id AS id, receipt_header.haulier_reference AS haulier_reference, receipt_header.delivery_note AS delivery_note FROM receipt_header WHERE receipt_header.haulier_reference='".$mHaulierReference."' AND upper(receipt_header.delivery_note)='".$mDeliveryNote."'";
            $mDataQuery .= " AND receipt_header.document_status_id IN(0,".$mDocStsId.",".$mDocCmpId.")";
            $mDataQuery .= " LIMIT 1";
            $mData = (mysqli_query($mConnection,$mDataQuery));
            if (mysqli_num_rows($mData) == 0)
            {
                $mDataQuery = "SELECT receipt_header.id AS id, receipt_header.haulier_reference AS haulier_reference, receipt_header.delivery_note AS delivery_note FROM receipt_header WHERE upper(receipt_header.delivery_note)='".$mDeliveryNote."'";
                $mDataQuery .= " AND receipt_header.document_status_id IN(0,".$mDocStsId.",".$mDocCmpId.")";
                $mDataQuery .= " LIMIT 1";
                $mData = (mysqli_query($mConnection,$mDataQuery));
            }
        }
    }
        
//  print_r("FAIL-TEST1-".$mDataQuery."-".mysqli_num_rows($mData));
//  $mRow = mysqli_fetch_assoc($mData);
// Check Number of results
    if (mysqli_num_rows($mData) ==0)
    {
//      exit("FAIL-Invalid Delivery Note");
        include_once('transaction.php');
        $mStatus = addReceiptHeader($mHaulierReference,$mDeliveryNote,$mTransactionTypeId,$mCurrentUser,$mHost,$mUser,$mPwd,$mDbName);
        if (substr($mStatus,0,2) == "FA")
            exit($mStatus);
        exit("OK  -Receipt Header Added");
    }
    else
    {
        $mRow = mysqli_fetch_assoc($mData);
        if (strtoupper($mHaulierReference) != strtoupper($mRow['haulier_reference']))
        {
            echo "FAIL-Wrong Haulier Reference for this Delivery Note.";
            return;
        }
    }
    echo "OK  -";
    return;
}

// Check for multiple Del.Notes for Haulier/Part
elseif (($mFunction != null) && ($mFunction == "dupdelnote"))
{   
    $mErrMsg = "";
    
    $mPartNumber = "";
    $mHaulierReference = "";
    $mSerialReference = "";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "haulierreference")
            $mHaulierReference = strtoupper($v2);
        elseif (strtolower($k2) == "partnumber")
            $mPartNumber = strtoupper($v2);
        elseif (strtolower($k2) == "serialreference")
            $mSerialReference = $v2;
        elseif ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty"))
            $mQty = floatval($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }
//  exit("FAIL-TEST-".$mFilter);
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        die("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 ($mDocStsId == null)
        $mDocStsId = 0;
    if ($mDocCmpId == null)
        $mDocCmpId = 0;

// Get Receipt Detail for scanned Serial / Part 
    $mRctDtlQty = "";
    $mRctStsId = "";
// If JIS Receipt - Check for Part & Serial
    if (($mSerialReference != "") && ($mTransactionTypeId == "JRBTP"))
    {
        $mDataQuery = "SELECT receipt_header.id AS id, receipt_header.delivery_note AS delivery_note, receipt_detail.advised_qty AS advised_qty, receipt_detail.received_qty AS received_qty FROM receipt_header JOIN receipt_body ON receipt_body.receipt_header_id=receipt_header.id JOIN receipt_detail ON receipt_body.id=receipt_detail.receipt_body_id WHERE upper(receipt_header.haulier_reference)='".$mHaulierReference."' AND upper(receipt_body.part_number)='".$mPartNumber."' AND receipt_detail.serial_reference = '".$mSerialReference."' AND receipt_header.document_status_id IN(0,".$mDocStsId.",".$mDocCmpId.") LIMIT 2";
    }
// Otherwise Check for Part
    else
    {
        $mDataQuery = "SELECT receipt_header.id AS id, receipt_header.delivery_note AS delivery_note, receipt_body.advised_qty AS advised_qty, receipt_body.received_qty AS received_qty FROM receipt_header JOIN receipt_body ON receipt_body.receipt_header_id=receipt_header.id JOIN part ON receipt_body.part_id=part.id WHERE upper(receipt_header.haulier_reference)='".$mHaulierReference."' AND (part.part_number='".$mPartNumber."') AND receipt_header.document_status_id IN(0,".$mDocStsId.",".$mDocCmpId.") LIMIT 2";
    }
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    
    $mData = (mysqli_query($mConnection,$mDataQuery));
    $mRow = mysqli_fetch_assoc($mData);
    
    $mDeliveryNote = "";
    $mDeliveryNote = ($mRow['delivery_note']);
    $mAdvisedQty = 0;
    $mAdvisedQty = ($mRow['advised_qty']);
    $mReceivedQty = 0;
    $mReceivedQty = ($mRow['received_qty']);
//  exit("FAIL-TEST1-".$mDataQuery."-".mysqli_num_rows($mData)."-".$mDeliveryNote."-".$mAdvisedQty."-".$mReceivedQty);
//  print_r("FAIL-TEST-".$mDataQuery."-".$mDeliveryNote."-".mysqli_num_rows($mData));
// Check Number of results
    if (($mSerialReference != "") && ($mTransactionTypeId != "JRBTP"))
    {
        if ((mysqli_num_rows($mData) > 1) || (mysqli_num_rows($mData) == 0) || ((mysqli_num_rows($mData) == 1) && ($mReceivedQty >= $mAdvisedQty)))
        {
            exit("DATA:serialReference:".$mSerialReference."::skipdeliveryNote,deliveryNote:");
        }
    }
    if (mysqli_num_rows($mData) > 1)
    {
        if ($mTransactionTypeId == "JRBTP")
            exit("FAIL-Duplicate Part and Serial");
        elseif ($mTransactionTypeId == "RBTP")
            exit("DATA:deliveryNote::HHIPHH");
        else
            exit("DATA:deliveryNote::HHIP");
    }
// Un-advised part
    elseif (mysqli_num_rows($mData) == 0)
    {
        if ($mTransactionTypeId == "JRBTP")
            exit("FAIL-Part or Serial does not exist");
        elseif ($mTransactionTypeId == "RBTP")
            exit("DATA:deliveryNote::HHIPHH");
        else
            exit("DATA:deliveryNote::HHIP");
    }
// over delivery
    elseif ((mysqli_num_rows($mData) == 1) && ($mReceivedQty >= $mAdvisedQty))
    {
        if (($mTransactionTypeId == "RBTP") || ($mTransactionTypeId == "JRBTP"))
            exit("DATA:deliveryNote::HHIPHH");
        else
            exit("DATA:deliveryNote::HHIP");
    }
    else
    {
        if (($mTransactionTypeId == "RBTP") || ($mTransactionTypeId == "JRBTP") || ($mTransactionTypeId == "RBTD"))
            exit("DATA:deliveryNote::HHHHHH,comment:".$mDeliveryNote);
//          exit("DATA:deliveryNote:".$mDeliveryNote.":HHHHHH");
        else
            exit("DATA:deliveryNote::HHHH,comment:".$mDeliveryNote);
//          exit("DATA:deliveryNote:".$mDeliveryNote.":HHHH");
    }
}

// Check for PRUFCUBE part on receipt
elseif (($mFunction != null) && ($mFunction == "recprufcube"))
{   
    $mErrMsg = "";
    
    $mPartNumber = "";
    $mHaulierReference = "";
    $mDeliveryNote = "";
    
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;

// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "haulierreference")
            $mHaulierReference = strtoupper($v2);
        elseif (strtolower($k2) == "deliverynote")
            $mDeliveryNote = strtoupper($v2);
        elseif (strtolower($k2) == "partnumber")
            $mPartNumber = strtoupper($v2);
        elseif (strtolower($k2) == "serialreference")
            $mSerialReference = $v2;
        elseif ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty"))
            $mQty = floatval($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        die("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
        
// Get Document Id for Status 'open'
    $mDocStsId = "";
    $mDataQuery = "SELECT id AS id FROM document_status WHERE lower(document_status_code) = 'open' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);   
    $mData = (mysqli_query($mConnection,$mDataQuery));
    $mRow = mysqli_fetch_assoc($mData);
    $mDocStsId = ($mRow['id']);
// Get id for product type
    $mPrufId = null;
    $mProdId = null;
    $mDataQuery = "SELECT id AS id, product_type_code AS product_type_code FROM product_type";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("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']);
    }
// Check if Rec.Body Part is flagged as PrufCube
    if (($mDeliveryNote) && ($mDeliveryNote != ""))
    {
        $mDataQuery = "SELECT receipt_header.id AS id, receipt_body.product_type_id AS product_type_id FROM receipt_header JOIN receipt_body ON receipt_body.receipt_header_id=receipt_header.id JOIN part ON receipt_body.part_id=part.id WHERE upper(receipt_header.haulier_reference)='".$mHaulierReference."' AND (part.part_number = '".$mPartNumber."') AND upper(receipt_header.delivery_note)='".$mDeliveryNote."' AND receipt_header.document_status_id=".$mDocStsId." LIMIT 1";
    }
    else
    {
        $mDataQuery = "SELECT receipt_header.id AS id, receipt_body.product_type_id AS product_type_id FROM receipt_header JOIN receipt_body ON receipt_body.receipt_header_id=receipt_header.id JOIN part ON receipt_body.part_id=part.id WHERE upper(receipt_header.haulier_reference)='".$mHaulierReference."' AND (part.part_number = '".$mPartNumber."') AND receipt_header.document_status_id=".$mDocStsId." LIMIT 1";
    }
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    $mData = (mysqli_query($mConnection,$mDataQuery));
    if (mysqli_num_rows($mData) > 0)
    {
        $mRow = mysqli_fetch_assoc($mData);
        if ($mRow['product_type_id'] == $mPrufId)
        {
            if ($mDeliveryNote != "")
                exit("DATA:deliveryNote:".$mDeliveryNote."::skipprufConfirm,prufConfirm:");
            else
                exit("DATA:serialReference:".$mSerialReference."::skipprufConfirm,prufConfirm:");
        }
        else
        {
            exit("OK  -Prufcube");
        }
    }
    exit("OK  -Prufcube");
}

elseif (($mFunction != null) && ($mFunction == "validateconfirm"))
{
    $mErrMsg = "";
    
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mValue = "";
    $mOptions = "yn";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "value")
            $mValue = strtolower($v2);
        elseif (strtolower($k2) == "options")
            $mOptions = strtolower($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
        if ((substr($mValue,0,1) != "y") && (substr($mValue,0,1) != "n"))
            exit("FAIL-Invalid Value");
        else
            exit("OK  -");
    }
}

// Process Receipt Transaction
elseif (($mFunction != null) && ($mFunction == "posttransaction"))
{
//  exit("FAIL-TEST-".$mFilter);
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $s=0;
    $e=0;
    $mJsonArray = array();
// Test for blank input
    if (($mFilter == "") || ($mFilter == null))
        exit("OK  -");
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    $i = 0;
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty"))
            $mJsonArray[strtolower($k2)] = floatval($v2);
        elseif (strtolower($k2) == "jserialreference")
            $mJsonArray['serialreference'] = $v2;
        elseif (strtolower($k2) == "expirydate")
        {
            if (($v2 != "") && (strlen($v2)> 0))
            {
                $v2 = str_replace("-","",$v2);
                $v2 = str_replace("/","",$v2);
                $v2 = str_replace(".","",$v2);
                $mDateChk = substr($v2,4,4)."-".substr($v2,2,2)."-".substr($v2,0,2);
                if (($mDateObj = strtotime($mDateChk)) === false) 
                {
                    echo ("FAIL-Incorrect Date ".$mDateChk);
                    return;
                } 
                else 
                {
                    $mJsonArray['expirydate'] = substr($v2,4,4)."-".substr($v2,2,2)."-".substr($v2,0,2);
                }
            }
        }
        elseif ((strtolower($k2) == "haulierreference") && ($v2 == ""))
            exit("FAIL-Incorrect Haulier Reference".$mFilter);
        elseif ((strtolower($k2) == "customerreference") && ($v2 == ""))
            exit("FAIL-Incorrect Customer Reference".$mFilter);
        else
            $mJsonArray[strtolower($k2)] = $v2;
//      if (($v2 != "") && ($v2 != 0))
            $i++;
    }

// All Values are blank
    if ($i == 0)
        exit("OK  -blankparms".$mFilter."-".$i);
// Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
    }
    catch(Exception $e)
    {
        exit("FAIL-Json Error");
    }

    include_once ('transaction.php');
    $mStatus = postTransaction($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
    echo($mStatus);
    return;
}

// PTM Locate
elseif (($mFunction != null) && ($mFunction == "postptm"))
{
    $mErrMsg = "";
    $mFromLocationHash = "";
    $mCustomerReference = "";
    $mDocumentReference = "";
    $mAisleCode = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "plt")
            $mPltNumber = trim($v2);
        elseif (strtolower($k2) == "fromlocationhashcode")
            $mFromLocationHash = trim($v2);
        elseif (strtolower($k2) == "tolocationhashcode")
            $mToLocationHash = trim($v2);
        elseif (strtolower($k2) == "customerreference")
            $mCustomerReference = trim($v2);
        elseif (strtolower($k2) == "documentreference")
            $mDocumentReference = trim($v2);
        elseif (strtolower($k2) == "aislecode")
            $mAisleCode = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
// Set path for locate Call
//  $mConnectp = str_replace(":8081/vantec",":8085/pick",$mConnect);
    include_once('transaction.php');
    $mStatus = postPtm($mPltNumber,$mToLocationHash,$mCurrentUser,$mHost,$mUser,$mPwd,$mDbName,$mConnect);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
// Set Location Filling Status
    $mStatus = locationFillingSts("",$mFromLocationHash,"",$mToLocationHash,$mHost,$mUser,$mPwd,$mDbName,$mJsonArray['currentUser']);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
    if ($mTransactionTypeId == "PBTP")
    {
        if ($mDocumentReference != "")
            exit("CHGTRAN:PBTP?DATA:documentReference:".$mDocumentReference.",aisleCode:".$mAisleCode."?5");
        else
            exit("CHGTRAN:PBTP?DATA:customerReference:".$mCustomerReference.",aisleCode:".$mAisleCode."?5");
    }
    elseif ($mTransactionTypeId == "PBTTP")
    {
        if ($mDocumentReference != "")
            exit("CHGTRAN:PBTTP?DATA:documentReference:".$mDocumentReference.",aisleCode:".$mAisleCode."?5");
        else
            exit("CHGTRAN:PBTTP?DATA:customerReference:".$mCustomerReference.",aisleCode:".$mAisleCode."?5");
    }
    else
//      exit($mStatus);
        exit("OKMS-Locate Complete");
}

// XD Pick Locate
elseif (($mFunction != null) && ($mFunction == "postxptm"))
{
    $mErrMsg = "";
    $mFromLocationHash = "";
    $mCustomerReference = "";
    $mAisleCode = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "plt")
            $mPltNumber = trim($v2);
        elseif (strtolower($k2) == "fromlocationhashcode")
            $mFromLocationHash = trim($v2);
        elseif (strtolower($k2) == "tolocationhashcode")
            $mToLocationHash = trim($v2);
        elseif (strtolower($k2) == "customerreference")
            $mCustomerReference = trim($v2);
        elseif (strtolower($k2) == "aislecode")
            $mAisleCode = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
// Set path for locate Call
    include_once('allocation.php');
    $mStatus = postXptm($mCustomerReference,$mPltNumber,$mToLocationHash,$mCurrentUser,$mHost,$mUser,$mPwd,$mDbName,$mConnect);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
// Set Location Filling Status
//  include_once ('transaction.php');
//  $mStatus = locationFillingSts("",$mFromLocationHash,"",$mToLocationHash,$mHost,$mUser,$mPwd,$mDbName,$mJsonArray['currentUser']);
//  if (substr($mStatus,0,2)=="FA")
//      exit($mStatus);
    if ($mTransactionTypeId == "PBTP")
        exit("CHGTRAN:PBTP?DATA:customerReference:".$mCustomerReference.",aisleCode:".$mAisleCode."?5");
    elseif ($mTransactionTypeId == "PBTTP")
        exit("CHGTRAN:PBTTP?DATA:customerReference:".$mCustomerReference.",aisleCode:".$mAisleCode."?5");
    else
        exit($mStatus);
}

// Missing Pick Serial
elseif (($mFunction != null) && ($mFunction == "missingpickserial"))
{
    $mErrMsg = "";
    $mFromLocationHash = "";
    $mCustomerReference = "";
    $mAisleCode = "";
    $mTaskType = "";
    $mToPlt = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "plt")
            $mPltNumber = trim($v2);
        elseif (strtolower($k2) == "fromlocationhashcode")
            $mFromLocationHash = trim($v2);
        elseif (strtolower($k2) == "tolocationhashcode")
            $mToLocationHash = trim($v2);
        elseif (strtolower($k2) == "documentreference")
            $mDocumentReference = trim($v2);
        elseif (strtolower($k2) == "aislecode")
            $mAisleCode = trim($v2);
        elseif (strtolower($k2) == "tasktype")
            $mTaskType = trim($v2);
        elseif (strtolower($k2) == "serialreference")
            $mSerialReference = trim($v2);
        elseif (strtolower($k2) == "partnumber")
            $mPartNumber = trim($v2);
        elseif (strtolower($k2) == "allocationid")
            $mPickDtlId = trim($v2);
        elseif (strtolower($k2) == "sequencingrequestid")
            $mPickInvId = trim($v2);
        elseif (strtolower($k2) == "toplt")
            $mToPlt = trim($v2);
        elseif ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty") || (strtolower($k2) == "qtyallocated"))
            $mPickQty = floatval($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        die("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());      
// Validate Initial Values  
    $mDataQuery = "SELECT location_code FROM location WHERE location_hash='".$mFromLocationHash."' LIMIT 1"; 
    if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    $mData = (mysqli_query($mConnection,$mDataQuery));
    if (mysqli_num_rows($mData) == 0)
        exit("FAIL-Location is Incorrect");
// Set path for locate Call
    include_once('allocation.php');
    $mStatus = missingPickSerial($mHost,$mUser,$mPwd,$mDbName,$mPickDtlId,$mPickInvId,$mSerialReference,$mPickQty,$mAisleCode,$mTaskType,$mCurrentUser,$mTransactionTypeId,$mFromLocationHash,$mToPlt);
    if (substr($mStatus,0,2) != "FA")
    {
        $mJsonArray = array();
        $mDataQuery = "SELECT location_code FROM location WHERE location_hash='".$mFromLocationHash."' OR location_code='".$mFromLocationHash."' LIMIT 1"; 
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $mData = (mysqli_query($mConnection,$mDataQuery));
        if (mysqli_num_rows($mData) > 0)
        {
            $mRow = mysqli_fetch_assoc($mData);
            $mJsonArray['partNumber'] = $mPartNumber;
            $mJsonArray['serialReference'] = $mSerialReference;
            $mJsonArray['locationCode'] = $mRow['location_code'];
            $mJsonArray['userId'] = $mCurrentUser;
            $mLocationCode = $mRow['location_code'];
// Convert Array to Json Object
            try
            {
                $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
            }
            catch(Exception $e)
            {
                exit("FAIL-Json Error");
            }
//          print_r("FAIL-TEST1-".$mJsonObject);
// 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."f6Pick");
                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);
            }
        
            $mConvFactor = 1;
            $mDataQuery = "SELECT id, part_number, conversion_factor FROM part WHERE (part.part_number='".$mPartNumber."') LIMIT 1";
            if (!mysqli_query($mConnection,$mDataQuery))
                exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
            $mData = (mysqli_query($mConnection,$mDataQuery));
            if (mysqli_num_rows($mData) > 0)
            {
                $mRow = mysqli_fetch_assoc($mData);
                $mConvFactor = $mRow['conversion_factor'];
                $mPartNumber = $mRow['part_number'];
            }
            $mQty = ($mPickQty * $mConvFactor);
            
// Add to F6 History
            $mDataQuery = "SELECT id FROM f6missing_history WHERE part_number='".$mPartNumber."' AND serial='".$mSerialReference."' LIMIT 1";
            if (!mysqli_query($mConnection,$mDataQuery))
                exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
            $mData = (mysqli_query($mConnection,$mDataQuery));
            if (mysqli_num_rows($mData) == 0)
            {
                $mDataQuery = "INSERT into f6missing_history (id,created_by,date_created,inventory_status_CODE,location_code,part_number,qty,serial)";
                $mDataQuery .= " VALUES(DEFAULT,'".$mCurrentUser."',now(),'MISSING','".$mLocationCode."','".$mPartNumber."',".$mQty.",'".$mSerialReference."')";
                if (!mysqli_query($mConnection,$mDataQuery))
                    exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
            }
        }
//      exit("FAIL-TEST1-".$mErrMsg."-".$mConnectp."-".$mJsonObject);
    }   
    exit($mStatus);
}

// validate Piece Part
elseif (($mFunction != null) && ($mFunction == "validatepiecepart"))
{
    $mReturn = "";
    $mErrMsg = "";
    $mPartNumber = "";
    $mPiecePart = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "partnumber")
            $mPartNumber = trim($v2);
        elseif (strtolower($k2) == "piecepart")
            $mPiecePart = trim($v2);
        elseif ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty") || (strtolower($k2) == "qtyallocated"))
            $mPickQty = floatval($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        die("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());      
    $mDataQuery = "SELECT piece_part_number AS piece_part_number FROM part WHERE (part_number = '".$mPartNumber."') LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    $mData = (mysqli_query($mConnection,$mDataQuery));
    if (mysqli_num_rows($mData) > 0)
    {
        $mRow = mysqli_fetch_assoc($mData);
        if ($mPiecePart == "")
        {
            if ($mRow['piece_part_number'] != "")
                $mReturn = "DATA:piecePart:::skippiecePart";
            else
//              $mReturn = "DATA:piecePart:";
                $mReturn = "OK  -validatepiecepart";
        }
        else
        {
            $l = strlen($mRow['piece_part_number']);
            if (substr($mPiecePart,0,$l) != strtoupper($mRow['piece_part_number']))
                $mReturn = "FAIL-Invalid Piece Part";
        }
    }
    else
    {
        $mReturn = "FAIL-Invalid Part Number-".$mPartNumber;
    }
//  mysqli_close($mConnection);
    if ($mReturn == "")
        $mReturn = "OK  -Piece Part";
    exit($mReturn);
}

// Server Call to Post Pick Transaction
elseif (($mFunction != null) && (strtolower($mFunction) == "ptmserverprocessed"))
{
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $s=0;
    $e=0;
    $mJsonArray = array();

// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (($k2 == "quantity") || ($k2 == "countQty") || ($k2 == "pickQty"))
            $mJsonArray[$k2] = floatval($v2);
        else
            $mJsonArray[$k2] = $v2;
    }
// Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
    }
    catch(Exception $e)
    {
        exit("FAIL-Json Error");
    }
// POST Operation
    try
    {
// Replace default Server Tomcat Service
        $mConnectp = str_replace(":8081/vantec",":8085/pick",$mConnect);
        if ($mConnectp == $mConnect)
        {
            $e = strpos($mConnect,":8081");
            $mConnectp = substr($mConnect,0,$e).":8095/pick/";
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $mConnectp."processTransaction");
        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  - Update Complete";
//          exit($mErrMsg);
//          print_r("FAIL-Message Code=".$mJsonObject.":".$mResult.":".$mResponse.":".$mErrors);
        }
    }
    catch (Exception $e)
    {
        $mErrMsg = ("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
    }
    exit("CHGTRAN:PBTP?DATA:customerReference:".$mJsonArray['customerReference'].",aisleCode:".$mJsonArray['aisleCode']."?5");
}

// Add Prefix
elseif (($mFunction != null) && (strtolower($mFunction) == "validateprefix"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
    $mPrefixes = "";
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "fieldname")
            $mFieldName = $v2;
        elseif ($k2 == "fieldvalue")
            $mFieldValue = $v2;
        elseif ($k2 == "prefix")
            $mPrefixes = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        die("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());  
// Get Default Settings 
    $mPrefix = "";
    if ($mPrefixes == "")
    {
        $mDataQuery = "SELECT id AS id, prefix_name AS prefix_name FROM default_setting WHERE field_name='".$mFieldName."' LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $mData = (mysqli_query($mConnection,$mDataQuery));
        if (mysqli_num_rows($mData) > 0)
        {
            $mRow = mysqli_fetch_assoc($mData);
            $mPrefixes = ($mRow['prefix_name']);
        }
    }
    if ($mPrefixes != "")
    {
// Test for matching Prefix

        $mPrefix = substr($mPrefixes,0,1);
        for($i=0;$i<strlen($mPrefixes);$i++)
        {
            if (substr($mFieldValue,0,1)==substr($mPrefixes,$i,1))
            {
                $mFieldValue = substr($mFieldValue,1);
                $mPrefix = substr($mPrefixes,$i,1);
                break;
            }
        }
//      $mFieldValue = $mPrefix.$mFieldValue;
        exit("DATA:".$mFieldName."input:".$mFieldValue);
    }
//  exit("FAIL-".$mDataQuery."-".$mPrefixes."-".$mPrefix."-".$mFieldName."-".$mFieldValue);
    exit("OK  -validateprefix".$mFieldName.":".$mFieldValue);
}

elseif (($mFunction != null) && (strtolower($mFunction) == "getcountonrcpt"))
{
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    $mPartNumber = "";
    $mSerialReference = "";
    $mPlt = "";
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "partnumber")
            $mPartNumber = strtoupper($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }
// blank input parameters - ignore
    if ($mPartNumber == "")
    {
        exit("OK  -");
    }
    // mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Set default error message
    $mErrMsg = "FAIL-No Matching Records";

    if ($mPartNumber != "")
    {
//      $mDataQuery = "SELECT part_number AS partNumber, count_on_rcpt AS countonrcpt, effective_from AS effective_from, effective_to AS effective_to FROM part WHERE part_number='".$mPartNumber."' LIMIT 1";
        $mDataQuery = "SELECT part_number AS partNumber, requires_count AS countonrcpt, effective_from AS effective_from, effective_to AS effective_to FROM part WHERE (part_number='".$mPartNumber."') LIMIT 1";

    }
    if (!mysqli_query($mConnection,$mDataQuery))
    {
        exit("FAIL-".mysqli_error($mConnection));
    }
    $mData = mysqli_query($mConnection,$mDataQuery);
    $i = 0;
    $mCountOnRcpt = "";
    $mEffFrom = "";
    $mEffTo = "";
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mPartNumber = ($mRow['partNumber']);
        $mCountOnRcpt=($mRow['countonrcpt']);
        $i++;
    }
//  mysqli_close($mConnection);
    $mDataStr = "";
    if ($i > 0)
    {
        if ($mCountOnRcpt == "1")
        {
            if ($mTransactionTypeId='RBTP')
            {
                $mDataStr = "DATA:countQty:::skipcountQty";
            }
            else
            {
                $mDataStr = "DATA:countQty:::skipcountQty";
            }
            $mErrMsg = "";
            exit($mDataStr);
        }
        else
        {
            exit("OK  -countonrcpt");
        }
    }
    else
    {
        exit("FAIL-Invalid Part ".$mPartNumber);
    }
}

// Get Replen Pallet
elseif (($mFunction != null) && (strtolower($mFunction) == "getreplenplt"))
{
    $mStatus = "";
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }
    
    include_once ('replen.php');
    $mStatus = getServerReplenPlt($mCurrentUser,$mConnect);
    if (substr($mStatus,0,2) == "FA")
        exit ($mStatus);
    else
    exit("DATA:toPlt:".$mStatus.":PPPPPPP:skip3");
}

// Get Replen
elseif (($mFunction != null) && (strtolower($mFunction) == "getreplen"))
{
    $mToPlt = "";
    $mStatus = "";
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "replengroup")
            $mReplenGroup = $v2;
        if ($k2 == "toplt")
            $mToPlt = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }   
    include_once ('replen.php');
    $mStatus = getServerReplen($mCurrentUser,$mReplenGroup,"ALL",$mConnect);
//  $mStatus = getReplen($mCurrentUser,$mReplenGroup,"ALL",$mConnect,$mHost,$mUser,$mPwd,$mDbName,$mTransactionTypeId);
    $mStatus = str_replace('{','',$mStatus);
    $mStatus = str_replace('}','',$mStatus);
    $mStatus = str_replace('"','',$mStatus);
    $mStatus = str_replace('fromlocationCode','fromLocationHashCode',$mStatus);
    $mStatus = str_replace('replenTaskId','sequencingRequestId',$mStatus);
    $s = strpos($mStatus,":");
    $e = strpos($mStatus,",");
    if ($e<$s)
        $e = strlen($mStatus);
    $e = $e-$s;
    $mReplenTaskId = substr($mStatus,$s+1,$e-1);
//  echo ("FAIL-TEST1-".$mStatus."-".$mReplenTaskId);
//  return;
    if (substr($mStatus,0,2) == "FA")
        exit($mStatus);
    if ($mStatus == "")
        if ($mToPlt == "")
            exit("OKMS-No Replen Tasks,CHGTRAN:REPLEN");
        else
            exit("OKMS-No more Replen Tasks,CHGTRAN:REPLOC?DATA:replenGroup:".$mReplenGroup);
    if (strpos($mStatus,"partNumber:null") >0)
        if ($mToPlt == "")
            exit("OKMS-No Replen Tasks,CHGTRAN:REPLEN");
        else
            exit("OKMS-No more Replen Tasks,CHGTRAN:REPLOC?DATA:replenGroup:".$mReplenGroup);

// Get Replen To-Loc
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
    if (!$mConnection)
        return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
    $mDataQuery = "SELECT to_location_code AS to_location_code FROM replen_task WHERE id=".$mReplenTaskId." LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
    {
        echo("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    }
//  $mData = mysqli_query($mConnection,$mDataQuery);
//  echo ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
    $mToLoc = "";
    while($mRow = mysqli_fetch_assoc($mData))
    {
        $mToLoc = $mRow['to_location_code'];    
    }
    if ($mStatus == "")
        $mStatus .= "toLocationHashCode:".$mToLoc;
    else
        $mStatus .= ",toLocationHashCode:".$mToLoc;
//  echo ("FAIL-TEST1-".$mStatus);  
    echo ("DATA:".$mStatus);
    return;
}

// Validate Replen Task
elseif (($mFunction != null) && ($mFunction == "validatereplen"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $s=0;
    $e=0;
    $mJsonArray = array();
// Test for blank input
    if (($mFilter == "") || ($mFilter == null))
        exit("OK  -");
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    $i = 0;
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty") || (strtolower($k2) == "qtyallocated"))
            $mJsonArray[strtolower($k2)] = floatval($v2);
        elseif (strtolower($k2) == "jserialreference")
            $mJsonArray['serialreference'] = $v2;
        else
            $mJsonArray[strtolower($k2)] = $v2;
            $i++;
    }
// All Values are blank
    if ($i == 0)
        exit("OK  -");
// Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
    }
    catch(Exception $e)
    {
        exit("FAIL-Json Error");
    }
// Set path for Service Call
    $mConnect = str_replace(":8081/vantec",":8081/vantec",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8081/vantec/";
    }
    include_once ('replen.php');
    $mStatus = validateReplen($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
    if (substr($mStatus,0,2)=="DA")
        exit($mStatus);
// Set Location Filling Status
//  include_once ('processtransaction.php');
//  $mStatus = locationFillingSts("","","",$mJsonArray['tolocationhashcode'],$mHost,$mUser,$mPwd,$mDbName,$mJsonArray['currentUser']);
//  if (substr($mStatus,0,2)=="FA")
//      exit($mStatus);
    if (substr($mStatus,0,2) == "OK")
        $mStatus = "OK  -Valid Replen";
    exit($mStatus);
}

// Process Replen
// Get Replen
elseif (($mFunction != null) && (strtolower($mFunction) == "replenprocessed"))
{
    $mJsonArray = array();
    $mStatus = "";
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "replengroup")
            $mReplenGroup = $v2;
        elseif (strtolower($k2) == "locationcode")
            $mLocationCode = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
            
        if ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty") || (strtolower($k2) == "qtyallocated"))
            $mJsonArray[$k2] = floatval($v2);
        elseif ($k2 == "currentUser")
            $mJsonArray['userId'] = $v2;
        else
            $mJsonArray[$k2] = $v2;
    }

// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
    if (!$mConnection)
        return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
    $mDataQuery = "SELECT id FROM pick_group WHERE pick_group_code='".$mReplenGroup."' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
            return("FAIL-1".mysqli_error($mConnection)."-".$mDataQuery);
    $mData = mysqli_query($mConnection,$mDataQuery);
    $mPickGroupId = "";
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mPickGroupId = $mRow['id'];
    }
    $mJsonArray['pickGroupId'] = $mPickGroupId;
    $mDataQuery = "SELECT id, location_code FROM location WHERE location_hash='".$mLocationCode."' OR location_code='".$mLocationCode."' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-1".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
    $mData = mysqli_query($mConnection,$mDataQuery);
    $mLocationCode = "";
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mLocationCode = $mRow['location_code'];
    }
    $mJsonArray['locationCode'] = $mLocationCode;
// Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
    }
    catch(Exception $e)
    {
        exit("FAIL-Json Error");
    }
    include_once ('replen.php');
    $mStatus = processServerReplen($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
    
    if (substr($mStatus,0,2) == "FA")
        exit($mStatus);
    
    if ($mStatus == "")
        exit("OK  -REPLEN processed");
}

// Locate Replen
elseif (($mFunction != null) && (strtolower($mFunction) == "validatereplenlocate"))
{
    $mJsonArray = array();
    $mStatus = "";
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mSerialReference="";
    $mPartNumber="";
    $mToLoc="";

// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "serialreference")
            $mReplenGroup = $v2;
        elseif (strtolower($k2) == "partnumber")
            $mPartNumber = $v2;
        elseif (strtolower($k2) == "locationcode")
            $mLocationCode = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
            
        if ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty") || (strtolower($k2) == "qtyallocated"))
            $mJsonArray[$k2] = floatval($v2);       
        else
            $mJsonArray[$k2] = $v2;
    }
// Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
    }
    catch(Exception $e)
    {
        exit("FAIL-Json Error");
    }
    include_once ('replen.php');
    $mStatus = validateServerReplenLocate($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
    
    if (substr($mStatus,0,2) == "FA")
        exit($mStatus);
    if ($mStatus == "")
        $mStatus = "OK  -Replen Locate";
    exit($mStatus);
}

// Missing Replen Serial
elseif (($mFunction != null) && ($mFunction == "missingreplenserial"))
{
    $mErrMsg = "";
    $mToPlt = "";
    $mFromLocationCode = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "sequencingrequestid")
            $mPickInvId = trim($v2);
        elseif (strtolower($k2) == "fromlocationhashcode")
            $mFromLocationCode = trim($v2);
        elseif (strtolower($k2) == "replengroup")
            $mReplenGroup = $v2;
        elseif (strtolower($k2) == "toplt")
            $mToPlt = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
// Check From Location
    if ($mFromLocationCode == "")
        exit ("FAIL-Invalid Location");
    
    $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, location.location_hash AS location_hash FROM replen_task JOIN location ON replen_task.from_location_code=location.location_code WHERE replen_task.id='".$mPickInvId."' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$DataQuery;
    $mData = mysqli_query($mConnection,$mDataQuery);
    $i = 0;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        if ($mFromLocationCode == $mRow['location_hash'])
            $i++;
    }
    if ($i == 0)
        exit ("FAIL-Invalid Location");
    
// Post Server Data from URL
//  http://172.16.1.70:8095/pick/f6Replen?replenTaskId=1&&userId=ta
    $mJsonArray = array();
    $mJsonArray['replenTaskId'] = $mPickInvId;
    $mJsonArray['userId'] = $mCurrentUser;
// 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."f6Replen?replenTaskId=".$mPickInvId."&userId=".$mCurrentUser);
        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);
    }   

// Get Next Replen Task
    include_once ('replen.php');
    $mStatus = getServerReplen($mCurrentUser,$mReplenGroup,"ALL",$mConnect);
//  $mStatus = getReplen($mCurrentUser,$mReplenGroup,"ALL",$mConnect,$mHost,$mUser,$mPwd,$mDbName,$mTransactionTypeId);
    $mStatus = str_replace('{','',$mStatus);
    $mStatus = str_replace('}','',$mStatus);
    $mStatus = str_replace('"','',$mStatus);
    $mStatus = str_replace('fromlocationCode','fromLocationHashCodecontent',$mStatus);
    $mStatus = str_replace('replenTaskId','sequencingRequestId',$mStatus);
//  print_r("FAIL-TEST1-".$mStatus);
    if (substr($mStatus,0,2) == "FA")
        exit($mStatus);
    if ($mStatus == "")
        if ($mToPlt == "")
            exit("OKMS-No Replen Tasks,REPLEN");
        else
            exit("OKMS-No more Replen Tasks,REPLOC");
    if (strpos($mStatus,"partNumber:null") >0)
        if ($mToPlt == "")
            exit("OKMS-No Replen Tasks,REPLEN");
        else
            exit("OKMS-No more Replen Tasks,REPLOC");
        
    exit("DATA:".$mStatus);
}

// Transfer Replen Task
elseif (($mFunction != null) && ($mFunction == "transferreplen"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $mJsonArray = array();
// Test for blank input
    if (($mFilter == "") || ($mFilter == null))
        exit("OK  -");
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    $i = 0;
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty") || (strtolower($k2) == "qtyallocated"))
            $mJsonArray[strtolower($k2)] = floatval($v2);
        elseif (strtolower($k2) == "jserialreference")
            $mJsonArray['serialreference'] = $v2;
        else
            $mJsonArray[strtolower($k2)] = $v2;
            $i++;
    }
// 
    if ($mJsonArray['replengroup'] == "")
        exit("FAIL-Invalid Replen Group");
    if ($mJsonArray['toplt'] != "")
        $mToPlt = $mJsonArray['toplt'];
    
// All Values are blank
    if ($i == 0)
        exit("OK  -");
// Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
    }
    catch(Exception $e)
    {
        exit("FAIL-Json Error");
    }
//  exit("FAIL-TEST1-".$mJsonObject);

// Set path for Service Call
    include_once ('replen.php');
    $mStatus = transferReplen($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
    if (substr($mStatus,0,2) == "OK")
    {   
        $mStatus = getServerReplen($mCurrentUser,$mJsonArray['replengroup'],"ALL",$mConnect);   
        $mStatus = str_replace('{','',$mStatus);
        $mStatus = str_replace('}','',$mStatus);
        $mStatus = str_replace('"','',$mStatus);
        $mStatus = str_replace('fromlocationCode','fromLocationHashCode',$mStatus);
        $mStatus = str_replace('replenTaskId','sequencingRequestId',$mStatus);
    
        if (substr($mStatus,0,2) == "FA")
            exit($mStatus);
        if ($mStatus == "")
            if ($mToPlt == "")
                exit("OKMS-No Replen Tasks,REPLEN");
            else
                exit("OKMS-No more Replen Tasks,REPLOC");
        if (strpos($mStatus,"partNumber:null") >0)
            if ($mToPlt == "")
                exit("OKMS-No Replen Tasks,REPLEN");
            else
                exit("OKMS-No more Replen Tasks,REPLOC");

// Get Replen To-Loc
        $s = strpos($mStatus,":");
        $e = strpos($mStatus,",");
        if ($e<$s)
            $e = strlen($mStatus);
        $e = $e-$s;
        $mReplenTaskId = substr($mStatus,$s+1,$e-1);
        $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
        if (!$mConnection)
            return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
        $mDataQuery = "SELECT to_location_code AS to_location_code FROM replen_task WHERE id=".$mReplenTaskId." LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
        {
            echo("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        }
//  $mData = mysqli_query($mConnection,$mDataQuery);
//  echo ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
        $mToLoc = "";
        while($mRow = mysqli_fetch_assoc($mData))
        {
            $mToLoc = $mRow['to_location_code'];    
        }
        if ($mStatus == "")
            $mStatus .= "toLocationHashCode:".$mToLoc;
        else
            $mStatus .= ",toLocationHashCode:".$mToLoc;
        if ($mToPlt != "")
            $mStatus .= ",toPlt:".$mToPlt;
        
        exit("DATA:".$mStatus);
    }
    else
        exit("FAIL-Replen transfer error");
    
        $mStatus = "OK  -Valid Replen";
    exit($mStatus);

}

// Validate MTT Serial
elseif (($mFunction != null) && ($mFunction=="validatemttserial"))
{
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Set default error message
    $mErrMsg = "FAIL-Serial does not exist";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mPartNumber = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "partnumber")
            $mPartNumber = strtoupper($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
//    exit("FAIL-TEST1-".$mFilter);
// Test for Pallet Tag
    if ($mPartNumber == "")
    {
        $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.serial_reference AS serial_reference, part.part_number FROM inventory_master JOIN part on inventory_master.part_id=part.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 inventory_master.tag_reference='".$mSerialReference."' AND inventory_master.inventory_qty > 0 AND ((inventory_master.picked_qty>0) or (lower(inventory_status.inventory_status_code) IN('pkd','lost','plt'))) LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        if (mysqli_num_rows($mData) > 0)
            exit("OK  -MTT tag");
    }
    
// Test for existence of multi Serials on Inventory
    if ($mPartNumber == "")
    {
        $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.tag_reference AS tag_reference";
        $mDataQuery .=", location_type.location_type_code AS location_type_code";
        $mDataQuery .=" FROM inventory_master";
        $mDataQuery .=" LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id";
        $mDataQuery .=" LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id";
        $mDataQuery .=" LEFT JOIN location ON inventory_master.current_location_id=location.id";
        $mDataQuery .=" LEFT JOIN location_type ON location.location_type_id=location_type.id";
        $mDataQuery .=" WHERE inventory_master.serial_reference='".$mSerialReference."' AND inventory_master.inventory_qty > 0 AND ((inventory_master.picked_qty>0) OR (lower(inventory_status.inventory_status_code) IN('ok','pkd','lost','plt')))";
        $mDataQuery .=" LIMIT 2";
    }
    else
    {
        $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.tag_reference AS tag_reference";
        $mDataQuery .=", location_type.location_type_code";
        $mDataQuery .=" FROM inventory_master";
        $mDataQuery .=" JOIN part ON inventory_master.part_id=part.id";
        $mDataQuery .=" LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id";
        $mDataQuery .=" LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id";
        $mDataQuery .=" LEFT JOIN location ON inventory_master.current_location_id=location.id";
        $mDataQuery .=" LEFT JOIN location_type ON location.location_type_id=location_type.id";
        $mDataQuery .=" WHERE inventory_master.serial_reference='".$mSerialReference."' AND (part.part_number='".$mPartNumber."') AND inventory_master.inventory_qty > 0 AND ((inventory_master.picked_qty>0) OR (lower(inventory_status.inventory_status_code) IN('ok','pkd','lost','plt')))";
        $mDataQuery .=" LIMIT 1";
    }
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
//      exit("FAIL-TEST1-".$mDataQuery."-".mysqli_num_rows($mData));
        if (mysqli_num_rows($mData) == 0)
            exit("FAIL-Incorrect tag or serial");
        if (mysqli_num_rows($mData) > 1)
            exit("DATA:serialReference:".$mSerialReference."::skippartNumber,partNumber:");
        $mTagReference = "";
        $mLocTypeCode = "";
// Return associated pallet tag 
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mTagReference = $mRow['tag_reference'];
            $mLocTypeCode = $mRow['location_type_code'];
        }
        if (strtoupper($mLocTypeCode) != "MA")
        {
            exit("FAIL-Pallet / Serial is in wrong location type ".$mLocTypeCode);
        }
        
        if ($mTagReference == "" || $mTagReference == null)
            $mTagReference = $mSerialReference;
        exit("DATA:serialReference:".$mTagReference."::,partNumber::H");
}

// Post MTT transaction
elseif (($mFunction != null) && ($mFunction == "postservermtt"))
{
    $mErrMsg = "";
    $mToPlt = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "serialreference")
            $mSerialReference = trim($v2);
        elseif (strtolower($k2) == "partnumber")
            $mPartNumber = $v2;
        elseif (strtolower($k2) == "tolocationcode")
            $mToLocationCode = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
//    exit("FAIL-TEST1-".$mFilter." ".$mSerialReference);
// Get Location Code
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
    if (!$mConnection)
        return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
    $mDataQuery = "SELECT location_code FROM location WHERE location_code='".$mToLocationCode."' OR location_hash='".$mToLocationCode."' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-1".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
    $mData = mysqli_query($mConnection,$mDataQuery);
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mToLocationCode = $mRow['location_code'];
    }
//  mysqli_close($mConnection);
    
// Post Server Data from URL
//  http://172.16.1.70:8094/dispatch/mttTransaction?tagReference=loose77&locationCode=AA001A&userId=tanny
    $mJsonArray = array();
    $mJsonArray['tagReference'] = $mSerialReference;
    $mJsonArray['locationCode'] = $mToLocationCode;
    $mJsonArray['userId'] = $mCurrentUser;
// 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."mttTransaction?tagReference=".$mSerialReference."&locationCode=".$mToLocationCode."&userId=".$mCurrentUser);
        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 = "OK06-Marshalled Ok - ".$mSerialReference;
            $mErrMsg = $mResult;
            if (substr($mErrMsg,0,6) == "FAIL  ")
                $mErrMsg = "FAIL-".substr($mErrMsg,7);
            if (substr($mErrMsg,0,2)=="OK")
//              $mErrMsg = "OK06".substr($mErrMsg,2);
                $mErrMsg = "OKMS-locate Complete";
        }
    }
    catch (Exception $e)
    {
        $mErrMsg = ("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
    }
    
//  if ($mErrMsg == "")
//      $mErrMsg = "OK06-Marshalled Ok - ".$mSerialReference;
//  exit($mErrMsg);
    echo $mErrMsg;
    return;
}

// RDT Clear REPLEN in-use
elseif (($mFunction != null) && (strtolower($mFunction) == "clearreplen"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "menu")
            $mMenu = strtoupper($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
    include_once('replen.php');
    $mReturn = clearReplen($mCurrentUser,$mConnect,$mHost,$mUser,$mPwd,$mDbName,$mMenu);
    exit($mReturn);
}

// Create Receipt from Document
elseif (($mFunction != null) && (strtolower($mFunction) == "documenttoreceipt"))
{
    $mErrMsg = "";
    $mReturn = "OK  -doctorec1";

// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "haulierreference")
            $mHaulierReference = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
    include_once('postdocument.php');
    $mReturn = documentToReceipt($mHaulierReference,$mCurrentUser,$mHost,$mUser,$mPwd,$mDbName);

    exit($mReturn);
}

// RDT Screen Field Settings
elseif (($mFunction != null) && (strtolower($mFunction) == "setscreenfield"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    $mInput = "";
    $mValue = "";
    $mLayout = "";
    $mValidation = "";
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "field")
            $mField = $v2;
        elseif ($k2 == "input")
            $mInput = $v2;
        elseif ($k2 == "value")
            $mValue = $v2;
        elseif ($k2 == "layout")
            $mLayout = strtoupper($v2);
        elseif ($k2 == "validation")
            $mValidation = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
    if ($mInput != "")
        exit("DATA:".$mField."input:".$mInput.":".$mLayout.":".$mValidation);
    else
        exit("DATA:".$mField.":".$mValue.":".$mLayout.":".$mValidation);
}

// Change User Password
elseif (($mFunction != null) && (strtolower($mFunction) == "changepwd"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "userid")
            $mUserId = $v2;
        elseif ($k2 == "password")
            $mOldPassword = strtolower($v2);
        elseif ($k2 == "password1")
            $mNewPassword1 = strtolower($v2);
        elseif ($k2 == "password2")
            $mNewPassword2 = strtolower($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
    
    include_once ('user.php');
    $mStatus = changePassword($mCurrentUser,$mOldPassword,$mNewPassword1,$mNewPassword2,$mHost,$mUser,$mPwd,$mDbName);
}

// Get Message Text
elseif (($mFunction != null) && ($mFunction == "getmessage"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "messagecode")
            $mMessageCode = $v2;
        elseif ($k2 == "messagetext")
            $mMessageText = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
    include_once ('getmessage.php');
    $mStatus = getMessage($mMessageCode,$mMessageText,$mHost,$mUser,$mPwd,$mDbName);
    exit($mStatus);
}

// Try to get keywords from Message Text
elseif (($mFunction != null) && ($mFunction == "getkeyword"))
{   
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "messagetext")
            $mMessageText = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
    include_once ('getmessage.php');
    $mStatus = getKeyword($mMessageText,$mHost,$mUser,$mPwd,$mDbName);
    exit($mStatus);
}

// Expiry Date Processing
elseif (($mFunction != null) && ($mFunction == "validateexpirydate"))
{   
    $mErrMsg = "";
    
    $mPartNumber = "";
    $mSerialReference = "";
    $mExpiryDate = "";
    
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "partnumber")
            $mPartNumber = strtoupper($v2);
        elseif (strtolower($k2) == "serialreference")
            $mSerialReference = $v2;
        elseif (strtolower($k2) == "expirydate")
            $mExpiryDate = $v2;
        elseif ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty"))
            $mQty = floatval($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }

// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        die("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Check if Expiry Date is required
    if ($mExpiryDate == "")
    {
// Get id for document status
        $mShelfLife = 0;
        $mDataQuery = "SELECT id AS id, shelf_life AS shelf_life FROM part WHERE (part_number ='".$mPartNumber."') LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        $mData = (mysqli_query($mConnection,$mDataQuery));
        while($mRow = mysqli_fetch_assoc($mData))
        {
            $mShelfLife=($mRow['shelf_life']);
        }
        if ($mShelfLife == 0)
        {
            echo ("OK  -shelflife");
            return;
        }
        if ($mShelfLife == 1)
        {
            $mReturn = "DATA:serialReference:".$mSerialReference.":PPPPPP,expiryDate::HHIPPP:skipexpiryDate";
            echo($mReturn);
            return;
        }
    }
    else
    {
//      echo("FAIL-TEST1 ".$mFilter);
//      return;
// Validate Expiry Date
// Remove serarators
    
        $mExpiryDate = str_replace("/","",$mExpiryDate);
        $mExpiryDate = str_replace("-","",$mExpiryDate);
        $mExpiryDate = str_replace(".","",$mExpiryDate);
        $mDate = substr($mExpiryDate,0,2)."-".substr($mExpiryDate,2,2)."-".substr($mExpiryDate,4,4);

        if (($mDateObj = strtotime($mDate)) === false) 
        {
            echo ("FAIL-Incorrect Date ".$mDate);
            return;
        } 
        else 
        {
//          $mReturn = date_format($mDateObj,"Y/m/d H:i:s");
            $mDate = substr($mExpiryDate,4,4)."-".substr($mExpiryDate,2,2)."-".substr($mExpiryDate,0,2);
            echo("OK  -expirydate ".$mDate);
            return;
        }
    }
}

// Validate Vendor
elseif (($mFunction != null) && ($mFunction == "validatevendor"))
{   
    $mErrMsg = "";  
    $mVendorReference = ""; 
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "vendor")
            $mVendorReference = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }

// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        die("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    
// Get id for Vendor
    $mDataQuery = "SELECT id AS id FROM vendor WHERE vendor_reference_code ='".$mVendorReference."' LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    while($mRow = mysqli_fetch_assoc($mData))
    {
        $mId=($mRow['id']);
    }
    if (mysqli_num_rows($mData) == 0)
        echo("FAIL-Invalid Vendor Code");
    else
        echo("OK  -validatevendor");
    return;

}

// Create Receipt
elseif (($mFunction != null) && ($mFunction == "createreceipt"))
{   
    $mErrMsg = "";  
    $mVendorReference = "";
    $mHaulierReference = "";
    
    // Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "vendor")
            $mVendorReference = strtoupper($v2);
        elseif (strtolower($k2) == "haulier")
            $mHaulierReference = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }
    
    include_once ('transaction.php');
    $mStatus = createReceipt($mVendorReference,$mHaulierReference,$mTransactionTypeId,$mCurrentUser,$mHost,$mUser,$mPwd,$mDbName);
    echo ($mStatus);
    return;
}

// Validate Pick Shortage
elseif (($mFunction != null) && ($mFunction == "validatemts"))
{   
    $mStatus = "";  
    $mCustomerReference = "";
    $mLocationHash = "";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "customerreference")
            $mCustomerReference = strtoupper($v2);
        if (strtolower($k2) == "locationcode")
            $mLocationHash = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }

    if (($mCustomerReference == "") && ($mLocationHash == ""))
    {
        echo ("FAIL-Invalid Entry");
        return;
    }
    
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        die("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
//  exit("FAIL-TEST1-".$mFilter."-".$mCustomerReference);   
    if ($mCustomerReference != "")
    {
// Get id for Pick
        $mDataQuery = "SELECT pick_header.id AS id,pick_header.order_header_id AS order_header_id FROM pick_header WHERE pick_header.customer_reference ='".$mCustomerReference."' AND EXISTS(SELECT id FROM document_status WHERE pick_header.document_status_id=document_status.id AND document_status.document_status_code IN('open','allocated')) LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit ( "FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        while($mRow = mysqli_fetch_assoc($mData))
        {
            $mId=($mRow['id']);
            $mOrdHdrId=($mRow['order_header_id']);
        }
        if (mysqli_num_rows($mData) == 0)
            $mStatus = "FAIL-Invalid Customer Reference";
        
        if ($mStatus == "")
        {
            $mDataQuery = "SELECT document_body.id AS id FROM document_body WHERE document_header_id=".$mOrdHdrId." AND qty_expected>qty_transacted LIMIT 1";
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
            if (mysqli_num_rows($mData) == 0)
            {
                $mStatus = "FAIL-No shortages on this pick";
            }
        }
    }
    
    if (($mStatus == "") && ($mLocationHash != ""))
    {

// Test for existence of Shortage Location Type
        $mDataQuery = "SELECT location.id AS id FROM location JOIN location_type ON location.location_type_id=location_type.id WHERE location.location_hash='".$mLocationHash."' AND lower(location_type.location_type_code)='shtg' LIMIT 1";
        $mData = mysqli_query($mConnection,$mDataQuery);
        if (mysqli_num_rows($mData) == 0)
            $mStatus = "FAIL-Wrong Location Type";
    }
    
    if ($mStatus == "")
        $mStatus = "OK  -validatemts";
}

// Process Pick Shortage
elseif (($mFunction != null) && ($mFunction == "postmts"))
{   
    $mStatus = "";  
    $mCustomerReference = "";
    $mLocationHash = "";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "customerreference")
            $mCustomerReference = strtoupper($v2);
        elseif (strtolower($k2) == "locationcode")
            $mLocationHash = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }

    if (($mCustomerReference == "") || ($mLocationHash == ""))
    {
        echo ("FAIL-Invalid Entry");
        return;
    }
//  exit("FAIL-".$mFilter."-".$mCustomerReference."-".$mLocationHash."-".$mCurrentUser."-".$mHost."-".$mUser."-".$mPwd."-".$mDbName."-".$mTransactionTypeId);
    include_once ('transaction.php');
    $mDataStr = postMts($mCustomerReference,$mLocationHash,$mCurrentUser,$mHost,$mUser,$mPwd,$mDbName,$mTransactionTypeId);
    if (substr($mDataStr,0,2) == "FA")
    {
        $mStatus = $mDataStr;
        $mDataStr = "";
    }
    else
        $mStatus = "OK  -postmts";

}

// Test receipt status
elseif (($mFunction != null) && ($mFunction == "checkrecsts"))
{   
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    $mSerialReference = "";
    $mPartNumber = "";
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "serialreference")
            $mSerialReference = $v2;
        elseif ($k2 == "partnumber")
            $mPartNumber= $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Get Company Settings
    $mCloseReceipt = 0;
    $mDataQuery = "SELECT company.id AS id, company.auto_close_receipt AS auto_close_receipt FROM company LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection).$mDataQuery);
    $mData = (mysqli_query($mConnection,$mDataQuery));
    while($mRow = mysqli_fetch_assoc($mData))
    {
        $mCloseReceipt = $mRow['auto_close_receipt'];
    }
    if ($mCloseReceipt == null)
        $mCloseReceipt = 0;
    
// Get id for document status
    $mDocStsId = 0;
    $mDocClsId = 0;
    $mDocCmpId = 0;
    $mDataQuery = "SELECT id AS id, document_status_code AS document_status_code FROM document_status";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit ("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']) == "closed")
            $mDocClsId=($mRow['id']);
        if (strtolower($mRow['document_status_code']) == "complete")
            $mDocCmpId=($mRow['id']);
    }
    if ($mDocClsId == null)
        $mDocClsId = 1;
    if ($mDocCmpId == null)
        $mDocCmpId = 1; 
    
// Get Related Receipt Data
    $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_header.document_status_id AS receipt_status, 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 JOIN part ON receipt_body.part_id=part.id WHERE (part.part_number='".$mPartNumber."') AND receipt_detail.serial_reference='".$mSerialReference."' LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-3".mysqli_error($mConnection).$mDataQuery);
    $mRow = mysqli_fetch_assoc($mData);
    $mRctDtlId = ($mRow['id']);
    $mHaulierRef = ($mRow['haulier_reference']);
    $mRctHdrId = ($mRow['hdr_id']);
    $mRctDocRef = ($mRow['document_reference']);
    $mRctSts = ($mRow['receipt_status']);

//  return ("FAIL-TEST1-".$mDataQuery."-".$mRctSts."-".$mCloseReceipt."-".$mDocClsId);
    
// If not auto_receipt Putaway not allowed on open receipt
    if ($mCloseReceipt == 0 && ($mRctSts == $mDocStsId || $mRctSts == $mDocCmpId))
    {
        if (($mTransactionTypeId == "RCTS") || ($mTransactionTypeId == "CTS"))
            $mStatus = "OKMS-Receipt-".$mHaulierRef." is not closed,RCTS";
        else
            $mStatus = "FAIL-Receipt-".$mHaulierRef." is not closed.";
    }
    else
        $mStatus = "OK  -checkrecsts";
    
    exit($mStatus);
}

// validate Part WI Code
elseif (($mFunction != null) && ($mFunction == "validatewicode"))
{
    $mReturn = "";
    $mErrMsg = "";
    $mPartNumber = "";
    $mPiecePart = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "partnumber")
            $mPartNumber = trim($v2);
        elseif (strtolower($k2) == "wicode")
            $mWiCode = trim($v2);
        elseif ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty") || (strtolower($k2) == "qtyallocated"))
            $mPickQty = floatval($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        die("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());      
    $mDataQuery = "SELECT wi_code AS wi_code FROM part WHERE (part_number = '".$mPartNumber."') LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    $mData = (mysqli_query($mConnection,$mDataQuery));
    if (mysqli_num_rows($mData) > 0)
    {
        $mRow = mysqli_fetch_assoc($mData);
        if ($mWiCode == "")
        {
            if (($mRow['wi_code'] != "") && ($mRow['wi_code'] != null))
                $mReturn = "DATA:wiCode::HHHHHHHHIH:skipwiCode";
            else
                $mReturn = "DATA:wiCode::HHHHHHHHHH";
        }
        else
        {
            $l = strlen($mRow['wi_code']);
//          if (substr($mWiCode,0,$l) != strtoupper($mRow['wi_code']))
            if (strpos($mWiCode,$mRow['wi_code']) !== false)
            {
            }
            else
            {
// Populate 'confirm' screen row (first segment - before ';' is YES processing, second segment - after ; is NO processing.              
                $mTxtValue = "validaterdt:setscreenfield?field=wiCode|AND|layout=HHHHHHHHIH|AND|value=,skipqtyAllocated;validaterdt:setscreenfield?field=wiCode|AND|layout=HHHHHHHHHH|AND|value=,clearscreen:8,clearscreen:7,clearscreen:6,allocation:postwicheck?allocationid=/allocationId/|AND|plt=/toPlt/|AND|sequencingrequestid=/sequencingRequestId/|AND|documentreference=/documentReference/|AND|partnumber=/partNumber/|AND|serialreference=/serialReference/|AND|qtyallocated=/qtyAllocated/|AND|transactionTypeId=/transactionTypeIdcontent/|AND|aisle=/aisleCodecontent/|AND|fromlocationhashcode=/fromLocationHashCode/";
                if ($mTransactionTypeId == "PBTP")
                    $mTxtValue .= ",skipfromLocationHashCode";
                if ($mTransactionTypeId == "PBTTP")
                    $mTxtValue .= ",skipfromLocationHashCode";
                elseIf ($mTransactionTypeId == "PBTM")
                    $mTxtValue .= ",skipfromLocationHashCode";
                else
                    $mTxtValue .= ",page:page3";
                $mTxtValue = str_replace(":","|COLON|",$mTxtValue);
                $mTxtValue = str_replace(",","|COMMA|",$mTxtValue);
                $mStatus = "OKCC-Invalid WI Code - Retry?:YES:NO:".$mTxtValue;
                echo $mStatus;
                return;
            }
        }
    }
    else
    {
        $mReturn = "FAIL-Invalid Part Number-".$mPartNumber;
    }
//  mysqli_close($mConnection);
    if ($mReturn == "")
        $mReturn = "OK  -WI Code";
    exit($mReturn);
}

// get next FQA Task
elseif (($mFunction != null) && ($mFunction == "getnextfqa"))
{
    $mReturn = "";
    $mErrMsg = "";
    $mPartNumber = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        die("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());      
    $mDataQuery = "SELECT document_reference,part_number,serial_reference,quantity FROM fqa_tasks WHERE processed=0 ORDER BY date_created,document_reference LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    if (mysqli_num_rows($mData) > 0)
    {
        $mRow = mysqli_fetch_assoc($mData);
        $mReturn = "DATA:allocationId:".$mRow['document_reference'].",serialReference:".$mRow['serial_reference'].",partNumber:".$mRow['part_number'].",quantity:".$mRow['quantity'];
    }
    else
    {
        $mReturn = "OKMS-No Outstanding Tasks";
//        $mReturn = "OKMS-No Outstanding Tasks,CHGTRAN:FQATASK";
    }
//  mysqli_close($mConnection);
    if ($mReturn == "")
        $mReturn = "OK  -getnextfqa";
    exit($mReturn);
}

// close FQA Task
elseif (($mFunction != null) && ($mFunction == "closefqa"))
{
    $mReturn = "";
    $mErrMsg = "";
    $mPartNumber = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "serialreference")
            $mSerialReference = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        die("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());      
    $mDataQuery = "UPDATE fqa_tasks SET processed=1 WHERE serial_reference='".$mSerialReference."' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
//  mysqli_close($mConnection);
    if ($mReturn == "")
        $mReturn = "OK  -closefqa";
    exit($mReturn);
}

// Skip / Resequence Current FQA Task
elseif (($mFunction != null) && ($mFunction == "skipfqa"))
{
    $mReference = "";
    $mErrMsg = "";
    $mConnect = null;
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    
//  exit("FAIL-TEST ".$mFilter);
    
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "reference")
            $mReference = $v2;
        elseif (strtolower($k2) == "pickdetailid")
            $mPickDtlId = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
        elseif ($k2 == "rdtstart")
            $mRdtStart = trim($v2);
        elseif ($k2 == "rdtend")
            $mRdtEnd = trim($v2);
    }
    $mRdtStart = str_replace("colon",":",$mRdtStart);
    $mRdtEnd = str_replace("colon",":",$mRdtEnd);
    if (empty($mReference))
    {
        exit("FAIL-Skip Failed");
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
        
// Update Pick Status
    if (!empty($mReference))
    {
        $mDataQuery = "UPDATE fqa_tasks SET date_created=now() WHERE document_reference='$mReference' LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
//      $mReturn = updatePickHistory($mHost,$mUser,$mPwd,$mDbName,$mPickDtlId,$mInvId,$mAlcQty,$mCurrentUser,"F2SKIP",$mDtlLineNo,"",$mDtlLineNo."-".$mPickDtlPriority);

//        $mErrMsg = getPick($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerReferenceCode,$mConnect,$mToPlt);
    }
    if ($mErrMsg == "")
        exit("OK  -");
    else
        exit($mErrMsg);
}

// prompt for user printer
elseif (($mFunction != null) && ($mFunction == "promptuserprinter"))
{
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mPrinter = "";
    $mLabel = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "label")
            $mLabel = strtoupper($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }    
    
//    exit("FAIL-TEST1-".$mLabel);
    if (($mLabel == "REFRESH") || ($mLabel == ""))
    {
        if (($mTransactionTypeId = "PBTM") || ($mTransactionTypeId = "PBTP") || ($mTransactionTypeId = "PBTTP"))
            $mTxtYesValue = "report:getuserprinter?label=/confirminput/|AND|printer=/confirminput/|AND|screenoption=PPHHHHHHHH,page:page1";
        else
            $mTxtYesValue = "report:getuserprinter?label=/confirminput/|AND|printer=/confirminput/|AND|screenoption=PPHHHHH,page:page1";
        $mTxtNoValue = "page:page1";
        $mTxtValue = $mTxtYesValue.";".$mTxtNoValue;
        $mTxtValue = str_replace(":","|COLON|",$mTxtValue);
        $mTxtValue = str_replace(",","|COMMA|",$mTxtValue);
        $mStatus = "OKCI-Printer:OK:CANCEL:".$mTxtValue;
    }
    else
    {
// mysql connection - Use Passed values...
        $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
            exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
        $mPrinterAdd = "";
        $mDataQuery = "SELECT id AS id, printer_address AS printer_address, description AS printer_name FROM printer_mapping WHERE printer_code='".$mLabel."' OR printer_address='".$mLabel."' LIMIT 1";
//  exit("FAIL-TEST1-".$mFilter."-".$mDataQuery);
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection).$mDataQuery);
//  exit ("FAIL-".mysqli_error($mConnection).$mDataQuery."-".mysqli_num_rows($mData));
        if (mysqli_num_rows($mData) == 0)
            exit("FAIL-Invalid Printer Code.");
        list($mPrinterId,$mPrinterAdd,$mPrinterName) = mysqli_fetch_row($mData);
// return Printer name & IP address 
//        $mPrinterAdd = $mPrinter;
//        $mPrinterName = $mLabel;
        $mStatus = "DATA:printercontent:".$mPrinterAdd.",printerinput:".$mPrinterName."::skipdocumentReference";
    }    
    echo $mStatus;
    return;
}

// prompt for user printer
elseif (($mFunction != null) && ($mFunction == "checkuserprinter"))
{
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mPrinter = "";
    $mLabel = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "label")
            $mLabel = strtoupper($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }    
    
//    exit("FAIL-TEST1-".$mLabel);
    if (($mLabel == "REFRESH"))
    {
       $mStatus = "OK  -checkusrprinter"; 
    }
    elseif ($mLabel == "")
    {
       $mStatus = "DATA:printerinput:ZEBK::skipprinter"; 
    }
    else
    {
// mysql connection - Use Passed values...
        $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
            exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
        $mPrinterAdd = "";
        $mDataQuery = "SELECT id AS id, printer_address AS printer_address, printer_code AS printer_name FROM printer_mapping WHERE printer_code='".$mLabel."' OR printer_address='".$mLabel."' LIMIT 1";
//  exit("FAIL-TEST1-".$mFilter."-".$mDataQuery);
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection).$mDataQuery);
//  exit ("FAIL-".mysqli_error($mConnection).$mDataQuery."-".mysqli_num_rows($mData));
        if (mysqli_num_rows($mData) == 0)
            exit("FAIL-Invalid Printer Code.");
        list($mPrinterId,$mPrinterAdd,$mPrinterName) = mysqli_fetch_row($mData);
// return Printer name & IP address 
//        $mPrinterAdd = $mPrinter;
//        $mPrinterName = $mLabel;
        $allowedTransactionTypes = ["PBTME", "PBTMF", "PBTMR"];
        if (in_array($mTransactionTypeId, $allowedTransactionTypes))
        {
            $mStatus = "DATA:printercontent:".$mPrinterAdd.",printerinput:".$mPrinterName.",txtstoredvalue:".$mPrinterName."::skiptaskType";
        }
        elseif ($mTransactionTypeId == "PBTM")
        {
            $mStatus = "DATA:printercontent:".$mPrinterAdd.",printerinput:".$mPrinterName.",txtstoredvalue:".$mPrinterName;
        }
        elseif ($mTransactionTypeId == "STKPULL")
        {
            $mStatus = "DATA:printercontent:".$mPrinterAdd.",printerinput:".$mPrinterName.",txtstoredvalue:".$mPrinterName;
        }
        else
        {
            $mStatus = "DATA:printercontent:".$mPrinterAdd.",printerinput:".$mPrinterName.",txtstoredvalue:".$mPrinterName."::skipdocumentReference";
        }
    }    
    echo $mStatus;
    return;
}

// populate session variable
elseif (($mFunction != null) && ($mFunction == "postsessionvar"))
{
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mPrinter = "";
    $mLabel = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "name")
            $mName = strtoupper($v2);
        elseif ($k2 == "value")
            $mValue = strtoupper($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
    
    session_start();
// Test for existing User Session   
    if(isset($_SESSION['userData']))
    {
// Check entered User against Stored-Session User
        if ($mCurrentUser == $_SESSION['userData']['user_id'])
        {
            $_SESSION['userData'][$mName] = $mValue;
        }
    }
}

// retrieve session variable
elseif (($mFunction != null) && ($mFunction == "getsessionvar"))
{
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mPrinter = "";
    $mLabel = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "name")
            $mName = strtoupper($v2);
        elseif ($k2 == "field")
            $mField = strtoupper($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
    
    session_start();
// Test for existing User Session   
    if(isset($_SESSION['userData']))
    {
// Check entered User against Stored-Session User
        if ($mCurrentUser == $_SESSION['userData']['user_id'])
        {
            $mValue = $_SESSION['userData'][$mName];
        }
    }
    exit("DATA:".$mField.":".$mValue);
}

// retrieve session variable
elseif (($mFunction != null) && ($mFunction == "getpdf"))
{
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mPrinter = "";
    $mLabel = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "name")
            $mName = strtoupper($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
    if (file_exists($mName))
    {
    }
    elseif(file_exists($_SERVER['DOCUMENT_ROOT']."/vimsreports/$mName.pdf"))
    {
        $mName = "/vimsreports/$mName.pdf";
    }
    elseif(file_exists($_SERVER['DOCUMENT_ROOT']."/vimsreports_arcv/$mName.pdf"))
    {
        $mName = "/vimsreports_arcv/$mName.pdf";
    }

    exit("IFRAME:$mName");
}

// Prompt for confirm of unknown serial
// retrieve session variable
elseif (($mFunction != null) && ($mFunction == "promptunknownserial"))
{
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mPartNumber = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "serialreference")
            $mSerialReference = $v2;
        elseif ($k2 == "partnumber")
            $mPartNumber = $v2;    
        elseif ($k2 == "locationhash")
            $mLocationHash = $v2;    
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }    
// Check if Scanned Serial Exists
    if ($mSerialReference != "")
    {
// mysql connection
        $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
            exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
        $mBigPart = 0;
        if ($mPartNumber != "")
        {
            $mDataQuery = "SELECT id AS id, full_box_pick AS full_box_pick FROM part WHERE part_number = '".$mPartNumber."' LIMIT 1";
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                exit ("FAIL-2".mysqli_error($mConnection)."-".$mDataQuery);
            if (mysqli_num_rows($mData) == 0)
            {
                exit("FAIL-Invalid Part Number");
            }
            else
            list($mId,$mBigPart) = mysqli_fetch_row($mData);
        }
        $mDataQuery = "SELECT id AS id FROM inventory_master WHERE serial_reference='".$mSerialReference."'";
        if ($mPartNumber != "")
            $mDataQuery .= " AND part_number = '".$mPartNumber."'";
        $mDataQuery .=" LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit ("FAIL-1".mysqli_error($mConnection)."-".$mDataQuery);
        if (mysqli_num_rows($mData) == 0)
        {
            $mDataQuery = "SELECT id AS id,part_number AS part_number FROM inventory_master WHERE serial_reference='".$mSerialReference."' LIMIT 1";
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                exit ("FAIL-1".mysqli_error($mConnection)."-".$mDataQuery);
            if (mysqli_num_rows($mData) > 0)
            {
                list($mId,$mBigPart) = mysqli_fetch_row($mData);
                $mStatus = "FAIL-Serial Exists for Part ".$mBigPart;
                echo $mStatus;
                return;
            }
        }
        if (mysqli_num_rows($mData) == 0)
        {
            $mDataQuery = "SELECT id AS id FROM inventory_master WHERE serial_reference='".$mSerialReference."' LIMIT 1";
            $mDataQuery = "SELECT location.id AS id, location_type.non_exist_serial AS non_exist_serial FROM location JOIN location_type ON location.location_type_id=location_type.id WHERE (location_hash='".$mLocationHash."' or location_code='".$mLocationHash."') LIMIT 1";
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                exit ("FAIL-2".mysqli_error($mConnection)."-".$mDataQuery);
            $mNoSerial = 0;
            if (mysqli_num_rows($mData) > 0)
            {
                list($mId,$mNoSerial) = mysqli_fetch_row($mData);
            }           
            if ($mBigPart == 1)
            {
                $mNoSerial = 0;
            }
            if ($mNoSerial == 0)
            {
                $mStatus = "FAIL-Unknown Serial";
            }
            else
            {
// Populate 'confirm' screen row (first segment - before ';' is YES processing, second segment - after ; is NO processing.  
            if ($mPartNumber == "")
            {
                if ($mTransactionTypeId == "PBTM")
                    $mTxtValue = "allocation:validatepick?fromlocationhashcode=/fromLocationHashCode/|AND|vldlocation=/fromLocationHashCodecontent/|AND|serialreference=/serialReference/|AND|vldserialreference=/serialReferencecontent/|AND|partnumber=|AND|vldpartnumber=/partNumbercontent/|AND|documentreference=/documentReference/|AND|vldqty=/qtyAllocatedcontent/,validaterdt:validatewicode?partnumber=/partNumber/,validaterdt:validatepiecepart?partnumber=/partNumber/,rdttime:start,validaterdt:setscreenfield?field=toLocationHashCode|AND|layout=HHHHHHH*HH,validaterdt:setscreenfield?field=qtyAllocated|AND|layout=HHPPPPIHHH,skipqtyAllocated;validaterdt:setscreenfield?field=serialReference|AND|value=,skipserialReference";
                elseif ($mTransactionTypeId == "PBTP")
                    $mTxtValue = "allocation:validatepick?fromlocationhashcode=/fromLocationHashCode/|AND|vldlocation=/fromLocationHashCodecontent/|AND|serialreference=/serialReference/|AND|vldserialreference=/serialReferencecontent/|AND|partnumber=|AND|vldpartnumber=/partNumbercontent/|AND|documentreference=/documentReference/|AND|vldqty=/qtyAllocatedcontent/,validaterdt:validatewicode?partnumber=/partNumber/,validaterdt:validatepiecepart?partnumber=/partNumber/,rdttime:start,validaterdt:setscreenfield?field=toLocationHashCode|AND|layout=HHHHHHHHHH,validaterdt:setscreenfield?field=qtyAllocated|AND|layout=HHPPPPIHHH,skipqtyAllocated;validaterdt:setscreenfield?field=serialReference|AND|value=,skipserialReference";
                elseif ($mTransactionTypeId == "PBTTP")
                    $mTxtValue = "allocation:validatepick?fromlocationhashcode=/fromLocationHashCode/|AND|vldlocation=/fromLocationHashCodecontent/|AND|serialreference=/serialReference/|AND|vldserialreference=/serialReferencecontent/|AND|partnumber=|AND|vldpartnumber=/partNumbercontent/|AND|documentreference=/documentReference/|AND|vldqty=/qtyAllocatedcontent/,validaterdt:validatewicode?partnumber=/partNumber/,validaterdt:validatepiecepart?partnumber=/partNumber/,rdttime:start,validaterdt:setscreenfield?field=toLocationHashCode|AND|layout=HHHHHHHHHH,validaterdt:setscreenfield?field=qtyAllocated|AND|layout=HHPPPPIHHH,skipqtyAllocated;validaterdt:setscreenfield?field=serialReference|AND|value=,skipserialReference";

                else
                    $mTxtValue = "allocation:validatepick?fromlocationhashcode=/fromLocationHashCode/|AND|vldlocation=/fromLocationHashCodecontent/|AND|serialreference=/serialReference/|AND|vldserialreference=/serialReferencecontent/|AND|partnumber=|AND|vldpartnumber=/partNumbercontent/|AND|documentreference=/documentReference/|AND|vldqty=/qtyAllocatedcontent/,validaterdt:validatewicode?partnumber=/partNumber/,validaterdt:validatepiecepart?partnumber=/partNumber/,rdttime:start,validaterdt:setscreenfield?field=toLocationHashCode|AND|layout=HHHHHHH*HH,validaterdt:setscreenfield?field=qtyAllocated|AND|layout=HHPPPPIHHH,skipqtyAllocated;validaterdt:setscreenfield?field=serialReference|AND|value=,skipserialReference";
            }
            else
            {
                if ($mTransactionTypeId == "PBTM")
                    $mTxtValue = "allocation:validatepick?fromlocationhashcode=/fromLocationHashCode/|AND|vldlocation=/fromLocationHashCodecontent/|AND|serialreference=/serialReference/|AND|vldserialreference=/serialReferencecontent/|AND|partnumber=/partNumber/|AND|vldpartnumber=/partNumbercontent/|AND|documentreference=/documentReference/|AND|vldqty=/qtyAllocatedcontent/,validaterdt:validatewicode?partnumber=/partNumber/,validaterdt:validatepiecepart?partnumber=/partNumber/,rdttime:start,validaterdt:setscreenfield?field=toLocationHashCode|AND|layout=HHHHHHH*HH,validaterdt:setscreenfield?field=qtyAllocated|AND|layout=HHPPPPIHHH,skipqtyAllocated;validaterdt:setscreenfield?field=serialReference|AND|value=,skipserialReference";
                elseif ($mTransactionTypeId == "PBTP")
                    $mTxtValue = "allocation:validatepick?fromlocationhashcode=/fromLocationHashCode/|AND|vldlocation=/fromLocationHashCodecontent/|AND|serialreference=/serialReference/|AND|vldserialreference=/serialReferencecontent/|AND|partnumber=/partNumber/|AND|vldpartnumber=/partNumbercontent/|AND|documentreference=/documentReference/|AND|vldqty=/qtyAllocatedcontent/,validaterdt:validatewicode?partnumber=/partNumber/,validaterdt:validatepiecepart?partnumber=/partNumber/,rdttime:start,validaterdt:setscreenfield?field=toLocationHashCode|AND|layout=HHHHHHHHHH,validaterdt:setscreenfield?field=qtyAllocated|AND|layout=HHPPPPIHHH,skipqtyAllocated;validaterdt:setscreenfield?field=serialReference|AND|value=,skipserialReference";
               elseif ($mTransactionTypeId == "PBTTP")
                    $mTxtValue = "allocation:validatepick?fromlocationhashcode=/fromLocationHashCode/|AND|vldlocation=/fromLocationHashCodecontent/|AND|serialreference=/serialReference/|AND|vldserialreference=/serialReferencecontent/|AND|partnumber=/partNumber/|AND|vldpartnumber=/partNumbercontent/|AND|documentreference=/documentReference/|AND|vldqty=/qtyAllocatedcontent/,validaterdt:validatewicode?partnumber=/partNumber/,validaterdt:validatepiecepart?partnumber=/partNumber/,rdttime:start,validaterdt:setscreenfield?field=toLocationHashCode|AND|layout=HHHHHHHHHH,validaterdt:setscreenfield?field=qtyAllocated|AND|layout=HHPPPPIHHH,skipqtyAllocated;validaterdt:setscreenfield?field=serialReference|AND|value=,skipserialReference";
               else
                    $mTxtValue = "allocation:validatepick?fromlocationhashcode=/fromLocationHashCode/|AND|vldlocation=/fromLocationHashCodecontent/|AND|serialreference=/serialReference/|AND|vldserialreference=/serialReferencecontent/|AND|partnumber=/partNumber/|AND|vldpartnumber=/partNumbercontent/|AND|documentreference=/documentReference/|AND|vldqty=/qtyAllocatedcontent/,validaterdt:validatewicode?partnumber=/partNumber/,validaterdt:validatepiecepart?partnumber=/partNumber/,rdttime:start,validaterdt:setscreenfield?field=toLocationHashCode|AND|layout=HHHHHHH*HH,validaterdt:setscreenfield?field=qtyAllocated|AND|layout=HHPPPPIHHH,skipqtyAllocated;validaterdt:setscreenfield?field=serialReference|AND|value=,skipserialReference";

            }
                $mTxtValue = str_replace(":","|COLON|",$mTxtValue);
                $mTxtValue = str_replace(",","|COMMA|",$mTxtValue);
                $mStatus = "OKCC-Unknown Serial - Accept?:YES:NO:".$mTxtValue;
            }
            echo $mStatus;
            return;
        }
    }
}

// validatetraintrolleyloc
// validate / retrieve train trolley from zone destination
elseif (($mFunction != null) && ($mFunction == "validatetraintrolleyloc"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mTrolley = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "serialreference")
            $mSerialReference = $v2;
        elseif ($k2 == "partnumber")
            $mPartNumber = $v2;    
        elseif ($k2 == "locationhash")
            $mLocationHash = $v2;    
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// get inventory_master
    $mDataQuery = "SELECT id, originating_detail_id FROM inventory_master WHERE tag_reference='".$mSerialReference."' LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    if (mysqli_num_rows($mData) == 0)
    {
        $mDataQuery = "SELECT id, originating_detail_id 
                        FROM inventory_master 
                        WHERE serial_reference='".$mSerialReference."'
                        OR tag_reference='".$mSerialReference."' LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    }
    if (mysqli_num_rows($mData) == 0)
    {
        $mErrMsg = "FAIL-Invalid Pallet or Serial";
    }
    if ($mErrMsg == "")
    {
        list($mInvId,$mInvPckId) = mysqli_fetch_row($mData);
        if (($mInvPckId == null) || ($mInvPckId == ""))
        {
            $mErrMsg = "FAIL-No Train Trolley for this Pallet";
        }
        else
        {
            $mDataQuery = "SELECT pick_detail.document_reference, trolley.trolley 
                            FROM pick_detail 
                            JOIN zone_destination ON pick_detail.zone_destination=zone_destination.zone_destination 
                            JOIN trolley ON zone_destination.trolley_id=trolley.id 
                            WHERE pick_detail.id=".$mInvPckId." LIMIT 1";
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
            if (mysqli_num_rows($mData) == 0)
            {
                $mErrMsg = "FAIL-No Train Trolley";
            }
            else
            {
                list($mDocRef,$mTrolley) = mysqli_fetch_row($mData);
                $mErrMsg = "DATA:sequencingRequestId:".$mDocRef.",toLocationHashCodecontent:".$mDocRef." - ".$mTrolley;
            }
        }
    }
    if ($mErrMsg == "")
    {
        $mErrMsg = "OK  -validatetraintrolleyloc";
    }
}

// validatetraintrolleyhash
// validate / retrieve train trolley from zone destination
elseif (($mFunction != null) && ($mFunction == "validatetraintrolleyhash"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mTrolley = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "serialreference")
            $mSerialReference = $v2;
        elseif ($k2 == "partnumber")
            $mPartNumber = $v2;    
        elseif ($k2 == "locationhash")
            $mLocationHash = strtoupper($v2);
        elseif ($k2 == "vldlocationhash")
            $mVldLocationHash = strtoupper($v2);
        elseif ($k2 == "mandatory")
            $mMandatory = strtoupper($v2);
        elseif ($k2 == "trainreference")
            $mTrainRef = $v2;    
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// get inventory_master
    $mDataQuery = "SELECT id FROM train_locations WHERE train_location_hash='".$mLocationHash."' AND train_location_code LIKE('".$mTrainRef."%') LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    if (mysqli_num_rows($mData) == 0)
    {
        $mErrMsg = "FAIL-Invalid Train Location";
    }
    if ($mErrMsg == "")
    {
        if ($mMandatory == "Y")
        {
            $mDataQuery = "SELECT id,train_location_hash FROM train_locations WHERE train_location_hash='".$mVldLocationHash."'";
            $mDataQuery .=" OR train_location_code='".$mVldLocationHash."'";
            $mDataQuery .=" LIMIT 1";
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
            list($mLocId,$mVldLocationHash) = mysqli_fetch_row($mData);
            if ($mLocationHash != $mVldLocationHash)
            {
                $mErrMsg = "FAIL-Train Location does not match prompt";
            }
        }
    }
    if (substr($mErrMsg,0,2) != "FA")
    {
        $mErrMsg = "OK  -validatetrain";
    }
        exit($mErrMsg);
}

elseif (($mFunction != null) && ($mFunction == "validatetrain"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mTrolley = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "train")
            $mTrainRef = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// get inventory_master
    $mDataQuery = "SELECT id FROM train WHERE train='".$mTrainRef."' LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    if (mysqli_num_rows($mData) == 0)
    {
        $mErrMsg = "FAIL-Invalid Train";
    }
    if ($mErrMsg == "")
    {
        $mErrMsg = "OK  -validatetrain";
    }
}

elseif (($mFunction != null) && ($mFunction == "validatetrainloc"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mTrolley = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "reference")
            $mReference = $v2;
        elseif ($k2 == "trolley")
            $mTrolley = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// get inventory_master
    $mDataQuery = "SELECT id,train_location_code FROM train_locations WHERE train_location_code LIKE('".$mReference."%') AND train_location_code LIKE('%".$mTrolley."%') LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    if (mysqli_num_rows($mData) == 0)
    {
        $mErrMsg = "FAIL-Invalid Train Trolley";
    }
    if ($mErrMsg == "")
    {
//        $mErrMsg = "OK  -validatetrain";
        LIST($mId,$mTrolley) = mysqli_fetch_row($mData);
        $mErrMsg = "DATA:traincontent:".$mTrolley.",traininput:".$mTrolley;
    }
}
/*
try
{
    if (mysqli_stat($mConnection) !== false) 
    {
        mysqli_close($mConnection);
    }
    else 
    {
    }
}
catch(Exception $e)
{
}
*/
if (($mStatus == "") && ($mErrMsg != ""))
    $mStatus = $mErrMsg;
// echo json_encode(array_merge(array("status" => $mStatus),array("data" => $mDataStr),$mSQLData));
if ($mDataStr == "")
    echo $mStatus;
elseif(substr($mDataStr,0,4) == "DATA")
    echo $mDataStr;
else
    echo $mStatus.$mDataStr;        
exit;

function validateGoodsInSerial($mHost,$mUser,$mPwd,$mDbName,$mFilter)
{
   // mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Set default error message
    $mErrMsg = "";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mMin = "";
    $mMax = "";
    $mTransactionTypeId = "";
    $mVendorPart = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "partnumber")
            $mPartNumber = strtoupper($v2);
        elseif ($k2 == "vendorpartcode")
            $mVendorPart = strtoupper($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = strtoupper($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
// Test for Valid Part Number
    $mDataQuery = "SELECT id, modular FROM part WHERE part_number='".$mPartNumber."' 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 Part Number";
    }
    else
    {
// test for modular part & RBTP
        $mRow = mysqli_fetch_assoc($mData); 
        if (($mRow['modular'] == 1) && ($mTransactionTypeId == "RBTD" || $mTransactionTypeId == "RBTC"))
        {
            return "FAIL-This Part must be received to a pallet";
        }
    }
// If no serial just return
    if (!$mSerialReference)
    {
        return "OK  - validategoodin";
    }
    $i = 0;
    if (substr($mTransactionTypeId,0,2)=="RB")
    {
// Test for existence of Part Serial on Inventory
        $mDataQuery = "SELECT inventory_master.id AS id FROM inventory_master JOIN part ON inventory_master.part_id=part.id WHERE (part.part_number='".$mPartNumber."') AND inventory_master.serial_reference='".$mSerialReference."' AND inventory_master.inventory_qty > 0 LIMIT 1";
        $mData = mysqli_query($mConnection,$mDataQuery);
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mErrMsg = "FAIL-Serial Already Exists for Part";
            $i++;
        }
        if ($i == 0)
        {
            $mDataQuery = "SELECT scan_data.id AS id FROM scan_data WHERE part_number='".$mPartNumber."' AND serial_reference='".$mSerialReference."' AND scan_qty > 0 LIMIT 1";
            $mData = mysqli_query($mConnection,$mDataQuery);
            $i = 0;
            while($mRow = mysqli_fetch_assoc($mData)) 
            {
                $mErrMsg = "FAIL-Scan Data already exists ";
                $i++;
            }
        }
    }
    if ($i == 0)
    {
// JIS Validation
        if ($mTransactionTypeId == "JRBTP")
        {
                $mDataQuery = "SELECT receipt_detail.id AS id FROM receipt_detail JOIN part ON receipt_detail.part_id=part.id WHERE (part.part_number='".$mPartNumber."' OR part.vendor_part_code='".$mPartNumber."') AND receipt_detail.serial_reference='".$mSerialReference."' LIMIT 1";
                $mData = mysqli_query($mConnection,$mDataQuery);
                if (mysqli_num_rows($mData) == 0)
                {
                    return "FAIL-Invalid Part or Serial";
                }
        }
    }
    if ($mErrMsg == "")
    {
// Get id for inventory status
        $mInvStsId = 0;
        $mInvRcvId = 0;
        $mInvPkdId = 0;
        $mInvPltId = 0;
        $mInvMisId = 0;
        $mInvQaId = 0;
        $mInvNrId = 0;
        $mInvOvrId = 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']) == "pkd")
                $mInvPkdId = ($mRow['id']);
            elseif (strtolower($mRow['inventory_status_code']) == "plt")
                $mInvPltId = ($mRow['id']);
            elseif (strtolower($mRow['inventory_status_code']) == "qtine")
                $mInvQaId = ($mRow['id']);
            elseif (strtolower($mRow['inventory_status_code']) == "missing")
                $mInvMisId = ($mRow['id']);
            elseif (strtolower($mRow['inventory_status_code']) == "noran")
                $mInvNrId = ($mRow['id']);
            elseif (strtolower($mRow['inventory_status_code']) == "overbooking")
                $mInvOvrId = ($mRow['id']);
        }
        if ($mInvPkdId == null && $mInvPltId != null)
            $mInvPkdId = $mInvPltId;
        if (($mInvNrId == 0) || ($mInvNrId == null))
            $mInvNrId = $mInvStsId;
            
        if ($mTransactionTypeId == "CTS" || $mTransactionTypeId == "CTL")
        {
            $mDataQuery = "SELECT inventory_master.id AS id,inventory_master.inventory_status_id AS inventory_status_id";
            $mDataQuery .=" ,part.fixed_location_id AS fixed_location_id";
            $mDataQuery .=" ,location_type.location_type_code AS location_type_code";
            $mDataQuery .=" FROM inventory_master";
            $mDataQuery .=" JOIN part ON inventory_master.part_id=part.id";
            $mDataQuery .=" LEFT JOIN location ON inventory_master.current_location_id=location.id";
            $mDataQuery .=" LEFT JOIN location_type ON location.location_type_id=location_type.id";
            $mDataQuery .=" WHERE (part.part_number='".$mPartNumber."') AND inventory_master.serial_reference='".$mSerialReference."' AND inventory_master.inventory_qty > 0";
            $mDataQuery .=" LIMIT 1";
            $mData = mysqli_query($mConnection,$mDataQuery);
            if (mysqli_num_rows($mData) == 0)
                $mErrMsg = "FAIL-No Available inventory exists for this serial reference";
            else
            {
                list($mInvId,$mInvInvId,$mInvLocId,$mLocTypeCode) = mysqli_fetch_row($mData);
    // CTS not allowed for inventory_status RCV
                if ($mInvInvId==$mInvRcvId)
                {
                    $mErrMsg = "FAIL-This Serial cannot be moved until receipt is closed";
                }
                if ($mErrMsg == "")
                {
                    if ($mInvInvId == $mInvOvrId)
                    {
                        $mOverBook = 1;
                        if (!empty($mInvLocId))
                        {
                            $mDataQuery = "SELECT id,locate_overbooking FROM location_type WHERE id=".$mInvLocId." LIMIT 1";
                            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                                exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
                            if (mysqli_num_rows($mData) > 0)
                            {                           
                                list($mId,$mOverBook) = mysqli_fetch_row($mData);
                                if ($mOverBook != 1)
                                    $mErrMsg = "FAIL-Overbooked Serials are not allowed";
                            }
                        }
                        else
                        {
//                          $mErrMsg = "FAIL-Overbooked Serials are not allowed";
                        }
                    }
                }
                if ($mErrMsg == "")
                {
                    if (strtolower($mLocTypeCode) == "qa")
                    {
                        $mErrMsg = "FAIL-Box in inspection – use FQA";
                    }
                }
            }
        }
    }
    
//  mysqli_close($mConnection);
    
    $mDataStr = "";
    If ($i == 0)
    {
        $mStatus = "OK  -validategoodinserial";
    }
    if ($mErrMsg == "")
    {
        $mStatus = "OK  -validategoodinserial";
    }
    else
    {
        $mStatus = $mErrMsg;
    }
    return $mStatus;
}

function validateCustomerPart($mHost,$mUser,$mPwd,$mDbName,$mFilter)
{
    // mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Set default error message
    $mErrMsg = "";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mPartNumber = "";
    $mVendorPartCode ="";
    $mHaulierReference = "";
    $mCustomerReference = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "haulierreference")
            $mHaulierReference = strtoupper($v2);
        elseif ($k2 == "customerreference")
            $mCustomerReference = strtoupper($v2);
        elseif ($k2 == "partnumber")
            $mPartNumber = strtoupper($v2);
        elseif ($k2 == "vendorpartcode")
            $mVendorPartCode = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
// Validate Part Number
    if ($mPartNumber != "")
    {
//      $mDataQuery = "SELECT id AS id, part_number AS part_number FROM part WHERE part_number = '".$mPartNumber."' OR vendor_part_code='".$mPartNumber."' LIMIT 1";
        $mDataQuery = "SELECT id AS id, part_number AS part_number FROM part WHERE part_number = '".$mPartNumber."' LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        if (mysqli_num_rows($mData) == 0)
        {
//          mysqli_close($mConnection);
            return "FAIL-Invalid Part Number";
        }
//      $mRow = mysqli_fetch_assoc($mData);
//      $mPartNumber = $mRow['part_number'];
        list($mPartId,$mPartNumber) = mysqli_fetch_row($mData);
    }
// Test for existence of vendor on Receipt Header & Part
    if ($mPartNumber != "")
        if ($mHaulierReference != "")
            $mDataQuery = "SELECT receipt_header.id AS id, part.vendor_id AS vendor_id, receipt_header.customer_reference AS reference FROM receipt_header JOIN part ON receipt_header.vendor_id=part.vendor_id WHERE receipt_header.haulier_reference='".$mHaulierReference."' AND part.part_number = '".$mPartNumber."' LIMIT 1";
        else
            $mDataQuery = "SELECT receipt_header.id AS id, part.vendor_id AS vendor_id, receipt_header.customer_reference AS reference FROM receipt_header JOIN part ON receipt_header.vendor_id=part.vendor_id WHERE receipt_header.customer_reference='".$mCustomerReference."' AND part.part_number = '".$mPartNumber."' LIMIT 1";
    elseif ($mVendorPartCode != "")
        if ($mHaulierReference != "")
            $mDataQuery = "SELECT receipt_header.id AS id, part.vendor_id AS vendor_id, receipt_header.customer_reference AS reference FROM receipt_header JOIN part ON receipt_header.vendor_id=part.vendor_id WHERE receipt_header.haulier_reference='".$mHaulierReference."' AND part.jis_supply_group = '".$mVendorPartCode."' LIMIT 1";
        else
            $mDataQuery = "SELECT receipt_header.id AS id, part.vendor_id AS vendor_id, receipt_header.customer_reference AS reference FROM receipt_header JOIN part ON receipt_header.vendor_id=part.vendor_id WHERE receipt_header.customer_reference='".$mCustomerReference."' AND part.jis_supply_group = '".$mVendorPartCode."' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    $mData = mysqli_query($mConnection,$mDataQuery);

    if ((mysqli_num_rows($mData) == 0) && ($mTransactionTypeId == "JRBTP"))
    {
        if ($mHaulierReference != "")
            $mDataQuery = "SELECT receipt_header.id AS id, receipt_header.vendor_id AS vendor_id, receipt_header.customer_reference AS reference FROM receipt_header WHERE upper(receipt_header.haulier_reference)='".$mHaulierReference."' LIMIT 1";
        else
            $mDataQuery = "SELECT receipt_header.id AS id, receipt_header.vendor_id AS vendor_id, receipt_header.customer_reference AS reference FROM receipt_header WHERE upper(receipt_header.customer_reference)='".$mCustomerReference."' 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)) 
    {
        $mRctHdrId = ($mRow['id']);
        $mVendorId =($mRow['vendor_id']);
        $mCustomerRef =($mRow['reference']);
        $i++;
    }
//  exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData)."-".$mVendorId."-".$mRctHdrId);
    $mDataStr = "";
    If ($i == 1)
    {
        $mStatus = "";
    }
    else
    {
        if ($mPartNumber != "")
//          $mDataQuery = "SELECT vendor.vendor_name AS vendor_code FROM vendor JOIN part ON vendor.id=part.vendor_id WHERE part.part_number='".$mPartNumber."' OR (part.jis_supply_group <> '' AND part.jis_supply_group='".$mPartNumber."') LIMIT 1";
            $mDataQuery = "SELECT vendor.vendor_name AS vendor_code FROM vendor JOIN part ON vendor.id=part.vendor_id WHERE part.part_number='".$mPartNumber."' LIMIT 1";
        elseif ($mVendorPartCode != "")
            $mDataQuery = "SELECT vendor.vendor_name AS vendor_code FROM vendor JOIN part ON vendor.id=part.vendor_id WHERE (part.jis_supply_group <> '' AND part.jis_supply_group='".$mVendorPartCode."') OR part.part_number='".$mVendorPartCode."' 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)) 
        {
            $mErrMsg = ($mRow['vendor_code']);
            $i++;
        }
        if ($i == 0)
//          $mStatus = "FAIL-Incorrect Vendor for this Part ";
//      else
            $mStatus = "FAIL-Invalid Vendor or Part";
    }
// JIS Receipt
    if (($mTransactionTypeId == "JRBTP") && ($mVendorPartCode != ""))
    {
        if ($mCustomerRef != "")
            if ($mHaulierReference != "")
                $mDataQuery = "SELECT part.id AS id, part.part_number AS part_number FROM receipt_body JOIN receipt_header ON receipt_body.receipt_header_id=receipt_header.id JOIN part ON receipt_body.part_id=part.id WHERE upper(receipt_header.haulier_reference)='".$mHaulierReference."' AND (upper(part.jis_supply_group)='".$mVendorPartCode."' OR upper(part.part_number)='".$mVendorPartCode."') LIMIT 1";
            else    
                $mDataQuery = "SELECT part.id AS id, part.part_number AS part_number FROM receipt_body JOIN receipt_header ON receipt_body.receipt_header_id=receipt_header.id JOIN part ON receipt_body.part_id=part.id WHERE upper(receipt_header.customer_reference)='".$mCustomerReference."' AND (upper(part.jis_supply_group)='".$mVendorPartCode."' OR upper(part.part_number)='".$mVendorPartCode."') LIMIT 1";
        else
            $mDataQuery = "SELECT part.id AS id, part.part_number AS part_number FROM part WHERE (upper(part.jis_supply_group)='".$mVendorPartCode."' OR upper(part.part_number)='".$mVendorPartCode."') LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $mData = mysqli_query($mConnection,$mDataQuery);
//      exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
        $i = 0;
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $i++;
            return "DATA:partNumber:".$mRow['part_number'].",quantity:1";
        }
        If ($i == 0)
        {
            return "FAIL-Incorrect Vendor Part for this Receipt";
        }
    }
}
