<?php
//
// VIMS RDT Receiving Processing
// ----------------------------------------------------------------------------------------
// Modified 2020-03-23 - Initial KUK Version
// 2020-12-02 - completeCase - Send message to service via curl.
// 2020-12-02 - completeCase - set status to complete not closed.
// 2021-04-13 - checkcase - check for 'closed' or 'transmitted'
// 2021-05-12 - Allow receipt of unknown parts
// 2021-07-01 - validatereceipt - Combine Receiving validation
// 2021-07-05 - validatecase,checkcase,checkpartcase - match scanned string.
// 2021-07-14 - validatereceipt - added serial field length check.    
// ----------------------------------------------------------------------------------------

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

$mFunction          = $_GET['function'];
$mConnect           = $_GET['connection'];
$mUser              = $_GET['user'];
$mPwd               = $_GET['pword'];
$mHost              = $_GET['host'];
$mDbName            = $_GET['dbase'];
$mTableName         = $_GET['table'];
$mFilter            = $_GET['filter'];
$mReturnFields      = $_GET['returnfields'];

$mFilter = str_replace("|AND|","&",$mFilter);
$mFilter = str_replace("/dbase/",$mDbName,$mFilter);

$mSQLData = array();

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

// echo("fail-TEST1".$mFunction."-".$mFilter);

// Get Case list for select
if (($mFunction != null) && (strtolower($mFunction) == "getcaselist"))
{
//  echo("FAIL-TEST2");
    $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")
            $mCustomerRef = trim($v2);
        elseif ($k2 == "tocase")
            $mToCase = trim($v2);
        elseif ($k2 == "key")
            $mKey = trim($v2);      
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    $mStatus = getCaseList($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerRef,$mKey);
    echo $mStatus;
    return;
}
elseif (($mFunction != null) && (strtolower($mFunction) == "checkcasecomplete"))
{
//  echo("FAIL-TEST2");
    $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")
            $mCustomerRef = trim($v2);
        elseif ($k2 == "tocase")
            $mToCase = trim($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = trim($v2);
        elseif ($k2 == "partnumber")
            $mPartNumber = trim($v2);
        elseif ($k2 == "key")
            $mKey = trim($v2);      
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    $mStatus = checkCaseComplete($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerRef,$mToCase,$mSerialReference,$mPartNumber,$mTransactionTypeId);
    echo $mStatus;
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "completecase"))
{
//  echo("FAIL-TEST2");
    $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 == "confirm")
            $mConfirm = strtoupper(trim($v2));
        elseif ($k2 == "customerreference")
            $mCustomerRef = trim($v2);
        elseif ($k2 == "tocase")
            $mToCase = trim($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = trim($v2);
        elseif ($k2 == "key")
            $mKey = trim($v2);      
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    if ((substr($mConfirm,0,1) == "N") || (substr($mConfirm,0,2) == "NO"))
        $mStatus = "DATA:confirm::HHHHHH:skip3";
    elseif ((substr($mConfirm,0,1) == "Y") || (substr($mConfirm,0,3) == "YES"))
        $mStatus = completeCase($mHost,$mUser,$mPwd,$mDbName,$mConnect,$mCurrentUser,$mCustomerRef,$mToCase);
    else
        $mStatus = "FAIL-Invalid option";
    echo $mStatus;
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "validatecase"))
{
//  echo("FAIL-TEST2");
    $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 == "confirm")
            $mConfirm = strtoupper(trim($v2));
        elseif ($k2 == "customerreference")
            $mCustomerRef = trim($v2);
        elseif ($k2 == "tocase")
            $mToCase = trim($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = trim($v2);
        elseif ($k2 == "key")
            $mKey = trim($v2);      
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    $mStatus = validateCase($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerRef,$mToCase,$mTransactionTypeId);
    echo $mStatus;
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "checkpartcase"))
{
//  echo("FAIL-TEST2");
    $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 == "confirm")
            $mConfirm = strtoupper(trim($v2));
        elseif ($k2 == "customerreference")
            $mCustomerRef = trim($v2);
        elseif ($k2 == "tocase")
            $mToCase = trim($v2);
        elseif ($k2 == "partnumber")
            $mPartNumber = trim($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = trim($v2);
        elseif ($k2 == "key")
            $mKey = trim($v2);      
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    $mStatus = checkPartCase($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerRef,$mToCase,$mSerialReference,$mPartNumber);
    echo $mStatus;
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "checkcase"))
{
//  echo("FAIL-TEST2");
    $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 == "confirm")
            $mConfirm = strtoupper(trim($v2));
        elseif ($k2 == "customerreference")
            $mCustomerRef = trim($v2);
        elseif ($k2 == "tocase")
            $mToCase = trim($v2);
        elseif ($k2 == "partnumber")
            $mPartNumber = trim($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = trim($v2);
        elseif ($k2 == "key")
            $mKey = trim($v2);      
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    $mStatus = checkCase($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerRef,$mToCase,$mSerialReference,$mPartNumber,$mTransactionTypeId);
    echo $mStatus;
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "confirmpartcase"))
{

//  echo("FAIL-TEST2");
    $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 == "confirm")
            $mConfirm = strtoupper(trim($v2));
        elseif ($k2 == "customerreference")
            $mCustomerRef = trim($v2);
        elseif ($k2 == "tocase")
            $mToCase = trim($v2);
        elseif ($k2 == "partnumber")
            $mPartNumber = trim($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = trim($v2);
        elseif ($k2 == "key")
            $mKey = trim($v2);      
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
//  exit ("FAIL-test1-".$mFilter);
    if ((substr($mConfirm,0,1) == "Y") || (substr($mConfirm,0,3) == "YES"))
    {
        $mStatus = "DATA:confirm::HHHHHH:skip4";
    }
    else
    {   
        $mStatus = "DATA:confirm::HHHHHH:skip3";
    }
    echo $mStatus;
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "confirmcase"))
{

//  echo("FAIL-TEST2");
    $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 == "confirm")
            $mConfirm = strtoupper(trim($v2));
        elseif ($k2 == "customerreference")
            $mCustomerRef = trim($v2);
        elseif ($k2 == "tocase")
            $mToCase = trim($v2);
        elseif ($k2 == "partnumber")
            $mPartNumber = trim($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = trim($v2);
        elseif ($k2 == "key")
            $mKey = trim($v2);      
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
//  exit ("FAIL-test1-".$mFilter);
    if ((substr($mConfirm,0,1) == "Y") || (substr($mConfirm,0,3) == "YES"))
    {
        $mStatus = validateCase($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerRef,$mToCase,$mTransactionTypeId);
        $mStatus = "DATA:confirm::HHHHHH:skip3";
    }
    else
    {   
        $mStatus = "DATA:confirm::HHHHHH:skip2,toCase::PIPPPP";
    }
    echo $mStatus;
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "showcaseplt"))
{
//  echo("FAIL-TEST2");
    $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")
            $mCustomerRef = trim($v2);
        elseif ($k2 == "case")
            $mToCase = trim($v2);
        elseif ($k2 == "partnumber")
            $mPartNumber = trim($v2);   
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    
    $mStatus = showCasePlt($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mPartNumber,$mTransactionTypeId);

    echo $mStatus;
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "zonecaseplt"))
{
//  echo("FAIL-TEST2");
    $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")
            $mCustomerRef = trim($v2);
        elseif ($k2 == "case")
            $mToCase = trim($v2);
        elseif ($k2 == "toplt")
            $mToPlt = trim($v2);
        elseif ($k2 == "partnumber")
            $mPartNumber = trim($v2);
        elseif ($k2 == "serialreference")
            $mSerialRef = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    
    $mStatus = zoneCasePlt($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerReference, $mPartNumber, $mSerialRef, $mToCase, $mToPlt);

    echo $mStatus;
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "checkoverbooking"))
{
//  echo("FAIL-TEST2");
    $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")
            $mCustomerRef = trim($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = trim($v2);
        elseif ($k2 == "partnumber")
            $mPartNumber = trim($v2);
        elseif ($k2 == "key")
            $mKey = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    $mStatus = checkOverbooking($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerRef,$mSerialReference,$mPartNumber,$mTransactionTypeId);
    echo $mStatus;
    return;
}

// validate scanned Qty against Counted Qty.
elseif (($mFunction != null) && ($mFunction == "checkcountqty"))
{
    $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
    {
// Populate 'confirm' screen row
        if ($mTransactionTypeId == "RBTP")
        {
            $mTxtValue = "receiving:confirmcountqty?confirm=/confirm/,validaterdt:updateplt?customerreference=/customerReference/|AND|tolocationhashcode=/toLocationHashCode/|AND|toplt=/toPlt/|AND|ranorder=/ranOrder/|AND|partnumber=/partNumber/|AND|serialreference=/serialReference/|AND|deliverynote=/deliveryNote/|AND|qty=/quantity/|AND|countqty=/countQty/,validaterdt:setscreenfield?field=countQty|AND|value=|AND|layout=HHHHHH,validaterdt:setscreenfield?field=confirm|AND|value=|AND|layout=HHHHHH,clearscreen:6,clearscreen:5,clearscreen:4,clearscreen:3,page:page3";
        }
        elseif ($mTransactionTypeId == "RBTC")
        {
            $mTxtValue = "receiving:confirmcountqty?confirm=/confirm/,validaterdt:posttransaction?customerReference=/customerReference/|AND|toLocationHashCode=/toLocationHashCode/|AND|partNumber=/partNumber/|AND|quantity=/quantity/|AND|countqty=/countQty/|AND|serialReference=/serialReference/|AND|deliveryNote=/deliveryNote/|AND|transactionTypeId=/transactionTypeIdcontent/|AND|tocase=/toCase/,receiving:showcaseplt?partnumber=/partNumber/|AND|transactionTypeId=/transactionTypeIdcontent/,receiving:checkcasecomplete?customerreference=/customerReference/|AND|tocase=/toCase/|AND|serialreference=/serialReference/|AND|partnumber=/partNumber/,clearscreen:6,clearscreen:5,clearscreen:4,clearscreen:3,validaterdt:setscreenfield?field=countQty|AND|value=|AND|layout=HHHHHHH,page:page4";
        }
        else
        {
            $mTxtValue = "receiving:confirmcountqty?confirm=/confirm/,validaterdt:posttransaction?customerReference=/customerReference/|AND|toLocationHashCode=/toLocationHashCode/|AND|partNumber=/partNumber/|AND|quantity=/quantity/|AND|countqty=/countQty/|AND|serialReference=/serialReference/|AND|deliveryNote=/deliveryNote/|AND|transactionTypeId=/transactionTypeIdcontent/|AND|tocase=,receiving:showcaseplt?partnumber=/partNumber/|AND|transactionTypeId=/transactionTypeIdcontent/,receiving:checkcasecomplete?customerreference=/customerReference/|AND|tocase=|AND|serialreference=/serialReference/|AND|partnumber=/partNumber/,clearscreen:6,clearscreen:5,clearscreen:4,clearscreen:3,validaterdt:setscreenfield?field=countQty|AND|value=|AND|layout=HHHHHH,page:page3";
        }
        $mTxtValue = str_replace(":","|COLON|",$mTxtValue);
        $mTxtValue = str_replace(",","|COMMA|",$mTxtValue);
        $mStatus = "OKCC-Is this count correct?:YES:NO";
    }
    echo $mStatus;
    return;
}
elseif (($mFunction != null) && ($mFunction == "confirmcountqty"))
{
    // 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 == "confirm")
            $mConfirm = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
    if ((substr($mConfirm,0,1) == "N") || (substr($mConfirm,0,2) == "NO"))
        $mStatus = "DATA:confirm::HHHHHH,countQty::HHHHHI:skip6";
    elseif ((substr($mConfirm,0,1) == "Y") || (substr($mConfirm,0,3) == "YES"))
        $mStatus = "OK  -confirmcountqty";
    else
        $mStatus = "FAIL-Invalid option".$mConfirm;
    echo $mStatus;
    return;
}
elseif (($mFunction != null) && ($mFunction == "checkreceiptqa"))
{
    // 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 == "customerreference")
            $mCustomerReference = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
    
    $mStatus = checkReceiptQa($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerReference);
    
    if (empty($mStatus))
        $mStatus = "FAIL-System Error";
    exit ($mStatus);
}

elseif (($mFunction != null) && (strtolower($mFunction) == "checkunadvisedpart"))
{
//  echo("FAIL-TEST2");
    $mConfirm = "";
    $mReference = "";
    $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 == "reference")
            $mReference = trim($v2);
        elseif ($k2 == "partnumber")
            $mPartNumber = trim($v2);
        elseif ($k2 == "confirm")
            $mConfirm = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }   
    $mStatus = checkUnadvisedPart($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mReference,$mPartNumber,$mConfirm,$mTransactionTypeId);
    echo $mStatus;
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "validatereceipt"))
{
    $mStatus = "";
    $mPartNumber = "";
    $mSerialReference = "";
// 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 :
    for ($i = 0; $i < count($mArray1); $i++)
    {
        $s = 0;
        $e = 0;
        $k1 = $mArray1[$i];
        $s = strpos($k1,":");
        if ($s >= 0)
        {
            $k2 = substr($k1,0,$s);
            $v2 = substr($k1,$s+1);
        }       
        if ($k2 == "partnumber")
            $mPartNumber = trim($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    if (($mPartNumber != "") && ($mSerialReference != ""))
    {
        $mStatus = validateFieldLength ($mHost,$mUser,$mPwd,$mDbName,"fieldname:serialReference,field:".$mSerialReference.",currentUser:".$mCurrentUser);
        if (substr($mStatus,0,2) != "FA")
            $mStatus = validateGoodsInSerial($mHost,$mUser,$mPwd,$mDbName,$mFilter);
        if (substr($mStatus,0,2) != "FA")
            $mStatus = validateCustomerPart($mHost,$mUser,$mPwd,$mDbName,$mFilter);
        if (substr($mStatus,0,2) != "FA")
            $mStatus = getCountOnRcpt($mHost,$mUser,$mPwd,$mDbName,$mFilter);
    }
    if ($mStatus == "")
        exit ("OK  -validateReceipt");
    exit ($mStatus);
}

elseif (($mFunction != null) && (strtolower($mFunction) == "sendstkmvmessage"))
{
    $mStatus = "";
    $mPartNumber = "";
    $mSerialReference = "";
// 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 :
    for ($i = 0; $i < count($mArray1); $i++)
    {
        $s = 0;
        $e = 0;
        $k1 = $mArray1[$i];
        $s = strpos($k1,":");
        if ($s >= 0)
        {
            $k2 = substr($k1,0,$s);
            $v2 = substr($k1,$s+1);
        }       
        if ($k2 == "partnumber")
            $mPartNumber = trim($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = trim($v2);
         elseif ($k2 == "tolocationhash")
            $mToLocHash = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    
// mysql connection - Use Passed values...
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    $mDataQuery = "SELECT inventory_master.inventory_qty AS inventory_qty, inventory_master.location_code AS location_code FROM inventory_master WHERE inventory_master.part_number='".$mPartNumber."' AND inventory_master.serial_reference='".$mSerialReference."' LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    list($mQty,$mLocationCode) = mysqli_fetch_row($mData);
/*
    http://van-kuk-test:8093/vantec/writeSTKMVOffsiteReturnMessage
    {
    "partNumber": "DUMMY",
    "fromLocation": "POT",
   "quantity": 1,
    "user": "admin" 
    }
*/
    if (mysqli_num_rows($mData) > 0)
    {
// Get Server Data from URL
        $mJsonArray = array();
        $mJsonArray['partNumber'] = $mPartNumber;
        $mJsonArray['fromLocation'] = $mLocationCode;
        $mJsonArray['quantity'] = $mQty;
        $mJsonArray['user'] = $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
        {
            $mUrl = "writeSTKMVOffsiteReturnMessage";
            curl_setopt($ch, CURLOPT_URL, $mConnectp.$mUrl);
            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")
            {
                $mUrl = str_replace("&","|AND|",$mUrl);
                print_r("FAIL-Unexpected System Error -".$mResult.":".$mResponse.":".$mErrors.":".$mConnectp.$mUrl.":".$mJsonObject);
            }
            else
            {
//                print_r("FAIL-OK -".$mResult.":".$mResponse.":".$mErrors.":".$mJsonObject.":".$mConnectp);
                $mJsonArray = json_decode($mResult, true);
                if ($mJsonArray['message'])
                {
                    if (substr($mJsonArray['message'],0,2) == "OK")
                    {
                        $mReturn = "OK  -".substr($mJsonArray['message'],2);
                    }
                    else
                    {
                        $mReturn = "FAIL-".$mJsonArray['message'];
                    }
                }
                else
                {
                    $mReturn = "OK  -sendstkmvmessage";
                }
            }
        }
        catch (Exception $e)
        {
            exit("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
        }
    }
    else
    {
        $mReturn = "FAIL-Inventory not found";
    }
    if ($mReturn == "")
        exit ("OK  -sendstkmvmessage");
    exit ($mReturn);
}


elseif (($mFunction != null) && (strtolower($mFunction) == "checkpltsts"))
{
	$mReturn = "";
    $mStatus = "";
    $mCustomerReference = "";
    $mPltRef = "";
	$mPartNumber = "";
	$mSerilaReference = "";
	$mStatusCheck = "";
	
// 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 :
    for ($i = 0; $i < count($mArray1); $i++)
    {
        $s = 0;
        $e = 0;
        $k1 = $mArray1[$i];
        $s = strpos($k1,":");
        if ($s >= 0)
        {
            $k2 = substr($k1,0,$s);
            $v2 = substr($k1,$s+1);
        }       
        if ($k2 == "partnumber")
            $mPartNumber = trim($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = trim($v2);
         elseif ($k2 == "plt")
            $mPltRef = trim($v2);
		elseif ($k2 == "customerreference")
            $mCustomerReference = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
	$mReturn = checkPltSts($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerReference,$mPltRef,$mPartNumber,$mSerialReference,$mStatusCheck);
	if ($mReturn == "")
	{
		$mReturn = "OK  -checkpltsts";
	}
	exit ($mReturn);
}

function getCaseList($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerRef,$mKey=null)
{   
//  echo("FAIL-TEST3");
// mysql connection - Use Passed values...
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    $mDataQuery = "SELECT receipt_header.id AS id, receipt_body.case_reference AS case_reference FROM receipt_header JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id JOIN document_status ON receipt_body.document_status_id=document_status.id WHERE receipt_header.customer_reference='".$mCustomerRef."' AND lower(document_status.document_status_code)='open' ORDER by receipt_body.case_reference";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
//  exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
    $mDropdown = array();
    $mPrevCase = null;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        if ($mRow['case_reference'] != $mPrevCase)
        {
//          echo("FAIL-TEST-".$mPrevCase."-".$mRow['case_reference']);
            $mDropdown[] = array('value' => "toCase:".$mRow['case_reference'],'text' => $mRow['case_reference'],'colour' => 'WHITE',);
        }
        $mPrevCase = $mRow['case_reference'];
    }
//  mysqli_close($mConnection);
    return "DROP-".json_encode($mDropdown);
}

function checkCaseComplete($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerRef,$mCaseRef,$mSerialReference="",$mPartNumber="",$mTransactionTypeId="")
{
    if (($mCaseRef == "") || ($mCaseRef == null))
        return "FAIL-Case cannot be blank";
// mysql connection - Use Passed values...
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    $mDataQuery = "SELECT receipt_body.id AS id FROM receipt_header JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id WHERE receipt_header.customer_reference='".$mCustomerRef."' AND receipt_body.case_reference='".$mCaseRef."' LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    if (mysqli_num_rows($mData) == 0)
        return "FAIL-Invalid Reference / case";
// Test for open receipt lines for this reference / case
    $mDataQuery = "SELECT receipt_body.id AS id FROM receipt_header JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id WHERE receipt_header.customer_reference='".$mCustomerRef."' AND receipt_body.case_reference='".$mCaseRef."' AND ((receipt_body.advised_qty<>receipt_body.received_qty) OR (receipt_body.received_qty IS null)) LIMIT 1";
    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)
    {
        if ($mTransactionTypeId = "RBTC")
            $mReturn = "OKCC-Is this case complete?:YES:NO:receiving:completecase?confirm=Y|AND|customerreference=/customerReference/|AND|tocase=/toCase/|AND|transactionTypeId=/transactionTypeIdcontent/,clearscreen:6,clearscreen:5,clearscreen:4,clearscreen:3,receiving:getcaselist?customerreference=/customerReference/|AND|key=toCase,page:page3;clearscreen:6,clearscreen:5,clearscreen:4,page:page4";
        else
            $mReturn = "OKCC-Is this case complete?:YES:NO:receiving:completecase?confirm=Y|AND|customerreference=/customerReference/|AND|tocase=/toCase/|AND|transactionTypeId=/transactionTypeIdcontent/,clearscreen:4,clearscreen:3,clearscreen:2,receiving:getcaselist?customerreference=/customerReference/|AND|key=toCase,page:page2;clearscreen:6,clearscreen:5,clearscreen:4,clearscreen:3,page:page3";
        $mReturn = str_replace(":","|COLON|",$mReturn);
        $mReturn = str_replace(",","|COMMA|",$mReturn);
        return $mReturn;
    }
// Test for overbooked case.
    if ($mPartNumber != "")
    {
        $mDataQuery = "SELECT receipt_body.id AS id FROM receipt_header JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id WHERE receipt_header.customer_reference='".$mCustomerRef."' AND receipt_body.part_number='".$mPartNumber."' AND receipt_body.case_reference='".$mCaseRef."' AND (receipt_body.advised_qty<receipt_body.received_qty) LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        if (mysqli_num_rows($mData)>0)
        {
            $mDataQuery = "UPDATE inventory_master SET inventory_status_id=(SELECT id FROM inventory_status WHERE lower(inventory_status_code)='overbooking') WHERE part_number='".$mPartNumber."' AND serial_reference='".$mSerialReference."' LIMIT 1";
            if (!mysqli_query($mConnection,$mDataQuery))
                exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        
            return "OKMS-Case Overbooked";
        }
    }
    else
    {
        $mDataQuery = "SELECT receipt_body.id AS id FROM receipt_header JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id WHERE receipt_header.customer_reference='".$mCustomerRef."' AND receipt_body.case_reference='".$mCaseRef."' AND (receipt_body.advised_qty<receipt_body.received_qty) LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        if (mysqli_num_rows($mData)>0)
        {
            $mDataQuery = "UPDATE inventory_master SET inventory_status_id=(SELECT id FROM inventory_status WHERE lower(inventory_status_code)='overbooking') WHERE part_number='".$mPartNumber."' AND serial_reference='".$mSerialReference."' LIMIT 1";
            if (!mysqli_query($mConnection,$mDataQuery))
                exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        
            return "OKMS-Case Overbooked";
        }
    }
    return "OK  -checkcasefull";
//  return "DATA:confirm::HHHHHI:skip6";
}

function completeCase($mHost,$mUser,$mPwd,$mDbName,$mConnect,$mCurrentUser,$mCustomerRef,$mCaseRef)
{
// mysql connection - Use Passed values...
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Get id for inventory status
        $mInvStsId = 0;
        $mInvRcvId = 0;
        $mInvPkdId = 0;
        $mInvPltId = 0;
        $mInvMisId = 0;
        $mInvQaId = 0;
        $mInvNrId = 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;
        
//      return "FAIL-Invalid Reference / case".$mDataQuery;
// Close receipt_body 
    $mDataQuery = "SELECT receipt_header.id AS hdr_id,receipt_header.document_reference, receipt_body.id AS id FROM receipt_header JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id WHERE receipt_header.customer_reference='".$mCustomerRef."' AND receipt_body.case_reference='".$mCaseRef."'";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    if (mysqli_num_rows($mData) == 0)
        return "FAIL-Invalid Reference / case ".$mDataQuery;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mBdyId = $mRow['id'];
        $mRctHdrId = $mRow['hdr_id'];
        $mDocumentReference = $mRow['document_reference'];
        
        $mUpdQuery = "UPDATE receipt_body SET document_status_id=(SELECT id FROM document_status WHERE lower(document_status.document_status_code)='complete') WHERE id=".$mBdyId." AND receipt_body.document_status_id=(SELECT id FROM document_status WHERE lower(document_status.document_status_code)='open') 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, receipt_detail.part_id AS part_id, receipt_detail.serial_reference AS serial_reference 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 inventory_master SET inventory_master.inventory_status_id=(SELECT id FROM inventory_status WHERE LOWER(inventory_status_code)='ok') WHERE inventory_master.part_id=".$mDtlRow['part_id']." AND inventory_master.serial_reference='".$mDtlRow['serial_reference']."' AND inventory_master.inventory_status_id <> ".$mInvOvrId." LIMIT 1";
            if (!mysqli_query($mConnection,$mUpdQuery))
                exit ("FAIL-".mysqli_error($mConnection)."-".$mUpdQuery);
            $mUpdQuery = "UPDATE receipt_detail SET document_status_id=(SELECT id FROM document_status WHERE lower(document_status.document_status_code)='complete') WHERE id=".$mDtlId." LIMIT 1";
            if (!mysqli_query($mConnection,$mUpdQuery))
                exit ("FAIL-".mysqli_error($mConnection)."-".$mUpdQuery);
        }
    }
// Check if entire receipt is closed
    $mCloseType = "";
    $mDataQuery = "SELECT receipt_header.id AS id FROM receipt_header JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id WHERE receipt_header.id=".$mRctHdrId." AND (receipt_body.received_qty < receipt_body.advised_qty OR receipt_body.received_qty IS null) LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-1".$mDataQuery.mysqli_error($mConnection);
    if (mysqli_num_rows($mData) == 0)
        $mCloseType = "R";
    else
    {
        $mDataQuery = "SELECT receipt_header.id AS id FROM receipt_header JOIN receipt_body ON receipt_body.receipt_header_id=receipt_header.id WHERE receipt_header.id=".$mRctHdrId." AND receipt_body.case_reference='".$mCaseRef."' AND (receipt_body.received_qty < receipt_body.advised_qty OR receipt_body.received_qty IS null) LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            return "FAIL-2".mysqli_error($mConnection).$mDataQuery;
        if (mysqli_num_rows($mData) == 0)
            $mCloseType = "C";
//      return "FAIL-TEST1 ".mysqli_num_rows($mData)."-".$mCloseType."-".$mDataQuery;
    }
    

// Check for Receipt Qty differences
    $mDataQuery = "SELECT receipt_header.id AS hdr_id,receipt_header.document_reference, receipt_body.id AS id FROM receipt_header JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id WHERE receipt_header.customer_reference='".$mCustomerRef."' AND receipt_body.case_reference='".$mCaseRef."' AND receipt_body.difference <> 0";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    if (mysqli_num_rows($mData) > 0)
    {
        return "OKMS-Differences Exist for case ".$mCaseRef;
    }
    
    if ($mCloseType != "")
    {
        if ($mCloseType == "R")
        {
            $mUpdQuery = "UPDATE receipt_header SET document_status_id=(SELECT id FROM document_status WHERE lower(document_status.document_status_code)='complete') WHERE id=".$mRctHdrId." LIMIT 1";
            if (!mysqli_query($mConnection,$mUpdQuery))
                return "FAIL-".mysqli_error($mConnection).$mUpdQuery;
        }
// Send IDOC Trigger for Confirm Case Receipt
//  http://van-kuk-test:8093/vantec/writeCompleteCaseMessage  {"documentReference":"RCP000001","caseReference":"TCKU625698428","userId":"admin}

// Get Server Data from URL
        $mJsonArray = array();
        $mJsonArray['documentReference'] = $mDocumentReference;
        $mJsonArray['userId'] = $mCurrentUser;
        if ($mCloseType == "C")
            $mJsonArray['caseReference'] = $mCaseRef;
// 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
        {
            if ($mCloseType == "C")
            {
                $mUrl = "writeCompleteCaseMessage?documentReference=".$mDocumentReference."&caseReference=".$mCaseRef."&userId=".$mCurrentUser;
            }
            else
            {
                $mUrl = "writeCompleteReceiptMessage?documentReference=".$mDocumentReference."&userId=".$mCurrentUser;
            }
            curl_setopt($ch, CURLOPT_URL, $mConnectp.$mUrl);
            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")
            {
                $mUrl = str_replace("&","|AND|",$mUrl);
                print_r("FAIL-Unexpected System Error -".$mResult.":".$mResponse.":".$mErrors.":".$mConnectp.$mUrl);
            }
            else
            {
//              print_r("FAIL-Unexpected System Error -".$mResult.":".$mResponse.":".$mErrors.":".$mJsonObject.":".$mConnectp);
                $mErrMsg = "OK  - Post Complete";
            }
        }
        catch (Exception $e)
        {
            exit("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
        }
    }
    return "OK  -completecase yes";
}

function validateCase($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerRef,$mCaseRef,$mTransactionTypeId="")
{
    $mCaseRef = str_replace(" ","",$mCaseRef);
// mysql connection - Use Passed values...
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    $mDataQuery = "SELECT receipt_body.id AS id, receipt_body.case_reference AS case_reference, receipt_body.document_status_id AS document_status_id, document_status.document_status_code AS document_status_code FROM receipt_header JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id LEFT JOIN document_status ON receipt_body.document_status_id=document_status.id WHERE receipt_header.customer_reference='".$mCustomerRef."' AND receipt_body.case_reference = '".$mCaseRef."' LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    if (mysqli_num_rows($mData)==0)
    {
        $mDataQuery = "SELECT receipt_body.id AS id, receipt_body.case_reference AS case_reference, receipt_body.document_status_id AS document_status_id, document_status.document_status_code AS document_status_code FROM receipt_header JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id LEFT JOIN document_status ON receipt_body.document_status_id=document_status.id WHERE receipt_header.customer_reference='".$mCustomerRef."' AND LOCATE(receipt_body.case_reference,'".$mCaseRef."')>0 LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    }
    if (mysqli_num_rows($mData)>0)
    {
        list($mBdyId,$mCaseRef,$mDocStsId,$mDocSts) = mysqli_fetch_row($mData); 
        if ((strtolower($mDocSts) == "closed") || (strtolower($mDocSts) == "transmitted"))
        {
            echo("OKMS-This Case is Closed,DATA:customerReferenceinput:".$mCustomerRef."::skip3,toLoc:::,toCase:::,partNumber:::");         
            return;
        }
    }
    return "DATA:toCase:".$mCaseRef;
}

function checkPartCase($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerRef,$mCaseRef,$mSerialReference="",$mPartNumber="")
{
// mysql connection - Use Passed values...
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    $mDataQuery = "SELECT receipt_body.id AS id, receipt_body.document_status_id AS document_status_id, document_status.document_status_code AS document_status_code FROM receipt_header JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id LEFT JOIN document_status ON receipt_body.document_status_id=document_status.id WHERE receipt_header.customer_reference='".$mCustomerRef."' AND receipt_body.part_number='".$mPartNumber."' AND LOCATE(receipt_body.case_reference,'".$mCaseRef."')>0 LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    if (mysqli_num_rows($mData) == 0) 
    {
        $mTxtValue = "validaterdt:setscreenfield?field=toCase|AND|value=".$mCaseRef."|AND|layout=PPIPPPP,page:page5;validaterdt:setscreenfield?field=toCase|AND|layout=PPIPPPP|AND|value=,validaterdt:setscreenfield?field=partNumber|AND|layout=PPPIPPP|AND|value=,page:page3";
        $mTxtValue = str_replace(":","|COLON|",$mTxtValue);
        $mTxtValue = str_replace(",","|COMMA|",$mTxtValue);
        $mStatus = "OKCC-Accept Unadvised Part / Case?:YES:NO:".$mTxtValue;
        return $mStatus;
    }
    return "OK  -checkPartCase";
}

function checkCase($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerRef,$mCaseRef,$mSerialReference="",$mPartNumber="")
{
// mysql connection - Use Passed values...
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    $mDataQuery = "SELECT receipt_body.id AS id, receipt_body.document_status_id AS document_status_id, document_status.document_status_code AS document_status_code FROM receipt_header JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id LEFT JOIN document_status ON receipt_body.document_status_id=document_status.id WHERE receipt_header.customer_reference='".$mCustomerRef."' AND LOCATE(receipt_body.case_reference,'".$mCaseRef."')>0 LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    if (mysqli_num_rows($mData) == 0) 
    {
        $mTxtValue = "validaterdt:setscreenfield?field=toCase|AND|value=".$mCaseRef."|AND|layout=PPIPPPP,page:page4;validaterdt:setscreenfield?field=toCase|AND|layout=PPIPPPP|AND|value=,page:page3";
        $mTxtValue = str_replace(":","|COLON|",$mTxtValue);
        $mTxtValue = str_replace(",","|COMMA|",$mTxtValue);
        $mStatus = "OKCC-Accept Unadvised Case?:YES:NO:".$mTxtValue;
        return $mStatus;
    }
    return "OK  -checkCase";
}


function showCasePlt($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mPartNumber,$mTransactionTypeId="")
{
// mysql connection - Use Passed values...
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    $mDataQuery = "SELECT part.id, location_type.location_type_code AS description FROM part JOIN location_type ON part.fixed_location_type_id=location_type.id WHERE part_number='".$mPartNumber."' AND location_type.plt_zone=1 LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
//  return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData);
    $mRow = mysqli_fetch_assoc($mData); 
    if (mysqli_num_rows($mData) > 0) 
    {
        return "DATA:toPltcontent:".$mRow['description'].":HHHHHHI:skiptoPlt";
    }
//  else
//      return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData);
    return "OK  -showCasePlt".mysqli_num_rows($mData);
}

function zoneCasePlt($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerReference, $mPartNumber, $mSerialRef, $mCaseRef, $mToPlt)
{
// mysql connection - Use Passed values...
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    if ($mToPlt == "")
    {
        return "FAIL-Pallet cannot be blank";
    }
// check for mixed zones on pallet
    $mDataQuery = "SELECT part.fixed_location_type_id AS id FROM part WHERE part_number='".$mPartNumber."' LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    $id = "";
    $i = 0;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $id = $mRow['id'];
    }
    $mDataQuery = "SELECT inventory_master.id AS id, part.fixed_location_type_id AS sub_id FROM inventory_master JOIN part ON inventory_master.part_id=part.id WHERE tag_reference='".$mToPlt."' AND part.fixed_location_type_id <> ".$id." LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    if (mysqli_num_rows($mData) > 0)
    {
        return "FAIL-Mixed Location Types are not allowed";
    }

    $mDataQuery = "SELECT inventory_master.id AS id, part.fixed_location_type_id AS sub_id FROM inventory_master JOIN part ON inventory_master.part_id=part.id WHERE tag_reference='".$mToPlt."'";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;

    $mPrvId = null;
    $i = 0;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        if($mPrvId==null)
            $mPrvId = $mRow['sub_id'];
        if ($mPrvId != $mRow['sub_id'])
            $i++;
    }
//  return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData)."-".$i."-".$mPrvId;
    if ($i > 0)
    {
        return "FAIL-Mixed Location Types are not allowed";
    }
// Test for existing parts on the pallet
    
    $mDataQuery = "SELECT id AS id FROM tag WHERE tag_reference='".$mToPlt."' AND (active IS null OR active = '1') LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
                
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mToTagId = ($mRow['id']);
    }
    if ($mToTagId == "")
    {
        $mDataQuery = "INSERT INTO tag (id,version,auto_generated,current_location_id,date_created,document_header_id,last_updated,last_updated_by,tag_reference,validated,active,picked) VALUES(DEFAULT,0,0,null,now(),null,now(),'".$mCurrentUser."','".$mToPlt."',1,1,0)";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        $mToTagId=mysqli_insert_id($mConnection);
    }

    $mDataQuery = "UPDATE inventory_master SET parent_tag_id=".$mToTagId.", tag_reference='".$mToPlt."', last_updated=now(),last_updated_by='".$mCurrentUser."' WHERE part_number='".$mPartNumber."' AND serial_reference='".$mSerialRef."' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    
    $mDataQuery = "SELECT document_reference AS document_reference FROM receipt_header WHERE customer_reference = '".$mCustomerReference."' LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;

    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mDocumentRef = ($mRow['document_reference']);
    }
    $mDataQuery = "SELECT inventory_master.location_code, inventory_master.ran_or_order, inventory_master.inventory_qty, part.conversion_factor, part.requires_inspection FROM inventory_master JOIN part ON inventory_master.part_id=part.id WHERE inventory_master.part_number = '".$mPartNumber."' AND inventory_master.serial_reference = '".$mSerialRef."' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
                
    $mData = mysqli_query($mConnection,$mDataQuery);
    $mRow = mysqli_fetch_assoc($mData);

    $mDataQuery = "INSERT INTO transaction_history (id,associated_document_reference,date_created,created_by,from_location_code,last_updated,last_updated_by,parent_tag,part_number,ran_or_order,serial_reference,short_code,source_tag,to_location_code,transaction_reference_code,txn_qty,count_qty,comment,active,conversion_factor,customer_reference,requires_inspection,to_plt) VALUES(DEFAULT,'".$mDocumentRef."',now(),'".$mCurrentUser."','".$mRow['location_code']."',now(),'".$mCurrentUser."','".$mToPlt."','".$mPartNumber."','".$mRow['ran_or_order']."','".$mSerialRef."','PLTZONE','".$mCaseRef."','".$mRow['location_code']."','PLTZONE',".$mRow['inventory_qty'].",".$mRow['inventory_qty'].",'',1,".$mRow['conversion_factor'].",'".$mRow['customer_reference']."',".$mRow['requires_inspection'].",'".$mToPlt."')";
    
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;  
    return "OK  -zoneCasePlt";
}

function checkReceiptQa($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerReference)
{
// mysql connection - Use Passed values...
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
/*
    $mDataQuery = "SELECT receipt_header.id AS id FROM receipt_header JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id WHERE receipt_header.customer_reference='".$mCustomerReference."' AND receipt_body.quarantined_qty=0 LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    $mRow = mysqli_fetch_assoc($mData); 
    if (mysqli_num_rows($mData) == 0) 
    {
        return "FAIL-This Receipt is Quarantined";
    }
*/
    $mDataQuery = "SELECT id FROM receipt_header WHERE document_status_id=(SELECT id FROM document_status WHERE receipt_header.customer_reference='".$mCustomerReference."' AND lower(document_status_code)='quarantine') LIMIT 1"; 
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    if (mysqli_num_rows($mData) > 0) 
    {
        return "FAIL-This Receipt is Quarantined";
    }
        return "OK  -checkreceiptqa";
}

function completeReceipt($mHost,$mUser,$mPwd,$mDbName,$mConnect,$mCurrentUser,$mCustomerRef)
{
// mysql connection - Use Passed values...
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Close receipt_body 
    $mDataQuery = "SELECT receipt_header.id AS hdr_id,receipt_header.document_reference, receipt_body.id AS id FROM receipt_header JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id WHERE receipt_header.customer_reference='".$mCustomerRef."'";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    if (mysqli_num_rows($mData) == 0)
        return "FAIL-Invalid Reference / case ".$mDataQuery;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mBdyId = $mRow['id'];
        $mRctHdrId = $mRow['hdr_id'];
        $mDocumentReference = $mRow['document_reference'];
        
        $mUpdQuery = "UPDATE receipt_body SET document_status_id=(SELECT id FROM document_status WHERE lower(document_status.document_status_code)='complete') WHERE id=".$mBdyId." AND receipt_body.document_status_id=(SELECT id FROM document_status WHERE lower(document_status.document_status_code)='open') 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, receipt_detail.part_id AS part_id, receipt_detail.serial_reference AS serial_reference 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 inventory_master SET inventory_master.inventory_status_id=(SELECT id FROM inventory_status WHERE LOWER(inventory_status_code)='ok') WHERE inventory_master.part_id=".$mDtlRow['part_id']." AND inventory_master.serial_reference='".$mDtlRow['serial_reference']."' LIMIT 1";
            if (!mysqli_query($mConnection,$mUpdQuery))
                exit ("FAIL-".mysqli_error($mConnection)."-".$mUpdQuery);
            $mUpdQuery = "UPDATE receipt_detail SET document_status_id=(SELECT id FROM document_status WHERE lower(document_status.document_status_code)='complete') WHERE id=".$mDtlId." LIMIT 1";
            if (!mysqli_query($mConnection,$mUpdQuery))
                exit ("FAIL-".mysqli_error($mConnection)."-".$mUpdQuery);
        }
    }
    $mUpdQuery = "UPDATE receipt_header SET document_status_id=(SELECT id FROM document_status WHERE lower(document_status.document_status_code)='complete') WHERE id=".$mRctHdrId." LIMIT 1";
    if (!mysqli_query($mConnection,$mUpdQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mUpdQuery);
    
// Check if entire receipt is closed
    $mDataQuery = "SELECT receipt_header.id AS id FROM receipt_header JOIN receipt_body ON receipt_body.receipt_header_id=receipt_header.id WHERE receipt_header.id=".$mRctHdrId." AND (receipt_body.received_qty<receipt_body.advised_qty) LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;
    $mData = (mysqli_query($mConnection,$mDataQuery));
    if (mysqli_num_rows($mData) == 0)
    {
// Send IDOC Trigger for Confirm Receipt
//  http://van-kuk-test:8093/vantec/writeCompleteReceiptMessage  {"documentReference":"RCP000001","userId":"admin}

// Get Server Data from URL
        $mJsonArray = array();
        $mJsonArray['documentReference'] = $mDocumentReference;
        $mJsonArray['userId'] = $mCurrentUser;
        $mJsonObject = '{"documentReference":"'.$mDocumentReference.'","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
        {
            $mUrl = "writeCompleteReceiptMessage?documentReference=".$mDocumentReference."&userId=".$mCurrentUser;
            curl_setopt($ch, CURLOPT_URL, $mConnectp.$mUrl);
            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")
            {
                $mUrl = str_replace("&","|AND|",$mUrl);
                print_r("FAIL-Unexpected System Error -".$mResult.":".$mResponse.":".$mErrors.":".$mJsonObject.":".$mConnectp.$mUrl);
            }
            else
            {
//              $mUrl = str_replace("&","|AND|",$mUrl);
//              return "FAIL-test curl -".$mResult.":".$mResponse.":".$mErrors.":".$mJsonObject.":".$mConnectp.$mUrl;
                $mErrMsg = "OK  - Post Complete";
            }
        }
        catch (Exception $e)
        {
            exit("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
        }
    }
    return "OK  -completeReceipt yes";
}

// check unadvised part
function checkUnadvisedPart($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mReference,$mPartNumber,$mConfirm,$mTransactionTypeId="")
{
// mysql connection - Use Passed values...
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    $mDataQuery = "SELECT part.id AS id FROM part WHERE part.part_number='".$mPartNumber."' LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    if ($mConfirm != 'Y')
    {
        if (mysqli_num_rows($mData) == 0)
        {
//            $mDataQuery = "SELECT receipt_header.id AS id FROM receipt_header JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id WHERE receipt_header.customer_reference='".$mReference."' AND receipt_body.part_number='".$mPartNumber."' LIMIT 1";
            $mDataQuery = "SELECT receipt_header.id AS id FROM receipt_header WHERE receipt_header.customer_reference='".$mReference."' LIMIT 1";
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
            if (mysqli_num_rows($mData)>0)
            {
                list($mHdrId) = mysqli_fetch_row($mData);
                $mDataQuery = "SELECT id FROM receipt_body WHERE receipt_body.receipt_header_id=".$mHdrId." AND receipt_body.part_number='".$mPartNumber."' LIMIT 1";
                if (!$mData = mysqli_query($mConnection,$mDataQuery))
                    exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
                if (mysqli_num_rows($mData)>0)
                {
                    if ($mTransactionTypeId == "RBTC")
                        $mReturn = "OKCC-Unknown Part Accept?:YES:NO:receiving:checkunadvisedpart?confirm=Y|AND|partnumber=/partNumber/|AND|transactionType=/transactionTypeIdcontent/;clearscreen:4,page:page4";
                    elseif ($mTransactionTypeId == "RBTP")
                        $mReturn = "OKCC-Unknown Part Accept?:YES:NO:receiving:checkunadvisedpart?confirm=Y|AND|partnumber=/partNumber/|AND|transactionType=/transactionTypeIdcontent/;clearscreen:4,page:page4";
                    else
                        $mReturn = "OKCC-Unknown Part Accept?:YES:NO:receiving:checkunadvisedpart?confirm=Y|AND|partnumber=/partNumber/|AND|transactionType=/transactionTypeIdcontent/;clearscreen:3,page:page3";
                    $mReturn = str_replace(":","|COLON|",$mReturn);
                    $mReturn = str_replace(",","|COMMA|",$mReturn);
                }
                else
                    $mReturn = "FAIL-Unknown Part Number";
            }
            else
                $mReturn = "FAIL-Unknown Receipt";
            return $mReturn;
        }
    }
    else
    {
        $mLocTypeId = 0;
        $mDataQuery = "SELECT id FROM location_type WHERE lower(location_type_code)='qr' LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        if (mysqli_num_rows($mData)>0)
            list($mLocTypeId)=mysqli_fetch_row($mData);
        $mLocSubTypeId = 0;
        $mDataQuery = "SELECT id FROM location_sub_type WHERE lower(location_sub_type_code)='qa' LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        if (mysqli_num_rows($mData)>0)
            list($mLocSubTypeId)=mysqli_fetch_row($mData);
        $mInvStsId = 0;
        $mDataQuery = "SELECT id FROM inventory_status WHERE lower(inventory_status_code)='qtine' LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        if (mysqli_num_rows($mData)>0)
            list($mInvStsId)=mysqli_fetch_row($mData);
        $mDate = date('Y-m-d');
        $mDataQuery = "INSERT INTO part (id,version,date_created,created_by,effective_from,effective_to,fixed_location_type_id,fixed_sub_type_id,imaginary_part,last_updated,last_updated_by,part_description,part_number)";
        $mDataQuery .=" VALUES(DEFAULT,0,now(),'".$mCurrentUser."','".$mDate." 00:00:01','".$mDate." 23:59:59',".$mLocTypeId.",".$mLocSubTypeId.",1,now(),'".$mCurrentUser."','UNADVISED PART','".$mPartNumber."')";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    }
    return "OK  -checkpart";
//  return "DATA:confirm::HHHHHI:skip6";
}

function checkOverbooking($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerRef,$mSerialReference="",$mPartNumber="",$mTransactionTypeId="")
{
// mysql connection - Use Passed values...
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Test for overbooked part.
    if ($mPartNumber != "")
    {
//      $mDataQuery = "SELECT receipt_body.id AS id FROM receipt_header JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id WHERE receipt_header.customer_reference='".$mCustomerRef."' AND receipt_body.part_number='".$mPartNumber."' AND (receipt_body.advised_qty<receipt_body.received_qty) LIMIT 1";
        if ($mSerialReference != "")
            $mDataQuery = "SELECT receipt_body.id AS id FROM receipt_header JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id JOIN receipt_detail ON receipt_body.id=receipt_detail.receipt_body_id WHERE receipt_header.customer_reference='$mCustomerRef' AND receipt_body.part_number='$mPartNumber' AND receipt_detail.serial_reference='$mSerialReference' AND (receipt_body.advised_qty<receipt_body.received_qty) LIMIT 1";
        else
            $mDataQuery = "SELECT receipt_body.id AS id FROM receipt_header JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id WHERE receipt_header.customer_reference='".$mCustomerRef."' AND receipt_body.part_number='".$mPartNumber."' AND (receipt_body.advised_qty<receipt_body.received_qty) LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        if (mysqli_num_rows($mData)>0)
        {
            $mDataQuery = "UPDATE inventory_master SET inventory_status_id=(SELECT id FROM inventory_status WHERE lower(inventory_status_code)='overbooking') WHERE part_number='".$mPartNumber."' AND serial_reference='".$mSerialReference."' LIMIT 1";
            if (!mysqli_query($mConnection,$mDataQuery))
                exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        
            return "OKMS-Overbooked";
        }
    }
    return "OK  -checkOverbooking";
//  return "DATA:confirm::HHHHHI:skip6";
}

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 == "transactionType")
            $mTransactionTypeId = 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;
        $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")
        {
//            $mDataQuery = "SELECT inventory_master.id AS id,inventory_master.inventory_status_id AS inventory_status_id FROM inventory_master JOIN part ON inventory_master.part_id=part.id WHERE (part.part_number='".$mPartNumber."' OR part.vendor_part_code='".$mPartNumber."') AND inventory_master.serial_reference='".$mSerialReference."' AND inventory_master.inventory_qty > 0 LIMIT 1";
            $mDataQuery = "SELECT inventory_master.id AS id,inventory_master.inventory_status_id AS inventory_status_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);
            if (mysqli_num_rows($mData) == 0)
                $mErrMsg = "FAIL-No Available inventory exists for this serial reference";
            else
            {
                list($mInvId,$mInvInvId) = 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";
                }
            }
        }
    }
    
    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 == "transactionType")
            $mTransactionTypeId = strtoupper($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."' 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";
        }
        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 (!$mData = mysqli_query($mConnection,$mDataQuery))

        exit("FAIL-".mysqli_error($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."' 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";
        }
    }
    if ($mStatus == "")
        return "OK  -validateCustomerPart";
    
    if ((substr($mStatus,0,2) != "FA") && (substr($mStatus,0,2) != "OK"))
        $mStatus = "FAIL-".$mStatus;
    return $mStatus;
}

function getCountOnRcpt($mHost,$mUser,$mPwd,$mDbName,$mFilter)
{
// 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);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
// blank input parameters - ignore
    if ($mPartNumber == "")
    {
        return "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::HHHHHHI:skip7";
            }
            else
            {
                $mDataStr = "DATA:countQty::HHHHHI:skip6";
            }
            $mErrMsg = "";
            return $mDataStr;
        }
        else
        {
            return "OK  -countonrcpt";
        }
    }
    else
    {
        return "FAIL-Invalid Part ".$mPartNumber;
    }
}

// Validate Field Min / Max Length
function validateFieldLength($mHost,$mUser,$mPwd,$mDbName,$mFilter)
{
// 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 = "";
//  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;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
    }
// Test for non-numeric Quantity
    if (($mFieldName == "quantity") || ($mFieldName=="number"))
        if(is_numeric($mField))
        {
        }
        else
        {
            return "FAIL-This must be a number only";
        }
// Test for Company Defaults
    if (($mErrMsg == "") && ($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;
            try
            {
                $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) 
            {
            }
            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++;
            }
        }
    }
    if (($mMax != "") && ($mMax != "0"))
    {
        if (($mFieldName == "quantity") || ($mFieldName=="number"))
        {
// Numeric Field outside Limits
            if (($mField < $mMin) || ($mField > $mMax))
                return "FAIL-Value Error";
        }
        else
        {
// Return Trimmed Field if required
            if (($mTrim != "") && (strlen($mField) > $mMax))
            {
                $mDataStr = "DATA-".$mFieldName.":".substr($mField,0,$mMax);
                return $mDataStr;
            }
// String Field outside limits                  
            if (strlen($mField) < $mMin)
                return "FAIL-Scanned ".$mFieldName." is too short";
            if (strlen($mField) > $mMax)
                return "FAIL-Scanned ".$mFieldName." is too long";
        }
    }
    if ($i > 0)
    {
        $mDataStr = "DATA:".$mFieldName.":".$mField;
        return $mDataStr;
    }
    
    if ($mErrMsg == "")
        return "OK  -validateFieldLength";
    else
        return $mErrMsg;
    return;
}

function checkPltSts($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerReference,$mPltRef,$mPartNumber,$mSerialReference,$mStatusCheck)
{
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
		
    $mDataQuery = "SELECT";
	$mDataQuery .=" receipt_body.inspect AS inspect, receipt_body.quarantined_qty AS quarantined_qty";
    $mDataQuery .=" FROM receipt_header";
    $mDataQuery .=" LEFT JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id";
    $mDataQuery .=" WHERE (receipt_header.customer_reference='".$mCustomerReference."' OR receipt_header.haulier_reference='".$mCustomerReference."')";
	$mDataQuery .=" AND receipt_body.part_number='".$mPartNumber."' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
		exit("FAIL-".mysqli_error($mConnection).":".$mDataQuery);
	$mData = mysqli_query($mConnection,$mDataQuery);
	$mRecInsp = null;
	$mRecQa = null;
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
		$mRecInsp = $mRow['inspect'];
		$mRecQa = $mRow['quarantined_qty'];
	} 
//	exit("FAIL-TEST1-".$mDataQuery." ".$mRecInsp);
	$mPltInsp = null;
	$mPltQa = null;
	$mPltPart = "";
    $mDataQuery = "SELECT";
	$mDataQuery .=" scan_data.id AS id, scan_data.part_number AS part_number";
	$mDataQuery .=" ,receipt_body.inspect AS inspect, receipt_body.quarantined_qty AS quarantined_qty";
	$mDataQuery .=" FROM scan_data";
    $mDataQuery .=" LEFT JOIN receipt_header ON scan_data.customer_reference=receipt_header.customer_reference OR scan_data.customer_reference=receipt_header.haulier_reference";
    $mDataQuery .=" LEFT JOIN receipt_body ON receipt_header.id=receipt_body.receipt_header_id AND receipt_body.part_id=scan_data.part_id";
    $mDataQuery .=" WHERE plt_reference='".$mPltRef."'";
	$mDataQuery .=" UNION";
	$mDataQuery .=" SELECT";
	$mDataQuery .=" inventory_master.id AS id, inventory_master.part_number AS part_number";
	$mDataQuery .=" ,receipt_body.inspect AS inspect, receipt_body.quarantined_qty AS quarantined_qty";
	$mDataQuery .=" FROM inventory_master";
	$mDataQuery .=" LEFT JOIN receipt_detail ON inventory_master.part_id=receipt_detail.part_id AND inventory_master.serial_reference=receipt_detail.serial_reference";
	$mDataQuery .=" LEFT JOIN receipt_body ON receipt_detail.receipt_body_id=receipt_body.id";
    $mDataQuery .=" LEFT JOIN receipt_header ON receipt_body.receipt_header_id=receipt_header.id";
    $mDataQuery .=" WHERE inventory_master.tag_reference='".$mPltRef."'";
    if (!mysqli_query($mConnection,$mDataQuery))
		exit("FAIL-".mysqli_error($mConnection).":".$mDataQuery);
	$mData = mysqli_query($mConnection,$mDataQuery);
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
		$mPltInsp = $mRow['inspect'];
		$mPltPart = $mRow['part_number'];
		$mPltQa = $mRow['quarantined_qty'];
		if ($mRecInsp != $mPltInsp)
		{
			$mReturn = "FAIL-Mixed insp. pallet is not allowed";
			break;
		}
		if (($mRecQa == 0 && $mPltQa != 0) || ($mRecQa != 0 && $mPltQa == 0))
		{
			$mReturn = "FAIL-Mixed qa. pallet is not allowed";
			break;
		}
	}
//	exit("FAIL-TEST1-".$mDataQuery." ".$mRecInsp." ".$mPltInsp." ".$mPltPart);
	If ($mReturn == "")
		$mReturn = "OK  -checkPltSts";
	return $mReturn;
}

?>