<?php
// inspect.php
// VIMS RDT
// ----------------------------------------------------------------------------------------

// ----------------------------------------------------------------------------------------
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Expires: 0');
// Header to allow Cross-Server AJAX Connection
header('Access-Control-Allow-Origin: *');
set_time_limit(0);
date_default_timezone_set('Europe/London');
// Enable exceptions for MySQLi errors
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// logMessage("TEST");

// 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'];
$mReturnFields      = $_GET['returnfields'];
$mFilter            = $_GET['filter'];

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

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

$mErrMsg = "OK  -";

// Validate Pick Reference
if (($mFunction != null) && (strtolower($mFunction) == "validatereference"))
{
    $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 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    
    $mDataQuery = "SELECT inspection_task_header.id AS id";
    $mDataQuery .=" FROM inspection_task_header";
    $mDataQuery .=" WHERE inspection_task_header.customer_reference LIKE('".$mCustomerRef."%')";
    $mDataQuery .=" LIMIT 1";

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

    if (mysqli_num_rows($mData) == 0)
    {
        $mErrMsg = "FAIL-Incorrect Reference ".$mCustomerRef;
    }
    if ($mErrMsg == "")
        $mErrMsg = "OK  -validatereference";
    exit ($mErrMsg);
}

// Reset Pick
if (($mFunction != null) && (strtolower($mFunction) == "resetpick"))
{
    $mErrMsg = "";
    $mToPlt = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "customerreference")
            $mCustomerRef = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    $mStatus = resetPick($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerRef);
    echo $mStatus;
    return;
}

// Get Pick
if (($mFunction != null) && (strtolower($mFunction) == "allocatepick"))
{
    $mErrMsg = "";
    $mToPlt = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "customerreference")
            $mCustomerRef = trim($v2);
        elseif ($k2 == "locationcode")
            $mLocationCode = strtoupper(trim($v2));
        elseif ($k2 == "aisle")
            $mAisle = trim($v2);
        elseif ($k2 == "toplt")
            $mToPlt = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    $mStatus = allocatePick($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerRef,$mConnect);
    echo $mStatus;
    return;
}

// Get Pick
if (($mFunction != null) && (strtolower($mFunction) == "getpick"))
{
    $mErrMsg = "";
    $mToPlt = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "customerreference")
            $mCustomerRef = trim($v2);
        elseif ($k2 == "locationcode")
            $mLocationCode = strtoupper(trim($v2));
        elseif ($k2 == "aisle")
            $mAisle = trim($v2);
        elseif ($k2 == "toplt")
            $mToPlt = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    $mStatus = getPick($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerRef,$mConnect,$mToPlt);
    echo $mStatus;
    return;
}

// post pick
elseif (($mFunction != null) && (strtolower($mFunction) == "postpick"))
{
    $mErrMsg = "";
    $mToPlt = "";
    $mToLocHash = "";
    $mPickQty = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "pickdetailid")
            $mPickDtlId = trim($v2);
        elseif (strtolower($k2) == "inventorymasterid")
            $mPickInvId = trim($v2);
        elseif (strtolower($k2) == "plt")
            $mToPlt = trim($v2);
        elseif (strtolower($k2) == "serialreference")
            $mSerialReference = trim($v2);
		elseif (strtolower($k2) == "partnumber")
            $mPartNumber = trim($v2);
        elseif ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty") || (strtolower($k2) == "pickqty"))   
            $mPickQty = floatval($v2);
        elseif (strtolower($k2) == "tolocationhashcode")
            $mToLocHash = trim($v2);        
        elseif (strtolower($k2) == "customerreference")
            $mCustomerRef = trim($v2);
        elseif (strtolower($k2) == "locationcode")
            $mLocationCode = strtoupper(trim($v2));
        elseif (strtolower($k2) == "aisle")
            $mAisle = trim($v2);
        elseif ($k2 == "fromlocationhashcode")
            $mFromLocation = strtoupper(trim($v2));
        elseif ($k2 == "vldpartnumber")
            $mVldPartNumber = strtoupper(trim($v2));
        elseif ($k2 == "vldlocation")
            $mVldLocation = strtoupper(trim($v2));
        elseif ($k2 == "vldserialreference")
            $mVldSerialReference = strtoupper(trim($v2));
        elseif ((strtolower($k2) == "vldqty"))
            $mVldQty = floatval($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
        elseif ($k2 == "rdtstart")
            $mRdtStart = trim($v2);
        elseif ($k2 == "rdtend")
            $mRdtEnd = trim($v2);
    }
    
    $mRdtStart = str_replace("colon",":",$mRdtStart);
    $mRdtEnd = str_replace("colon",":",$mRdtEnd);
    $mStatus = updatePickDetail($mHost,$mUser,$mPwd,$mDbName,$mPickDtlId,$mPickInvId,$mSerialReference,$mPartNumber,$mPickQty,$mCurrentUser,$mTransactionTypeId,$mToPlt,$mToLocHash,$mConnect,$mRdtStart,$mRdtEnd);
    if (substr($mStatus,0,2) == "OK")
    {
    }
    echo $mStatus;
    return;
}

// Validate Pick
elseif (($mFunction != null) && ($mFunction=="validatepickqty"))
{
    $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 = null;
    $mSerialReference = null;
    $mFromLocation = null;
    $mVldLocationHash = "";
    $mVldPartNumber = "";
    $mVldSerialReference = "";
    $mQty = "";
    $mVldQty = "";
    $mCustomerReference = "";
    $mCurrentUser = "UNKNOWN";
// 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(trim($v2));
        elseif ($k2 == "partnumber")
            $mPartNumber = strtoupper(trim($v2));
        elseif ($k2 == "serialreference")
            $mSerialReference = strtoupper(trim($v2));
        elseif ($k2 == "fromlocationhashcode")
            $mFromLocation = strtoupper(trim($v2));
        elseif ($k2 == "vldpartnumber")
            $mVldPartNumber = strtoupper(trim($v2));
        elseif ($k2 == "vldlocation")
            $mVldLocation = strtoupper(trim($v2));
        elseif ($k2 == "vldserialreference")
            $mVldSerialReference = strtoupper(trim($v2));
        elseif ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty"))
            $mQty = floatval($v2);
        elseif ((strtolower($k2) == "vldquantity") || (strtolower($k2) == "vldqty"))
            $mVldQty = floatval($v2);
		elseif ($k2 == "printer")
            $mPrinter = strtoupper(trim($v2));
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    if ($mErrMsg == "")
    {
        if (!empty($mQty) && $mQty <> $mVldQty)
        {
            $mErrMsg = "FAIL-Incorrect Quantity".$mQty." ".$mVldQty;
        }
    }
    if ($mErrMsg == "")
    {
  // mysql connection
        $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
            exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error()); 
        if ($mPartNumber == "")
            if ($mVldPartNumber == "")
                $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_qty AS inventory_qty, inventory_master.requires_inspection AS inspect, location.location_code, part.conversion_factor AS conversion_factor FROM inventory_master JOIN part ON inventory_master.part_id=part.id JOIN location on inventory_master.current_location_id=location.id WHERE UPPER(inventory_master.serial_reference)='".$mSerialReference."' AND inventory_master.inventory_qty > 0 LIMIT 2";
            else
                $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_qty AS inventory_qty, inventory_master.requires_inspection AS inspect, location.location_code,part.part_number AS part_number, part.conversion_factor AS conversion_factor FROM inventory_master LEFT JOIN part ON inventory_master.part_id=part.id LEFT JOIN location on inventory_master.current_location_id=location.id WHERE UPPER(inventory_master.serial_reference)='".$mSerialReference."' AND (part.part_number='".$mVldPartNumber."' OR part.jis_supply_group ='".$mVldPartNumber."') AND inventory_master.inventory_qty > 0 LIMIT 1"; 
        else
            $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_qty AS inventory_qty, inventory_master.requires_inspection AS inspect, location.location_code,part.part_number AS part_number, part.conversion_factor AS conversion_factor FROM inventory_master JOIN part ON inventory_master.part_id=part.id JOIN location on inventory_master.current_location_id=location.id WHERE UPPER(inventory_master.serial_reference)='".$mSerialReference."' AND (part.part_number='".$mPartNumber."' OR part.jis_supply_group ='".$mPartNumber."') AND inventory_master.inventory_qty > 0 LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);

        $mData = mysqli_query($mConnection,$mDataQuery);
        $i = 0;
        $mInvId = "";
        $mInvQty = 0;
        $mPartConvFactor = 1;
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mDataStr = ($mRow['location_code']);
            $mInspect = ($mRow['inspect']);
            $mInvId = ($mRow['id']);
            $mInvQty = ($mRow['inventory_qty']);
            $mPartConvFactor = ($mRow['conversion_factor']);
            $mPartNumber = ($mRow['part_number']);
            $i++;
        }
        if (mysqli_num_rows($mData) == 0)
        {
            $mErrMsg = "FAIL-Serial / part_number is Incorrect";
        }
		if ($mErrMsg == "")
		{
// Apply Conversion Factor
			if ($mPartConvFactor > 0)
				$mInvQty = $mInvQty / $mPartConvFactor;
// Check if decant is Required
			if (!empty(vldQty))
			{
				if ($mInvQty > $mVldQty)
				{
					$mErrMsg = "FAIL-This box must be Decanted";
				}
			}
		}
		if ($mErrMsg == "")
		{
// Check Scanned Qty against Serial
			if (!empty($mQty) && $mQty > $mInvQty)
				$mErrMsg = "FAIL-Scanned quantity is greater than serial quantity";
		}
    }
    if ($mErrMsg == "")
        $mErrMsg = "OK  -validatepickqty";
    exit($mErrMsg);
}

// validate Pick Serial
elseif (($mFunction != null) && ($mFunction == "validatepickserial"))
{
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    $mErrMsg = "";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    $mPartNumber = "";
    $mReference = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "serialreference")
            $mSerialReference = $v2;
        elseif (strtolower($k2) == "partnumber")
            $mPartNumber = $v2;
        elseif (strtolower($k2) == "reference")
            $mReference = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper($v2);
    }
    if (($mSerialReference == "") || (strlen($mSerialReference)==0))
    {
        echo "FAIL-Blank Serial is not allowed";
        return;
    }
    $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.part_id AS part_id, inventory_master.requires_inspection AS requires_inspection";
    $mDataQuery .=", part.part_number AS part_number, location.location_type_id AS location_type, location_type.location_area AS location_area, location_type.location_type_code AS location_type_code";
    $mDataQuery .= " FROM inventory_master";
    $mDataQuery .= " JOIN part ON inventory_master.part_id=part.id";
    $mDataQuery .= " JOIN location ON inventory_master.current_location_id=location.id";
    $mDataQuery .= " LEFT JOIN location_type ON location.location_type_id=location_type.id";
    $mDataQuery .= " LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id";
    $mDataQuery .= " WHERE inventory_master.serial_reference = '".$mSerialReference."' AND inventory_master.inventory_qty > 0";
    $mDataQuery .= " AND inventory_status_code IN('ok','missing','pc','qtine')";
    if ($mPartNumber != "")
        $mDataQuery .= " AND part.part_number='".$mPartNumber."' LIMIT 1";
    else
        $mDataQuery .= " LIMIT 2";
    if(!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    $mData = mysqli_query($mConnection,$mDataQuery);
//  exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
    $i = mysqli_num_rows($mData);
    if ($i == 0)
    {
        echo "FAIL-Invalid Serial ";
        return;
    }
    if ($i > 1)
    {
        $mDataStr = "DATA:partNumber:::skippartNumber";
        exit($mDataStr);
    }
    exit("OK  -validatepickserial");
}

// Validate In-Use
elseif (($mFunction != null) && ($mFunction=="validateinuse"))
{
    
    $mReturn = "";
// 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;
    $mCurrentUser = "UNKNOWN";
// 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 == "pickdtlid")
            $mPickDtlId = strtoupper(trim($v2));
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    $mDataQuery = "SELECT id,location_code,serial_reference,part_number,qty_allocated,inventory_master_id,blocked,in_use_by,last_updated_date, DATE_SUB(NOW(), INTERVAL 5 MINUTE) as cut_off FROM inspection_task_detail WHERE inspection_task_body_id=".$mPickDtlId." AND processed=0 LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    if (mysqli_num_rows($mData) > 0)
    {
        list($mId,$mLocationCode,$mSerialReference,$mPartNumber,$mPickQty,$mInvId,$mBlocked,$mInUseBy,$mInUseTime,$mCutOff) = mysqli_fetch_row($mData);
        
        if ($mInUseBy == null || $mInUseBy == '' || $mInUseBy == $mCurrentUser || $mInUseTime < $mCutOff)
        {
            $mInUseBy = "";
        }
    }
    if ($mReturn == "")
        $mReturn = "OK  -validateinuse";
    exit($mReturn);
}

// Validate Pick
elseif (($mFunction != null) && ($mFunction=="validatepick"))
{
    $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 = null;
    $mSerialReference = null;
    $mFromLocation = null;
    $mVldLocationHash = "";
    $mVldPartNumber = "";
    $mVldSerialReference = "";
    $mQty = "";
    $mVldQty = "";
    $mCustomerReference = "";
    $mCurrentUser = "UNKNOWN";
// 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(trim($v2));
        elseif ($k2 == "partnumber")
            $mPartNumber = strtoupper(trim($v2));
        elseif ($k2 == "serialreference")
            $mSerialReference = strtoupper(trim($v2));
        elseif ($k2 == "fromlocationhashcode")
            $mFromLocation = strtoupper(trim($v2));
        elseif ($k2 == "vldpartnumber")
            $mVldPartNumber = strtoupper(trim($v2));
        elseif ($k2 == "vldlocation")
            $mVldLocation = strtoupper(trim($v2));
        elseif ($k2 == "vldserialreference")
            $mVldSerialReference = strtoupper(trim($v2));
        elseif ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty"))
            $mQty = floatval($v2);
        elseif ((strtolower($k2) == "vldquantity") || (strtolower($k2) == "vldqty"))
            $mVldQty = floatval($v2);
		elseif ($k2 == "printer")
            $mPrinter = strtoupper(trim($v2));
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
		elseif (strtolower($k2) == "transactiontypeid")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    $mErrMsg = validatePick($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerReference,$mFromLocation,$mVldLocation,$mPartNumber,$mVldPartNumber,$mSerialReference,$mVldSerialReference,$mQty,$mVldQty,$mTransactionTypeId,$mPrinter);
    echo $mErrMsg;
    return;
}

// Test for full-box-pick
elseif (($mFunction != null) && ($mFunction=="checkfullboxpick"))
{
// 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 = "";
    
    $mSerialReference = "";
    $mPartNumber = "";
    $mFullBoxPick = 0;
    
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $mSerialReference = "";
    $i=0;
    $mPartNumber = "";
    $mFullBoxPick = 0;
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "customerreference")
            $mCustomerReference = strtoupper($v2);
        elseif (strtolower($k2) == "partnumber")
            $mPartNumber = strtoupper($v2);
        elseif (strtolower($k2) == "serialreference")
            $mSerialReference = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
// Check Order Type Settings
    $mDataQuery = "SELECT document_header.id AS id, document_header.document_reference_code AS document_reference, document_header.time_slot AS time_slot, order_type.inspection_task_by_line, order_type.order_type_code AS order_type_code, order_type.full_box_pick AS full_box_pick FROM document_header LEFT JOIN document_status ON document_header.document_status_id=document_status.id LEFT JOIN order_type ON document_header.order_type=order_type.order_type_code WHERE document_header.document_type='RRM Order' AND document_header.customer_reference_code='".$mCustomerReference."' AND (document_header.document_status_id IS null OR document_header.document_status_id=0 OR lower(document_status.document_status_code) in('open','allocated')) LIMIT 1";       
    if (!mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    $mData = mysqli_query($mConnection,$mDataQuery);
    if (mysqli_num_rows($mData) == 0)
    {
        $mDataQuery = "SELECT document_header.id AS id, document_header.document_reference_code AS document_reference, document_header.time_slot AS time_slot, order_type.order_type_code AS order_type_code, order_type.inspection_task_by_line, order_type.full_box_pick AS full_box_pick FROM document_header LEFT JOIN document_status ON document_header.document_status_id=document_status.id LEFT JOIN order_type ON document_header.order_type=order_type.order_type_code WHERE document_header.time_slot='".$mCustomerReference."' AND (document_header.document_status_id IS null OR document_header.document_status_id=0 OR lower(document_status.document_status_code) in('open','allocated')) ORDER BY document_header.expected_delivery";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $mData = mysqli_query($mConnection,$mDataQuery);
    }
    $mPickByLine = 0;
    $mFullBoxPick = 0;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mOrderType = ($mRow['order_type_code']);
        $mPickByLine = ($mRow['pick_by_line']);
        $mFullBoxPick = ($mRow['full_box_pick']);
    }
    mysqli_close($mConnection);
// Set Qty screen settings based on full-box flag
    if ($mFullBoxPick == 0)
        if ($mSerialReference == "")
            $mDataStr = "DATA:toLocationHashCode::HHHHHHH,boxCountQty::HHHHHHH";
        elseif ($mPartNumber == "")
            $mDataStr = "DATA:serialReference:".$mSerialReference."::skipqtyAllocated,qtyAllocated:";
        else
            $mDataStr = "DATA:partNumber:".$mPartNumber."::skipqtyAllocated,qtyAllocated:";
    else
        if ($mSerialReference == "")
            $mDataStr = "DATA:toLocationHashCode::HHHHHHH,boxCountQty::HHHHHHH";
        elseif ($mPartNumber == "")
            $mDataStr = "DATA:serialReference:".$mSerialReference.",qtyAllocated:";
        else
            $mDataStr = "DATA:partNumber:".$mPartNumber.",qtyAllocated:";
    echo $mDataStr;
    return;
}

// Skip / Resequence Current Pick Task
elseif (($mFunction != null) && ($mFunction == "skippick"))
{
    $mReference = "";
    $mToPlt = "";
    $mTrys = "0";
    $mErrMsg = "";
    $mConnect = null;
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    
//  exit("FAIL-TEST ".$mFilter);
    
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "reference")
            $mReference = $v2;
        elseif (strtolower($k2) == "pickdetailid")
            $mPickDtlId = strtoupper($v2);
        elseif (strtolower($k2) == "locationcode")
            $mLocationCode = strtoupper($v2);
        elseif (strtolower($k2) == "aislecode")
            $mAisle = $v2;
        elseif (strtolower($k2) == "toplt")
            $mToPlt = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
        elseif ($k2 == "rdtstart")
            $mRdtStart = trim($v2);
        elseif ($k2 == "rdtend")
            $mRdtEnd = trim($v2);
    }
    $mRdtStart = str_replace("colon",":",$mRdtStart);
    $mRdtEnd = str_replace("colon",":",$mRdtEnd);
    if (!isset($mPickDtlId) || $mPickDtlId == "" || $mPickDtlId == null)
    {
        exit("FAIL-Skip Failed");
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());

// Get id for document status
    $mDocStsId = 0;
    $mDocPkdId = 0;
    $mDataQuery = "SELECT id AS id, document_status_code AS document_status_code FROM document_status";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;
    $mData = (mysqli_query($mConnection,$mDataQuery));
    while($mRow = mysqli_fetch_assoc($mData))
    {
        if (strtolower($mRow['document_status_code']) == "open")
            $mDocStsId=($mRow['id']);
        if (strtolower($mRow['document_status_code']) == "picked")
            $mDocPkdId=($mRow['id']);
    }
        
// Update Pick Status
    $mDataQuery = "SELECT inspection_task_detail.document_reference AS document_reference, inspection_task_detail.inventory_master_id AS inventory_master_id, inspection_task_detail.part_id AS part_id, inspection_task_detail.part_number AS part_number,inspection_task_detail.qty_allocated AS qty_allocated, inspection_task_detail.line_no AS line_no, inspection_task_detail.inspection_task_body_id AS inspection_task_body_id, inspection_task_detail.pick_priority AS pick_priority";
    $mDataQuery .= ",inspection_task_body.inspection_task_header_id AS inspection_task_header_id";
    $mDataQuery .= ",0 AS blocked";
    $mDataQuery .= ",inspection_task_header.customer_reference AS customer_reference";
    $mDataQuery .= " FROM inspection_task_detail";
    $mDataQuery .= " JOIN inspection_task_body ON inspection_task_detail.inspection_task_body_id=inspection_task_body.id";
    $mDataQuery .= " JOIN inspection_task_header ON inspection_task_body.inspection_task_header_id=inspection_task_header.id";
    $mDataQuery .= " WHERE inspection_task_detail.id=".$mPickDtlId." AND inspection_task_detail.processed=0 LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
//  $mData = mysqli_query($mConnection,$mDataQuery);
    $mDocumentRef = "";
    $mInvId = "";
    $mAlcQty = 0;
    $mBlocked = 0;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mDocumentRef = $mRow['document_reference'];
        $mInvId = $mRow['inventory_master_id'];
        $mAlcQty = $mRow['qty_allocated'];
        $mPickBdyId = $mRow['inspection_task_body_id'];
        $mPickHdrId = $mRow['inspection_task_header_id'];
        $mPickPartId = $mRow['part_id'];
        $mPickPartNumber = $mRow['part_number'];
        $mDtlLineNo = $mRow['line_no'];
        $mBlocked = $mRow['blocked'];
        $mCustomerReferenceCode = $mRow['customer_reference'];
        $mPickDtlPriority = $mRow['pick_priority'];
    }
    if ($mDocumentRef != "")
    {
        if ($mBlocked == 0)
        {
            $mDataQuery = "UPDATE inspection_task_detail SET processed=0,pick_priority=CASE WHEN pick_priority < 900 then 900 WHEN pick_priority IS null then 900 ELSE pick_priority+1 END";
        }
        elseif ($mBlocked == 2)
        {
            $mDataQuery = "UPDATE inspection_task_detail SET processed=1,pick_priority=CASE WHEN pick_priority < 950 then 950 WHEN pick_priority IS null then 950 ELSE pick_priority+1 END";
        }
        else
        {
            $mDataQuery = "UPDATE inspection_task_detail SET pick_priority=999999, processed=1";
        }
        $mDataQuery .=" ,in_use_by='',last_updated_date=now(),created_by='".$mCurrentUser."-SKIP'";
        $mDataQuery .= " WHERE inspection_task_detail.id='".$mPickDtlId."' AND processed=0 LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);

		$mReturn = updatePickHistory($mHost,$mUser,$mPwd,$mDbName,$mPickDtlId,$mInvId,$mAlcQty,$mCurrentUser,"F2SKIP",$mDtlLineNo,"",$mDtlLineNo."-".$mPickDtlPriority);

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

// Missing Pick Serial
elseif (($mFunction != null) && ($mFunction == "missingpickserial"))
{
    $mErrMsg = "";
    $mStatus = "";
    $mFromLocationHash = "";
    $mCustomerReference = "";
    $mAisleCode = "";
    $mToPlt = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "plt")
            $mPltNumber = trim($v2);
        elseif (strtolower($k2) == "fromlocationhashcode")
            $mFromLocationHash = trim($v2);
        elseif (strtolower($k2) == "tolocationhashcode")
            $mToLocationHash = trim($v2);
        elseif (strtolower($k2) == "customerreference")
            $mCustomerReference = trim($v2);
        elseif (strtolower($k2) == "aislecode")
            $mAisleCode = trim($v2);
        elseif (strtolower($k2) == "serialreference")
            $mSerialReference = trim($v2);
        elseif (strtolower($k2) == "partnumber")
            $mPartNumber = trim($v2);
        elseif (strtolower($k2) == "allocationid")
            $mPickDtlId = trim($v2);
        elseif (strtolower($k2) == "sequencingrequestid")
            $mPickInvId = trim($v2);
        elseif (strtolower($k2) == "toplt")
            $mToPlt = trim($v2);
        elseif ((strtolower($k2) == "quantity") || (strtolower($k2) == "countqty") || (strtolower($k2) == "qtyallocated"))
            $mPickQty = floatval($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        die("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Validate Initial Values  
    $mDataQuery = "SELECT location_code FROM location WHERE location_hash='".$mFromLocationHash."' LIMIT 1"; 
    if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    $mData = (mysqli_query($mConnection,$mDataQuery));
    if (mysqli_num_rows($mData) == 0)
        exit("FAIL-Location is Incorrect");

    $mStatus = missingPickSerial($mHost,$mUser,$mPwd,$mDbName,$mPickDtlId,$mPickInvId,$mSerialReference,$mPartNumber,$mPickQty,$mAisleCode,$mCurrentUser,$mTransactionTypeId,$mFromLocationHash,$mToPlt);
    if ($mStatus == "")
        $mStatus = $mErrMsg;
    if ($mStatus == "")
        $mStatus = "OK  -missingpickserial";
    if (substr($mStatus,0,2) != 'FA' && substr($mStatus,0,2) != 'OK' && substr($mStatus,0,2) != 'DA')
        $mStatus = "FAIL-".$mStatus;
    exit($mStatus);
}

// Get Pallet Id
elseif (($mFunction != null) && ($mFunction == "getpickplt"))
{
        $mStatus = "OK  -getpickplt";
    exit ($mStatus);
}
// Clear Pick Flag
elseif (($mFunction != null) && (strtolower($mFunction) == "clearpickflag"))
{
    $mErrMsg = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "customerreference")
            $mCustomerReference = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    $mConnectp = str_replace(":8081/vantec",":8085/pick",$mConnect);
    $mStatus = clearPickDetail($mCurrentUser,$mHost,$mUser,$mPwd,$mDbName,$mCustomerReference);
    if (substr($mStatus,0,2)=="FA")
        exit($mStatus);
    exit("OK  -clearpickflag");
}

// Validate To-Loc
elseif (($mFunction != null) && (strtolower($mFunction) == "validateqaloc"))
{
    $mErrMsg = "";
	$mVldLocation = "";
// 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 == "locationhash")
            $mLocationHash = trim($v2);
		if ($k2 == "vldtolocation")
            $mVldLocation = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
    $mDataQuery = "SELECT location.id AS id,location.location_code AS location_code, location_type.location_type_code FROM location";
    $mDataQuery .=" LEFT JOIN location_type ON location.location_type_id=location_type.id";
    $mDataQuery .=" WHERE location_code='$mLocationHash' OR location_hash='$mLocationHash' LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    if (mysqli_num_rows($mData) >0)
    {
        list($mId,$mLocationCode,$mLocationType) = mysqli_fetch_row($mData);
        if (strtolower($mLocationType) != "qa")
        {
            $mErrMsg = "FAIL-Incorrect Location Type";
        }
    }
    else
    {
        $mErrMsg = "FAIL-Incorrect Location";
    }
	if ($mErrMsg == "")
	{
		if (!empty($mVldLocation) && $mVldLocation != $mLocationCode)
		{
			$mErrMsg = "FAIL-Wrong Location";
		}
	}
    if (substr($mErrMsg,0,2)=="FA")
        exit($mErrMsg);
    exit("OK  -validateqaloc");
}

// Get task_type list for select
if (($mFunction != null) && (strtolower($mFunction) == "getpicklist"))
{
//	echo("FAIL-TEST2");
	$mErrMsg = "";
    $mReference="";
    $mOffset=0;
// Replace Chars in Input String to emulate a JSON format instead of GET format
	$mFilter = str_replace("=",":",$mFilter);
	$mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
	$mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
	foreach($mArray1 as $k1=>$v1)
	{
		list($k2, $v2) = explode(":",$mArray1[$k1]);
		if ($k2 == "reference")
			$mReference = trim($v2);
		elseif ($k2 == "key")
			$mKey = trim($v2);
        elseif ($k2 == "offset")
			$mOffset = trim($v2);	
		elseif ($k2 == "currentUser")
			$mCurrentUser = trim($v2);
		elseif ($k2 == "transactionType")
			$mTransactionTypeId = strtoupper(trim($v2));
	}
	$mStatus = getPickList($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mReference,$mKey,$mOffset);
	echo $mStatus;
	return;
}

// Get FQA headers_list
// Get task_type list for select
if (($mFunction != null) && (strtolower($mFunction) == "getfqalist"))
{
//	echo("FAIL-TEST2");
	$mErrMsg = "";
    $mReference="";
    $mOffset=0;
// Replace Chars in Input String to emulate a JSON format instead of GET format
	$mFilter = str_replace("=",":",$mFilter);
	$mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
	$mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
	foreach($mArray1 as $k1=>$v1)
	{
		list($k2, $v2) = explode(":",$mArray1[$k1]);
		if ($k2 == "reference")
			$mReference = trim($v2);
		elseif ($k2 == "key")
			$mKey = trim($v2);
        elseif ($k2 == "offset")
			$mOffset = trim($v2);	
		elseif ($k2 == "currentUser")
			$mCurrentUser = trim($v2);
		elseif ($k2 == "transactionType")
			$mTransactionTypeId = strtoupper(trim($v2));
	}
	$mStatus = getFqaList($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mReference,$mKey,$mOffset);
	echo $mStatus;
	return;
}

// Get FQA Pick
if (($mFunction != null) && (strtolower($mFunction) == "getfqatask"))
{
    $mErrMsg = "";
    $mToPlt = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "documentreference")
            $mDocumentRef = trim($v2);
        elseif ($k2 == "locationcode")
            $mLocationCode = strtoupper(trim($v2));
        elseif ($k2 == "aisle")
            $mAisle = trim($v2);
        elseif ($k2 == "toplt")
            $mToPlt = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
//	exit("FAIL-TEST1-".$mFilter." ".$mDocumentRef);
    $mStatus = getFqaTask($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mDocumentRef,$mConnect,$mToPlt);
    echo $mStatus;
    return;
}

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

// Set path for Service Call
	$mConnectp = str_replace(":8081/vantec",":8081/vantec",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8081/vantec/";
    }
	include_once ('transaction.php');
	$mStatus = postRcts($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
	if (substr($mStatus,0,2)=="FA")
		exit($mStatus);
// Set Location Filling Status
	$mStatus = locationFillingSts("","","",$mJsonArray['tolocationhashcode'],$mHost,$mUser,$mPwd,$mDbName,$mJsonArray['currentUser']);
	if (substr($mStatus,0,2)=="FA")
		exit($mStatus);
// Close Replen Tasks
	include_once ('replen.php');
	$mStatus = closeReplen($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
	if (substr($mStatus,0,2)=="FA")
		exit($mStatus);
	
// Post fqa IDOC
//	http://172.16.1.70:8092/screen/writeQAINAndQAOUTMessage?serialNumber=PARTA&&partNumber=PARTA&&status=QAIN
// Replace default Server Tomcat Service
	$mConnectp = str_replace(":8081/vantec",":8092/screen",$mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect,":8081");
        $mConnectp = substr($mConnect,0,$e).":8092/screen/";
    }
	$ch = curl_init();
	try
	{
		curl_setopt($ch, CURLOPT_URL, $mConnectp."writeQAINAndQAOUTMessage?serialNumber=".$mJsonArray['serialreference']."&partNumber=".$mJsonArray['partnumber']."&status=QOUT");
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $mJsonObject);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$mResult = curl_exec($ch);
		$mErrors = curl_error($ch);
		$mResponse = curl_getinfo($ch, CURLINFO_HTTP_CODE);

		curl_close($ch);
		if ($mResponse != "200")
			$mErrMsg = ("FAIL-Unexpected System Error -".$mResult.":".$mResponse.":".$mErrors.":".$mJsonObject);
		else
		{
			$mErrMsg = "OK  - Post Complete";
		}
	}
	catch (Exception $e)
	{
		$mErrMsg = ("FAIL-Connection Error at - ".$mConnect.$mFilter.":".$e);
	}			
	
	exit("OK  -postfqa");
}
// close FQA Task
elseif (($mFunction != null) && ($mFunction == "closefqa"))
{
	$mReturn = "";
	$mErrMsg = "";
	$mPartNumber = "";
	$mDocumentReference = "";
// 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 == "documentreference")
			$mDocumentReference = trim($v2);
		elseif ($k2 == "serialreference")
			$mSerialReference = trim($v2);
		elseif ($k2 == "partnumber")
			$mPartNumber = trim($v2);
        elseif ($k2 == "currentUser")
			$mCurrentUser = trim($v2);
		elseif ($k2 == "transactionTypeId")
			$mTransactionTypeId = strtoupper(trim($v2));
	}
// mysql connection
	$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
		die("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());		
	if (empty($mDocumentReference))
	{
		$mDataQuery = "SELECT document_reference FROM fqa_task_body WHERE serial+reference='".$mSerialReference."' AND part_number='".$mPartNumber."' LIMIT 1";
		if (!$mData = mysqli_query($mConnection,$mDataQuery))
			exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
		if (mysqli_num_rows($mData) == 0)
		{
			exit ("OK  -closefqa");
		}
		list ($mDocumentReference) = mysqli_fetch_row($mData);
	}
	$mDataQuery = "UPDATE fqa_task_body SET qty_transacted=qty_expected,difference=0,document_status_id=(SELECT id FROM document_status WHERE document_status_code='COMPLETE' LIMIT 1) WHERE document_reference='$mDocumentReference' AND serial_reference='$mSerialReference' AND part_number='$mPartNumber' LIMIT 1";
	if (!mysqli_query($mConnection,$mDataQuery))
		exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
	$mDataQuery = "SELECT id FROM fqa_task_body WHERE document_reference = '$mDocumentReference' AND document_status_id=1 LIMIT 1";
	if (!$mData = mysqli_query($mConnection,$mDataQuery))
		exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
	if (mysqli_num_rows($mData) == 0)
	{
		$mDataQuery = "UPDATE fqa_task_header SET processed=1, document_status_id=(SELECT id FROM document_status WHERE document_status_code='COMPLETE' LIMIT 1) WHERE document_reference='$mDocumentReference' LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
			exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
	}
//	mysqli_close($mConnection);
	if ($mReturn == "")
		$mReturn = "OK  -closefqa";
	exit($mReturn);
}
// Skip / Resequence Current FQA Task
elseif (($mFunction != null) && ($mFunction == "skipfqa"))
{
    $mReference = "";
    $mErrMsg = "";
    $mConnect = null;
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    
//  exit("FAIL-TEST ".$mFilter);
    
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "reference")
            $mReference = $v2;
        elseif (strtolower($k2) == "serialreference")
            $mSerialReference = strtoupper($v2);
		elseif (strtolower($k2) == "partnumber")
            $mPartNumber = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
        elseif ($k2 == "rdtstart")
            $mRdtStart = trim($v2);
        elseif ($k2 == "rdtend")
            $mRdtEnd = trim($v2);
    }
    $mRdtStart = str_replace("colon",":",$mRdtStart);
    $mRdtEnd = str_replace("colon",":",$mRdtEnd);
    if (empty($mReference))
    {
        exit("FAIL-Skip Failed");
    }
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
        
// Update Pick Status
    if (!empty($mReference))
    {
		$mDataQuery = "UPDATE fqa_task_body SET date_created=now() WHERE document_reference='$mReference' AND serial_reference='$mSerialReference' AND part_number='$mPartNumber' LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    }
    if ($mErrMsg == "")
        exit("OK  -");
    else
        exit($mErrMsg);
}

// Get / Validate Fixed Loc.
elseif (($mFunction != null) && ($mFunction == "getfqafixedloc"))
{
    $mReference = "";
    $mErrMsg = "";
    $mConnect = null;
	$mVldLoc = "";
// Explode Input Parm
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
    $i=0;
    
//  exit("FAIL-TEST ".$mFilter);
    
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if (strtolower($k2) == "reference")
            $mReference = $v2;
        elseif (strtolower($k2) == "serialreference")
            $mSerialReference = strtoupper($v2);
		elseif (strtolower($k2) == "partnumber")
            $mPartNumber = strtoupper($v2);
		elseif (strtolower($k2) == "vldloc")
            $mVldLoc = strtoupper($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper($v2);
        elseif ($k2 == "rdtstart")
            $mRdtStart = trim($v2);
        elseif ($k2 == "rdtend")
            $mRdtEnd = trim($v2);
    }

	$mErrMsg = getFqaFixedLoc($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mSerialReference,$mPartNumber,$mVldLoc);
    if ($mErrMsg == "")
        exit("OK  -");
    else
        exit($mErrMsg);
}
elseif (($mFunction != null) && (strtolower($mFunction) == "createinsserial"))
{
	$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);
    $mQuantity = null;
// Create Associative Array by Exploding Array Elements on :
	foreach($mArray1 as $k1=>$v1)
	{
		list($k2, $v2) = explode(":",$mArray1[$k1]);
		if ($k2 == "serialreference")
			$mSerialReference = trim($v2);
        elseif ($k2 == "partnumber")
			$mPartNumber = trim($v2);
		elseif ($k2 == "allocationid")
			$mAllocationId = trim($v2);	
        elseif ($k2 == "quantity")
			$mQuantity = trim($v2);
		elseif ($k2 == "printer")
			$mPrinter = trim($v2);
		elseif ($k2 == "currentUser")
			$mCurrentUser = trim($v2);
		elseif ($k2 == "transactionType")
			$mTransactionTypeId = strtoupper(trim($v2));
        elseif ($k2 == "transactionTypeId")
			$mTransactionTypeId = strtoupper(trim($v2));
	}
	$mResult = createInsSerial($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mAllocationId,$mSerialReference,$mPartNumber,$mQuantity,$mPrinter);
    if (substr($mResult,0,2)=="FA") 
        exit($mResult);
	exit ("OK  -createinsserial");
}


// Reset Pick
function resetPick($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerReference)
{
// reset pick_priority
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
    $mStartTime = date('Y-m-d H:i:s');
    $mEndTime = date('Y-m-d H:i:s');
//  exit("FAIL-".$mStartTime." ".$mEndTime);
    $mDataQuery = "SELECT document_reference FROM inspection_task_header WHERE customer_reference='$mCustomerReference' LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    if (mysqli_num_rows($mData) > 0)
    {
        list($mPickDocumentReference) = mysqli_fetch_row($mData);
        try
        {
            $mDataQuery = "DELETE FROM inspection_task_detail WHERE id>0 AND document_reference='$mPickDocumentReference' AND processed=0 AND (serial_reference='NO-STOCK')";
            mysqli_query($mConnection,$mDataQuery);
        }
        catch(Exception $e)
        {
            $mDataQuery = "UPDATE inspection_task_detail SET qty_allocated=0,processed=1 WHERE id>0 AND document_reference='$mPickDocumentReference' AND processed=0 AND (serial_reference='NO-STOCK')";
            if (!mysqli_query($mConnection,$mDataQuery))
                exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        }
        
        $mDataQuery = "UPDATE inspection_task_detail SET pick_priority = line_no WHERE pick_priority < 999998 AND pick_priority>=900 AND document_reference='$mPickDocumentReference'";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    }
    $mEndTime = date('Y-m-d H:i:s');
//  exit("FAIL-".$mStartTime." ".$mEndTime);
    mysqli_close($mConnection);

    if ($mErrMsg == "")
    {
        $mErrMsg = "OK  - resetPick";
    }
    return $mErrMsg;
}

// Validate Pick Entries
function validatePick($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerReference,$mFromLocation,$mVldLocation,$mPartNumber,$mVldPartNumber,$mSerialReference,$mVldSerialReference,$mQty,$mVldQty,$mTransactionTypeId,$mPrinter=null)
{
//  echo "FAIL-TEST1";
//  return;

//  exit( "FAIL-TEST2-".$mSerialReference."-".$mQty."+".$mVldQty." ".$mVldSerialReference);
    
    if (($mFromLocation == "") || ($mFromLocation == null))
    {
        $mErrMsg = "FAIL-Wrong Location";
        return $mErrMsg;
    }
    
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    
    if (($mErrMsg == "") && (($mFromLocation != "") || ($mVldLocation != "")))
    {
        $mDataQuery = "SELECT location.id AS id, location.location_code AS location_code";
		$mDataQuery .=",location_type.no_serial_scan AS no_serial_scan";
		$mDataQuery .=" FROM location";
		$mDataQuery .=" LEFT JOIN location_type ON location.location_type_id=location_type.id";
		$mDataQuery .=" WHERE location.location_hash = '".$mFromLocation."'";
		$mDataQuery .=" LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $i = 0;
		$mNoSerial = 0;
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mFromLocId = $mRow['id'];
			$mFromLocCode = ($mRow['location_code']);
			$mNoSerial = ($mRow['no_serial_scan']);
            $i++;
        }
        if (($i == 0) || ($mFromLocCode != $mVldLocation))
        {
            $mErrMsg = "FAIL-Wrong Location";
            return $mErrMsg;
        }
    }
	if (empty($mErrMsg) && !empty($mVldPartNumber))
	{
		$mDataQuery = "SELECT part.id AS id";
		$mDataQuery .=",location_type.no_serial_scan AS no_serial_scan";
		$mDataQuery .=" FROM part";
		$mDataQuery .=" LEFT JOIN location_type ON part.fixed_location_type_id=location_type.id";
		$mDataQuery .=" WHERE part.part_number = '$mVldPartNumber'";
		$mDataQuery .=" LIMIT 1";
		if (!$mData = mysqli_query($mConnection,$mDataQuery))
			exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
		if (mysqli_num_rows($mData) > 0)
		{
			list($mPartId,$mNoSerial) = mysqli_fetch_row($mData);
		}
	}
// create default smmall-parts inventory.    
	if ($mNoSerial == 1 && $mTransactionTypeId == "STKPULL" && substr($mSerialReference,0,7) !='PULL' && empty($mQty))
	{
		$mDataQuery = "SELECT inspection_task_body.part_number AS part_number,inspection_task_body.qty_expected-inspection_task_body.qty_transacted AS tran_qty";
		$mDataQuery .=", part.id AS part_id,part.conversion_factor AS conversion_factor";
		$mDataQuery .=" FROM inspection_task_body";
		$mDataQuery .=" LEFT JOIN part ON inspection_task_body.part_number=part.part_number";
		$mDataQuery .=" WHERE inspection_task_body.customer_reference = '$mCustomerReference'";
		$mDataQuery .=" AND inspection_task_body.part_id='$mPartId'";
		$mDataQuery .=" LIMIT 1";
		if (!$mData = mysqli_query($mConnection,$mDataQuery))
			exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
		if (mysqli_num_rows($mData) > 0)
		{
			list($mPartNumber,$mQty,$mPartId,$mConvFactor) = mysqli_fetch_row($mData);
		}
		$found = true;
		Do 
		{
			$yymmdd = "PULL".date('His');
			$mDataQuery = "SELECT id FROM inventory_master WHERE serial_reference = '$yymmdd' LIMIT 1";
			if (!$mData = mysqli_query($mConnection,$mDataQuery))
				exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
			if (mysqli_num_rows($mData) == 0)
			{
				$found = false;
			}
		}
		while($found == true);
		if ($found == false)
		{
// Downdata existing Serials
			$mDataQuery = "SELECT id,inventory_qty,inventory_status_id FROM inventory_master WHERE part_id=$mPartId AND location_id=$mFromLocId AND serial_reference <> '$yymmdd' AND inventory_qty > 0";
			if (!$mData = mysqli_query($mConnection,$mDataQuery))
				exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
			$mOutsQty = $mQty;
			$mTrnQty = 0;
			$mInvQty = 0;
//			exit("FAIL-TEST1-".$mDataQuery." ".mysqli_num_rows($mData));
			While($mRow = mysqli_fetch_assoc($mData))
			{
				$mInvId = $mRow['id'];
				$mInvQty = $mRow['inventory_qty'];
				$mInvStsId = $mRow['inventory_status_id'];
				
				if (empty($mInvStsId))
				{
					$mInvStsId = 1;
				}
				
				if ($mInvQty > $mOutsQty)
				{
					$mInvQty = $mInvQty - $mOutsQty;
					$mTrnQty = $mTrnQty + $mOutsQty;
					$mOutsQty = 0;
				}
				else
				{
					$mOutsQty = $mOutsQty - $mInvQty;
					$mTrnQty = $mTrnQty + $mInvQty;
					$mInvQty = 0;
				}
//				exit("FAIL-TEST1-".$mQty." ".$mOutsQty." ".$mTrnQty." ".$mInvQty);
				$mDataQuery = "UPDATE inventory_master SET inventory_qty=$mInvQty, last_updated=now(),last_updated_by='$mCurrentUser',available_qty=inventory_qty WHERE id=$mInvId LIMIT 1";
				if (!mysqli_query($mConnection,$mDataQuery))
					exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
				if ($mOutsQty <= 0)
				{
					break;
				}
				$mDataQuery = "UPDATE inventory_master SET inventory_qty=$mTrnQty, available_qty=inventory_qty WHERE serial_reference='$yymmdd' LIMIT 1";
				if (!mysqli_query($mConnection,$mDataQuery))
					exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
			}
			if ($mTrnQty <= 0)
			{
				exit("FAIL-No Inventory for ".$mPartNumber);
			}
			try
			{
				$mDataQuery = "INSERT INTO inventory_master";
				$mDataQuery .=" (id,version,allocated_qty,hold_qty,current_inventory_status_id,current_location_id,location_id,location_code,date_created,created_by,expiry_date,inventory_qty,available_qty,last_updated,last_updated_by,parent_tag_id,part_id,part_number,ran_or_order,recorded_missing,requires_decant,requires_inspection,serial_reference,originating_detail_id,conversion_factor,stock_date,active,inventory_status_id,product_type_id,pruf_cube)";
				$mDataQuery .=" VALUES(DEFAULT,0,0,0,null,".$mFromLocId.",".$mFromLocId.",'".$mFromLocCode."',now(),'".$mCurrentUser."',null,".$mTrnQty.",".$mTrnQty.",now(),'".$mCurrentUser."',null,".$mPartId.",'".$mPartNumber."','".$mCustomerReference."',0,0,0,'".$yymmdd."',null,".$mConvFactor.",now(),1,".$mInvStsId.",0,0)";
				if (!mysqli_query($mConnection,$mDataQuery))
					exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
				$mInvId = mysqli_insert_id($mConnection);
			}
			catch (Exception $e)
			{
				$mDataQuery = "INSERT INTO inventory_master";
				$mDataQuery .=" (id,version,allocated_qty,hold_qty,current_inventory_status_id,current_location_id,location_id,location_code,date_created,created_by,expiry_date,inventory_qty,available_qty,last_updated,last_updated_by,parent_tag_id,part_id,part_number,ran_or_order,recorded_missing,requires_decant,requires_inspection,serial_reference,originating_detail_id,conversion_factor,stock_date,active,inventory_status_id,product_type_id,pruf_cube)";
				$mDataQuery .=" VALUES(DEFAULT,0,0,0,null,".$mFromLocId.",".$mFromLocId.",'".$mFromLocCode."',now(),'".$mCurrentUser."',null,".$mTrnQty.",".$mTrnQty.",now(),'".$mCurrentUser."',null,".$mPartId.",'".$mPartNumber."','".$mCustomerReference."',0,0,0,'".$yymmdd."',null,".$mConvFactor.",now(),1,1,0,0)";
				if (!mysqli_query($mConnection,$mDataQuery))
					exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
				$mInvId = mysqli_insert_id($mConnection);
			}
			
			try
			{
				$mDataQuery ="DELETE FROM inventory_master";
				$mDataQuery .=" WHERE id > 0 AND inventory_qty <= 0 AND current_location_id=$mFromLocId";
				if (!mysqli_query($mConnection,$mDataQuery))
					exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
			}
			catch (Exception $e)
			{
			}
			$mDataQuery = "UPDATE inspection_task_detail SET inventory_master_id=".$mInvId.",serial_reference='".$yymmdd."' WHERE serial_reference='$mVldSerialReference' AND part_number='$mPartNumber' LIMIT 1";
			try
			{
				mysqli_query($mConnection,$mDataQuery);
			}
			catch (Exception $e) 
			{
				exit ("FAIL-".$e."-".$mDataQuery);
			}

			if (!empty($mPrinter))
			{
				$mDataQuery = "SELECT document_reference FROM inspection_task_detail WHERE serial_reference='$yymmdd' AND part_number='$mPartNumber' LIMIT 1";
				try
				{
					$mdata = mysqli_query($mConnection,$mDataQuery);
				}
				catch (Exception $e) 
				{
					exit ("FAIL-".$e."-".$mDataQuery);
				}
				list($mDocRef) = mysqli_fetch_row($mData);
				include_once('../reports/insplabelpdf.php');
				$mStatus = labelPrint($mCustomerReference,$mPrinter,$mLabel,$mHost,$mUser,$mPwd,$mDbName,"n");
			}
			$mStatus = "DATA:serialReferenceinput:".$yymmdd.",qtyAllocatedinput:".$mTrnQty."::skiptoLocationHashCode";
			exit ($mStatus);
		}
	}
	
    if (($mSerialReference == null) || ($mSerialReference == ""))
    {
        $mErrMsg = "DATA:serialReference:::skipserialReference";
        return $mErrMsg;
    }

// Check Scanned Part against pick
    if (($mErrMsg == "") && ($mPartNumber != ""))
    {
        if (trim($mPartNumber) != trim($mVldPartNumber))
        {
            $mDataQuery = "SELECT id AS id, part_number AS part_number FROM part WHERE upper(part_number) = '".$mPartNumber."' OR (upper(part_number)='".$mVldPartNumber."' AND upper(jis_supply_group)='".$mPartNumber."') LIMIT 1";
            if (!mysqli_query($mConnection,$mDataQuery))
                exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
            $mData = mysqli_query($mConnection,$mDataQuery);
            $i = 0;
            while($mRow = mysqli_fetch_assoc($mData)) 
            {
                $mPartNumber = $mRow['part_number'];
                $i++;
            }
            
            if (($i == 0) || (strtoupper($mPartNumber) != $mVldPartNumber))
                $mErrMsg = "FAIL-Incorrect Part Number";
        }
    }
// Validate Entered Serial  
    if (($mErrMsg == "") && ($mSerialReference != ""))
    {
        if ($mPartNumber == "")
        {
            if ($mVldPartNumber == "")
            {
                $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_qty AS inventory_qty, inventory_master.requires_inspection AS inspect";
                $mDataQuery .=", location.location_code";
                $mDataQuery .=", part.conversion_factor AS conversion_factor, part.importanta AS strict_serial, part.full_box_pick AS full_box";
                $mDataQuery .=" FROM inventory_master";
                $mDataQuery .=" JOIN part ON inventory_master.part_id=part.id";
                $mDataQuery .=" JOIN location on inventory_master.current_location_id=location.id";
                $mDataQuery .=" LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id";
                $mDataQuery .=" WHERE UPPER(inventory_master.serial_reference)='".$mSerialReference."' AND inventory_master.inventory_qty > 0";
                $mDataQuery .=" AND inventory_status_code IN('ok','missing')";
                $mDataQuery .=" LIMIT 2";
            }
            else
            {
                $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_qty AS inventory_qty, inventory_master.requires_inspection AS inspect";
                $mDataQuery .=", location.location_code";
                $mDataQuery .=",part.part_number AS part_number, part.conversion_factor AS conversion_factor,part.importanta AS strict_serial, part.full_box_pick AS full_box";
                $mDataQuery .=" FROM inventory_master";
                $mDataQuery .=" LEFT JOIN part ON inventory_master.part_id=part.id";
                $mDataQuery .=" LEFT JOIN location on inventory_master.current_location_id=location.id";
                $mDataQuery .=" LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id";
                $mDataQuery .=" WHERE UPPER(inventory_master.serial_reference)='".$mSerialReference."' AND (part.part_number='".$mVldPartNumber."' OR part.jis_supply_group ='".$mVldPartNumber."') AND inventory_master.inventory_qty > 0";
                $mDataQuery .=" AND inventory_status_code IN('ok','missing')";
                $mDataQuery .=" LIMIT 1";
            }
        }
        else
        {
            $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_qty AS inventory_qty, inventory_master.requires_inspection AS inspect";
            $mDataQuery .=", location.location_code";
            $mDataQuery .=",part.part_number AS part_number, part.conversion_factor AS conversion_factor, part.importanta AS strict_serial, part.full_box_pick AS full_box";
            $mDataQuery .=" FROM inventory_master";
            $mDataQuery .=" JOIN part ON inventory_master.part_id=part.id";
            $mDataQuery .=" JOIN location on inventory_master.current_location_id=location.id";
            $mDataQuery .=" LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id";
            $mDataQuery .=" WHERE UPPER(inventory_master.serial_reference)='".$mSerialReference."' AND (part.part_number='".$mPartNumber."' OR part.jis_supply_group ='".$mPartNumber."') AND inventory_master.inventory_qty > 0";
            $mDataQuery .=" AND inventory_status_code IN('ok','missing','qtine')";
            $mDataQuery .=" LIMIT 1";
        }
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        
//      exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".$mPartNumber."-".$mVldPartNumber."-".$mFilter);
        
        $i = 0;
        $mInvId = "";
        $mInvQty = 0;
        $mPartConvFactor = 1;
        $mPartStrict = 0;
		$mFullBox = 0;
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mDataStr = ($mRow['location_code']);
            $mInspect = ($mRow['inspect']);
            $mInvId = ($mRow['id']);
            $mInvQty = ($mRow['inventory_qty']);
            $mPartConvFactor = ($mRow['conversion_factor']);
            $mPartNumber = ($mRow['part_number']);
            $mPartStrict = ($mRow['strict_serial']);
			$mFullBox = ($mRow['full_box']);
            $i++;
        }
        if ($i == 0)
        {
            $mErrMsg = "FAIL-Serial / part is wrong";
            return $mErrMsg;
        }
// Multiple Serials - Prompt for Part Number
        if ($i > 1)
        {
            $mErrMsg = "DATA:serialReferencecontent:".$mSerialReference."::skippartNumber,partNumber:";
            return $mErrMsg;
        }
        if ($i == 1)
        {
            if ($mDataStr != $mVldLocation)
            {
                $mErrMsg = "FAIL-Scan Serl is in a different Location ".$mVldLocation;
            }

            if ($mErrMsg == "")
            {
// check if Inventory Qty > required Qty.
				if ($mFullBox == 0)
				{
					if ($mTransactionTypeId == "STKPULL")
					{
						$mDataQuery = "SELECT inspection_task_body.id AS id,inspection_task_body.qty_expected-inspection_task_body.qty_transacted AS qty FROM inspection_task_body JOIN inspection_task_header ON inspection_task_body.inspection_task_header_id=inspection_task_header.id WHERE inspection_task_header.customer_reference='$mCustomerReference' AND inspection_task_body.part_number='$mPartNumber' LIMIT 1";
						if (!$mData = mysqli_query($mConnection,$mDataQuery))
							exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
						if (mysqli_num_rows($mData) > 0)
						{
							list($mBdyId,$mBdyQty) = mysqli_fetch_row($mData);
							if ($mInvQty > $mBdyQty)
							{
								$mErrMsg = "FAIL-This serial must be decanted to ".$mBdyQty;
								return $mErrMsg;
							}
						}
					}
				}
// Apply Conversion Factor
                if ($mPartConvFactor > 0)
                {
                    if (floor($mInvQty / $mPartConvFactor) == $mInvQty / $mPartConvFactor)
                    {
                        $mInvQty = intval($mInvQty / $mPartConvFactor);
                    }
                    else
                    {
                        $mInvQty = $mInvQty / $mPartConvFactor;
                    }
                }
// scanned serial <> prompted serial
                if ($mSerialReference != $mVldSerialReference)
                {
                    if ($mInvQty <> $mVldQty)
                    {
                        return "DATA:sequencingRequestId:".$mInvId.",qtyAllocated:".$mInvQty;
                    }
                    else
                    {
                        return "DATA:sequencingRequestId:".$mInvId;
                    }
                }
            }
        }
    }
// Force full-box pick
    if ($mErrMsg == "")
    {
        $mStrictSerial = 0;
        $mFullBoxPick = 1;
    }

// Test for Piece (non-full-box) pick
    if ($mErrMsg == "")
    {
        if (($mSerialReference != "") && ($mQty == ""))
        {
            if ($mFullBoxPick == 1)
            {
                $mErrMsg = "DATA:sequencingRequestId:".$mInvId.",qtyAllocatedvalue:".$mInvQty;
            }
            else
            {
                if ($mPartNumber == "")
                {
                    $mErrMsg = "DATA:sequencingRequestId:".$mInvId.",serialReferencecontent:".$mSerialReference."::skipqtyAllocated";
                }
            }
        }
    }
//    mysqli_close($mConnection);
    if ($mErrMsg == "")
    {
        $mErrMsg = "OK  -Valid Pick";
    }
//  echo $mErrMsg;
    return $mErrMsg;
}

// Allocate Pick
function allocatePick($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerReferenceCode,$mConnect,$mToPlt="")
{
    $mReturn = "";
    if (($mCustomerReferenceCode != null) && ($mCustomerReferenceCode != ""))
    {
// mysql connection
        $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
        if (!$mConnection)
            return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
// Order Header
        $mReturn = "";
        $mDataQuery = "SELECT inspection_task_header.id AS id, inspection_task_header.document_reference_code AS document_reference,inspection_task.header.task_type AS task_type";
        $mDataQuery .=", document_status.document_status_code";
        $mDataQuery .=" FROM inspection_task_header";
        $mDataQuery .=" LEFT JOIN document_status ON document_header.document_status_id=document_status.id";
        $mDataQuery .=" WHERE inspection_task_header.customer_reference='$mCustomerReferenceCode'";
        $mDataQuery .=" LIMIT 1";

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

        $mHdrId = "";
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mHdrId = ($mRow['id']);
            $mDocumentReferenceCode = ($mRow['document_reference']);

// Pick Header
            $mReturn = addUpdatePick($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerReferenceCode,$mHdrId,$mTimeSlot);
            $mPickHdrId = $mReturn;

            $mReturn = addPickBody($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mHdrId,$mCustomerReferenceCode);
            $mDataQuery = "SELECT id FROM document_body WHERE document_header_id=".$mRow['id']." LIMIT 1";
            if (!$mBdyData = mysqli_query($mConnection,$mDataQuery))
                return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
            $mReturn = getOrderLine($mHost,$mUser,$mPwd,$mDbName,$mPickHdrId, $mCurrentUser,$mCustomerReferenceCode,$mTransactionType,$mToPlt);
                
            if ($mReturn == "FAIL-Unavailable")
            {
                $mReturn = getOrderLine($mHost,$mUser,$mPwd,$mDbName,$mPickHdrId, $mCurrentUser,$mCustomerReferenceCode,$mTransactionType,$mToPlt);
            }
            if (substr($mReturn,0,8) == "DATA:EOD" || substr($mReturn,0,8) == "FAIL-EOD")
            {
                $mReturn = getOrderLine($mHost,$mUser,$mPwd,$mDbName,$mPickHdrId, $mCurrentUser,$mCustomerReferenceCode,$mTransactionType,$mToPlt);
            }
            return "OK  -pickAllocate";
        }
    }
    else
    {
        $mReturn = "FAIL-EOD-No Matching Customer Reference";
    }
    return $mReturn;
}

// Get Next Pick
function getPick($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerReferenceCode,$mConnect,$mToPlt="")
{
    $mReturn = "";
    if (($mCustomerReferenceCode != null) && ($mCustomerReferenceCode != ""))
    {
// mysql connection
        $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
        if (!$mConnection)
            return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
// Order Header
        $mReturn = "";
        $mDataQuery = "SELECT inspection_task_header.id AS id, inspection_task_header.document_reference AS document_reference, inspection_task_header.to_location_id AS to_location_id,inspection_task_header.task_type AS task_type";
        $mDataQuery .=",location.location_code AS location_code ";
        $mDataQuery .=", document_status.document_status_code";
        $mDataQuery .=" FROM inspection_task_header";
        $mDataQuery .=" LEFT JOIN location ON inspection_task_header.to_location_id=location.id";
        $mDataQuery .=" LEFT JOIN document_status ON inspection_task_header.document_status_id=document_status.id";
        $mDataQuery .=" WHERE inspection_task_header.customer_reference='$mCustomerReferenceCode'";
        $mDataQuery .=" LIMIT 1";

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

        if (mysqli_num_rows($mData) == 0)
        {
            $mToPlt = "";
            if ($mTransactionType != "")
            {
                if ($mToPlt != "")
                {
                    return "OKMS-Task Complete,CHGTRAN:".$mTransactionType."?DATA:customerReference:,toPlt:".$mToPlt;
                }
                else
                {
                    return "OKMS-No Tasks - Task is Complete,CHGTRAN:".$mTransactionType."?DATA:customerReference:,toPlt:".$mToPlt;
                }
            }
            else
            {
                $mTransactionType = "STKPULL";
                return "OKMS-No Tasks for ".$mTransactionType.",CHGTRAN:".$mTransactionType."?DATA:customerReference:,toPlt:".$mToPlt;
            }
        }
        $mPickByLine = 0;
        $mFullBoxPick = 1;
        $mToLoc = "INSP00";
        $mTaskType=1;
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mHdrId = ($mRow['id']);
            $mDocumentReferenceCode = ($mRow['document_reference']);
            if (!empty($mRow['location_code']))
            {
                $mToLoc = $mRow['location_code'];
            }
            $mDocStsCode = $mRow['document_status_code'];
            if (!empty($mRow['task_type']))
            {
                $mTaskType = $mRow['task_type'];
            }
// Test if order is complete
            if (strtolower($mRow['document_status_code']) == "picked" || strtolower($mRow['document_status_code']) == "transmitted")
            {
                $mToPlt = "";
                $mTransactionType="STKPULL";
                exit ("OKMS-The Task is ".$mDocStsCode.",CHGTRAN:".$mTransactionType."?DATA:customerReference:,toPlt:".$mToPlt);
            }
            if (!ISSET($mTransactionType) || $mTransactionType == null || $mTransactionType == "")
                $mTransactionType="STKPULL";

// Pick Header
            $mReturn = addUpdatePick($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerReferenceCode,$mHdrId);
            if (substr($mReturn,0,4) == "FAIL")
                return "OKMS-".$mReturn.",CHGTRAN:".$mTransactionType."?DATA:customerReference:,toPlt:".$mToPlt;
            else
            {
                $mHdrId = $mReturn;
           
                if (strtolower($mRow['document_status_code']) != "open" && strtolower($mRow['document_status_code']) != "allocated")
                {
                    $mTransactionType="STKPULL";
                    return "OKMS-This Task is Not Available,CHGTRAN:".$mTransactionType."?DATA:customerReference:,toPlt:".$mToPlt;
                }
                $mReturn = addPickBody($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mHdrId,$mCustomerReferenceCode);
                $mDataQuery = "SELECT id FROM inspection_task_body WHERE inspection_task_header_id=".$mHdrId." LIMIT 1";
                if (!$mBdyData = mysqli_query($mConnection,$mDataQuery))
                    return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
                if (mysqli_num_rows($mBdyData) == 0)
                {
                    return "FAIL-No Tasks for this Reference";
                }
                
                $mReturn = getOrderLine($mHost,$mUser,$mPwd,$mDbName,$mHdrId, $mCurrentUser,$mCustomerReferenceCode,$mTransactionType,$mToPlt,$mToLoc,$mTaskType);
                if ($mReturn == "")
                    return "OKMS-Allocation Error,CHGTRAN:".$mTransactionType."?DATA:customerReference:,toPlt:".$mToPlt;
                if ($mReturn == "DATA:EOD-This Task is Complete")
                {
                    if ($mTransactionType != "")
                    {
                        if ($mToPlt != "")
                            return "CHGTRAN:".$mTransactionType."?DATA:customerReference:,toPlt:".$mToPlt.",rdtMessage:The Task $mCustomerReferenceCode is Complete";
                        else
                            return "OKMS-No Tasks to Allocate,CHGTRAN:".$mTransactionType."?DATA:customerReference:,toPlt:".$mToPlt;
                    }
                    return $mReturn;
                }
                if ($mReturn == "FAIL-No Serials to Pick")
                {
                    if ($mTransactionType != "")
                    {
                        if ($mToPlt != "")
                            $mReturn = "CHGTRAN:".$mTransactionType."?DATA:customerReference:,toPlt:".$mToPlt.",rdtMessage:".substr($mReturn,9);
                        else
                            return "CHGTRAN:".$mTransactionType."?DATA:customerReference:,toPlt:".$mToPlt.",rdtMessage:".substr($mReturn);
                    }
                    else
                    {
                        $mTransactionType="STKPULL";
                        return "CHGTRAN:".$mTransactionType."?DATA:customerReference:,rdtMessage:".substr($mReturn);
                    }
                }
                if ($mReturn == "FAIL-Unavailable")
                {
                    $mReturn = getOrderLine($mHost,$mUser,$mPwd,$mDbName,$mHdrId, $mCurrentUser,$mCustomerReferenceCode,$mTransactionType,$mToPlt,$mToLoc,$mTaskType);
                }
                if (substr($mReturn,0,8) == "DATA:EOD" || substr($mReturn,0,8) == "FAIL-EOD")
                {
                    $mReturn = getOrderLine($mHost,$mUser,$mPwd,$mDbName,$mHdrId, $mCurrentUser,$mCustomerReferenceCode,$mTransactionType,$mToPlt,$mToLoc,$mTaskType);
                    
                    if (substr($mReturn,0,8) == "DATA:EOD" || substr($mReturn,0,8) == "FAIL-EOD")
                    {
                        $mToPlt = "";
// Hard-coding for Kanban Pick
                        if ($mTransactionType != "")
                        {
                            if ($mToPlt != "")
                                $mReturn = "OKMS-No Serials for this pick,CHGTRAN:".$mTransactionType."?DATA:customerReference:,aisleCode:ALL,toPlt:".$mToPlt.",rdtMessage:".substr($mReturn,9);
                            else
                                $mReturn = "OKMS-No Serials for this pick,CHGTRAN:".$mTransactionType."?DATA:customerReference:,aisleCode:ALL,toPlt:".$mToPlt.",rdtMessage:".substr($mReturn,9);
                        }
                        else
                        {
                            $mTransactionType="STKPULL";
                            return "OKMS-No Stock for this Task,CHGTRAN:".$mTransactionType."?DATA:customerReference:,rdtMessage:".substr($mReturn,9);
                        }
                    }
                    elseif ($mReturn == "")
                        $mReturn = "FAIL-Task Error";
                }
            }
            
            return $mReturn;
        }
    }
    else
    {
        $mReturn = "FAIL-EOD-No Matching Customer Reference";
    }
    return $mReturn;
}

// Update Pick Header
function addUpdatePick($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerReferenceCode)
{
    $mDocumentReferenceCode = "";
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
    if (!$mConnection)
        return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
    
// Pick_Header
    $mDataQuery = "SELECT id,document_reference FROM inspection_task_header WHERE customer_reference='".$mCustomerReferenceCode."' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    $mData = mysqli_query($mConnection,$mDataQuery);
    $mDocumentReferenceCode = "";
    $mPickHdrId = "";
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mPickHdrId = ($mRow['id']);
        $mDocumentReferenceCode = ($mRow['document_reference']);
    }
// No Pick_header
    if ($mPickHdrId == "")
    {
        if ($mDocumentReferenceCode == "")
            $mDocumentReferenceCode = "INS9999999";
        $mDataQuery = "Insert INTO inspection_task_header (id, document_reference, customer_reference, document_status_id, date_created, created_by, last_updated_date, last_updated_by) VALUES(DEFAULT,'".$mDocumentReferenceCode."','".$mCustomerReferenceCode."',now(),'".$mCurrentUser."',now(),'".$mCurrentUser."')";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        $mPickHdrId=mysqli_insert_id($mConnection);
// Create new Pick Document_Ref.
        $mDocumentReferenceCode = "0000000".round($mPickHdrId);
        $mDocumentReferenceCode = "INS".substr($mDocumentReferenceCode,-7);
        $mDataQuery = "UPDATE inspection_task_header SET document_reference='".$mDocumentReferenceCode."', document_status_id=(SELECT document_status.id FROM document_status WHERE lower(document_status.document_status_code)='open') WHERE id=".$mPickHdrId." LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        
        $mDataQuery = "UPDATE inspection_task_header SET inspection_task_header.document_status_id = (SELECT id FROM document_status WHERE lower(document_status.document_status_code)='allocated'), inspection_task_header.last_updated=now(),inspection_task_header.last_updated_by='".$mCurrentUser."' WHERE inspection_task_header.id=".$mOrderHdrId." LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    }
    else
    {
        $mDataQuery = "UPDATE inspection_task_header SET last_updated_date=now(), last_updated_by='".$mCurrentUser."' WHERE id=".$mPickHdrId." LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    }
        
    mysqli_close($mConnection);
    return $mPickHdrId;
}
function addPickBody($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerReferenceCode)
{
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
    if (!$mConnection)
        return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
    
    return "OK  -addPickBody";
}
function getOrderLine($mHost,$mUser,$mPwd,$mDbName,$mPickHdrId, $mCurrentUser,$mCustomerReferenceCode,$mTransactionType,$mToPlt,$mToLoc,$mTaskType=1)
{
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
    if (!$mConnection)
        return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();

// Check for Unallocated Pick Bodies
    
    $i = $i+1;
    $mDataQuery = "SELECT inspection_task_body.id AS id,inspection_task_body.part_number AS part_number,inspection_task_body.part_id AS part_id,inspection_task_body.qty_expected AS qty_expected,inspection_task_body.qty_transacted AS qty_transacted, inspection_task_body.line_no AS line_no, inspection_task_body.document_reference AS document_reference";
    $mDataQuery .=" FROM inspection_task_body";
    $mDataQuery .=" WHERE inspection_task_body.inspection_task_header_id=".$mPickHdrId;
    $mDataQuery .=" AND inspection_task_body.qty_expected>inspection_task_body.qty_transacted";
    $mDataQuery .=" AND inspection_task_body.document_status_id=1";
    $mDataQuery .=" LIMIT 50";

    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
//    return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery." ".mysqli_num_rows($mData);
    
    if (mysqli_num_rows($mData) == 0)
    {
        $mReturn = "FAIL-No Lines to Pick";
    }
    else
    {
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mInUseBy = '';
            $mPickDocumentReference = ($mRow['document_reference']);
            $mPickBdyId = ($mRow['id']);
            $mOrdQty = ($mRow['qty_expected']);
            $mScanQty = ($mRow['qty_transacted']);
            $mPartId = ($mRow['part_id']);
            $mPartNumber = ($mRow['part_number']);
            $mRdtPrompt = ($mRow['rdt_prompt']);
            $mPickBdyLine = $mRow['line_no'];
            $mConversionFactor = 1;
            $mRdtPrompt = str_replace("!","",$mRdtPrompt);
// Try to Allocate Inventory
            $mPickQty = $mOrdQty;
            $mReturn = "";
            if ($mPickQty > $mScanQty)
                $mPickQty = $mPickQty-$mScanQty;
            else
                $mPickQty = 0;
            if ($mPickQty > 0)
            {
                $mPickDtlQty = 0;
                $mPickQuery = "SELECT sum(qty_allocated) AS qty_allocated FROM inspection_task_detail WHERE inspection_task_body_id=".$mPickBdyId." AND processed=0";
                if (!$mPickData = mysqli_query($mConnection,$mPickQuery))
                    return "FAIL-".mysqli_error($mConnection)."-".$mPickQuery;
                if (mysqli_num_rows($mPickData) > 0)
                {
                    list($mPickDtlQty) = mysqli_fetch_row($mPickData);
                }
                $mPickQty = $mPickQty-$mPickDtlQty;
                if ($mPickQty > 0)
                {
                    $mReturn = allocatePickLine($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mPickDocumentReference,$mCustomerReferenceCode,$mPickHdrId,$mPickBdyId,$mPickQty,$mPartId,$mTaskType);
                }
                if (substr($mReturn,0,21) == 'FAIL-EOD-No Inventory')
                {
                    If ($mNoInvList != "")
                        $mNoInvList .="_";
                    else
                        if (!empty($mPartNumber))
                            $mNoInvList .=" For ";
                    $mNoInvList .= $mPartNumber;
                    continue;
                }
                if (substr($mReturn,0,2) == 'FA')
                {
                    break;
                }
            }
        }
    }
//        exit("FAIL-TEST1-".$mPickDocumentReference." ".$mReturn);
    $mReturn = getPickLine($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mPickDocumentReference,$mCustomerReferenceCode,$mToPlt,$mToLoc,$mTaskType,$mPickHdrId);
    if ($mReturn == "FAIL-EOD-No Inventory")
    {
//        $mReturn = allocatePickLine($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mPickDocumentReference,$mCustomerReferenceCode,$mOrderHdrId,$mPickHdrId,$mPickOrdLine,$mPickDtlLine,$mPickBdyId,$mPickQty,$mAisle,$mPartId,$mOrderType,$mPickType,$mJisSerial,$mToPlt);
        $mReturn = getPickLine($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mPickDocumentReference,$mCustomerReferenceCode,$mToPlt,$mToLoc,$mTaskType);
        if ($mReturn == "FAIL-EOD-No Inventory")
        {   
            $mReturn .= " ".$mNoInvList;
        }
    }
    if ($mReturn == "")
    {
        $mReturn = "FAIL-This Order cannot be picked - Scanner Error";
    }
    return $mReturn;
}

function getPickLine($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mPickDocumentReference,$mCustomerReferenceCode,$mToPlt,$mToLoc,$mTaskType=1,$mPickHdrId=null)
{
    $mAllocFlag = false;
    $mInUse = "";
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
    if (!$mConnection)
        return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
    
    $mFullBoxPick = 1;
    $mPickByLine = "";
    $i = 0;

// Get Next task_detail
    $i = 0;
    While ($i == 0)
    {
        $mDataQuery = "SELECT id,part_id,inspection_task_body_id,location_code,serial_reference,qty_allocated,inventory_master_id,line_no,pick_priority,in_use_by,last_updated_date, DATE_SUB(NOW(), INTERVAL 2 MINUTE) as cut_off,created_by FROM inspection_task_detail WHERE document_reference='$mPickDocumentReference' AND processed=0 AND (inspection_task_detail.in_use_by IS null OR inspection_task_detail.in_use_by='' OR inspection_task_detail.in_use_by='".$mCurrentUser."' OR (inspection_task_detail.last_updated_date < DATE_SUB(NOW(), INTERVAL 5 MINUTE))) ORDER BY document_reference,pick_priority,line_no LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit( "FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        if (mysqli_num_rows($mData) > 0)
        {
            list($mPickDtlId,$mPartId,$mPickBdyId,$mLocationCode,$mSerialReference,$mPickQty,$mInvId,$mPickOrdLine,$mPickDtlLine,$mInUseBy,$mInUseTime,$mCutOff,$mCreatedBy) = mysqli_fetch_row($mData);
// Check that Pick is still valid
            if (!empty($mInvId))
            {
                $mInvQuery = "SELECT inventory_master.id AS id, inventory_qty AS inventory_qty FROM inventory_master";
                $mInvQuery .=" JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id";
                $mInvQuery .=" WHERE";
                $mInvQuery .=" inventory_master.part_id=".$mPartId." AND inventory_master.serial_reference='".$mSerialReference."'";
                $mInvQuery .=" AND inventory_master.location_code='$mLocationCode' AND inventory_master.inventory_qty>0 AND lower(inventory_status_code) IN('ok','lost','qtine')";
                $mInvQuery .=" LIMIT 1";
                if (!$mInvData = mysqli_query($mConnection,$mInvQuery))
                    return "FAIL-".mysqli_error($mConnection)."-".$mInvQuery;
                list ($mInvId, $mInvQty) = mysqli_fetch_row($mInvData);
            }
            if ((mysqli_num_rows($mInvData)==0) || empty($mInvId) || ($mPickQty <= 0) || ($mInvQty<$mPickQty) || ($mOrderType=='913' && $mCreatedBy=='sys'))
            {
                $mInvQuery = "UPDATE inspection_task_detail SET processed=1,in_use_by='' WHERE id=".$mPickDtlId." LIMIT 1";
                if (!mysqli_query($mConnection,$mInvQuery))
                    return "FAIL-".mysqli_error($mConnection)."-".$mInvQuery;
                $mReturn = allocatePickLine($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mPickDocumentReference,$mCustomerReferenceCode,$mPickHdrId,$mPickBdyId,$mPickQty,$mPartId,$mTaskType);
                $i = 0;
                continue;
            }

// Get related data
            $mPickQuery = "SELECT part.id,part.part_number,part.conversion_factor AS conversion_factor FROM part WHERE part.id=".$mPartId." LIMIT 1";
            if (!$mPickData = mysqli_query($mConnection,$mPickQuery))
                exit("FAIL-".mysqli_error($mConnection)."-".$mPickQuery);
            
            $mPartNumber = "";
            $mConversionFactor = 1;
            $mRdtPrompt = "";
            
            list($mPartId,$mPartNumber,$mConversionFactor,$mRdtPrompt) = mysqli_fetch_row($mPickData);
            $mPickQty = $mPickQty / $mConversionFactor;

            $mRdtPrompt = str_replace("!","",$mRdtPrompt);
            if (substr($mRdtPrompt,0,1) == '*')
            {
                if ($mToPlt == "")
                    $mReturn = "OKMS-".$mRdtPrompt.",DATA:customerReference:".$mCustomerReferenceCode.",fromLocationHashCodecontent:".$mLocationCode.",serialReferencecontent:".$mSerialReference.",partNumbervalue:".$mPartNumber.",qtyAllocatedvalue:".$mPickQty.",allocationId:".$mPickDtlId.",sequencingRequestId:".$mPickInvId.",lineNo:".$mPickOrdLine.",rdttime:start,rdtMessage:".$mRdtPrompt."::skiptoPlt";
                else
                    $mReturn = "OKMS-".$mRdtPrompt.",DATA:customerReference:".$mCustomerReferenceCode.",fromLocationHashCodecontent:".$mLocationCode.",serialReferencecontent:".$mSerialReference.",partNumbervalue:".$mPartNumber.",qtyAllocatedvalue:".$mPickQty.",allocationId:".$mPickDtlId.",sequencingRequestId:".$mPickInvId.",lineNo:".$mPickOrdLine.",rdttime:start,rdtMessage:".$mRdtPrompt."::skipfromLocationHashCode";
            }
            else
            {
                if ($mToPlt == "")
                    $mReturn = "DATA:customerReference:".$mCustomerReferenceCode.",fromLocationHashCodecontent:".$mLocationCode.",serialReferencecontent:".$mSerialReference.",partNumbervalue:".$mPartNumber.",qtyAllocatedvalue:".$mPickQty.",allocationId:".$mPickDtlId.",sequencingRequestId:".$mPickInvId.",lineNo:".$mPickOrdLine.",toLocationHashCodecontent:".$mToLoc.",rdttime:start,rdtMessage:".$mRdtPrompt."::skipfromLocationHashCode";
                else
                    $mReturn = "DATA:customerReference:".$mCustomerReferenceCode.",fromLocationHashCodecontent:".$mLocationCode.",serialReferencecontent:".$mSerialReference.",partNumbervalue:".$mPartNumber.",qtyAllocatedvalue:".$mPickQty.",allocationId:".$mPickDtlId.",sequencingRequestId:".$mPickInvId.",lineNo:".$mPickOrdLine.",toLocationHashCode:content".$mToLoc.",rdttime:start,rdtMessage:".$mRdtPrompt."::skipfromLocationHashCode";
            }
            $mUpdDataQuery = "UPDATE inspection_task_detail SET in_use_by='$mCurrentUser',last_updated_date=now() WHERE id = ".$mPickDtlId." LIMIT 1";
            if (!mysqli_query($mConnection,$mUpdDataQuery))
                return "FAIL-".mysqli_error($mConnection)."-".$mUpdDataQuery;
            $i = 1;
            break;
        }
        else
        {
            $mReturn = "FAIL-EOD-No Inventory";
            break;
        }
        if ($mReturn == "")
        {
            $mReturn = "FAIL-EOD-No Inventory";
            break;
        }
    }
//    exit("FAIL-TEST1-".$mReturn);
    return $mReturn;
}

function allocatePickLine($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mPickDocumentReference,$mCustomerReferenceCode,$mPickHdrId,$mPickBdyId,$mBdyQty,$mPartId,$mTaskType=1,$mBdyLineNo=1,$mToPlt="")
{
//    $mBlocked = 0;
    $mAllocFlag = false;
    $mInUse = "";
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
    if (!$mConnection)
        return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
    
// Get related data
    $mDataQuery = "SELECT part.id,part.part_number,part.conversion_factor AS conversion_factor,part.rdt_prompt FROM part WHERE part.id=".$mPartId." LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    
    $mPartNumber = "";
    $mConversionFactor = 1;
    $mRdtPrompt = "";
    
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mPartId = ($mRow['id']);
        $mPartNumber = ($mRow['part_number']);
        $mConversionFactor = ($mRow['conversion_factor']);
        $mRdtPrompt = $mRow['rdt_prompt'];
    }
    $mFullBoxPick = 0;
    $i = 0;
    
// Allocate Inventory to Pick line

// Standard Allocation
    $mInvQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_qty AS inventory_qty, inventory_master.allocated_qty AS allocated_qty, part.part_number AS part_number, inventory_master.serial_reference AS serial_reference, inventory_master.ran_or_order AS ran_order, location.location_code AS location_code";
    $mInvQuery .=",inventory_master.last_updated,DATE_SUB(NOW(), INTERVAL 10 MINUTE) as cut_off";
    $mInvQuery .=" FROM inventory_master";
    $mInvQuery .=" LEFT JOIN location ON inventory_master.current_location_id=location.id";
    $mInvQuery .=" LEFT JOIN part ON inventory_master.part_id=part.id";
    $mInvQuery .=" LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id";
    $mInvQuery .=" LEFT JOIN location_type ON location.location_type_id=location_type.id";
    $mInvQuery .=" WHERE inventory_master.part_id=".$mPartId." AND inventory_master.serial_reference IS NOT null AND inventory_master.inventory_qty >0";
    $mInvQuery .=" AND (inventory_master.inventory_qty>inventory_master.allocated_qty OR inventory_master.last_updated < (DATE_SUB(NOW(), INTERVAL 10 MINUTE)))";
//    $mInvQuery .=" AND inventory_master.requires_inspection=1";
	$mInvQuery .=" AND inventory_master.requires_inspection=1 AND lower(location_type.location_area)='storage'";
    $mInvQuery .=" AND (inventory_master.inventory_status_id IS null OR lower(inventory_status.inventory_status_code) IN('ok','qtine'))";
    $mInvQuery .=" AND NOT EXISTS(SELECT id FROM inspection_task_detail WHERE inspection_task_detail.inventory_master_id=inventory_master.id AND inspection_task_detail.processed=0)";
    $mInvQuery .=" ORDER BY inventory_master.date_created, inventory_master.location_code";
    if ($mTaskType != 2)
    {
        $mInvQuery .=" LIMIT 50";
    }
    if (!$mInvData = mysqli_query($mConnection,$mInvQuery))
        exit ("FAIL-1".mysqli_error($mConnection)."-".$mInvQuery);
    if (mysqli_num_rows($mInvData) > 0)
        $mAlcType .= "";

    if (mysqli_num_rows($mInvData) == 0)
    {
        $mInvQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_qty AS inventory_qty, inventory_master.allocated_qty AS allocated_qty, part.part_number AS part_number, inventory_master.serial_reference AS serial_reference, inventory_master.ran_or_order AS ran_order, location.location_code AS location_code";
        $mInvQuery .=",inventory_master.last_updated,DATE_SUB(NOW(), INTERVAL 10 MINUTE) as cut_off";
        $mInvQuery .=" FROM inventory_master";
        $mInvQuery .=" JOIN location ON inventory_master.current_location_id=location.id";
        $mInvQuery .=" JOIN part ON inventory_master.part_id=part.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id";
        $mInvQuery .=" LEFT JOIN location_type ON location.location_type_id=location_type.id";
        $mInvQuery .=" WHERE inventory_master.part_id=".$mPartId." AND inventory_master.serial_reference IS NOT null AND inventory_master.inventory_qty >0";
        $mInvQuery .=" AND (inventory_master.inventory_qty>inventory_master.allocated_qty OR inventory_master.last_updated < (DATE_SUB(NOW(), INTERVAL 10 MINUTE)))";
//        $mInvQuery .=" AND inventory_master.requires_inspection=1";
        $mInvQuery .=" AND lower(location_type.location_area)='storage'";
        $mInvQuery .=" AND (inventory_master.inventory_status_id IS null OR lower(inventory_status.inventory_status_code) IN('ok','qtine'))";
        $mInvQuery .=" AND NOT EXISTS(SELECT id FROM inspection_task_detail WHERE inspection_task_detail.inventory_master_id=inventory_master.id AND inspection_task_detail.processed=0)";
        $mInvQuery .=" ORDER BY inventory_master.date_created, inventory_master.location_code";
        if ($mTaskType != 2)
        {
            $mInvQuery .=" LIMIT 50";
        }
        if (!$mInvData = mysqli_query($mConnection,$mInvQuery))
            exit ("FAIL-2".mysqli_error($mConnection)."-".$mInvQuery);
        if (mysqli_num_rows($mInvData) > 0)
            $mAlcType .= "";
    }
    $mAlcInvId = "";
    $mInvQty = 0;
    $mInvAllocatedQty = 0;
    $mInvSerialReference = "";
    $mInvRanOrder = "";
    $mInvLocationCode = "";
    $mInvPickPriority = 999;
    $mFullBoxPick = 1;
//    exit("FAIL-TEST1-".$mInvQuery." ".mysqli_num_rows($mInvData)." ".mysqli_error($mConnection));
    while($mInvRow = mysqli_fetch_assoc($mInvData)) 
    {
//        exit("FAIL-TEST1-".$mInvRow['last_updated']." ".$mInvRow['cut_off']." ".$mInvQuery);
        $mAlcInvId = ($mInvRow['id']);
        $mInvQty = ($mInvRow['inventory_qty']);
        $mInvAllocatedQty = ($mInvRow['allocated_qty']);
        $mBdyPartNumber = ($mInvRow['part_number']);
        $mInvSerialReference = ($mInvRow['serial_reference']);
        $mInvRanOrder = ($mInvRow['ran_order']);
        $mInvLocationCode = ($mInvRow['location_code']);
 
        $mPickAllocatedQty = 0;
        $mPickAllocatedQty = $mInvAllocatedQty;

        if ($mPickAllocatedQty > $mInvQty)
            $mPickAllocatedQty = $mInvQty;

// Existing Order expected Qty.
        $mOrdAllocatedQty = $mBdyQty;
// Calculate Pick / Required Qty.
// Full Box Pick - take all Serial Inventory
        if ($mFullBoxPick == 1)
        {
            $mReqQty = $mInvQty;
            $mBdyQty = $mBdyQty - $mInvQty;
        }
// Order Qty > Serial Inventory - Take all Serial Inventory
        elseif ($mBdyQty >= $mInvQty)
        {
            $mReqQty = $mInvQty;
            $mBdyQty = $mBdyQty - $mInvQty;
        }
// Take Order Requirement Qty.
        else
        {
            $mReqQty = $mBdyQty;
            $mBdyQty = 0;
        }
    
// Create Pick Detail
        if ($mInvPickPriority < 1)
            $mInvPickPriority = 1;
        if ($mPriority <1)
            $mPriority = 1;
        if ($mBdyLineNo < 1)
            $mBdyLineNo = 1;
        if ($mBlocked == "" || $mBlocked == null)
            $mBlocked = 0;
        $mPickQuery = "INSERT INTO inspection_task_detail (id,inventory_master_id,inspection_task_body_id,part_id,part_number,serial_reference,document_reference,location_code,qty_allocated,line_no,pick_priority,processed,qty_scanned,date_created,created_by,last_updated_date,last_updated_by)";
        if ($mBlocked == 0)
            $mPickQuery .= " VALUES(DEFAULT,".$mAlcInvId.",".$mPickBdyId.",".$mPartId.",'".$mPartNumber."','".$mInvSerialReference."','".$mPickDocumentReference."','".$mInvLocationCode."',".$mReqQty.",".$mBdyLineNo.",".$mPriority.",0,0,now(),'".$mCurrentUser."_RDT',now(),'".$mCurrentUser."_".$mAlcType."')";
        else
            $mPickQuery .= " VALUES(DEFAULT,null,".$mPickBdyId.",".$mPartId.",'".$mPartNumber."','BLOCKED','".$mPickDocumentReference."','',".$mReqQty.",".$mBdyLineNo.",".$mPriority.",0,0,now(),'".$mCurrentUser."_RDT',now(),'".$mCurrentUser."_".$mAlcType."')";
        if (!mysqli_query($mConnection,$mPickQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mPickQuery;
        $mPickDtlId=mysqli_insert_id($mConnection);
        
        if ($mTaskType != 2 && $mBdyQty <=0)
        {
            $mReturn = "OK  -Allocated";
            break;
        }
    }
    if ($mAlcInvId == "")
    {
        $mReturn = "FAIL-EOD-No Inventory for ".$mPartNumber;
    }    
    mysqli_close($mConnection);
    if ($mReturn == "")
        $mReturn = "OK  -Allocated";
//    exit("FAIL-TEST1-".$mReturn);
    return $mReturn;
}

function updatePickDetail($mHost,$mUser,$mPwd,$mDbName,$mPickDtlId,$mPickInvId,$mSerialReference,$mPartNumber,$mPickQty,$mCurrentUser,$mTransactionTypeId,$mToPlt,$mToLocHash,$mConnect="",$mRdtStart="",$mRdtEnd="")
{
    if (($mPickDtlId == "") || ($mPickDtlId == null))
        return "FAIL-incorrect Pick Reference";
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
    if (!$mConnection)
        return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
// Validate Scanned Serial
    $mInvQuery = "SELECT id FROM inventory_master WHERE serial_reference='$mSerialReference' AND part_number='$mPartNumber' LIMIT 1";
    if (!$mInvData = mysqli_query($mConnection,$mInvQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mInvQuery;
    if (mysqli_num_rows($mInvData)==0)
    {
        exit("FAIL-Invalid Serial Scanned");
    }
    $mDataQuery = "SELECT in_use_by,last_updated_date, DATE_SUB(NOW(), INTERVAL 5 MINUTE) as cut_off FROM inspection_task_detail WHERE id=".$mPickDtlId." LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    if (mysqli_num_rows($mData) > 0)
    {
        list($mInUseBy,$mInUseTime,$mCutOff) = mysqli_fetch_row($mData);
        
        if ($mInUseBy == null || $mInUseBy == '' || $mInUseBy == $mCurrentUser || $mInUseTime < $mCutOff)
        {
            $mInUseBy = "";
        }
        else
        {
            return "FAIL-This Pick is in use by - ".$mInUseBy;
        }
    }

// Check for Inspect serial
	$mResult = updateInsSerial($mHost,$mUser,$mPwd,$mDbName,$mPickDtlId,$mPickInvId,$mSerialReference,$mPartNumber,$mPickQty);
    
// Get id for document status
    $mDocStsId = 0;
    $mDocPkdId = 0;
    $mDocAlcId = 0;
    $mDocLckId = 0;
    $mDataQuery = "SELECT id AS id, document_status_code AS document_status_code FROM document_status";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;
    $mData = (mysqli_query($mConnection,$mDataQuery));
    while($mRow = mysqli_fetch_assoc($mData))
    {
        if (strtolower($mRow['document_status_code']) == "open")
            $mDocStsId=($mRow['id']);
        if (strtolower($mRow['document_status_code']) == "allocated")
            $mDocAlcId=($mRow['id']);
        if (strtolower($mRow['document_status_code']) == "picked")
            $mDocPkdId=($mRow['id']);
        if (strtolower($mRow['document_status_code']) == "locked")
            $mDocLckId=($mRow['id']);
    }
    if ($mDocPkdId == "")
    {
        $mDocPkdId = null;
    }
    
// Get id for inventory status
    $mInvStsId = 0;
    $mInvRcvId = 0;
    $mInvPckId = 0;
    $mInvPltId = 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']);
    }
    if ($mInvPkdId == null && $mInvPltId != null)
        $mInvPkdId = $mInvPltId;
    if ($mInvQaId == null && $mInvStsId != null)
        $mInvQaId = $mInvStsId;

    
//  $mTagId = null;
// Get Tag Id if Required
    if ($mToPlt != "")
    {
        $mDataQuery = "SELECT id FROM tag WHERE tag_reference='".$mToPlt."' LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        while($mRow = mysqli_fetch_assoc($mData))
        {
            $mTagId = ($mRow['id']);
        }
    }
// Get default Pick Location Id
    $mPickLocId = null;
    $mDataQuery = "SELECT id,location_code FROM location WHERE location_code='INSP00' LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    while($mRow = mysqli_fetch_assoc($mData))
    {
        $mToLocId = ($mRow['id']);
        $mToLocCode = "INSP00";
    }
// Get Location Id if Required
    if ($mToLocHash != "")
    {
        $mToLocId = null;
        $mDataQuery = "SELECT id,location_code FROM location WHERE location_hash='".$mToLocHash."' OR location_code='".$mToLocHash."'LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        while($mRow = mysqli_fetch_assoc($mData))
        {
            $mToLocId = ($mRow['id']);
            $mToLocCode = ($mRow['location_code']);
        }
    }
// Store Inventory_master id from inspection_task_detail
    $mPrvInvId = "";
    $mPickBdyId = "";
    $mPickHdrId = "";
    $mPickDtlQty = 0;
    $mConversionFactor = 1;
    $mDocDtlId = "";
    $mPickSerialRef = "";
    $mCustomerReference = "";
    $mProcessed = 0;
    $mDataQuery = "SELECT inspection_task_detail.inventory_master_id AS inventory_master_id, inspection_task_detail.inspection_task_body_id AS pick_body_id, inspection_task_detail.qty_allocated AS qty_allocated, inspection_task_detail.line_no AS line_no, inspection_task_detail.pick_priority AS pick_priority, inspection_task_detail.processed AS processed, inspection_task_body.inspection_task_header_id AS pick_header_id, part.part_number AS part_number, part.conversion_factor AS conversion_factor, CASE WHEN inspection_task_detail.serial_reference_scanned <> '' THEN inspection_task_detail.serial_reference_scanned ELSE inspection_task_detail.serial_reference END AS serial_reference, inspection_task_header.customer_reference AS customer_reference,inspection_task_header.document_status_id AS document_status_id FROM inspection_task_detail LEFT JOIN inspection_task_body ON inspection_task_detail.inspection_task_body_id=inspection_task_body.id LEFT JOIN inspection_task_header ON inspection_task_body.inspection_task_header_id=inspection_task_header.id LEFT JOIN part ON inspection_task_detail.part_id=part.id WHERE inspection_task_detail.id=".$mPickDtlId." LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    while($mRow = mysqli_fetch_assoc($mData))
    {
        $mPrvInvId = ($mRow['inventory_master_id']);
        $mPickBdyId = ($mRow['pick_body_id']);
        $mPickHdrId = ($mRow['pick_header_id']);
        $mPickDtlQty = ($mRow['qty_allocated']);
        $mPickDtlAlcQty = ($mRow['qty_allocated']);
        $mConversionFactor = ($mRow['conversion_factor']);
        $mPartNumber = ($mRow['part_number']);
        $mDocDtlId = ($mRow['line_no']);
        $mPickSerialRef = ($mRow['serial_reference']);
        $mPickPriority = ($mRow['pick_priority']);
        $mCustomerReference = ($mRow['customer_reference']);
        $mProcessed = ($mRow['processed']);
        $mPickHdrSts = ($mRow['document_status_id']);
    }

    if ($mProcessed==1)
    {
        return("OKMS-This Pick Task is already done.");
    }
// Zero Qty Not allowed
    if ((empty($mPickQty)) || ($mPickQty <= 0))
    {
        return("FAIL-Incorrect quantity-".$mPickQty);
    }

// Use Scanned Qty if Entered
    if (!empty($mPickQty))
        $mPickDtlQty = $mPickQty*$mConversionFactor;
    else
        $mPickQty = $mPickDtlQty;
    
    if (empty($mSerialReference))
        $mSerialReference = $mPickSerialRef;
    
// Check if Full Serial has been picked
    $mDataQuery = "SELECT inventory_master.id AS id,inventory_master.part_id AS part_id,part.part_number AS part_number,inventory_master.ran_or_order AS ran_order,inventory_master.current_location_id AS location_id,inventory_master.requires_inspection AS requires_inspection,location.location_code AS location_code,inventory_master.product_type_id AS product_type_id ,inventory_master.tag_reference AS plt_number,inventory_master.inventory_qty AS inventory_qty";
    $mDataQuery .=" FROM inventory_master";
    $mDataQuery .=" JOIN part ON inventory_master.part_id=part.id";
    $mDataQuery .=" JOIN location ON inventory_master.current_location_id=location.id";
    $mDataQuery .=" WHERE inventory_master.part_number='$mPartNumber' AND inventory_master.serial_reference='$mSerialReference'";
    $mDataQuery .=" LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    $mInvQty = 0;
    $mFromLocCode = "";
    $mRanOrder = "";
    $mInvRow = array();
	$mInspect = 0;
    while($mRow = mysqli_fetch_assoc($mData))
    {
        $mPickInvId = $mRow['id'];
        $mInvQty = ($mRow['inventory_qty']);
        $mFromLocCode = ($mRow['location_code']);
        $mRanOrder = ($mRow['ran_order']);
        $mInvRow = ($mRow);
		$mInspect = $mRow['requires_inspection'];
    }
// force full-Pick
    $mPickDtlQty = $mInvQty;
    if ($mInvQty <= $mPickDtlQty)
    {
// Change Inventory Master Status - Full Serial Pick
        $mDataQuery = "UPDATE inventory_master SET allocated_qty=0,available_qty=inventory_qty,requires_inspection=1";
//		$mDataQuery .=",inventory_status_id=".$mInvQaId;
        if ($mToPlt != "")
            $mDataQuery .= ",inventory_master.tag_reference='".$mToPlt."'";
        if (($mTagId != null) && ($mTagId != ""))
            $mDataQuery .= ",inventory_master.parent_tag_id=".$mTagId;
        if ($mToLocCode != "")
            $mDataQuery .= ",inventory_master.current_location_id=".$mToLocId.",inventory_master.location_id=".$mToLocId.",inventory_master.location_code='".$mToLocCode."'";
        elseif ($mPickLocId != null)
            $mDataQuery .= ",inventory_master.current_location_id=".$mPickLocId.",inventory_master.location_id=".$mPickLocId.",inventory_master.location_code='PICK01'";
        if (($mRanOrder == "") || ($mRanOrder == "NO-RAN"))
            $mDataQuery .= ", ran_or_order = '".$mCustomerReference."'";
        $mDataQuery .= ",last_updated=now(),last_updated_by='".$mCurrentUser."_FULL' WHERE inventory_master.id=".$mPickInvId." LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;

// Update unselected Inventory_master
        if ($mPrvInvId != $mPickInvId)
        {
            $mDataQuery = "UPDATE inventory_master SET requires_inspection=".$mInspect;
//			$mDataQuery .=",inventory_status_id=".$mInvStsId;
			$mDataQuery .=" WHERE id=".$mPrvInvId." LIMIT 1";
            if (!mysqli_query($mConnection,$mDataQuery))
                return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        }
        
// Set Pick Detail to Processed 
        $mDataQuery = "UPDATE inspection_task_detail SET processed=1,in_use_by=''";
        if ($mPickInvId != "")
            $mDataQuery .= ",inventory_master_id=".$mPickInvId;
        if ($mSerialReference != "")
            $mDataQuery .= ",serial_reference_scanned='".$mSerialReference."'";
        if ($mPickQty != "")
            $mDataQuery .= ",qty_scanned=".$mPickDtlQty.",qty_allocated=0";
        $mDataQuery .= ",last_updated_date=now(),last_updated_by='".$mCurrentUser."' WHERE id=".$mPickDtlId." LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        
    // verify that the update has been performed
        $mDataQuery = "SELECT id FROM inspection_task_detail WHERE id=".$mPickDtlId." AND processed=0 LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        if (mysqli_num_rows($mData) > 0)
        {
            return "FAIL-Update Error - please scan again";
        }
    }
    else
// Partial Pick Reduce Existing Inventory - Create New Pick Inventory
    {
        $mDataQuery = "UPDATE inventory_master SET inventory_qty = inventory_qty - ".$mPickDtlQty.",allocated_qty=CASE WHEN allocated_qty>inventory_qty THEN 0 WHEN allocated_qty>=".$mPickDtlQty." THEN allocated_qty-".$mPickDtlQty." ELSE 0 END, available_qty = inventory_qty-allocated_qty, inventory_status_id=".$mInvStsId.",last_updated=now(),last_updated_by='".$mCurrentUser."_PCK',requires_inspection=1 WHERE inventory_master.id=".$mPickInvId." LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        
        if (($mRanOrder == "") || ($mRanOrder == "NO-RAN"))
            $mRanOrder = $mCustomerReference;
        
        if ($mPickLocId == null)
            $mPickLocId = ($mInvRow['location_id']);
        if ($mToLocCode == "")
            if (($mTagId == "") || ($mTagId == null))
                $mDataQuery = "INSERT INTO inventory_master (id,allocated_qty,current_inventory_status_id,current_location_id,date_created,expiry_date,inventory_qty,last_updated,last_updated_by,parent_tag_id,part_id,ran_or_order,recorded_missing,requires_decant,requires_inspection,serial_reference,originating_detail_id,conversion_factor,stock_date,active,part_number,version,pruf_cube,available_qty,created_by,location_code,tag_reference,product_type_id,location_id,inventory_status_id) VALUES(DEFAULT,0,null,".$mPickLocId.",now(),null,".$mPickDtlQty.",now(),'".$mCurrentUser."',null,".$mInvRow['part_id'].",'".$mRanOrder."',0,0,0,null,null,".$mConversionFactor.",now(),1,'".$mInvRow['part_number']."',0,0,".$mPickDtlQty.",'".$mCurrentUser."','PICK01','".$mToPlt."',null,".$mPickLocId.",".$mInvQaId.")";
            else
                $mDataQuery = "INSERT INTO inventory_master (id,allocated_qty,current_inventory_status_id,current_location_id,date_created,expiry_date,inventory_qty,last_updated,last_updated_by,parent_tag_id,part_id,ran_or_order,recorded_missing,requires_decant,requires_inspection,serial_reference,originating_detail_id,conversion_factor,stock_date,active,part_number,version,pruf_cube,available_qty,created_by,location_code,tag_reference,product_type_id,location_id,inventory_status_id) VALUES(DEFAULT,0,null,".$mPickLocId.",now(),null,".$mPickDtlQty.",now(),'".$mCurrentUser."',".$mTagId.",".$mInvRow['part_id'].",'".$mRanOrder."',0,0,0,null,null,".$mConversionFactor.",now(),1,'".$mInvRow['part_number']."',0,0,".$mPickDtlQty.",'".$mCurrentUser."','PICK01','".$mToPlt."',null,".$mPickLocId.",".$mInvQaId.")";
        else
            if (($mTagId == "") || ($mTagId == null))
                $mDataQuery = "INSERT INTO inventory_master (id,allocated_qty,current_inventory_status_id,current_location_id,date_created,expiry_date,inventory_qty,last_updated,last_updated_by,parent_tag_id,part_id,ran_or_order,recorded_missing,requires_decant,requires_inspection,serial_reference,originating_detail_id,conversion_factor,stock_date,active,part_number,version,pruf_cube,available_qty,created_by,location_code,tag_reference,product_type_id,location_id,inventory_status_id) VALUES(DEFAULT,0,null,".$mToLocId.",now(),null,".$mPickDtlQty.",now(),'".$mCurrentUser."',null,".$mInvRow['part_id'].",'".$mRanOrder."',0,0,0,null,null,".$mConversionFactor.",now(),1,'".$mInvRow['part_number']."',0,0,".$mPickDtlQty.",'".$mCurrentUser."','".$mToLocCode."','".$mToPlt."',null,".$mToLocId.",".$mInvQaId.")";
            else
                $mDataQuery = "INSERT INTO inventory_master (id,allocated_qty,current_inventory_status_id,current_location_id,date_created,expiry_date,inventory_qty,last_updated,last_updated_by,parent_tag_id,part_id,ran_or_order,recorded_missing,requires_decant,requires_inspection,serial_reference,originating_detail_id,conversion_factor,stock_date,active,part_number,version,pruf_cube,available_qty,created_by,location_code,tag_reference,product_type_id,location_id,inventory_status_id) VALUES(DEFAULT,0,null,".$mToLocId.",now(),null,".$mPickDtlQty.",now(),'".$mCurrentUser."',".$mTagId.",".$mInvRow['part_id'].",'".$mRanOrder."',0,0,0,null,null,".$mConversionFactor.",now(),1,'".$mInvRow['part_number']."',0,0,".$mPickDtlQty.",'".$mCurrentUser."','".$mToLocCode."','".$mToPlt."',null,".$mToLocId.",".$mInvQaId.")";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        $mPickInvId=mysqli_insert_id($mConnection);
// Set Pick Detail to Processed 
        $mDataQuery = "UPDATE inspection_task_detail SET processed=1,in_use_by=''";
        if ($mPickInvId != "")
            $mDataQuery .= ",inventory_master_id=".$mPickInvId;
        if ($mSerialReference != "")
            $mDataQuery .= ",serial_reference_scanned='".$mSerialReference."'";
        if ($mPickQty != "")
            $mDataQuery .= ",qty_scanned=".$mPickDtlQty.",qty_allocated=0";
        $mDataQuery .= ",last_updated_date=now(),last_updated_by='".$mCurrentUser."' WHERE id=".$mPickDtlId." LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        
    // verify that the update has been performed
        $mDataQuery = "SELECT id FROM inspection_task_detail WHERE id=".$mPickDtlId." AND processed=0 LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        if (mysqli_num_rows($mData) > 0)
        {
            return "FAIL-Update Error - please scan again";
        }
    }

    $mDataQuery = "UPDATE inspection_task_body SET";
    $mDataQuery .= " qty_transacted=(SELECT SUM(inspection_task_detail.qty_scanned) FROM inspection_task_detail WHERE inspection_task_detail.inspection_task_body_id=".$mPickBdyId." AND inspection_task_detail.inspection_task_body_id=inspection_task_body.id)"; 
    $mDataQuery .= ", difference=qty_transacted-qty_expected";
	$mDataQuery .= ",last_updated=now(),last_updated_by='".$mCurrentUser."'";
    $mDataQuery .= " WHERE inspection_task_body.id=".$mPickBdyId." LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;

// If Pick Body is Complete Check for outstanding Pick Details
    $mDataQuery = "SELECT inspection_task_detail.id AS id, inspection_task_detail.inventory_master_id AS inventory_master_id, inspection_task_detail.qty_allocated AS qty_allocated FROM inspection_task_body JOIN inspection_task_detail ON inspection_task_detail.inspection_task_body_id=inspection_task_body.id WHERE inspection_task_body.id=".$mPickBdyId." AND inspection_task_body.qty_expected<=inspection_task_body.qty_transacted AND inspection_task_detail.processed=0";
    $mData = mysqli_query($mConnection,$mDataQuery);
    $mAlcQty = 0;
    while($mRow = mysqli_fetch_assoc($mData))
    {
        $mPickQuery = "UPDATE inspection_task_detail SET qty_allocated=0,processed=1 WHERE id=".$mRow['id']." LIMIT 1";
        if (!mysqli_query($mConnection,$mPickQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mPickQuery;
		$mPickQuery = "UPDATE inventory_master SET requires_inspection=0 WHERE id=".$mRow['inventory_master_id']." LIMIT 1";
        if (!mysqli_query($mConnection,$mPickQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mPickQuery;
    }
    
//    $mDataQuery = "SELECT inspection_task_body.id AS id FROM inspection_task_body JOIN inspection_task_detail ON inspection_task_body.id=inspection_task_detail.inspection_task_body_id WHERE inspection_task_header_id=".$mPickHdrId." AND inspection_task_detail.processed=0 LIMIT 1";
    $mDataQuery = "SELECT inspection_task_body.id AS id FROM inspection_task_body WHERE inspection_task_header_id=".$mPickHdrId." AND inspection_task_body.qty_expected>inspection_task_body.qty_transacted LIMIT 1";
    $mData = mysqli_query($mConnection,$mDataQuery);
    if (mysqli_num_rows($mData) ==0)
    {
        $mDataQuery = "UPDATE inspection_task_header SET document_status_id=".$mDocPkdId.",last_updated_date=now(),last_updated_by='$mCurrentUser' WHERE id=".$mPickHdrId." LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    }    
    $mReturn = updatePickHistory($mHost,$mUser,$mPwd,$mDbName,$mPickDtlId,$mPickInvId,$mPickDtlQty,$mCurrentUser,$mTransactionTypeId,$mFromLocCode,$mOrderType,$mDocDtlId."-".$mPickPriority);

// Set Location Filling Status
    flagEmptyLoc($mFromLocCode,$mCurrentUser,$mHost,$mUser,$mPwd,$mDbName);
    
    if ($mReturn != "")
        return $mReturn;
    
    return "OK  -";
}


// Update Transaction History
function updatePickHistory($mHost,$mUser,$mPwd,$mDbName,$mPickDtlId,$mPickInvId,$mPickDtlQty,$mCurrentUser,$mTransactionTypeId,$mFromLocCode="",$mOrderType="",$mPickPriority="")
{
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
    if (!$mConnection)
        return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
// Order Type
    $mOrderDesc = $mOrderType;
    if ($mOrderType != "")
    {
        $mDataQuery = "SELECT description AS order_desc FROM order_type WHERE order_type_code='".$mOrderType."' LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        $mData = mysqli_query($mConnection,$mDataQuery);
        while($mRow = mysqli_fetch_assoc($mData))
        {
            $mOrderDesc = $mRow['order_desc'];
        }
    }

// Pick Detail
    $mDataQuery = "SELECT inspection_task_detail.part_number, inspection_task_detail.qty_allocated,CASE WHEN inspection_task_detail.serial_reference_scanned IS null THEN inspection_task_detail.serial_reference ELSE inspection_task_detail.serial_reference_scanned END AS serial_reference,inspection_task_body.customer_reference,inspection_task_body.document_reference,inspection_task_body.inspection_task_header_id AS pick_header_id FROM inspection_task_detail JOIN inspection_task_body ON inspection_task_detail.inspection_task_body_id=inspection_task_body.id WHERE inspection_task_detail.id=".$mPickDtlId." LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    $mDtlRow = array();
    if (mysqli_num_rows($mData) > 0)
    {
        while($mRow = mysqli_fetch_assoc($mData))
        {
            $mDtlRow = $mRow;
        }
    
        $mPickHdrId = $mDtlRow['pick_header_id'];
        $mComment = "";
    }
    $mSerialRef = $mDtlRow['serial_reference'];
    $mPartNumber = $mDtlRow['part_number'];
// Inventory Master
    if (empty($mPickInvId))
    {
        $mPickInvId = 0;
    }
    $mDataQuery = "SELECT inventory_master.ran_or_order AS ran_order, inventory_master.current_location_id AS location_id, part.part_number,location.location_code,inventory_master.tag_reference AS plt_number, inventory_master.serial_reference AS serial_reference, inventory_master.inventory_qty AS inventory_qty FROM inventory_master JOIN part ON inventory_master.part_id=part.id JOIN location ON inventory_master.current_location_id=location.id WHERE inventory_master.id=".$mPickInvId." LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    if (mysqli_num_rows($mData) == 0)
    {
        $mDataQuery = "SELECT inventory_master.ran_or_order AS ran_order, inventory_master.current_location_id AS location_id, part.part_number,location.location_code,inventory_master.tag_reference AS plt_number, inventory_master.serial_reference AS serial_reference, inventory_master.inventory_qty AS inventory_qty FROM inventory_master JOIN part ON inventory_master.part_id=part.id JOIN location ON inventory_master.current_location_id=location.id WHERE inventory_master.part_number='$mPartNumber' AND inventory_master.serial_reference='$mSerialRef' LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    }
    $mInvRow = array();
    if (mysqli_num_rows($mData) > 0)
    {
        while($mRow = mysqli_fetch_assoc($mData))
        {
            $mInvRow = $mRow;
        }
    }
    if (($mSerialRef == "" || $mSerialRef == null) && $mInvRow['serial_reference'] != null)
        $mSerialRef = $mInvRow['serial_reference'];
    if ($mTransactionTypeId == "MISSING")
        $mPickDtlQty = $mInvRow['inventory_qty'];
    $mRanOrder = $mInvRow['ran_order'];
    if (($mRanOrder == "") || ($mRanOrder == null) || ($mRanOrder == "NORAN"))
        $mRanOrder = $mDtlRow['customer_reference'];
// Transaction History  
//  $mDataQuery = "INSERT INTO transaction_history (id,ran_or_order,part_number,serial_reference,short_code,txn_qty,from_location_code,to_location_code,to_plt,customer_reference,associated_document_reference,date_created,created_by,last_updated,last_updated_by,parent_tag,transaction_reference_code) VALUE(DEFAULT,'".$mInvRow['ran_order']."','".$mInvRow['part_number']."','".$mInvRow['serial_reference']."','".$mTransactionTypeId."',".$mPickDtlQty.",'".$mFromLocCode."','".$mInvRow['location_code']."','".$mInvRow['plt_number']."','".$mDtlRow['customer_reference']."','".$mDtlRow['document_reference']."',now(),'".$mCurrentUser."',now(),'".$mCurrentUser."','".$mInvRow['plt_number']."','".$mTransactionTypeId."')";
    if ($mOrderType != "")
    {
        if ($mTransactionTypeId == 'MISSING')
        {
            $mDataQuery = "INSERT INTO transaction_history";
            $mDataQuery .= " (id,ran_or_order,part_number,serial_reference,short_code,txn_qty,from_location_code,to_location_code,to_plt,customer_reference,associated_document_reference,date_created,created_by,last_updated,last_updated_by,parent_tag,transaction_reference_code,comment,source_tag)";
            $mDataQuery .= " VALUE(DEFAULT,'".$mRanOrder."','".$mPartNumber."','".$mSerialRef."','".$mTransactionTypeId."',".$mPickDtlQty.",'".$mInvRow['location_code']."','".$mFromLocCode."','".$mInvRow['plt_number']."','".$mDtlRow['customer_reference']."','".$mDtlRow['document_reference']."',now(),'".$mCurrentUser."',now(),'".$mCurrentUser."','".$mInvRow['plt_number']."','".$mTransactionTypeId."','".$mComment."','".$mPickPriority."')";
        }
        else
        {
            if ($mTransactionTypeId == "F2SKIP")
                $mDataQuery = "INSERT INTO transaction_history_skip";
            else
                $mDataQuery = "INSERT INTO transaction_history";
            $mDataQuery .= " (id,ran_or_order,part_number,serial_reference,short_code,txn_qty,from_location_code,to_location_code,to_plt,customer_reference,associated_document_reference,date_created,created_by,last_updated,last_updated_by,parent_tag,transaction_reference_code,comment,source_tag) VALUE(DEFAULT,'".$mRanOrder."','".$mPartNumber."','".$mSerialRef."','".$mTransactionTypeId."',".$mPickDtlQty.",'".$mFromLocCode."','".$mInvRow['location_code']."','".$mInvRow['plt_number']."','".$mDtlRow['customer_reference']."','".$mDtlRow['document_reference']."',now(),'".$mCurrentUser."',now(),'".$mCurrentUser."','".$mInvRow['plt_number']."','".$mTransactionTypeId."','".$mComment."','".$mPickPriority."')";
        }
   }
    else
    {
        if ($mTransactionTypeId == 'MISSING')
        {
            $mDataQuery = "INSERT INTO transaction_history";
            $mDataQuery .= " (id,ran_or_order,part_number,serial_reference,short_code,txn_qty,from_location_code,to_location_code,to_plt,customer_reference,associated_document_reference,date_created,created_by,last_updated,last_updated_by,parent_tag,transaction_reference_code,comment,source_tag)";
            $mDataQuery .= " VALUE(DEFAULT,'".$mRanOrder."','".$mPartNumber."','".$mSerialRef."','".$mTransactionTypeId."',".$mPickDtlQty.",'".$mInvRow['location_code']."','".$mFromLocCode."','".$mInvRow['plt_number']."','".$mDtlRow['customer_reference']."','".$mDtlRow['document_reference']."',now(),'".$mCurrentUser."',now(),'".$mCurrentUser."','".$mInvRow['plt_number']."','".$mTransactionTypeId."','".$mComment."','".$mPickPriority."')";
        }
        else
        {
            if ($mTransactionTypeId == "F2SKIP")
                $mDataQuery = "INSERT INTO transaction_history_skip";
            else
                $mDataQuery = "INSERT INTO transaction_history";
            $mDataQuery .= " (id,ran_or_order,part_number,serial_reference,short_code,txn_qty,from_location_code,to_location_code,to_plt,customer_reference,associated_document_reference,date_created,created_by,last_updated,last_updated_by,parent_tag,transaction_reference_code,comment,source_tag) VALUE(DEFAULT,'".$mRanOrder."','".$mPartNumber."','".$mSerialRef."','".$mTransactionTypeId."',".$mPickDtlQty.",'".$mFromLocCode."','".$mInvRow['location_code']."','".$mInvRow['plt_number']."','".$mDtlRow['customer_reference']."','".$mDtlRow['document_reference']."',now(),'".$mCurrentUser."',now(),'".$mCurrentUser."','".$mInvRow['plt_number']."','".$mTransactionTypeId."','".$mComment."','".$mPickPriority."')";
        }
   }
    
//  exit("FAIL-TEST1".mysqli_error($mConnection)."-".$mDataQuery);
//  return;
    
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
//  return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
//    mysqli_close($mConnection);
    return "OK  -";
}

// Clear Pick Detail in_use_by
function clearPickDetail($mCurrentUser,$mHost=null,$mUser=null,$mPwd=null,$mDbName=null,$mCustomerReference=null)
{
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
    if (!$mConnection)
        return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();    
// Set Pick Detail to Processed 
    $mDataQuery = "UPDATE inspection_task_detail SET in_use_by='',last_updated_date=now(),last_updated_by='".$mCurrentUser."'";
    if ($mCustomerReference==null)
        $mDataQuery .= " WHERE in_use_by='".$mCurrentUser."'";
    else
        $mDataQuery .= " WHERE in_use_by='".$mCurrentUser."' AND EXISTS(SELECT id FROM inspection_task_body WHERE inspection_task_detail.inspection_task_body_id=inspection_task_body.id AND inspection_task_body.customer_reference='".$mCustomerReference."') LIMIT 1";  
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
//    mysqli_close($mConnection);
    return "OK  -";
//    return "CHGTRAN:MENUPICK";
}

// Flag Inventory / Pick Task as Missing
function missingPickSerial($mHost,$mUser,$mPwd,$mDbName,$mPickDtlId,$mPickInvId,$mSerialReference,$mPartNumber,$mPickQty,$mCurrentUser,$mTransactionTypeId,$mFromLoc,$mToPlt="")
{
    $mReturn = "";
    $mConnect = null;
    
    if ($mPickQty == null)
        $mPickQty = 0;
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
    if (!$mConnection)
        return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
// Get id for inventory status
    $mInvStsId = 0;
    $mInvRcvId = 0;
    $mInvPckId = 0;
    $mInvPltId = 0;
    $mInvMisId = 0;
    $mDataQuery = "SELECT id AS id, inventory_status_code AS inventory_status_code FROM inventory_status";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;
    $mData = (mysqli_query($mConnection,$mDataQuery));
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        if (strtolower($mRow['inventory_status_code']) == "ok")
            $mInvStsId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "rcv")
            $mInvRcvId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "pkd")
            $mInvPkdId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "plt")
            $mInvPltId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "missing")
            $mInvMisId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "lost")
            $mInvMisId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "pc")
            $mInvPcId = ($mRow['id']);
    }
    
    if ($mInvPkdId == null && $mInvPltId != null)
        $mInvPkdId = $mInvPltId;
    $mPickDtlQty = 0;
    $mDataQuery = "SELECT inspection_task_detail.id AS id, inspection_task_detail.inspection_task_body_id AS pick_body_id, inspection_task_detail.document_reference AS document_reference, inspection_task_detail.part_id AS part_id, inspection_task_detail.qty_allocated AS qty_allocated, inspection_task_detail.location_code AS location_code,inspection_task_detail.line_no AS line_no, inspection_task_detail.pick_priority AS pick_priority";
    $mDataQuery .=",inspection_task_header.customer_reference AS customer_reference";
    $mDataQuery .=" FROM inspection_task_detail";
    $mDataQuery .=" JOIN inspection_task_body ON inspection_task_detail.inspection_task_body_id=inspection_task_body.id";
    $mDataQuery .=" JOIN inspection_task_header ON inspection_task_body.inspection_task_header_id=inspection_task_header.id";
    $mDataQuery .=" WHERE inspection_task_detail.id=".$mPickDtlId." LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$DataQuery;
    $mPickBdyId = "";
    $mPickDtlLoc = "";
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mPickBdyId = $mRow['pick_body_id'];
        $mDocumentReference = $mRow['document_reference'];
        $mPartId = $mRow['part_id'];
        $mPickDtlQty = $mRow['qty_allocated'];
        $mPickDtlLoc = $mRow['location_code'];
        $mDocDtlId = $mRow['line_no'];
        $mPickPriority = $mRow['pick_priority'];
        $mCustomerReference = $mRow['customer_reference'];
//        exit("FAIL-TEST1-".$mRow['pick_body_id']." ".$mPickDtlId." ".mysqli_num_rows($mData));
    }
    
    $i = 0;
    if ($mPickDtlQty > 0)
    {
// Validate Entered Location
        $mDataQuery = "SELECT id AS id, location_hash AS location_hash FROM location WHERE location_code='".$mPickDtlLoc."' LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$DataQuery;
        $mData = mysqli_query($mConnection,$mDataQuery);
        $i = 0;
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            if ($mFromLoc == $mRow['location_hash'])
                $i++;
        }
// Get Entered Location
        $mDataQuery = "SELECT id AS id, location_code AS location_code FROM location WHERE location_hash='".$mFromLoc."' OR location_code ='".$mFromLoc."' LIMIT 1";
        if (!$mLocData = mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$DataQuery;
        list($mLocId,$mLocationCode) = mysqli_fetch_row($mLocData);
        
        $mDataQuery = "UPDATE inspection_task_detail SET qty_allocated=0,processed=1,last_updated_date=now(),last_updated_by='".$mCurrentUser."' WHERE id=".$mPickDtlId." LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        mysqli_query($mConnection,$mDataQuery);
        if ($mPickBdyId != "")
        {
//      $mDataQuery = "UPDATE inspection_task_body SET qty_allocated=(SELECT (CASE WHEN sum(qty_allocated) IS null THEN 0 ELSE sum(qty_allocated) END) FROM inspection_task_detail WHERE inspection_task_detail.inspection_task_body_id=inspection_task_body.id AND inspection_task_detail.processed=0) WHERE inspection_task_body.id=".$mPickBdyId." LIMIT 1";
//            $mDataQuery = "UPDATE inspection_task_body SET qty_allocated=(SELECT (CASE WHEN sum(qty_allocated) IS null THEN 0 ELSE sum(qty_allocated+qty_scanned) END) FROM inspection_task_detail WHERE inspection_task_detail.inspection_task_body_id=inspection_task_body.id) WHERE inspection_task_body.id=".$mPickBdyId." LIMIT 1";
//            if (!mysqli_query($mConnection,$mDataQuery))
//                return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        }
        if ($mInvMisId != null)
            $mDataQuery = "UPDATE inventory_master SET inventory_status_id=".$mInvMisId.", allocated_qty=0,available_qty=inventory_qty,last_updated=now(),last_updated_by='$mCurrentUser' WHERE serial_reference='$mSerialReference' AND part_number='$mPartNumber' AND inventory_status_id<>".$mInvPkdId." LIMIT 1";
        else
            $mDataQuery = "UPDATE inventory_master SET inventory_qty = 0, allocated_qty=0,available_qty=inventory_qty,last_updated=now(),last_updated_by='$mCurrentUser' WHERE serial_reference='$mSerialReference' AND part_number='$mPartNumber' AND inventory_status_id<>".$mInvPkdId." LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        
        $mReturn = updatePickHistory($mHost,$mUser,$mPwd,$mDbName,$mPickDtlId,$mPickInvId,$mPickDtlQty,$mCurrentUser,"MISSING",$mLocationCode);
    
// Add to F6 History
        $mDataQuery = "DELETE FROM f6missing_history WHERE id>0 AND part_number='".$mPartNumber."' AND serial='".$mSerialReference."' LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $mDataQuery = "INSERT into f6missing_history (id,created_by,date_created,inventory_status_CODE,location_code,part_number,qty,serial)";
        $mDataQuery .= " VALUES(DEFAULT,'".$mCurrentUser."_F6',now(),'MISSING','".$mLocationCode."','".$mPartNumber."',".$mPickDtlQty.",'".$mSerialReference."')";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
//      exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
// Set Location Filling Status
        flagEmptyLoc($mLocationCode,$mCurrentUser,$mHost,$mUser,$mPwd,$mDbName);
// Look for alternative Serial
        $mInvQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_qty AS inventory_qty, inventory_master.allocated_qty AS allocated_qty, part.part_number AS part_number, part.conversion_factor AS conversion_factor, inventory_master.serial_reference AS serial_reference, inventory_master.ran_or_order AS ran_order, location.location_code AS location_code FROM inventory_master JOIN location ON inventory_master.current_location_id=location.id JOIN part ON inventory_master.part_id=part.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id LEFT JOIN location_type ON location.location_type_id=location_type.id WHERE inventory_master.part_id=".$mPartId." AND inventory_master.inventory_qty >0 AND inventory_master.inventory_qty>inventory_master.allocated_qty AND inventory_master.requires_inspection=1 AND lower(location_type.location_area)='storage' AND lower(location_type.location_type_code)<>'nopick' AND inventory_status.non_pickable<>1 AND (inventory_master.inventory_status_id IS null OR lower(inventory_status.inventory_status_code) IN('ok','ok')) ORDER BY inventory_master.date_created, location.location_code,inventory_master.inventory_qty LIMIT 1";
        if (!mysqli_query($mConnection,$mInvQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mInvQuery;
        $mInvData = mysqli_query($mConnection,$mInvQuery);
        $mTest = "_PICKFACE";
        if (mysqli_num_rows($mInvData) == 0)
        {
            $mInvQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_qty AS inventory_qty, inventory_master.allocated_qty AS allocated_qty, part.part_number AS part_number, part.conversion_factor AS conversion_factor, part.rdt_prompt AS rdt_prompt, inventory_master.serial_reference AS serial_reference, inventory_master.ran_or_order AS ran_order, location.location_code AS location_code FROM inventory_master JOIN location ON inventory_master.current_location_id=location.id JOIN part ON inventory_master.part_id=part.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id LEFT JOIN location_type ON location.location_type_id=location_type.id WHERE inventory_master.part_id=".$mPartId." AND inventory_master.inventory_qty >0 AND inventory_master.inventory_qty>inventory_master.allocated_qty AND inventory_master.requires_inspection=0 AND lower(location_type.location_area)='storage' AND lower(location_type.location_type_code)<>'nopick' AND inventory_status.non_pickable<>1 AND (inventory_master.inventory_status_id IS null OR lower(inventory_status.inventory_status_code) IN('ok','ok')) ORDER BY inventory_master.date_created, location.location_code,inventory_master.inventory_qty LIMIT 1";
            if (!mysqli_query($mConnection,$mInvQuery))
                return "FAIL-".mysqli_error($mConnection)."-".$mInvQuery;
            $mInvData = mysqli_query($mConnection,$mInvQuery);
            $mTest="_NOTPICKFACE";
        }
        if (!mysqli_query($mConnection,$mInvQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$InvQuery;
        $mData = mysqli_query($mConnection,$mInvQuery);
        $i = 0;
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            if (($mRow['inventory_qty'] > 0) && ($mRow['inventory_qty'] < $mPickDtlQty))
                $mPickDtlQty = $mRow['inventory_qty'];
            if ($mRow['conversion_factor'] > 1)
                $mPickQty = $mPickDtlQty/$mRow['conversion_factor'];
            else
                $mPickQty = $mPickDtlQty;
                
            $mDataQuery = "UPDATE inspection_task_detail SET inventory_master_id=".$mRow['id'].",part_id=".$mPartId.",part_number='".$mRow['part_number']."',serial_reference='".$mRow['serial_reference']."',location_code='".$mRow['location_code']."',qty_allocated=".$mPickDtlQty.", processed=0 WHERE id=".$mPickDtlId." LIMIT 1";
            if (!mysqli_query($mConnection,$mDataQuery))
                return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
// return Pick Details to the screen
            if ($mToPlt == "")
                $mReturn = "DATA:fromLocationHashCodecontent:".$mRow['location_code'].",serialReferencecontent:".$mRow['serial_reference'].",qtyAllocated:".$mPickQty.",sequencingRequestId:".$mRow['id'].",rdtMessage:".$mRow['rdt_prompt'];
            else
                $mReturn = "DATA:fromLocationHashCodecontent:".$mRow['location_code'].",serialReferencecontent:".$mRow['serial_reference'].",qtyAllocated:".$mPickQty.",sequencingRequestId:".$mRow['id'].",rdtMessage:".$mRow['rdt_prompt']."::skip3";
            $i++;
        }
    }
    if ($i == 0)
    {
        $mReturn = getPick($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mCustomerReference,$mConnect,$mToPlt);
    }
    if ($mReturn == "")
        $mReturn = "OK  -Missing Serial";
    return($mReturn);
}

// Flag Empty Location
function flagEmptyLoc($mLocationCode,$mCurrentUser,$mHost,$mUser,$mPwd,$mDbName,$mConnect='')
{
    $mErrMsg = "";
    $mInvCount = 0;

// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        die("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    $mDataQuery = "";
// Check for Inventory in Location  
    if ($mLocationCode != "")
    {
        $mDataQuery = "SELECT inventory_master.id AS inv_count FROM inventory_master LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE inventory_master.location_code='".$mLocationCode."' AND inventory_qty > 0 AND (inventory_master.inventory_status_id IS null OR lower(inventory_status.inventory_status_code) NOT IN('pkd','plt','missing')) LIMIT 1";
    }
    if ($mDataQuery != "")
    {
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-1".mysqli_error($mConnection)."-".$mDataQuery);
        $mData = mysqli_query($mConnection,$mDataQuery);
        $i = 0;
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mInvCount = ($mRow['inv_count']);
            $i++;
        }
        if ($i == 0)
        {
            if ($mLocationCode != "")
            {
                $mDataQuery = "UPDATE location SET location.filling_status_id=(SELECT id FROM location_filling_status WHERE lower(filling_code) = 'empty') WHERE location.location_code='".$mLocationCode."' LIMIT 1";
                if (!mysqli_query($mConnection,$mDataQuery))
                    exit ("FAIL-3".mysqli_error($mConnection)."-".$mDataQuery);
            }
        }
    }
    return "OK  -Location Filling Status";
}

// Create / Return Pallet Tag
function processPickPlt($mPlt,$mVirtualPalletLbl,$mTransactionTypeId,$mPltSts,$mCurrentUser,$mHost,$mUser,$mPwd,$mDbName)
{
//  $mParms = json_decode($mJsonObject, true);
// Blank Pallet
    if (($mVirtualPalletLbl == "0") && ($mPlt == ""))
        return("FAIL-Invalid Pallet");
// Check Pallet Type
    if ((substr($mPlt,0,3) == "PCK" && substr($mTransactionTypeId,0,2) != "PB"))
        return("FAIL-Invalid Pallet Type");
    elseif ((substr($mPlt,0,3) == "RCV" && substr($mTransactionTypeId,0,2) != "RB"))
        return("FAIL-Invalid Pallet Type");
    elseif ((substr($mPlt,0,3) == "RXD" && substr($mTransactionTypeId,0,3) != "JRB"))
        return("FAIL-Invalid Pallet Type");
    elseif ((substr($mPlt,0,3) == "REP" && substr($mTransactionTypeId,0,3) != "REPLEN"))
        return("FAIL-Invalid Pallet Type");
    
// mysql connection - Use Passed values...
        $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
            exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    
// Check Pallet Status
    if ($mPlt != "" && $mPltSts != "")
    {
        $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_status_id AS inventory_status_id, inventory_status.inventory_status_code AS inventory_status_code FROM inventory_master LEFT JOIN tag on inventory_master.parent_tag_id=tag.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE inventory_status.inventory_status_code='".$mPltSts."' AND (tag.tag_reference='".$mPlt."' OR inventory_master.serial_reference='".$mPlt."') LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-1".mysqli_error($mConnection)."-".$mDataQuery;             
        $mData = mysqli_query($mConnection,$mDataQuery);
        if (mysqli_num_rows($mData) == 0)
        {
            $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_status_id AS inventory_status_id, inventory_status.inventory_status_code AS inventory_status_code FROM inventory_master LEFT JOIN tag on inventory_master.parent_tag_id=tag.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE tag.tag_reference='".$mPlt."' OR inventory_master.serial_reference='".$mPlt."' LIMIT 1";
            if (!mysqli_query($mConnection,$mDataQuery))
                return "FAIL-1".mysqli_error($mConnection)."-".$mDataQuery;             
            $mData = mysqli_query($mConnection,$mDataQuery);
        }       
        $mInvId = "";
        $mInvStsId = "";
        $mInvStsCode = "";
        $mRow = mysqli_fetch_assoc($mData);
        if (mysqli_num_rows($mData) > 0)
        {
            $mInvStsId = ($mRow['inventory_status_id']);
            $mInvStsCode = ($mRow['inventory_status_code']);
// Check Inventory Status of the Pallet
            if (strtolower($mInvStsCode) != strtolower($mPltSts))
            {
                return "FAIL-This Pallet is in Use.";
            }
        }       
    }
// Test for Existing Pallet / Tag
    if ($mPlt != "")
    {
// Select by Serial
//      $mDataQuery = "SELECT inventory_master.parent_tag_id AS parent_tag_id, tag.tag_reference AS tag_reference FROM inventory_master LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE (inventory_master.serial_reference='".$mPlt."' OR inventory_master.serial_reference='".substr($mPlt,1)."') LIMIT 1";
        $mDataQuery = "SELECT inventory_master.parent_tag_id AS parent_tag_id, tag.tag_reference AS tag_reference FROM inventory_master LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE (inventory_master.serial_reference='".$mPlt."') LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-2".mysqli_error($mConnection)."-".$mDataQuery;             
        $mData = mysqli_query($mConnection,$mDataQuery);
        if (mysqli_num_rows($mData) == 0)
        {
//          $mDataQuery = "SELECT scan_data.plt_reference AS tag_reference FROM scan_data WHERE (scan_data.serial_reference='".$mPlt."' OR scan_data.serial_reference='".substr($mPlt,1)."') LIMIT 1";
            $mDataQuery = "SELECT scan_data.plt_reference AS tag_reference FROM scan_data WHERE (scan_data.serial_reference='".$mPlt."') LIMIT 1";
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                return "FAIL-3".mysqli_error($mConnection)."-".$mDataQuery;             
//          $mData = mysqli_query($mConnection,$mDataQuery);
        }
        $mTagRef = "";
        $mRow = mysqli_fetch_assoc($mData); 
        $mTagRef = ($mRow['tag_reference']);
        if ($mTagRef != "")
        {
            return($mTagRef);
        }
        
        $mDataQuery = "SELECT id FROM tag WHERE tag_reference='".$mPlt."' AND (active IS null OR active = '1') LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-3".mysqli_error($mConnection)."-".$mDataQuery;
                
        $mData = mysqli_query($mConnection,$mDataQuery);
        $mTagId = "";
        $mRow = mysqli_fetch_assoc($mData); 
        $mTagId = ($mRow['id']);
        if ($mTagId == "")
        {
            $mDataQuery = "INSERT INTO tag (id,version,auto_generated,current_location_id,date_created,document_header_id,last_updated,last_updated_by,tag_reference,validated,active,picked) VALUES(DEFAULT,0,0,null,now(),null,now(),'".$mCurrentUser."','".$mPlt."',1,1,0)";
            if (!mysqli_query($mConnection,$mDataQuery))
                return "FAIL-4".mysqli_error($mConnection).$mDataQuery;
        }
        return($mPlt);
    }
// Create Virtual Pallet / Tag
    else
    {
        $mDataQuery = "INSERT INTO tag (id,version,auto_generated,current_location_id,date_created,document_header_id,last_updated,last_updated_by,tag_reference,validated,active,picked) VALUES(DEFAULT,0,0,null,now(),null,now(),'".$mCurrentUser."','PLT000000',1,1,0)";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        $mTagId=mysqli_insert_id($mConnection);
        $mTagReference = "000000".round($mTagId);
        if (substr($mTransactionTypeId,0,2) == "PB")
            $mTagReference = "PCK".substr($mTagReference,-6);
        elseIf (substr($mTransactionTypeId,0,2) == "RB")
            $mTagReference = "RCV".substr($mTagReference,-6);
        elseIf (substr($mTransactionTypeId,0,3) == "JRB")
            $mTagReference = "RXD".substr($mTagReference,-6);
        elseIf (substr($mTransactionTypeId,0,3) == "REP")
            $mTagReference = "REP".substr($mTagReference,-6);
        else
            $mTagReference = "PLT".substr($mTagReference,-6);
        $mDataQuery = "UPDATE tag SET tag_reference='".$mTagReference."' WHERE id=".$mTagId." LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
                return "FAIL-5".mysqli_error($mConnection).$mDataQuery;
        return($mTagReference);
    }
}

// Get Input Parameters from POST or GET
if (!empty($_POST))
{
    $mFilter = "";
    foreach($_POST as $k1=>$v1)
    {
//      print_r("TEST".$k1.":".$v1);
        if ($mFilter != "")
            $mFilter .= "&";
        $mFilter .= $k1."=".$v1;
    }
}
else
{
    $mFilter = $_SERVER['QUERY_STRING'];
}

$mFilter = str_replace("=",":",$mFilter);
$mFilter = str_replace("&",",",$mFilter);

if (strpos($mFilter,"clearpickdetail"))
{
    $mCurrentUser = "";
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    $mDbHost = "";
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "function")
            $mFunction = $v2;
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
        elseif ($k2 == "host")
            $mDbHost = $v2;
        elseif ($k2 == "user")
            $mDbUser = $v2;
        elseif ($k2 == "pword")
            $mDbPwd = $v2;
        elseif ($k2 == "dbase")
            $mDbase = $v2;
    }
    if ($mDbHost == "")
        echo clearPickDetail($mCurrentUser);
    else
        echo clearPickDetail($mCurrentUser,$mDbHost,$mDbUser,$mDbPwd,$mDbase);
}

function getPickList($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mReference,$mKey=null,$mOffset=0)
{	
// 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 inspection_task_header.id AS id, inspection_task_header.document_reference AS document_reference,inspection_task_header.customer_reference";
    $mDataQuery .=",(SELECT part_number FROM inspection_task_body WHERE inspection_task_body.inspection_task_header_id=inspection_task_header.id LIMIT 1) AS part_number";
    $mDataQuery .=" FROM inspection_task_header";
    $mDataQuery .=" LEFT JOIN document_status ON inspection_task_header.document_status_id=document_status.id";
    $mDataQuery .=" WHERE inspection_task_header.customer_reference LIKE('".$mReference."%')AND (lower(document_status.document_status_code)='open') ORDER by inspection_task_header.id LIMIT 50 OFFSET ".$mOffset;
	if (!$mData = mysqli_query($mConnection,$mDataQuery))
		exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
//	exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
	$mDropdown = array();
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
//		echo("FAIL-TEST-".$mPrevCase."-".$mRow['case_reference']);
		$mDropdown[] = array('value' => "customerReference:".$mRow['customer_reference'],'text' => $mRow['customer_reference']." ".$mRow['part_number'],);
	}
	mysqli_close($mConnection);
	return "DROP-".json_encode($mDropdown);
}

function getFqaList($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mReference,$mKey=null,$mOffset=0)
{	
// 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 fqa_task_header.id AS id, fqa_task_header.document_reference AS document_reference, fqa_task_header.customer_reference, fqa_task_body.part_number AS part_number";
    $mDataQuery .= " FROM fqa_task_header";
    $mDataQuery .= " LEFT JOIN document_status ON fqa_task_header.document_status_id=document_status.id";
    $mDataQuery .= " LEFT JOIN fqa_task_body ON fqa_task_header.id = fqa_task_body.fqa_task_header_id";
    $mDataQuery .= " WHERE (lower(document_status.document_status_code)='open') ORDER by fqa_task_header.id LIMIT 50 OFFSET ".$mOffset;
	if (!$mData = mysqli_query($mConnection,$mDataQuery))
		exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
//	exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
	$mDropdown = array();
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
//		echo("FAIL-TEST-".$mPrevCase."-".$mRow['case_reference']);
		$mDropdown[] = array('value' => "documentReference:".$mRow['document_reference'],'text' => $mRow['document_reference']." ".$mRow['customer_reference']." - ".$mRow['part_number'],);
	}
	mysqli_close($mConnection);
	return "DROP-".json_encode($mDropdown);
}

// Get Next Pick
function getFqaTask($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mDocumentReferenceCode,$mConnect,$mToPlt="")
{
    $mReturn = "";
    if (($mDocumentReferenceCode != null) && ($mDocumentReferenceCode != ""))
    {
// mysql connection
        $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
        if (!$mConnection)
            return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
// Order Header
        $mReturn = "";
        $mDataQuery = "SELECT fqa_task_header.id AS id, fqa_task_header.document_reference AS document_reference, fqa_task_header.to_location_id AS to_location_id,fqa_task_header.order_type AS order_type";
        $mDataQuery .=",location.location_code AS location_code ";
        $mDataQuery .=", document_status.document_status_code";
        $mDataQuery .=" FROM fqa_task_header";
        $mDataQuery .=" LEFT JOIN location ON fqa_task_header.to_location_id=location.id";
        $mDataQuery .=" LEFT JOIN document_status ON fqa_task_header.document_status_id=document_status.id";
        $mDataQuery .=" WHERE fqa_task_header.document_reference='$mDocumentReferenceCode'";
        $mDataQuery .=" LIMIT 1";

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

        if (mysqli_num_rows($mData) == 0)
        {
            
                $mTransactionType = "FQATASK";
                return "OKMS-No Tasks for ".$mTransactionType.",CHGTRAN:".$mTransactionType."?DATA:documentReference:,toPlt:".$mToPlt;
        }
        $mPickByLine = 0;
        $mFullBoxPick = 1;
        $mToLoc = "";
        $mOrderType="";
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mHdrId = ($mRow['id']);
            $mDocumentReferenceCode = ($mRow['document_reference']);
            if (!empty($mRow['location_code']))
            {
                $mToLoc = $mRow['location_code'];
            }
            $mDocStsCode = $mRow['document_status_code'];
            if (!empty($mRow['order_type']))
            {
                $mOrderType = $mRow['order_type'];
            }
// Test if order is complete
            if (strtolower($mRow['document_status_code']) == "complete" || strtolower($mRow['document_status_code']) == "picked" || strtolower($mRow['document_status_code']) == "transmitted")
            {
                $mToPlt = "";
                $mTransactionType="FQATASK";
                exit ("OKMS-The Task is ".$mDocStsCode.",CHGTRAN:".$mTransactionType."?DATA:documentReference:,toPlt:".$mToPlt);
            }
            if (!ISSET($mTransactionType) || $mTransactionType == null || $mTransactionType == "")
                $mTransactionType="FQATASK";

			$mDataQuery = "SELECT document_reference,fqa_task_body.part_number AS part_number,fqa_task_body.serial_reference AS serial_reference,qty_expected-qty_transacted AS quantity";
			$mDataQuery .=",inventory_master.part_id AS part_id,inventory_master.location_code AS location_code,inventory_master.pruf_cube AS pruf_cube,inventory_master.product_type_id AS product_type_id";
			$mDataQuery .=" FROM fqa_task_body";
			$mDataQuery .=" JOIN inventory_master ON fqa_task_body.serial_reference=inventory_master.serial_reference AND fqa_task_body.part_number=inventory_master.part_number";
			$mDataQuery .=" WHERE fqa_task_body.fqa_task_header_id=".$mHdrId." AND fqa_task_body.document_status_id=1 ORDER BY fqa_task_body.date_created,fqa_task_body.document_reference";
			$mDataQuery .=" LIMIT 1";
			if (!$mData = mysqli_query($mConnection,$mDataQuery))
				exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
			
			if (mysqli_num_rows($mData) > 0)
			{
				$mRow = mysqli_fetch_assoc($mData);
				if (empty($mToLoc))
				{
					include_once ('location.php');
					$mToLoc = getNextLocation($mRow['part_id'],$mRow['product_type_id'],"","",$mRow['pruf_cube'],0,$mHost,$mUser,$mPwd,$mDbName,"FQA");
				}
				$mReturn = "DATA:allocationId:".$mRow['document_reference'].",fromLocationHashCodecontent:".$mRow['location_code'].",serialReference:".$mRow['serial_reference'].",partNumber:".$mRow['part_number'].",quantity:".$mRow['quantity'].",toLocationHashCode:".$mToLoc;
			}
			else
			{
				$mReturn = "OKMS-No Outstanding Tasks";
		//        $mReturn = "OKMS-No Outstanding Tasks,CHGTRAN:FQATASK";
			}
		//	mysqli_close($mConnection);
			if ($mReturn == "")
				$mReturn = "OK  -getfqatask";
			exit($mReturn);
        }
    }
    else
    {
        $mReturn = "FAIL-EOD-No Matching Document Reference";
    }
    return $mReturn;
}

// Get FQA fixed_location
function getFqaFixedLoc($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mSerialReference,$mPartNumber,$mVldLoc="")
{
    $mReturn = "";
    
// mysql connection
	try
	{
        $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
	}
	catch (Exception $e) 
    {
        exit ("FAIL-".$e);
    }
// Order Header
	$mReturn = "";
	$mDataQuery = "SELECT fqa_task_header.id AS id, fqa_task_header.to_location_id AS to_location_id,fqa_task_header.order_type AS order_type";
	$mDataQuery .=",location.location_code AS location_code, location.location_hash AS location_hash";
	$mDataQuery .=", document_status.document_status_code";
	$mDataQuery .=" FROM fqa_task_body";
	$mDataQuery .=" JOIN fqa_task_header ON fqa_task_header.id=fqa_task_body.fqa_task_header_id";
	$mDataQuery .=" LEFT JOIN location ON fqa_task_header.to_location_id=location.id";
	$mDataQuery .=" LEFT JOIN document_status ON fqa_task_header.document_status_id=document_status.id";
	$mDataQuery .=" WHERE fqa_task_body.serial_reference='".$mSerialReference."' AND fqa_task_body.part_number='".$mPartNumber."' AND fqa_task_body.document_status_id=1";
	$mDataQuery .=" LIMIT 1";
	try
	{
		$mData = mysqli_query($mConnection,$mDataQuery);
	}
	catch (Exception $e) 
	{
		exit ("FAIL-".$e."-".$mDataQuery);
	}
// No FQA Task, just exit.
	if (mysqli_num_rows($mData) == 0)
	{
		exit ("OK  -getFqaFixedLoc");
	}
// Populate To-Location on Screen
	$mRow = mysqli_fetch_assoc($mData);
//	exit("FAIL-TEST1-".$mDataQuery." ".mysqli_num_rows($mData)." ".$mRow['id']);
	if (empty($mVldLoc))
	{
		exit ("DATA:toLocationHashCodecontent:".$mRow['location_code']);
	}
// Check Fixed Location
	if (!empty($mRow['location_hash']))
	{
		if ($mVldLoc != $mRow['location_hash'])
		{
			exit("FAIL-Not fixed location");
		}
	}
	exit("OK  -getFqaFixedLoc");
}
function createInsSerial($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mAllocationId,$mSerialReference,$mPartNumber,$mQuantity=null,$mPrinter=null)
{	
//	echo("FAIL-TEST3");
	$mSerialReferenceO = $mSerialReference;
// mysql connection - Use Passed values...
	try
	{
		$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
	}
	catch (Exception $e) 
    {
        exit ("FAIL-".$e);
    }
    $i =  strpos($mSerialReference,'INS');
    if ($i > 0)
    {
        $mSerialReference = substr($mSerialReference,0,$i);
    }
    $mDataQuery = "SELECT id,inventory_qty FROM inventory_master WHERE part_number = '".$mPartNumber."' AND serial_reference ='".$mSerialReference."' LIMIT 1";
    try
	{
		$mData = mysqli_query($mConnection,$mDataQuery);
	}
	catch (Exception $e) 
    {
        exit ("FAIL-".$e."-".$mDataQuery);
    }
    if (mysqli_num_rows($mData) == 0)
    {
        exit ("OK  -No matching serial");
    }
    $mRow = mysqli_fetch_assoc($mData);
// Check for pick_qty < inventory_qty    
    if (!empty($mQuantity))
    {
        if ($mQuantity >= $mRow['inventory_qty'])
            exit ("OK  -Full box");
    }
    
	$mDataQuery = "SELECT * FROM inventory_master WHERE part_number = '".$mPartNumber."' AND serial_reference LIKE('".$mSerialReference."%') ORDER BY serial_reference DESC LIMIT 1";
    try
	{
		$mData = mysqli_query($mConnection,$mDataQuery);
	}
	catch (Exception $e) 
    {
        exit ("FAIL-".$e."-".$mDataQuery);
    }
    if (mysqli_num_rows($mData) == 0)
    {
        exit ("OK  -No matching serial");
    }
    
    $mRow = mysqli_fetch_assoc($mData);
// Generate Pick Serial
    $mInvSerial = $mRow['serial_reference'];
    $i = strpos($mInvSerial,'INS');
    if ($i > 0)
    {
        $i = $i+3;
        $mSuffix = substr($mInvSerial,$i);
        if (is_numeric($mSuffix))
        {
            $i = intval($mSuffix);
            $i++;
            $mSuffix = substr('00'.$i,-3);
            $mSuffix = 'INS'.$mSuffix;
        }
    }
    else
    {
        $mSuffix = 'INS001';
    }
// Insert Pick_serial Record
    $mSerialReference=$mSerialReference.$mSuffix;
	if (empty($mRow['location_id']))
		$mRow['location_id']=$mRow['current_location_id'];
	if (empty($mRow['stock_date']))
	{
		$mCurrentTimestamp = time();
		$mFormattedTimestamp = date('Y-m-d H:i:s', $mCurrentTimestamp);
		$mRow['stock_date'] = $mFormattedTimestamp;
	}
    $mDataQuery = "INSERT INTO inventory_master (id,version,allocated_qty,hold_qty,current_inventory_status_id,current_location_id,location_id,location_code,date_created,created_by,expiry_date,inventory_qty,available_qty,last_updated,last_updated_by,parent_tag_id,part_id,part_number,ran_or_order,recorded_missing,requires_decant,requires_inspection,serial_reference,originating_detail_id,conversion_factor,stock_date,active,inventory_status_id,product_type_id,pruf_cube)";
    if (empty($mRow['pruf_cube']))
        $mDataQuery .=" VALUES(DEFAULT,0,0,0,null,".$mRow['current_location_id'].",".$mRow['location_id'].",'".$mRow['location_code']."','".$mRow['date_created']."','".$mCurrentUser."',null,0,0,now(),'".$mCurrentUser."',null,".$mRow['part_id'].",'".$mRow['part_number']."','".$mRow['ran_or_order']."',0,0,0,'".$mSerialReference."',null,".$mRow['conversion_factor'].",'".$mRow['stock_date']."',1,".$mRow['inventory_status_id'].",null,null)";
    else
        $mDataQuery .=" VALUES(DEFAULT,0,0,0,null,".$mRow['current_location_id'].",".$mRow['location_id'].",'".$mRow['location_code']."','".$mRow['date_created']."','".$mCurrentUser."',null,0,0,now(),'".$mCurrentUser."',null,".$mRow['part_id'].",'".$mRow['part_number']."','".$mRow['ran_or_order']."',0,0,0,'".$mSerialReference."',null,".$mRow['conversion_factor'].",'".$mRow['stock_date']."',1,".$mRow['inventory_status_id'].",".$mRow['product_type_id'].",".$mRow['pruf_cube'].")";
//    exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
	try
	{
		mysqli_query($mConnection,$mDataQuery);
    }
	catch (Exception $e) 
    {
        exit ("FAIL-".$e."-".$mDataQuery);
    }
	$mInvId=mysqli_insert_id($mConnection);
//	exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
	$mDataQuery = "UPDATE inspection_task_detail SET inventory_master_id=".$mInvId.",serial_reference='".$mSerialReference."' WHERE serial_reference='$mSerialReferenceO' AND part_number='$mPartNumber' LIMIT 1";
	try
	{
		mysqli_query($mConnection,$mDataQuery);
	}
	catch (Exception $e) 
    {
        exit ("FAIL-".$e."-".$mDataQuery);
    }
	if (!empty($mPrinter))
	{
/*
		$mDataQuery = "SELECT document_reference FROM inspection_task_detail WHERE serial_reference='$mSerialReference' AND part_number='$mPartNumber' LIMIT 1";
		try
		{
			$mData = mysqli_query($mConnection,$mDataQuery);
		}
		catch (Exception $e) 
		{
			exit ("FAIL-".$e."-".$mDataQuery);
		}
		list($mDocRef) = mysqli_fetch_row($mData);
		include_once('../reports/insplabelpdf.php');
		$mStatus = labelPrint($mDocRef,$mPrinter,$mLabel,$mHost,$mUser,$mPwd,$mDbName,"n");
*/
	}
	mysqli_close($mConnection);
	exit ("DATA:serialReferenceinput:".$mSerialReference);
}

function updateInsSerial($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mAllocationId,$mSerialReference,$mPartNumber,$mQuantity=null)
{	
//	echo("FAIL-TEST3");
// mysql connection - Use Passed values...
	try
	{
		$mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
	}
	catch (Exception $e) 
    {
        exit ("FAIL-".$e);
    }
    $i =  strpos($mSerialReference,'INS');
    if ($i == 0)
	{
		return "OK  -noInsSerial";
	}
	else
    {
        $mSerialReferenceO = substr($mSerialReference,0,$i);
    }
    $mDataQuery = "Update inventory_master";
	$mDataQuery .=" SET inventory_qty= CASE WHEN inventory_qty >= ".$mQuantity." THEN inventory_qty-$mQuantity ELSE 0 END";
	$mDataQuery .=" ,allocated_qty= CASE WHEN allocated_qty >= ".$mQuantity." THEN allocated_qty-$mQuantity ELSE 0 END";
	$mDataQuery .=" ,available_qty=inventory_qty-allocated_qty";
	$mdataQuery .=" WHERE part_number = '".$mPartNumber."' AND serial_reference ='".$mSerialReferenceO."' LIMIT 1";
    try
	{
		mysqli_query($mConnection,$mDataQuery);
	}
	catch (Exception $e) 
    {
        exit ("FAIL-".$e."-".$mDataQuery);
    }
    $mDataQuery = "Update inventory_master";
	$mDataQuery .=" SET inventory_qty = inventory_qty+".$mQuantity;
	$mDataQuery .=" ,allocated_qty=0";
	$mDataQuery .=" ,available_qty=inventory_qty-allocated_qty";
	$mdataQuery .=" WHERE part_number = '".$mPartNumber."' AND serial_reference ='".$mSerialReference."' LIMIT 1";
    try
	{
		mysqli_query($mConnection,$mDataQuery);
	}
	catch (Exception $e) 
    {
        exit ("FAIL-".$e."-".$mDataQuery);
    }
	mysqli_close($mConnection);
	return "OK  -updateInsSerial";
}
function logMessage($mMessage,$mLogFile="")
{
    $mNow = date("Y-m-d H:i:s");
    if ($mLogFile == "")
        $mLogFile = "E:/php_logs/php_vims.log";
    error_log(print_r($mNow."-".$mMessage."\r\n", TRUE), 3, $mLogFile);
}
?>
