<?php
// ----------------------------------------------------------------------------------------
// Modified 2021-05-06 - Initial version
// ----------------------------------------------------------------------------------------
// picking.php
// VIMS RDT Order / Pick Process

// ----------------------------------------------------------------------------
// Use Statements
// ----------------------------------------------------------------------------
use classes\MysqliVeu;
use classes\RDTResponse;
use classes\Part;

// ----------------------------------------------------------------------------------------
// Includes and Requires
// ----------------------------------------------------------------------------------------
require_once __DIR__ . '/coreInit.php';


// ----------------------------------------------------------------------------------------
// Global Variables
// ----------------------------------------------------------------------------------------
$mFunction = $_GET['function'];
$mConnect = $_GET['connection'];
$mUser = $_GET['user'];
$mPwd = $_GET['pword'];
$mHost = $_GET['host'];
$mDbName = $_GET['dbase'];
$mTableName = $_GET['table'];
$mFilter = $_GET['filter'];
$mReturnFields = $_GET['returnfields'];
$mFilter = str_replace("|AND|", "&", $mFilter);
$mFilter = str_replace("/dbase/", $mDbName, $mFilter);
$mErrMsg = "OK  -";

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

// Check Lock
if (($mFunction != null) && (strtolower($mFunction) == "checklock"))
{
    $mErrMsg = "";
    $mKey = "";

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

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

    // Create Associative Array by Exploding Array Elements on :
    for ($i = 0; $i < count($mArray1); $i++)
    {
        $s = 0;
        $e = 0;
        $k1 = $mArray1[$i];
        $s = strpos($k1, ":");
        if ($s >= 0)
        {
            $k2 = substr($k1, 0, $s);
            $v2 = substr($k1, $s + 1);
        }
        if ($k2 == "key")
        {
            $mKey = strtoupper(trim($v2));
        }
        elseif ($k2 == "currentUser")
        {
            $mCurrentUser = trim($v2);
        }
        elseif ($k2 == "lock")
        {
            $mLock = trim($v2);
        }
        elseif ($k2 == "transactionType")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
        elseif ($k2 == "transactionTypeId")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
    }

    // Data posted validations
    if (!isset($mCurrentUser))
    {
        RDTResponse::fail("Missing current user");
    }

    // DB connection
    $database = new MysqliVeu();

    // Unlocks pick
    if (isset($mLock) && $mLock === "OFF")
    {
        if ($mKey !== "")
        {
            $sql = "DELETE FROM pick_in_use
                WHERE 
                    id > 0 
                    AND pick_key = ? 
                    AND in_use_by = ?";

            $params = [$mKey, $mCurrentUser];
        }
        else
        {
            $sql = "DELETE FROM pick_in_use
                WHERE
                    id > 0
                    AND in_use_by = ?";

            $params = [$mCurrentUser];
        }

        if (!$database->execute($sql, $params))
        {
            RDTResponse::fail('Unable to unlock pick');
        }
    }
    else
    {
        // Checks if the pick is currently in use within the last 5 minutes
        $sql = "SELECT
                id
            FROM pick_in_use
            WHERE 
                pick_key = ?
                AND in_use_by <> ?
                AND last_updated_at >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)
            LIMIT 1";

        $params = [$mKey, $mCurrentUser];

        if ($database->numRows($sql, $params) > 0)
        {
            RDTResponse::fail("Task in Use");
        }
        else // Creates a record on pick_in_use table
        {
            $sql = "SELECT id
                FROM pick_in_use
                WHERE 
                    pick_key = ?
                    AND in_use_by = ?
                LIMIT 1";

            $params = [$mKey, $mCurrentUser];

            if ($database->numRows($sql, $params) === 0) // Creates record
            {
                $sql = "INSERT INTO pick_in_use
                        (id, pick_key, in_use_by, last_updated_at)
                    VALUES
                        (DEFAULT, ?, ?, NOW())";

                $params = [$mKey, $mCurrentUser];

                if (!$database->execute($sql, $params))
                {
                    RDTResponse::fail("Unable to lock pick for $mCurrentUser");
                }
            }
            else // Updates records
            {
                $sql = "UPDATE pick_in_use
                    SET last_updated_at = NOW()
                    WHERE 
                        pick_key = ?
                        AND in_use_by = ?
                    LIMIT 1";

                $params = [$mKey, $mCurrentUser];

                if (!$database->execute($sql, $params))
                {
                    RDTResponse::fail("Unable to update pick status");
                }
            }
        }
    }

    // Success Response
    RDTResponse::ok("checklock");
}

// Get Pick
if (($mFunction != null) && (strtolower($mFunction) == "getpick"))
{
    $mStatus = getPick($mHost, $mUser, $mPwd, $mDbName, $mConnect, $mFilter);
    echo $mStatus;

    return;
}

// Get EMG Pick
if (($mFunction != null) && (strtolower($mFunction) == "getemgpick"))
{
    $mErrMsg = "";
    $mToPlt = "";
    $mTrain = "";
    // Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=", ":", $mFilter);
    $mFilter = str_replace("&", ",", $mFilter);
    // Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",", $mFilter);
    // Create Associative Array by Exploding Array Elements on :
    for ($i = 0; $i < count($mArray1); $i++)
    {
        $s = 0;
        $e = 0;
        $k1 = $mArray1[$i];
        $s = strpos($k1, ":");
        if ($s >= 0)
        {
            $k2 = substr($k1, 0, $s);
            $v2 = substr($k1, $s + 1);
        }
        if ($k2 == "customerreference")
        {
            $mCustomerRef = trim($v2);
        }
        elseif ($k2 == "picktype")
        {
            $mPickType = trim($v2);
        }
        elseif ($k2 == "locationcode")
        {
            $mLocationCode = strtoupper(trim($v2));
        }
        elseif ($k2 == "tasktype")
        {
            $mTaskType = strtoupper(trim($v2));
        }
        elseif ($k2 == "aisle")
        {
            $mAisle = trim($v2);
        }
        elseif ($k2 == "train")
        {
            $mTrain = trim($v2);
        }
        elseif ($k2 == "toplt")
        {
            $mToPlt = trim($v2);
        }
        elseif ($k2 == "printername")
        {
            $mPrinterName = trim($v2);
        }
        elseif ($k2 == "printeraddr")
        {
            $mPrinterAddr = trim($v2);
        }
        elseif ($k2 == "currentUser")
        {
            $mCurrentUser = trim($v2);
        }
        elseif ($k2 == "transactionType")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
        elseif ($k2 == "transactionTypeId")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
    }
    // mysql connection
    $mConnection = mysqli_connect($mHost, $mUser, $mPwd, $mDbName);
    if (!$mConnection)
    {
        exit("FAIL-Connect failed: " . mysqli_connect_errno() . " : " . mysqli_connect_error());
    }

    $mDataQuery = "SELECT 
            pick_header.id AS id,
            pick_header.document_reference AS document_reference,
            pick_body.processed AS processed
        FROM pick_header
        LEFT JOIN pick_body ON pick_header.id=pick_body.pick_header_id
        LEFT JOIN part ON pick_body.part_id=part.id
        LEFT JOIN location_type ON part.fixed_location_type_id=location_type.id
        WHERE 
            pick_header.pick_type='{$mPickType}' AND
            pick_header.document_status_id=1 AND
            pick_body.processed<>1 AND
            location_type.location_type_code='{$mTaskType}'
        ORDER BY pick_header.date_created LIMIT 100";

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

    if (mysqli_num_rows($mData) == 0)
    {
        exit("FAIL-No Picks for this task type");
    }

    while ($mRow = mysqli_fetch_assoc($mData))
    {
        //      exit("FAIL-TEST1-".$mDataQuery);
        if ($mRow['processed'] == null)
        {
            continue;
        }
        $mStatus = "DATA:documentReferenceinput:" . $mRow['document_reference'] . "::skipapdocumentReference";
        exit($mStatus);
    }

    exit("FAIL-No Picks for this task type");
}

// post pick
elseif (($mFunction != null) && (strtolower($mFunction) == "postpick"))
{
    $mErrMsg = "";
    $mToPlt = "";
    $mToLocHash = "";
    $mPickQty = "";
    $mDocumentRef = "";
    // 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);

    //    exit("FAIL-TEST1-".$mFilter);

    // Create Associative Array by Exploding Array Elements on :
    for ($i = 0; $i < count($mArray1); $i++)
    {
        $s = 0;
        $e = 0;
        $k1 = $mArray1[$i];
        $s = strpos($k1, ":");
        if ($s >= 0)
        {
            $k2 = substr($k1, 0, $s);
            $v2 = substr($k1, $s + 1);
        }
        if (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) == "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) == "documentreference")
        {
            $mDocumentRef = trim($v2);
        }
        elseif (strtolower($k2) == "locationcode")
        {
            $mLocationCode = strtoupper(trim($v2));
        }
        elseif (strtolower($k2) == "aisle")
        {
            $mAisle = trim($v2);
        }
        elseif ($k2 == "tasktype")
        {
            $mTaskType = strtoupper(trim($v2));
        }
        elseif ($k2 == "train")
        {
            $mTrain = 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) == "vldqty"))
        {
            $mVldQty = floatval($v2);
        }
        elseif ($k2 == "currentUser")
        {
            $mCurrentUser = trim($v2);
        }
        elseif ($k2 == "transactionTypeId")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
        elseif ($k2 == "transactionType")
        {
            $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);

    if ((!$mPickQty) || ($mPickQty == "") || ($mPickQty == null))
    {
        $mPickQty = $mVldQty;
    }

    $mStatus = updatePickDetail($mHost, $mUser, $mPwd, $mDbName, $mPickDtlId, $mPickInvId, $mSerialReference, $mPickQty, $mCurrentUser, $mTransactionTypeId, $mToPlt, $mToLocHash, $mTaskType, $mDocumentRef, 0, 0, $mConnect, $mRdtStart, $mRdtEnd);

    exit($mStatus);
}

// Skip / Resequence Current Pick Task
elseif (($mFunction != null) && ($mFunction == "skippick"))
{
    $mErrMsg = "";
    $mToPlt = "";
    $mToLocHash = "";
    $mPickQty = "";
    $mDocumentRef = "";
    // 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);

    //    exit("FAIL-TEST1-".$mFilter);

    // Create Associative Array by Exploding Array Elements on :
    for ($i = 0; $i < count($mArray1); $i++)
    {
        $s = 0;
        $e = 0;
        $k1 = $mArray1[$i];
        $s = strpos($k1, ":");

        if ($s >= 0)
        {
            $k2 = substr($k1, 0, $s);
            $v2 = substr($k1, $s + 1);
        }

        if (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) == "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) == "documentreference")
        {
            $mDocumentRef = trim($v2);
        }
        elseif (strtolower($k2) == "locationcode")
        {
            $mLocationCode = strtoupper(trim($v2));
        }
        elseif (strtolower($k2) == "aisle")
        {
            $mAisle = trim($v2);
        }
        elseif ($k2 == "tasktype")
        {
            $mTaskType = strtoupper(trim($v2));
        }
        elseif ($k2 == "train")
        {
            $mTrain = 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) == "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, $mPickQty, $mCurrentUser, $mTransactionTypeId, $mToPlt, $mToLocHash, $mTaskType, $mDocumentRef, 0, 1, $mConnect, $mRdtStart, $mRdtEnd);
    if (substr($mStatus, 0, 2) == "OK")
    {
        $mStatus = getPick($mHost, $mUser, $mPwd, $mDbName, $mConnect, $mFilter, '', '', 1);
    }

    exit($mStatus);
}

// Missing Pick Serial
// Skip / Resequence Current Pick Task
elseif (($mFunction != null) && ($mFunction == "missingpickserial"))
{
    $mErrMsg = "";
    $mToPlt = "";
    $mToLocHash = "";
    $mPickQty = "";
    $mDocumentRef = "";
    // 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);

    //    exit("FAIL-TEST1-".$mFilter);

    // Create Associative Array by Exploding Array Elements on :
    for ($i = 0; $i < count($mArray1); $i++)
    {
        $s = 0;
        $e = 0;
        $k1 = $mArray1[$i];
        $s = strpos($k1, ":");
        if ($s >= 0)
        {
            $k2 = substr($k1, 0, $s);
            $v2 = substr($k1, $s + 1);
        }

        if (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) == "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) == "documentreference")
        {
            $mDocumentRef = trim($v2);
        }
        elseif (strtolower($k2) == "locationcode")
        {
            $mLocationCode = strtoupper(trim($v2));
        }
        elseif (strtolower($k2) == "aisle")
        {
            $mAisle = trim($v2);
        }
        elseif ($k2 == "tasktype")
        {
            $mTaskType = strtoupper(trim($v2));
        }
        elseif ($k2 == "train")
        {
            $mTrain = 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) == "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, $mPickQty, $mCurrentUser, $mTransactionTypeId, $mToPlt, $mToLocHash, $mTaskType, $mDocumentRef, 1, 0, $mConnect, $mRdtStart, $mRdtEnd);
    if (substr($mStatus, 0, 2) == "OK")
    {
        $mStatus = getPick($mHost, $mUser, $mPwd, $mDbName, $mConnect, $mFilter, '', '', 1);
    }

    exit($mStatus);
}

// Get task_type list for select
elseif (($mFunction != null) && (strtolower($mFunction) == "getpicklist"))
{
    $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 task_type list for select
elseif (($mFunction != null) && (strtolower($mFunction) == "gettasktypelist"))
{
    $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 = getTaskTypeList($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mReference, $mKey, $mOffset);
    echo $mStatus;
    return;
}

// Get task_type list for select
elseif (($mFunction != null) && (strtolower($mFunction) == "getzonelist"))
{
    $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 = getZoneList($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mReference, $mKey, $mOffset);
    echo $mStatus;
    return;
}

// check for mixed zone pallet
elseif ((!empty($mFunction)) && (strtolower($mFunction) == "checkmixedzoneplt"))
{
    $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 == "plt")
        {
            $mPlt = trim($v2);
        }
        elseif ($k2 == "zone")
        {
            $mZone = trim($v2);
        }
        elseif ($k2 == "currentUser")
        {
            $mCurrentUser = trim($v2);
        }
        elseif ($k2 == "transactionType")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
    }
    // mysql connection
    $mConnection = mysqli_connect($mHost, $mUser, $mPwd, $mDbName);
    if (!$mConnection)
    {
        exit("FAIL-Connect failed: " . mysqli_connect_errno() . " : " . mysqli_connect_error());
    }

    $mDataQuery = "SELECT 
            inventory_master.part_number,
            inventory_master.serial_reference,
            pickdetail.zone_destination,
            pickdetail.serial_reference
        FROM 
            inventory_master
        LEFT JOIN (
            SELECT 
                zone_destination, 
                CASE 
                    WHEN serial_reference_scanned IS NOT NULL THEN serial_reference_scanned 
                    ELSE serial_reference 
                END AS serial_reference 
            FROM 
                pick_detail
        ) AS pickdetail 
        ON 
            inventory_master.serial_reference = pickdetail.serial_reference
        WHERE 
            inventory_master.tag_reference = '$mPlt'";
    if (!$mData = mysqli_query($mConnection, $mDataQuery))
    {
        exit("FAIL-" . mysqli_error($mConnection) . "-" . $mDataQuery);
    }

    if (mysqli_num_rows($mData) == 0)
    {
        exit("OK  -empty pallet");
    }

    $mPrvZone = null;
    while ($mRow = mysqli_fetch_assoc($mData))
    {
        if ($mPrvZone == null)
        {
            $mPrvZone = $mRow['zone_destination'];
        }
        if ($mRow['zone_destination'] != $mPrvZone)
        {
            exit("FAIL-Mixed zone pallet is not allowed");
        }
        if ($mRow['zone_destination'] != $mZone)
        {
            exit("FAIL-Mixed zone pallet is not allowed");
        }
    }
    exit("OK  -checkmixedzoneplt");
}

// Get the train list for select
elseif (($mFunction != null) && (strtolower($mFunction) == "gettrainlist"))
{
    $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 = getTrainList($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mReference, $mKey, $mOffset);
    echo $mStatus;
    return;
}

// Get the train list for select
if (($mFunction != null) && (strtolower($mFunction) == "gettrainloclist"))
{
    //  echo("FAIL-TEST2");
    $mErrMsg = "";
    $mReference = "";
    $mTaskType = "";
    $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 == "tasktype")
        {
            $mTaskType = 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 = getTrainLocList($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mReference, $mTaskType, $mKey, $mOffset);
    echo $mStatus;
    return;
}

// Print Pick Label
elseif (($mFunction != null) && (strtolower($mFunction) == "printpicklabel"))
{
    $mErrMsg = "";
    $mPickDtlId = 0;
    $mPrinter = "";
    $mLabel = "";
    $mSerialReference = "";
    $mQty = 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 == "pickdetailid")
        {
            $mPickDtlId = trim($v2);
        }
        elseif ($k2 == "printer")
        {
            $mPrinter = trim($v2);
        }
        elseif ($k2 == "serialreference")
        {
            $mSerialReference = trim($v2);
        }
        elseif ($k2 == "partnumber")
        {
            $mPartNumber = trim($v2);
        }
        elseif ($k2 == "qty")
        {
            $mQty = trim($v2);
        }
        elseif ($k2 == "currentUser")
        {
            $mCurrentUser = trim($v2);
        }
        elseif ($k2 == "transactionType")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
        elseif ($k2 == "transactionTypeId")
        {
            $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";
    $mDataQuery .= " inventory_master.inventory_qty/part.conversion_factor AS inventory_qty";
    $mDataQuery .= ",part.full_box_pick AS full_box_pick";
    $mDataQuery .= ",location_type.no_serial_scan";
    $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 .= " WHERE inventory_master.serial_reference='" . $mSerialReference . "'";
    $mDataQuery .= " AND (part.part_number='" . $mPartNumber . "')";
    $mDataQuery .= " LIMIT 1";
    if (!$mData = mysqli_query($mConnection, $mDataQuery))
    {
        exit("FAIL-21" . mysqli_error($mConnection) . "-" . $mDataQuery);
    }
    //    exit("FAIL-21".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
    if (mysqli_num_rows($mData) > 0)
    {
        list($mInvQty, $mFullBox, $mNoSerial) = mysqli_fetch_row($mData);
    }
    if ($mInvQty > 0 && $mInvQty < $mQty)
    {
        $mQty = $mInvQty;
    }
    // No label for full-Box
//  if ($mFullBox == 1)
//  {
//      exit ("OK  -Full Box");
//  }
// Get Printer Address
    $mPrinterAddress = $mPrinter;
    $mDataQuery = "SELECT
            id AS id,
            printer_address AS printer_address,
            description AS printer_name
        FROM printer_mapping
        WHERE
            printer_code='{$mPrinter}'
            OR printer_address='{$mPrinter}'
        LIMIT 1";

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

    if (mysqli_num_rows($mData) > 0)
    {
        list($mPrintId, $mPrinterAddress) = mysqli_fetch_row($mData);
    }

    // Check if the printer is connected
    if (ping($mPrinterAddress) == false)
    {
        //        exit ("OKMS-Printer ".$mPrinterAddress." Not Found");
        $mPrinterAddress = "";
    }
    //    if (($mFullBox == 1 && $mSerialReference != "") || ($mQty <> 0))
    try
    {
        if (($mSerialReference != "") || ($mQty <> 0))
        {
            if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/kuk/reports/picklabelpdf.php'))
            {
                require_once($_SERVER['DOCUMENT_ROOT'] . '/kuk/reports/picklabelpdf.php');
                $mErrMsg = labelPrint($mPrinterAddress, $mLabel, $mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, "n", $mPickDtlId, 0, $mSerialReference, $mQty);
            }
            elseif (file_exists($_SERVER['DOCUMENT_ROOT'] . '/kuk/reports/picklabelpdf.php'))
            {
                require_once($_SERVER['DOCUMENT_ROOT'] . '/kuk/reports/picklabelpdf.php');
                $mErrMsg = labelPrint($mPrinterAddress, $mLabel, $mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, "n", $mPickDtlId, 0, $mSerialReference, $mQty);
            }
            else
            {
                exit("FAIL-Include error");
            }
        }
    }
    catch (Exception $e)
    {
        exit("OKMS-No Printer ".$e);
    }

    if ($mErrMsg == "")
    {
        $mErrMsg = "DATA:rdtMessage:Printer Error";
    }
    if (substr($mErrMsg,0,2) != "FA" && substr($mErrMsg,0,2) != "OK" && substr($mErrMsg,0,2) != "DA")
    {
        $mErrMsg = "OK  -".$mErrMsg;
    }
    exit($mErrMsg);
}

// Post PTTT
elseif (($mFunction != null) && (strtolower($mFunction) == "postpttt"))
{
    $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 == "serialreference")
        {
            $mSerialReference = trim($v2);
        }
        elseif ($k2 == "partnumber")
        {
            $mPartNumber = trim($v2);
        }
        elseif ($k2 == "tolocationcode")
        {
            $mToLoc = trim($v2);
        }
        elseif ($k2 == "currentUser")
        {
            $mCurrentUser = trim($v2);
        }
        elseif ($k2 == "transactionType")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
        elseif ($k2 == "transactionTypeId")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
    }

    // mysql connection
    $mConnection = mysqli_connect($mHost, $mUser, $mPwd, $mDbName);
    if (!$mConnection)
    {
        return "FAIL-Connect failed: " . mysqli_connect_errno() . " : " . mysqli_connect_error();
    }

    $mDataQuery = "SELECT
            tag_reference
        FROM inventory_master
        WHERE
            serial_reference='{$mSerialReference}'
            OR tag_reference='{$mSerialReference}'
        LIMIT 1";

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

    if (mysqli_num_rows($mData) > 0)
    {
        list($mTagReference) = mysqli_fetch_row($mData);
    }
    else
    {
        $mTagReference = $mSerialReference;
    }

    $mDataQuery = "SELECT train_location_code FROM train_locations WHERE train_location_hash='" . $mToLoc . "' LIMIT 1";
    if (!$mData = mysqli_query($mConnection, $mDataQuery))
    {
        exit("FAIL-1" . mysqli_error($mConnection) . "-" . $mDataQuery);
    }
    if (mysqli_num_rows($mData) > 0)
    {
        list($mToLocCode) = mysqli_fetch_row($mData);
    }
    else
    {
        $mToLocCode = $mToLoc;
    }
// if serial scanned - find matching pallet tag.
    $mDataQuery = "SELECT tag_reference FROM inventory_master WHERE serial_reference='$mTagReference' LIMIT 1";
    if (!$mData = mysqli_query($mConnection, $mDataQuery))
    {
        exit("FAIL-1" . mysqli_error($mConnection) . "-" . $mDataQuery);
    }
    if (mysqli_num_rows($mData) > 0)
    {
        list($tagRef) = mysqli_fetch_row($mData);
        if (!empty($tagRef))
        {
            $mTagReference = $tagRef;
        }
    }
// Update inventory with Train_trolley location
    $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.part_number AS part_number,inventory_master.serial_reference AS serial_reference,
                    inventory_master.ran_or_order,inventory_master.picked_qty AS picked_qty,inventory_master.location_code AS location_code,
                    inventory_master.conversion_factor AS conversion_factor
            FROM inventory_master 
            WHERE tag_reference='$mTagReference' or serial_reference='$mTagReference'";
    if (!$mData = mysqli_query($mConnection, $mDataQuery))
    {
        exit("FAIL-1" . mysqli_error($mConnection) . "-" . $mDataQuery);
    }
    if (mysqli_num_rows($mData) == 0)
    {
        exit("FAIL-This pallet is empty");
    }
    $mPickedQty = 0;
    while ($mRow = mysqli_fetch_assoc($mData))
    {
        $mPickedQty .= $mRow['picked_qty'];
        $mTranQuery = "UPDATE inventory_master 
                SET location_code='$mToLocCode',
                current_location_id=null,location_id=null,
                parent_tag_id=null, tag_reference=null,
                inventory_status_id=(SELECT id FROM inventory_status WHERE upper(inventory_status_code)='PKD' LIMIT 1),
                last_updated=now(),last_updated_by='$mCurrentUser'
                WHERE id = ".$mRow['id']." LIMIT 1";
        if (!mysqli_query($mConnection, $mTranQuery))
        {
            exit("FAIL-1" . mysqli_error($mConnection) . "-" . $mDataQuery);
        }
        $mRanOrder = $mRow['ran_or_order'];
        $mDocumentReference = $mRow['ran_or_order'];
        $mInvId = ($mRow['id']);
        $mPlt = $mTagReference;
        if (!empty($mDocumentReference))
        {
            $mTranQuery = "INSERT INTO transaction_history (id,associated_document_reference,short_code,part_number,serial_reference,ran_or_order,txn_qty,source_tag,from_location_code,to_location_code,date_created,created_by,last_updated,last_updated_by,transaction_reference_code,from_plt,conversion_factor)";
            $mTranQuery .=" VALUES(DEFAULT,'".$mDocumentReference."','PTTT','".($mRow['part_number'])."','".($mRow['serial_reference'])."','".$mRanOrder."',".($mRow['picked_qty']).",'".$mPlt."','".($mRow['location_code'])."','".$mToLocCode."',now(),'".$mCurrentUser."',now(),'".$mCurrentUser."','PTTT','".$mRow['plt_number']."',".$mRow['conversion_factor'].")";   
        }
        else
        {
            $mTranQuery = "INSERT INTO transaction_history (id,associated_document_reference,short_code,part_number,serial_reference,ran_or_order,txn_qty,source_tag,from_location_code,to_location_code,date_created,created_by,last_updated,last_updated_by,transaction_reference_code,from_plt,conversion_factor)"; 
            $mTranQuery .=" VALUES(DEFAULT,null,'PTM','".($mRow['part_number'])."','".($mRow['serial_reference'])."','".$mRanOrder."',".($mRow['picked_qty']).",'".$mPlt."','".($mRow['location_code'])."','".$mToLocCode."',now(),'".$mCurrentUser."',now(),'".$mCurrentUser."','PTM','".$mRow['plt_number']."',".$mRow['conversion_factor'].")";    
        }
        if (!mysqli_query($mConnection,$mTranQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mTranQuery;
    }
    if (!empty($mTagReference))
    {
        try
        {
            $mTranQuery = "DELETE FROM tag WHERE tag_reference='$mTagReference' LIMIT 1";
            if (!mysqli_query($mConnection,$mTranQuery))
                return "FAIL-".mysqli_error($mConnection)."-".$mTranQuery;
        }
        catch(Exception $e)
        {
            $mTranQuery = "UPDATE tag SET tag_reference='$mTagReference.DEL' WHERE tag_reference='$mTagReference' LIMIT 1";
            if (!mysqli_query($mConnection,$mTranQuery))
                return "FAIL-".mysqli_error($mConnection)."-".$mTranQuery;
        }
    }
/*
    // Get Server Data from URL
    $mJsonArray = array();
    $mJsonArray['tagReference'] = $mTagReference;
    $mJsonArray['locationCode'] = $mToLocCode;
    $mJsonArray['userId'] = $mCurrentUser;
    //    $mJsonArray['transactionCode'] = $mTransactionType;
// Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
    }
    catch (Exception $e)
    {
        exit("FAIL-Json Error");
    }

    // Replace default Server Tomcat Service
    $mConnectp = str_replace(":8081/vantec", ":8095/pick", $mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect, ":8081");
        $mConnectp = substr($mConnect, 0, $e) . ":8095/pick/";
    }

    $ch = curl_init();

    try
    {
        $mToLocCode = urlencode($mToLocCode);
        $mUrl = "ptttTransaction?tagReference=" . $mTagReference . "&locationCode=" . $mToLocCode . "&userId=" . $mCurrentUser;
        //        $mUrl = "ptttTransaction";
        curl_setopt($ch, CURLOPT_URL, $mConnectp . $mUrl);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_POST, 0);
        //        curl_setopt($ch, CURLOPT_POSTFIELDS, $mJsonObject);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $mResult = curl_exec($ch);
        $mErrors = curl_error($ch);
        $mResponse = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($mResponse != "200")
        {
            $mUrl = str_replace("&", "|AND|", $mUrl);
            print_r("FAIL-Unexpected System Error -" . $mResult . ":" . $mResponse . ":" . $mErrors . ":" . $mConnectp . $mUrl . ":" . $mJsonObject);
        }
        else
        {
            //            print_r("FAIL-OK -1".$mResult.":2".$mResponse.":3".$mErrors.":".$mJsonObject.":".$mConnectp);
//            $mJsonArray = json_decode($mResult, true);
            $mResult = str_replace("OK -", "OK  -", $mResult);
            $mResult = str_replace("FAIL -", "FAIL-", $mResult);
            if (substr($mResult, 0, 2) == "OK")
            {
                exit("OK  -" . $mResult);
            }
            else
            {
                exit("FAIL-" . $mResult);
            }
        }
    }
    catch (Exception $e)
    {
        exit("FAIL-Connection Error at - " . $mConnect . $mFilter . ":" . $e);
    }
*/
    exit("OK  -postpttt");
}

// Close Train
elseif (($mFunction != null) && (strtolower($mFunction) == "closetrain"))
{
    $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 == "trolley")
        {
            $mTrolleyReference = trim($v2);
        }
        elseif ($k2 == "currentUser")
        {
            $mCurrentUser = trim($v2);
        }
        elseif ($k2 == "transactionType")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
        elseif ($k2 == "transactionTypeId")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
    }

    // mysql connection
    $mConnection = mysqli_connect($mHost, $mUser, $mPwd, $mDbName);
    if (!$mConnection)
    {
        return "FAIL-Connect failed: " . mysqli_connect_errno() . " : " . mysqli_connect_error();
    }

    $mDataQuery = "SELECT
            train_location_code
        FROM train_locations
        WHERE train_location_hash='{$mTrolleyReference}'
        LIMIT 1";

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

    if (mysqli_num_rows($mData) > 0)
    {
        list($mTrainCode) = mysqli_fetch_row($mData);
    }
    else
    {
        exit("FAIL-Invalid Trolly Reference");
    }

    $mDataQuery = "SELECT
            inventory_master.id AS id
        FROM inventory_master
        WHERE location_code='{$mTrainCode}'
        LIMIT 1";

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

    if (mysqli_num_rows($mData) == 0)
    {
        exit("FAIL-No Picks exist for this Train Trolley");
    }

    // Get Server Data from URL
    $mJsonArray = array();
    $mJsonArray['trainLocation'] = $mTrainCode;
    $mJsonArray['userId'] = $mCurrentUser;
    //    $mJsonArray['transactionCode'] = $mTransactionType;

// Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
    }
    catch (Exception $e)
    {
        exit("FAIL-Json Error");
    }

    // Replace default Server Tomcat Service
    $mConnectp = str_replace(":8081/vantec", ":8095/pick", $mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect, ":8081");
        $mConnectp = substr($mConnect, 0, $e) . ":8095/pick/";
    }

    $ch = curl_init();
    try
    {
        $mTrainCode = urlencode($mTrainCode);
        $mUrl = "closeTrain?trainLocation=" . $mTrainCode . "&userId=" . $mCurrentUser;
        curl_setopt($ch, CURLOPT_URL, $mConnectp . $mUrl);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_POST, 0);
        //        curl_setopt($ch, CURLOPT_POSTFIELDS, $mJsonObject);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $mResult = curl_exec($ch);
        $mErrors = curl_error($ch);
        $mResponse = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($mResponse != "200")
        {
            $mUrl = str_replace("&", "|AND|", $mUrl);
            print_r("FAIL-Unexpected System Error -" . $mResult . ":" . $mResponse . ":" . $mErrors . ":" . $mConnectp . $mUrl . ":" . $mJsonObject);
        }
        else
        {
            //            print_r("FAIL-OK -1".$mResult.":2".$mResponse.":3".$mErrors.":".$mJsonObject.":".$mConnectp);
//            $mJsonArray = json_decode($mResult, true);
            $mResult = str_replace("OK -", "OK  -", $mResult);
            $mResult = str_replace("FAIL -", "FAIL-", $mResult);
            if (substr($mResult, 0, 2) == "OK")
            {
                exit("OK  -" . $mResult);
            }
            else
            {
                exit("FAIL-" . $mResult);
            }
        }
    }
    catch (Exception $e)
    {
        exit("FAIL-Connection Error at - " . $mConnect . $mFilter . ":" . $e);
    }

    exit("OKMS-Train is Closed");
}

// Allocate Parts
elseif (($mFunction != null) && (strtolower($mFunction) == "allocateparts"))
{
    $mErrMsg = "";
    // Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=", ":", $mFilter);
    $mFilter = str_replace("&", ",", $mFilter);
    // Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",", $mFilter);
    // Create Associative Array by Exploding Array Elements on :
    foreach ($mArray1 as $k1 => $v1)
    {
        list($k2, $v2) = explode(":", $mArray1[$k1]);
        if ($k2 == "partnumber")
        {
            $mPartNumber = trim($v2);
        }
        elseif ($k2 == "currentUser")
        {
            $mCurrentUser = trim($v2);
        }
        elseif ($k2 == "transactionType")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
        elseif ($k2 == "transactionTypeId")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
    }
    $mResult = allocatePart($mHost, $mUser, $mPwd, $mDbName, $mConnect, $mCurrentUser, $mPartNumber);
    if (substr($mResult, 0, 2) == "FA")
    {
        exit($mResult);
    }

    exit("OK  -allocateparts");
}

// Allocate Parts
elseif (($mFunction != null) && (strtolower($mFunction) == "createpickserial"))
{
    $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 == "currentUser")
        {
            $mCurrentUser = trim($v2);
        }
        elseif ($k2 == "transactionType")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
        elseif ($k2 == "transactionTypeId")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
    }
    $mResult = createPickSerial($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mAllocationId, $mSerialReference, $mPartNumber, $mQuantity);
    if (substr($mResult, 0, 2) == "FA")
    {
        exit($mResult);
    }
    exit("OK  -createpickserial");
}

// ----------------------------------------------------------------------------------------
// Main Functions
// ----------------------------------------------------------------------------------------

// Get Next Pick
function getPick($mHost, $mUser, $mPwd, $mDbName, $mConnect, $mFilter, $mLost = null)
{
    $mReturn = "";

    $mErrMsg = "";
    $mToPlt = "";
    $mTrain = "";
    $mZone = "";
    // Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=", ":", $mFilter);
    $mFilter = str_replace("&", ",", $mFilter);
    // Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",", $mFilter);

    // Create Associative Array by Exploding Array Elements on :
    for ($i = 0; $i < count($mArray1); $i++)
    {
        $s = 0;
        $e = 0;
        $k1 = $mArray1[$i];
        $s = strpos($k1, ":");
        if ($s >= 0)
        {
            $k2 = substr($k1, 0, $s);
            $v2 = substr($k1, $s + 1);
        }
        if ($k2 == "customerreference")
        {
            $mCustomerRef = trim($v2);
        }
        elseif ($k2 == "documentreference")
        {
            $mDocumentRef = trim($v2);
        }
        elseif ($k2 == "locationcode")
        {
            $mLocationCode = strtoupper(trim($v2));
        }
        elseif ($k2 == "tasktype")
        {
            $mTaskType = strtoupper(trim($v2));
        }
        elseif ($k2 == "zone")
        {
            $mZone = strtoupper(trim($v2));
        }
        elseif ($k2 == "aisle")
        {
            $mAisle = trim($v2);
        }
        elseif ($k2 == "train")
        {
            $mTrain = trim($v2);
        }
        elseif ($k2 == "toplt")
        {
            $mToPlt = trim($v2);
        }
        elseif ($k2 == "printername")
        {
            $mPrinterName = trim($v2);
        }
        elseif ($k2 == "printeraddr")
        {
            $mPrinterAddr = trim($v2);
        }
        elseif ($k2 == "currentUser")
        {
            $mCurrentUser = trim($v2);
        }
        elseif ($k2 == "transactionType")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
        elseif ($k2 == "transactionTypeId")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
    }

    if ($mAisle == "NONE")
    {
        return "OK  -";
    }
    if (($mCustomerReferenceCode == null || $mCustomerReferenceCode == "") && ($mDocumentRef == null || $mDocumentRef == ""))
    {
        return "FAIL-noPickRef";
    }

    // Send request for next pick task
//  URL: http://van-kuk-test:8095/pick/getPickDetail
/*
    {
        "id": 7775,
        "inventoryMasterId": 1292,
        "pickBodyId": 4611,
        "partId": null,
        "documentReference": "PCK000109",
        "partNumber": "0902102739",
        "serialReference": "SAINTESTwer",
        "serialReferenceScanned": null,
        "locationCode": "AA",
        "qtyAllocated": 1,
        "qtyScanned": null,
        "bodyQtyAllocated":1,
        "pickPriority": null,
        "processed": false,
        "blocked": null,
        "inUseBy": null,
        "zoneDestination": "PT",
        "pickSequence": "AAA11AA",
        "transactionCode": "PBTP",
        "createdBy": "admin",
        "dateCreated": 1623746995000,
        "updatedBy": "admin",
        "dateUpdated": 1623746995000,
        "message": "OK",
        "isStandardPick": true,
        "noSerialScan": true,
        "isFullBoxPick": false,
        "isModular": false,
        "orderBodies":
        [
            {
                "lineNo": 4810,
                "orderBodyId": 41229
            }
        ]
    }
*/

    // Get Server Data from URL
    $mJsonArray = array();
    $mJsonArray['pickDocRef'] = $mDocumentRef;
    $mJsonArray['pickTask'] = $mTaskType;
    $mJsonArray['zone'] = $mZone;
    $mJsonArray['train'] = $mTrain;
    $mJsonArray['userId'] = $mCurrentUser;
    $mJsonArray['transactionCode'] = $mTransactionTypeId;
    // Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
    }
    catch (Exception $e)
    {
        exit("FAIL-Json Error");
    }
    // Replace default Server Tomcat Service
    $mConnectp = str_replace(":8081/vantec", ":8095/pick", $mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect, ":8081");
        $mConnectp = substr($mConnect, 0, $e) . ":8095/pick/";
    }
    $ch = curl_init();
    try
    {
        //        $mUrl = "getPickDetail?pickDocRef=".$mDocumentRef."&pickTask=".$mTaskType."&train=".$mTrain."&userId=".$mCurrentUser;
        $mUrl = "getPickDetail";
        curl_setopt($ch, CURLOPT_URL, $mConnectp . $mUrl);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $mJsonObject);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $mResult = curl_exec($ch);
        $mErrors = curl_error($ch);
        $mResponse = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);
        if ($mResponse != "200")
        {
            $mUrl = str_replace("&", "|AND|", $mUrl);
            print_r("FAIL-Unexpected System Error -" . $mResult . ":" . $mResponse . ":" . $mErrors . ":" . $mConnectp . $mUrl . ":" . $mJsonObject);
        }
        else
        {
            $mJsonArray = json_decode($mResult, true);

            if (substr($mJsonArray['message'], 0, 2) == "OK")
            {
                // Check Fixed Location Code
                $mToLocCode = $mJsonArray['tolocationCode'];
                
// mysql connection
                $mConnection = mysqli_connect($mHost, $mUser, $mPwd, $mDbName);
                if (!$mConnection)
                {
                    return "FAIL-Connect failed: " . mysqli_connect_errno() . " : " . mysqli_connect_error();
                }
                
                if (empty($mToLocCode))
                {
/*
// site Fixed location
                    $mInvQuery = "SELECT location.location_code 
                                    FROM pick_header
                                    JOIN order_header ON order_header.pick_header_id=pick_header.id
                                    JOIN site on order_header.site_id=site.id
                                    JOIN location ON site.default_location_id=location.id
                                    WHERE
                                    pick_header.document_reference='".$mJsonArray['documentReference']."'
                                    AND site.site_name='POT'
                                    LIMIT 1
                                ";
                    if (!$mInvData = mysqli_query($mConnection, $mInvQuery))
                    {
                        return "FAIL-" . mysqli_error($mConnection) . "-" . $mInvQuery;
                    }
                    if (mysqli_num_rows($mInvData) > 0)
                    {
                        list($mToLocCode) = mysqli_fetch_row($mInvData);
                    }

// order_type Fixed Location
                    if (empty($mToLocCode))
                    {
                        $mInvQuery = "SELECT location.location_code FROM pick_header 
                                        JOIN order_header ON order_header.pick_header_id=pick_header.id
                                        JOIN order_type ON order_header.order_type=order_type.order_type_code
                                        AND 
                                        (
                                            LEFT(order_header.customer_reference, LENGTH(order_type.order_type_prefix)) = order_type.order_type_prefix
                                            OR order_type.order_type_prefix IS null OR order_type.order_type_prefix = ''
                                        )
                                        LEFT JOIN location ON order_type.fixed_to_location_id=location.id 
                                        WHERE pick_header.document_reference='" . $mJsonArray['documentReference'] . "' LIMIT 1
                                    ";
                        if (!$mInvData = mysqli_query($mConnection, $mInvQuery))
                        {
                            return "FAIL-" . mysqli_error($mConnection) . "-" . $mInvQuery;
                        }
                        if (mysqli_num_rows($mInvData) > 0)
                        {
                            list($mToLocCode) = mysqli_fetch_row($mInvData);
                        }
                    }
*/
                }
                // Full Box
                if ($mJsonArray['isFullBoxPick'] == 1)
                {
                    $mRdtPrompt = "FULL BOX";
                }
                else
                {
                    $mRdtPrompt = "";
                }

                // get location hash
                $mInvQuery = "SELECT location.location_hash AS location_hash, location_type.no_serial_scan AS no_serial_scan FROM location LEFT JOIN location_type ON location.location_type_id=location_type.id WHERE location.location_code='" . $mJsonArray['locationCode'] . "' LIMIT 1";
                if (!$mInvData = mysqli_query($mConnection, $mInvQuery))
                {
                    return "FAIL-" . mysqli_error($mConnection) . "-" . $mInvQuery;
                }
                list($mLocHash) = mysqli_fetch_row($mInvData);
                // get part description
                $mPartDesc = "";
                $mInvQuery = "SELECT part_description FROM part WHERE part_number = '{$mJsonArray['partNumber']}' LIMIT 1";
                if (!$mInvData = mysqli_query($mConnection, $mInvQuery))
                {
                    return "FAIL-" . mysqli_error($mConnection) . "-" . $mInvQuery;
                }
                list($mPartDesc) = mysqli_fetch_row($mInvData);

                //Gets Part Weight
                $mPartWeight = getPartNumberWeight($mJsonArray['partNumber'], $mConnection);

                $mRdtPrompt .= $mPartDesc;

                // return Pick Details to the screen
                if ($mJsonArray['blocked'] != 1)
                {
                    if ($mJsonArray['NoSerialScan'] == 1)
                    {
                        if ($mToPlt == "")
                        {
                            $mReturn = "DATA:aisleCode:{$mAisle},fromLocationHashCodecontent:{$mJsonArray['locationCode']},serialReferencevalue:{$mJsonArray['serialReference']},partNumbervalue:{$mJsonArray['partNumber']},qtyAllocatedvalue:{$mJsonArray['qtyAllocated']},orderQtyvalue:{$mJsonArray['bodyQtyAllocated']},allocationId:{$mJsonArray['id']},sequencingRequestId:{$mJsonArray['inventoryMasterId']},zone:{$mJsonArray['zoneDestination']},boxCountQty:,toLocationHashCodecontent:{$mToLocCode},wiCode:,rdttime:start,rdtMessage:{$mRdtPrompt},partWeight:{$mPartWeight}";
                        }
                        else
                        {
                            $mReturn = "DATA:aisleCode:{$mAisle},fromLocationHashCodecontent:{$mJsonArray['locationCode']},serialReferencevalue:{$mJsonArray['serialReference']},partNumbervalue:{$mJsonArray['partNumber']},qtyAllocatedvalue:{$mJsonArray['qtyAllocated']},orderQtyvalue:{$mJsonArray['bodyQtyAllocated']},allocationId:{$mJsonArray['id']},sequencingRequestId:{$mJsonArray['inventoryMasterId']},zone:{$mJsonArray['zoneDestination']},boxCountQty:,toLocationHashCodecontent:{$mToLocCode},wiCode:,rdttime:start,rdtMessage:{$mRdtPrompt},partWeight:{$mPartWeight}";
                        }
                    }
                    else
                    {
                        if ($mToPlt == "")
                        {
                            $mReturn = "DATA:aisleCode:{$mAisle},fromLocationHashCodecontent:{$mJsonArray['locationCode']},serialReferencecontent:{$mJsonArray['serialReference']},partNumbervalue:{$mJsonArray['partNumber']},orderQtyvalue:{$mJsonArray['bodyQtyAllocated']},allocationId:{$mJsonArray['id']},sequencingRequestId:{$mJsonArray['inventoryMasterId']},zone:{$mJsonArray['zoneDestination']},boxCountQty:,toLocationHashCodecontent:{$mToLocCode},wiCode:,rdttime:start,rdtMessage:{$mRdtPrompt},partWeight:{$mPartWeight}";
                            if ($mJsonArray['isFullBoxPick'] == 1)
                            {
                                $mReturn .= ",qtyAllocatedvalue:{$mJsonArray['qtyAllocated']}";
                            }
                            else
                            {
                                $mReturn .= ",qtyAllocatedvalue:{$mJsonArray['qtyAllocated']}";
                            }
                        }
                        else
                        {
                            $mReturn = "DATA:aisleCode:{$mAisle},fromLocationHashCodecontent:{$mJsonArray['locationCode']},serialReferencecontent:{$mJsonArray['serialReference']},partNumbervalue:{$mJsonArray['partNumber']},orderQtyvalue:{$mJsonArray['bodyQtyAllocated']},allocationId:{$mJsonArray['id']},sequencingRequestId:{$mJsonArray['inventoryMasterId']},zone:{$mJsonArray['zoneDestination']},boxCountQty:,toLocationHashCodecontent:{$mToLocCode},wiCode:,rdttime:start,rdtMessage:{$mRdtPrompt},partWeight:{$mPartWeight}";
                            if ($mJsonArray['isFullBoxPick'] == 1)
                            {
                                $mReturn .= ",qtyAllocatedvalue:{$mJsonArray['qtyAllocated']}";
                            }
                            else
                            {
                                $mReturn .= ",qtyAllocatedvalue:{$mJsonArray['qtyAllocated']}";
                            }
                        }
                        if ($mLost == 1)
                        {
                            $mReturn .= ",fromLocationHashCodeInput:::skipfromLocationHashCode";
                        }
                        else
                        {
                            if ($mToPlt != "")
                            {
                                $mReturn .= ",fromLocationHashCodeInput:::skipfromLocationHashCode";
                            }
                        }
                        // $mReturn .= ",fromLocationHashCodeInput:".$mLocHash;
                    }
                }
                else
                {
                    $mRdtPrompt = "This task is BLOCKED - F2 To Skip";
                    if ($mToPlt == "")
                    {
                        $mReturn = "DATA:aisleCode:{$mAisle},fromLocationHashCodecontent:BLOCKED:HHHPPHPHPP,serialReferencecontent:BLOCKED:HHHPPHPHPP,partNumbervalue:{$mJsonArray['partNumber']},qtyAllocatedvalue:{$mJsonArray['qtyAllocated']},orderQty:{$mJsonArray['bodyQtyAllocated']},allocationId:{$mJsonArray['id']},sequencingRequestId:{$mJsonArray['inventoryMasterId']},zone:{$mJsonArray['zoneDestination']},boxCountQty:,toLocationHashCodecontent:{$mToLocCode}:HHHHHHHHHH,,wiCode::HHHHHHHHHH,rdttime:start,rdtMessage:{$mRdtPrompt},partWeight:{$mPartWeight}";
                    }
                    else
                    {
                        $mReturn = "DATA:aisleCode:{$mAisle},fromLocationHashCodecontent:BLOCKED:HHHPPHPHPP,serialReferencecontent:BLOCKED:HHHPPHPHPP,partNumbervalue:{$mJsonArray['partNumber']},qtyAllocatedvalue:{$mJsonArray['qtyAllocated']},orderQty:{$mJsonArray['bodyQtyAllocated']},allocationId:{$mJsonArray['id']},sequencingRequestId:{$mJsonArray['inventoryMasterId']},zone:{$mJsonArray['zoneDestination']},boxCountQty:,toLocationHashCodecontent:{$mToLocCode}:HHHHHHHHHH,,wiCode::HHHHHHHHHH,rdttime:start,rdtMessage:{$mRdtPrompt},partWeight:{$mPartWeight}";
                    }
                }
            }
            else
            {
                //                $mReturn = "FAIL-".$mJsonArray['message'];

                $mReturn = $mJsonArray['message'];

                // 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
                        location_type.id AS id
                    FROM pick_header
                        JOIN pick_body ON pick_header.id = pick_body.pick_header_id
                        JOIN part ON pick_body.part_id = part.id
                        JOIN location_type ON part.fixed_location_type_id = location_type.id
                    WHERE
                        pick_header.document_reference='{$mDocumentRef}'
                        AND pick_body.processed<>1
                    LIMIT 1";

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

                $mReturn = $mJsonArray['message'];
                //                return "FAIL-TEST1-".$mDataQuery."-".$mReturn;

                if (mysqli_num_rows($mData) == 0)
                {
                    if ($mTransactionTypeId != "")
                    {
                        if ($mToPlt != "")
                        {
                            $mReturn = "OKMS-" . $mReturn . ",CHGTRAN:" . $mTransactionTypeId . "?DATA:documentReference:,aisleCode:ALL,toPlt:" . $mToPlt;
                        }
                        else
                        {
                            $mReturn = "OKMS-" . $mReturn . ",CHGTRAN:" . $mTransactionTypeId . "?DATA:documentReference:,aisleCode:ALL,toPlt:" . $mToPlt;
                        }
                    }
                    else
                    {
                        $mTransactionTypeId = "PBTP";
                        $mReturn = "OKMS-" . $mReturn . ",CHGTRAN:" . $mTransactionTypeId . "?DATA:documentReference:,aisleCode:ALL,toPlt:" . $mToPlt;
                    }
                }
                else
                {
                    if ($mTransactionTypeId != "")
                    {
                        // Returns Dropdown list for PBTMAAA, PBTMAAAF AND PBTMAAAR transaction
                        if (stripos($mTransactionTypeId, 'PBTMAAA') !== false)
                        {
                            $mReturn = 'OKMS-' . $mReturn . ',DATA:documentReferenceinput:' . $mDocumentRef . '::skipdocumentReference,aisleCode:ALL,toPlt:' . $mToPlt . ',taskType:';
                            $mReturn .= "!allocation:getpicklist?key=AAA";
                        }
                        if ($mToPlt != "")
                        {
                            $mReturn = "OKMS-" . $mReturn . ",DATA:documentReferenceinput:" . $mDocumentRef . "::skipdocumentReference,aisleCode:ALL,toPlt:" . $mToPlt . ",taskType:";
                            $mReturn .= "!allocation:getpicklist?key=pick_type NOT IN|OPEN|'AAA'|COMMA|'EMG|CLOSE|";
                        }
                        else
                        {
                            $mReturn = "OKMS-" . $mReturn . ",DATA:documentReferenceinput:" . $mDocumentRef . "::skipdocumentReference,aisleCode:ALL,toPlt:" . $mToPlt . ",taskType:";
                            $mReturn .= "!allocation:getpicklist?key=pick_type NOT IN|OPEN|'AAA'|COMMA|'EMG'|CLOSE|";
                        }
                    }
                    else
                    {
                        $mTransactionTypeId = "PBTP";
                        $mReturn = "OKMS-" . $mReturn . ",DATA:documentReferenceinput:" . $mDocumentRef . "::skiptaskType,aisleCode:ALL,toPlt:" . $mToPlt . ",taskType:";
                    }

                    if ($mTransactionTypeId == "PBTME")
                    {
                        $mReturn .= "!picking:gettasktypelist?reference=EMG";
                    }
                    else if ($mTransactionTypeId === "PBTMF")
                    {
                        $mReturn .= "!picking:gettasktypelist?reference=FAB";
                    }
                    else if ($mTransactionTypeId === "PBTMR")
                    {
                        $mReturn .= "!picking:gettasktypelist?reference=/documentReference/";
                    }
                    else
                    {
                        $mReturn .= "!picking:gettasktypelist?reference=/documentReference/";
                    }
                }
            }
        }

        return $mReturn;
    }
    catch (Exception $e)
    {
        exit("FAIL-Connection Error at - " . $mConnect . $mFilter . ":" . $e);
    }
}

function updatePickDetail($mHost, $mUser, $mPwd, $mDbName, $mPickDtlId, $mPickInvId, $mSerialReference, $mPickQty, $mCurrentUser, $mTransactionTypeId, $mToPlt, $mToLocHash, $mTaskType, $mDocumentRef, $mMissingSerial = 0, $mSkip = 0, $mConnect = "", $mRdtStart = "", $mRdtEnd = "")
{
    $mMissing = $mMissingSerial;
    if (($mPickDtlId == "") || ($mPickDtlId == null))
    {
        return "FAIL-Incorrect Pick Reference";
    }

    if (($mTransactionTypeId == "") || ($mTransactionTypeId == null))
    {
        return "FAIL-Incorrect Transaction Type";
    }
    if ($mMissingSerial = 0 && $mSkip == 0)
    {
        if (($mSerialReference == "") || ($mSerialReference == null))
        {
            return "FAIL-Invalid Serial Reference";
        }
        if (($mPickQty == "") || ($mPickQty == null) || ($mPickQty <= 0))
        {
            return "FAIL-Invalid Pick Qty.";
        }
    }
    if (($mToPlt != "" && $mToPlt != null) && ($mToLocHash == null || $mToLocHash == ""))
    {
        $mToLocHash = "INTRAN";
    }

    // mysql connection - Use Passed values...
    $mConnection = mysqli_connect($mHost, $mUser, $mPwd, $mDbName) or
    exit("FAIL-Connect failed: " . mysqli_connect_errno() . " : " . mysqli_connect_error());
    /*
        if (($mPartNumber = "") || ($mPartNumber == null))
            $mDataQuery = "SELECT inventory_qty FROM inventory_master WHERE serial_reference = '".$mSerialReference."' LIMIT 1";
        else
            $mDataQuery = "SELECT inventory_qty FROM inventory_master WHERE serial_reference = '".$mSerialReference."' AND part_number = '".$mPartNumber."' LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-18".mysqli_error($mConnection)."-".$mDataQuery);
        if (mysqli_num_rows($mData) > 0)
        {
            list($mInvQty) = mysqli_fetch_row($mData);
            if ($mPickQty > $mInvQty)
            {
                $mPickQty = $mInvQty;
            }
        }
    */
    $mDataQuery = "SELECT
            location.location_code AS location_code
        FROM location
        WHERE
            location.location_hash = '{$mToLocHash}'
            OR location.location_code = '{$mToLocHash}'
        LIMIT 1";

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

    $i = 0;
    if (mysqli_num_rows($mData) > 0)
    {
        list($mLocationCode) = mysqli_fetch_row($mData);
    }
    else
    {
        $mLocationCode = $mToLocHash;
    }

    //    exit("FAIL-18".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData)."-".$mLocationCode);
    /*
        URL: http://van-kuk-test:8095/pick/processPick
        Request object :
        {
        "pickId": 7793,
        "serialScanned": "TESTTRAIN1",
        "pallet": "PL",
        "toLocation": "INTRAN",
        "qtyScanned": 2,
        "userId": "admin",
        "transactionCode": "PBTP",
        "missingSerial": false,
        "skip":false
    }

    */
    // Get Server Data from URL
    $mJsonArray = array();
    $mJsonArray['pickId'] = $mPickDtlId;
    $mJsonArray['serialScanned'] = $mSerialReference;
    $mJsonArray['pallet'] = $mToPlt;
    $mJsonArray['toLocation'] = $mLocationCode;
    $mJsonArray['qtyScanned'] = $mPickQty;
    $mJsonArray['userId'] = $mCurrentUser;
    $mJsonArray['transactionCode'] = $mTransactionTypeId;
    $mJsonArray['missingSerial'] = $mMissing;
    $mJsonArray['skip'] = $mSkip;

    // Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
    }
    catch (Exception $e)
    {
        exit("FAIL-Json Error");
    }

    //    exit("FAIL-TEST1-".$mJsonObject);
// Replace default Server Tomcat Service
    $mConnectp = str_replace(":8081/vantec", ":8095/pick", $mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect, ":8081");
        $mConnectp = substr($mConnect, 0, $e) . ":8095/pick/";
    }

    $ch = curl_init();
    try
    {
        $mUrl = "processPick";
        curl_setopt($ch, CURLOPT_URL, $mConnectp . $mUrl);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $mJsonObject);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $mResult = curl_exec($ch);
        $mErrors = curl_error($ch);
        $mResponse = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);
        if ($mResponse != "200")
        {
            $mUrl = str_replace("&", "|AND|", $mUrl);
            print_r("FAIL-Unexpected System Error -" . $mResult . ":" . $mResponse . ":" . $mErrors . ":" . $mConnectp . $mUrl . ":" . $mJsonObject);
        }
        else
        {
// Delete 0 inventory
/*
        try
        {
            $mDataQuery = "DELETE FROM inventory_master
                        WHERE inventory_qty=0
                        LIMIT 20";
            if (!mysqli_query($mConnection,$mDataQuery))
                    exit("FAIL-18".mysqli_error($mConnection)."-".$mDataQuery);
        }
        catch (Exception $e)
        {
        }
*/
/*
// Delete Picked inventory
            try
            {
                $mDataQuery = "DELETE inventory_master
                                FROM inventory_master
                                JOIN location ON inventory_master.current_location_id = location.id
                                JOIN location_type ON location.location_type_id = location_type.id
                                WHERE
                                inventory_master.serial_reference = '".$mSerialReference."'
                                AND location_type.delete_after_pick = 1
                                AND inventory_master.inventory_qty = inventory_master.picked_qty;
                ";
                if (!mysqli_query($mConnection,$mDataQuery))
                    exit("FAIL-18".mysqli_error($mConnection)."-".$mDataQuery);
            }
            catch (Exception $e)
            {
            }
*/
//            print_r("FAIL-OK -".$mResult.":".$mResponse.":".$mErrors.":".$mJsonObject.":".$mConnectp);
            $mJsonArray = json_decode($mResult, true);
            if (substr($mJsonArray['message'], 0, 2) == "OK")
            {
                                    $partNumber = $mJsonArray['partNumber'];
                                    $database = new MysqliVeu();
                                    $part = new Part($partNumber, $database);
                                    $partDetails = $part->getPartNumberDetails();                                   
                if ($mJsonArray['blocked'] != 1)
                {
                    if ($mJsonArray['NoSerialScan'] == 1)
                    {
                        if ($mToPlt == "")
                        {
                            $mReturn = "DATA:aisleCode:" . $mAisle . ",fromLocationHashCodecontent:" . $mJsonArray['locationCode'] . ",serialReferencevalue:" . $mJsonArray['serialReference'] . ",partNumbervalue:" . $mJsonArray['partNumber'] . ",qtyAllocatedvalue:" . $mJsonArray['qtyAllocated'] . ",orderQtyvalue:" . $mJsonArray['bodyQtyAllocated'] . ",allocationId:" . $mJsonArray['id'] . ",sequencingRequestId:" . $mJsonArray['inventoryMasterId'] . ",zone:" . $mJsonArray['zoneDestination'] . ",boxCountQty:,toLocationHashCodecontent:" . $mToLocCode . ",wiCode:,rdttime:start,rdtMessage:" . $mRdtPrompt. ",partWeight:" .  $partDetails['weight'];
                        }
                        else
                        {
                                    
                           if($mRdtPrompt==""){
                            $mRdtPrompt =$partDetails['part_description'];
                            }
                            $mReturn = "DATA:aisleCode:" . $mAisle . ",fromLocationHashCodecontent:" . $mJsonArray['locationCode'] . ",serialReferencevalue:" . $mJsonArray['serialReference'] . ",partNumbervalue:" . $mJsonArray['partNumber'] . ",qtyAllocatedvalue:" . $mJsonArray['qtyAllocated'] . ",orderQtyvalue:" . $mJsonArray['bodyQtyAllocated'] . ",allocationId:" . $mJsonArray['id'] . ",sequencingRequestId:" . $mJsonArray['inventoryMasterId'] .
                            ",zone:" . $mJsonArray['zoneDestination'] . ",boxCountQty:,toLocationHashCodecontent:" . $mToLocCode . ",wiCode:,rdttime:start,rdtMessage:" . $mRdtPrompt. ",partWeight:" .  $partDetails['weight'] ;
                         }
                    }
                    else
                    {
                        if ($mToPlt == "")
                        {
                            if($mRdtPrompt==""){
                            $mRdtPrompt =$partDetails['part_description'];
                            }
                            $mReturn = "DATA:aisleCode:" . $mAisle . ",fromLocationHashCodecontent:" . $mJsonArray['locationCode'] . ",serialReferencecontent:" . $mJsonArray['serialReference'] . ",partNumbervalue:" . $mJsonArray['partNumber'] . ",orderQtyvalue:" . $mJsonArray['bodyQtyAllocated'] . ",allocationId:" . $mJsonArray['id'] . ",sequencingRequestId:" . $mJsonArray['inventoryMasterId'] .
                            ",zone:" . $mJsonArray['zoneDestination'] . ",boxCountQty:,toLocationHashCodecontent:" . $mToLocCode . ",wiCode:,rdttime:start,rdtMessage:" . $mRdtPrompt. ",partWeight:" .  $partDetails['weight'];
                            if ($mJsonArray['isFullBoxPick'] == 1)
                            {
                                $mReturn .= ",qtyAllocatedvalue:" . $mJsonArray['qtyAllocated'];
                            }
                            else
                            {
                                $mReturn .= ",qtyAllocatedvalue:" . $mJsonArray['qtyAllocated'];
                            }
                        }
                        else
                        {
                            if($mRdtPrompt==""){
                            $mRdtPrompt =$partDetails['part_description'];
                            }
                            $mReturn = "DATA:aisleCode:" . $mAisle . ",fromLocationHashCodecontent:" . $mJsonArray['locationCode'] . ",serialReferencecontent:" . $mJsonArray['serialReference'] . ",partNumbervalue:" . $mJsonArray['partNumber'] . ",orderQtyvalue:" . $mJsonArray['bodyQtyAllocated'] . ",allocationId:" . $mJsonArray['id'] . ",sequencingRequestId:" . $mJsonArray['inventoryMasterId'] .
                            ",zone:" . $mJsonArray['zoneDestination'] . ",boxCountQty:,toLocationHashCodecontent:" . $mToLocCode . ",wiCode:,rdttime:start,rdtMessage:" . $mRdtPrompt. ",partWeight:" .  $partDetails['weight'];
                         if ($mJsonArray['isFullBoxPick'] == 1)
                            {
                                $mReturn .= ",qtyAllocatedvalue:" . $mJsonArray['qtyAllocated'];
                            }
                            else
                            {
                                $mReturn .= ",qtyAllocatedvalue:" . $mJsonArray['qtyAllocated'];
                            }
                        }
                        if ($mMissing == 1)
                        {
                            $mReturn .= ",fromLocationHashCodeInput:::skipfromLocationHashCode";
                        }
                        //                            $mReturn .= ",fromLocationHashCodeInput:".$mLocHash;
                    }
                }
                else
                {
                    $mRdtPrompt = "This task is BLOCKED - F2 To Skip";
                    if ($mToPlt == "")
                    {
                        $mReturn = "DATA:aisleCode:" . $mAisle . ",fromLocationHashCodecontent:BLOCKED:HHHPPHPHPP,serialReferencecontent:BLOCKED:HHHPPHPHPP,partNumbervalue:" . $mJsonArray['partNumber'] . ":HHHPPPPHPP,qtyAllocatedvalue:" . $mJsonArray['qtyAllocated'] . ":HHPPPPPHHH,orderQty:" . $mJsonArray['bodyQtyAllocated'] . ",allocationId:" . $mJsonArray['id'] . ",sequencingRequestId:" . $mJsonArray['inventoryMasterId'] . ",zone:" . $mJsonArray['zoneDestination'] . ",boxCountQty:,toLocationHashCodecontent:" . $mToLocCode . ":HHHHHHHHHH,,wiCode::HHHHHHHHHH,rdttime:start,rdtMessage:" . $mRdtPrompt;
                    }
                    else
                    {
                        $mReturn = "DATA:aisleCode:" . $mAisle . ",fromLocationHashCodecontent:BLOCKED:HHHPPHPHPP,serialReferencecontent:BLOCKED:HHHPPHPHPP,partNumbervalue:" . $mJsonArray['partNumber'] . ":HHHPPPPHPP,qtyAllocatedvalue:" . $mJsonArray['qtyAllocated'] . ":HHPPPPPHHH,orderQty:" . $mJsonArray['bodyQtyAllocated'] . ",allocationId:" . $mJsonArray['id'] . ",sequencingRequestId:" . $mJsonArray['inventoryMasterId'] . ",zone:" . $mJsonArray['zoneDestination'] . ",boxCountQty:,toLocationHashCodecontent:" . $mToLocCode . ":HHHHHHHHHH,,wiCode::HHHHHHHHHH,rdttime:start,rdtMessage:" . $mRdtPrompt;
                    }
                }
            }
            else
            {
                //                $mReturn = "FAIL-".$mJsonArray['message'];
// 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 location_type.id AS id FROM pick_header JOIN pick_body ON pick_header.id=pick_body.pick_header_id JOIN part ON pick_body.part_id=part.id JOIN location_type ON part.fixed_location_type_id=location_type.id WHERE pick_header.document_reference='".$mDocumentRef."' AND location_type.location_type_code LIKE('".$mTaskType."%') AND pick_body.processed<>1 LIMIT 1";
                $mDataQuery = "SELECT
                        location_type.id AS id
                    FROM pick_header
                        JOIN pick_body ON pick_header.id = pick_body.pick_header_id
                        JOIN part ON pick_body.part_id = part.id
                        JOIN location_type ON part.fixed_location_type_id = location_type.id
                    WHERE 
                        pick_header.document_reference='{$mDocumentRef}'
                        AND pick_body.processed <> 1
                    LIMIT 1";

                if (!$mData = mysqli_query($mConnection, $mDataQuery))
                {
                    exit("FAIL-" . mysqli_error($mConnection) . "-" . $mDataQuery);
                }
                $mReturn = $mJsonArray['message'];

                //                return "FAIL-TEST1-".$mDataQuery."-".$mReturn;
                if (mysqli_num_rows($mData) == 0)
                {
                    if ($mTransactionTypeId != "")
                    {
                        if ($mToPlt != "")
                        {
                            $mReturn = "OKMS-" . $mReturn . ",CHGTRAN:" . $mTransactionTypeId . "?DATA:documentReference:,aisleCode:ALL,toPlt:" . $mToPlt;
                        }
                        else
                        {
                            $mReturn = "OKMS-" . $mReturn . ",CHGTRAN:" . $mTransactionTypeId . "?DATA:documentReference:,aisleCode:ALL,toPlt:" . $mToPlt;
                        }
                    }
                    else
                    {
                        $mTransactionTypeId = "PBTP";
                        $mReturn = "OKMS-" . $mReturn . ",CHGTRAN:" . $mTransactionTypeId . "?DATA:documentReference:,aisleCode:ALL,toPlt:" . $mToPlt;
                    }
                }
                else
                {
                    if ($mTransactionTypeId != "")
                    {
                        if ($mToPlt != "")
                        {
                            $mReturn = "OKMS-" . $mReturn . ",DATA:documentReferenceinput:" . $mDocumentRef . "::skiptaskType,aisleCode:ALL,toPlt:" . $mToPlt . ",taskType:,rdtmessage:";
                        }
                        else
                        {
                            $mReturn = "OKMS-" . $mReturn . ",DATA:documentReferenceinput:" . $mDocumentRef . "::skiptaskType,aisleCode:ALL,toPlt:" . $mToPlt . ",taskType:,rdtmessage";
                        }
                    }
                    else
                    {
                        $mTransactionTypeId = "PBTP";
                        $mReturn = "OKMS-" . $mReturn . ",DATA:documentReferenceinput:" . $mDocumentRef . "::skiptaskType,aisleCode:ALL,toPlt:" . $mToPlt . ",taskType:,rdtmessage";
                    }
                }
                $mReturn .= "!picking:gettasktypelist?reference=/documentReference/,skip:taskType";
            }
        }
    }
    catch (Exception $e)
    {
        exit("FAIL-Connection Error at - " . $mConnect . $mFilter . ":" . $e);
    }

    if ($mReturn != "")
    {
        return $mReturn;
    }

    return "OK  -";
}

function getPickList($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mReference, $mKey = null, $mOffset = 0)
{
    $mKey = str_replace("|COMMA|", ",", $mKey);
    $mKey = str_replace("|OPEN|", "(", $mKey);
    $mKey = str_replace("|CLOSE|", ")", $mKey);

    // 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
            pick_header.id AS id,
            pick_header.document_reference AS document_reference
        FROM pick_header
            JOIN pick_body ON pick_header.id=pick_body.pick_header_id
            LEFT JOIN document_status ON pick_header.document_status_id = document_status.id
        WHERE
            pick_header.id > 0
            AND lower(document_status.document_status_code) IN('open','allocated')
            AND pick_body.processed=0";

    if (!empty($mKey))
    {
        if ($mKey === "PBTM")
        {
            $mDataQuery .= " AND pick_header.pick_type NOT IN ('AAA', 'EMG', 'REJECT')";
        }
        else if ($mKey === "AAA")
        {
            $mDataQuery .= " AND pick_header.pick_type IN ('AAA') AND (original_pick_header_reference IN (SELECT document_reference FROM pick_header WHERE pick_type <> 'FAB') OR original_pick_header_reference IS NULL)";
            // $mDataQuery .=" AND pick_header.pick_type IN ('AAA') AND pick_header.id IN (SELECT pick_header_id FROM order_header WHERE customer_reference NOT LIKE 'M%')";
        }
        else if ($mKey === 'AAAFAB')
        {
            $mDataQuery .= " AND pick_header.pick_type = 'AAA' AND (original_pick_header_reference IN (SELECT document_reference FROM pick_header WHERE pick_type = 'FAB') OR pick_header.id IN (SELECT pick_header_id FROM order_header WHERE customer_reference LIKE 'M%'))";
        }
        else if ($mKey === "REJECT")
        {
            $mDataQuery .= " AND pick_header.pick_type = 'REJECT'";
        }
        else
        {
            $mDataQuery .=" AND ".$mKey;
        }
    }
    $mDataQuery .= " GROUP BY pick_header_id ORDER by pick_header.id DESC LIMIT 50 OFFSET " . $mOffset;

    if (!$mData = mysqli_query($mConnection, $mDataQuery))
    {
        exit("FAIL-" . mysqli_error($mConnection) . "-" . $mDataQuery);
    }
    $mDropdown = array();
    while ($mRow = mysqli_fetch_assoc($mData))
    {
        $mDropdown[] = array('value' => "documentReference:" . $mRow['document_reference'], 'text' => $mRow['document_reference'], );
//        $mDropdown[] = array('value' => $mRow['document_reference'], 'text' => $mRow['document_reference'], );
    }
    if (mysqli_num_rows($mData) == 0)
    {
        $mDropdown[] = array('value' => "No Results", 'text' => "No Results");
    }
    mysqli_close($mConnection);

    return "DROP-" . json_encode($mDropdown);
}

/**
 * Retrieves a list of task types based on the reference provided.
 *
 * @param string $mHost Database host name or IP address.
 * @param string $mUser Username for the database connection.
 * @param string $mPwd Password for the database connection.
 * @param string $mDbName Name of the database to connect to.
 * @param string $mCurrentUser Username of the current user.
 * @param string $mReference Reference to filter task types, such as 'EMG' or 'FAB'.
 * @param string|null $mKey Optional key for additional functionality (default is null).
 * @param int $mOffset Optional offset for pagination (default is 0).
 *
 * @return string JSON encoded string containing an array of task types for dropdown selection.
 */
function getTaskTypeList($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser = '', $mReference = '', $mKey = null, $mOffset = 0): string
{
// mysql connection - Use Passed values...
    $mConnection = mysqli_connect($mHost, $mUser, $mPwd, $mDbName) or
        exit("FAIL-Connect failed: " . mysqli_connect_errno() . " : " . mysqli_connect_error());

    // Conditionally selects task groups from task type dropdown menu on the frontend
    if (in_array($mReference, ['EMG', 'FAB']))
    {
        $mDataQuery = "SELECT
                location_type.id AS id,
                location_type.task_group AS task_group
            FROM pick_header
                JOIN pick_body ON pick_header.id = pick_body.pick_header_id
                JOIN part ON pick_body.part_id = part.id
                JOIN location_type ON part.fixed_location_type_id=location_type.id
            WHERE
                pick_header.pick_type='{$mReference}'
                AND pick_header.document_status_id = 1
                AND pick_body.processed <> 1
            GROUP by location_type.location_type_code
            ORDER by location_type.location_type_code
            LIMIT 25 OFFSET {$mOffset}";
    }
    else
    {
        $mDataQuery = "SELECT
                location_type.task_group AS task_group
            FROM pick_body
                JOIN pick_detail ON pick_body.id=pick_detail.pick_body_id
                JOIN part ON pick_body.part_id = part.id
                JOIN location_type ON part.fixed_location_type_id = location_type.id
            WHERE
                pick_body.document_reference = '{$mReference}'
                AND pick_body.processed = 0";
        if ($mKey == "train")
        {
            $mDataQuery .= " AND location_type.is_train=1";
        }
        $mDataQuery .=" GROUP BY location_type.task_group
                        ORDER BY location_type.task_group
                        LIMIT 50 OFFSET {$mOffset}";
    }

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


    // Creates the dropdown array
    $mDropdown = [];
    while ($mRow = mysqli_fetch_assoc($mData))
    {
        $mDropdown[] = array('value' => "taskType:" . $mRow['task_group'], 'text' => $mRow['task_group'], );
    }
    if (mysqli_num_rows($mData) == 0)
    {
        $mDropdown[] = array('value' => "No Results", 'text' => "No Results");
    }
    mysqli_close($mConnection);

    return "DROP-" . json_encode($mDropdown);
}

function getZoneList($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mReference, $mKey = null, $mOffset = 0)
{
    $params = [];
    $paramTypes = "";
    $mLimit = 25;

    // 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
            pick_body.zone_destination AS zone_destination
        FROM pick_body
            JOIN part ON pick_body.part_id = part.id
            JOIN location_type ON part.fixed_location_type_id = location_type.id
            JOIN zone_destination ON pick_body.zone_destination = zone_destination.zone_destination
            JOIN trolley ON zone_destination.trolley_id = trolley.id";
    if (!empty($mKey))
    {
        $mDataQuery .= " WHERE
            pick_body.document_reference = ?
            AND location_type.task_group = ?
            AND pick_body.processed<>1
            AND pick_body.qty_allocated>0";
        $params[] = $mReference;
        $params[] = $mKey;
        $paramTypes .= "ss";
    }
    $mDataQuery .= " GROUP BY pick_body.zone_destination
                     ORDER BY trolley.trolley";
    if (!empty($mLimit))
    {
        $mDataQuery .= " LIMIT ?";
        $params[] = $mLimit;
        $paramTypes .= "i";
    }

    // $mDataQuery = "SELECT
    //         pick_detail.zone_destination
    //     FROM pick_detail
    //         JOIN pick_body ON pick_detail.pick_body_id = pick_body.id
    //         JOIN pick_header ON pick_body.pick_header_id=pick_header.id
    //         JOIN part ON pick_body.part_id=part.id
    //         JOIN location_type ON part.fixed_location_type_id=location_type.id";
    // if (!empty($mKey))
    // {
    //     $mDataQuery .= " WHERE pick_header.document_reference= ? AND location_type.task_group=?";
    //     $params[] = $mReference;
    //     $params[] = $mKey;
    //     $paramTypes .= "ss";
    // }
    // $mDataQuery .= " GROUP BY pick_detail.zone_destination";
    // if (!empty($mLimit))
    // {
    //     $mDataQuery .= " LIMIT ?";
    //     $params[] = $mLimit;
    //     $paramTypes .= "i";
    // }

    $stmt = mysqli_prepare($mConnection, $mDataQuery);

    // Bind the parameters
    try
    {
        $stmt->bind_param($paramTypes, ...$params);
        mysqli_stmt_execute($stmt);
    }
    catch (Exception $e)
    {
        exit("FAIL-" . $mDataQuery . "-" . $e . var_dump($stmt));
    }

    $mData = mysqli_stmt_get_result($stmt);

    $mDropdown = [];

    while ($mRow = mysqli_fetch_assoc($mData))
    {
        $mDropdown[] = array('value' => "zone:" . $mRow['zone_destination'], 'text' => $mRow['zone_destination'], );
    }

    mysqli_stmt_close($stmt);
    mysqli_close($mConnection);

    return "DROP-" . json_encode($mDropdown);
}

function getTrainList($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 train.id AS id,train AS train, description AS description FROM train LIMIT 50 OFFSET " . $mOffset;

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

    $mDropdown = array();
    while ($mRow = mysqli_fetch_assoc($mData))
    {
        $mDropdown[] = array('value' => "train:" . $mRow['train'], 'text' => $mRow['description'],);
    }

    mysqli_close($mConnection);

    return "DROP-" . json_encode($mDropdown);
}

function allocatePart($mHost, $mUser, $mPwd, $mDbName, $mConnect, $mCurrentUser, $mPartNumber)
{
    // Get Server Data from URL
    $mJsonArray = array();
    $mJsonArray['parts'] = array_values(array($mPartNumber));
    $mJsonArray['userId'] = $mCurrentUser;
    //    $mJsonArray['transactionCode'] = $mTransactionType;
// Convert Array to a Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray);
    }
    catch (Exception $e)
    {
        exit("FAIL-Json Error");
    }

    // Replace default Server Tomcat Service
    $mConnectp = str_replace(":8081/vantec", ":8095/pick", $mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect, ":8081");
        $mConnectp = substr($mConnect, 0, $e) . ":8095/pick/";
    }

    $ch = curl_init();
    try
    {
        $mPartNumber = urlencode($mPartNumber);
        $mUrl = "allocateForParts?parts=" . $mPartNumber . "&userId=" . $mCurrentUser;
        curl_setopt($ch, CURLOPT_URL, $mConnectp . $mUrl);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $mJsonObject);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $mResult = curl_exec($ch);
        $mErrors = curl_error($ch);
        $mResponse = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($mResponse != "200")
        {
            $mUrl = str_replace("&", "|AND|", $mUrl);
            print_r("FAIL-Unexpected System Error -" . $mResult . ":" . $mResponse . ":" . $mErrors . ":" . $mConnectp . $mUrl . ":" . $mJsonObject);
        }
        else
        {
            $mResult = str_replace("OK -", "OK  -", $mResult);
            $mResult = str_replace("FAIL -", "FAIL-", $mResult);
            if (substr($mResult, 0, 4) == "true")
            {
                exit("OK  -" . $mResult);
            }
            elseif (substr($mResult, 0, 2) == "OK")
            {
                exit("OK  -" . $mResult);
            }
            else
            {
                exit("FAIL-" . $mResult);
            }
        }
    }
    catch (Exception $e)
    {
        // exit("FAIL-Connection Error at - " . $mConnect . $mFilter . ":" . $e);
        exit("FAIL-Connection Error at - " . $mConnect . ":" . $e);
    }
}

function getTrainLocList($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mReference, $mTaskType = null, $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
        train_locations.id AS id,train_locations.train_location_code AS train_location_code
        FROM pick_header
        JOIN pick_body ON pick_header.id=pick_body.pick_header_id
        JOIN part ON pick_body.part_id=part.id
        JOIN location_type ON part.fixed_location_type_id=location_type.id
        JOIN train_locations ON train_location_code LIKE(CONCAT(pick_header.document_reference,'%'))
        AND train_location_code LIKE(CONCAT('%',pick_body.zone_destination))
        LEFT JOIN train_locations_status ON train_locations.train_locations_status_id=train_locations_status.id
        WHERE pick_body.document_reference='$mReference'";
    if (!empty($mTaskType))
    {
        $mDataQuery .=" AND location_type.task_group='$mTaskType'";
    }
    $mDataQuery .=" AND location_type.is_train=1";
    $mDataQuery .=" AND pick_body.processed<>1
                    AND pick_body.qty_allocated>0
                    AND upper(train_locations_status)<>'CLOSED'";
    $mDataQuery .=" GROUP BY train_location_code
                    ORDER BY train_location_code
                    LIMIT 50
                    OFFSET ".$mOffset;
*/
    $mDataQuery = "
        SELECT train_locations.id AS id,train_locations.train_location_code AS train_location_code,
        train.train AS train,
        trolley.sequence AS sequence
        FROM pick_header
        JOIN pick_body ON pick_header.id=pick_body.pick_header_id
        JOIN part ON pick_body.part_id=part.id
        JOIN location_type ON part.fixed_location_type_id=location_type.id
        JOIN zone_destination ON pick_body.zone_destination=zone_destination.zone_destination
        JOIN trolley ON zone_destination.trolley_id=trolley.id
        JOIN train ON trolley.train_id=train.id
        JOIN train_locations ON train_location_code LIKE(CONCAT(pick_header.document_reference,'%'))
        AND train_location_code LIKE(CONCAT('%',pick_body.zone_destination))
        LEFT JOIN train_locations_status ON train_locations.train_locations_status_id=train_locations_status.id
        WHERE pick_body.document_reference='$mReference'";
    if (!empty($mTaskType))
    {
        $mDataQuery .=" AND location_type.task_group='$mTaskType'";
    }
    $mDataQuery .=" AND location_type.is_train=1";
    $mDataQuery .=" AND pick_body.processed<>1
                    AND pick_body.qty_allocated>0
                    AND upper(train_locations_status)<>'CLOSED'";
    $mDataQuery .=" GROUP BY train, sequence
                    ORDER BY train, sequence
                    LIMIT 50
                    OFFSET ".$mOffset;
        
    if (!$mData = mysqli_query($mConnection, $mDataQuery))
    {
        exit("FAIL-" . mysqli_error($mConnection) . "-" . $mDataQuery);
    }

    $mDropdown = array();
    while ($mRow = mysqli_fetch_assoc($mData))
    {
        $mDropdown[] = array('value' => "train:" . $mRow['train_location_code'], 'text' => $mRow['train_location_code'], );
    }
    if (mysqli_num_rows($mData) == 0)
    {
        $mDropdown[] = array('value' => "No Results", 'text' => "No Results");
    }
    mysqli_close($mConnection);

    return "DROP-" . json_encode($mDropdown);
}

// Get Next Pick
function printPickLabel($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mTransactionType, $mPickDtlId, $mPrinterName, $mPrinterAddr) {}

function ping($mAddress)
{
    if (strtolower(PHP_OS) == 'winnt')
    {
        $command = "ping -n 1  -w 2000 $mAddress";
        exec($command, $output, $status);
    }
    else
    {
        $command = "ping -c 1 -w 2000 $mAddress";
        exec($command, $output, $status);
    }
    if ($status === 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

function createPickSerial($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,'PCK');
    if ($i > 0)
    {
        $mSerialReference = substr($mSerialReference, 0, $i);
    }
    $mDataQuery = "SELECT inventory_master.id,inventory_master.inventory_qty";
    $mDataQuery .= ",part.full_box_pick";
    $mDataQuery .= " FROM inventory_master";
    $mDataQuery .= " JOIN part ON inventory_master.part_id=part.id";
    $mDataQuery .= " WHERE inventory_master.part_number = '" . $mPartNumber . "' AND inventory_master.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 ($mRow['full_box_pick'] == 1)
    {
//        error_log("picking.php-Not Full-box".$mDataQuery," ".$mQuantity." ".$mRow['inventory_qty']." ".$mRow['full_box_pick']);
        exit ("OK  -Full box");
    }

    if (!empty($mQuantity))
    {
        if ($mQuantity >= $mRow['inventory_qty'])
//        if (bccomp($mQuantity, $mRow['inventory_qty']) >= 0)
        {
//            error_log("picking.php-Not Full-box".$mDataQuery," ".$mQuantity." ".$mRow['inventory_qty']." ".$mRow['full_box_pick']);
            exit ('OK  -Full box');
        }
    }

    $mOrigInvId = $mRow['id'];
    $mDataQuery = "SELECT inventory_master_id AS id
                    FROM pick_detail WHERE id=$mAllocationId
                    LIMIT 1";
    $mData = mysqli_query($mConnection,$mDataQuery);
    if (mysqli_num_rows($mData) > 0)
    {
        list($mOrigInvId) = mysqli_fetch_row($mData);
    }
    $mDataQuery = "SELECT * FROM inventory_master WHERE part_number = '".$mPartNumber."' AND serial_reference LIKE('".$mSerialReference."%') ORDER BY id 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 = strrpos($mInvSerial, 'PCK');
    if ($i > 0)
    {
        $i = $i + 3;
        $mSuffix = substr($mInvSerial, $i);
        if ($mRow['inventory_qty'] > 0)
        {
            if (is_numeric($mSuffix))
            {
                $i = intval($mSuffix);
                $i++;
                $mSuffix = substr('000' . $i, -3);
            }
        }
        $mSuffix = trim(str_replace('PCK', '', $mSuffix));
        $mSuffix = 'PCK' . $mSuffix;
    }
    else
    {
        $mSuffix = 'PCK001';
    }
// Insert Pick_serial Record
    $mSerialReference = trim(str_replace('PCK', '', $mSerialReference));
    $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 = "SELECT id FROM inventory_master WHERE part_number='".$mRow['part_number']."' 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)
    {
        if (empty($mRow['current_location_id']))
        {
            $mRow['current_location_id'] = null;
        }
        if (empty($mRow['location_id']))
        {
            $mRow['location_id'] = null;
        }
        $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']))
        {
            if (empty($mRow['current_location_id']))
            {
                $mDataQuery .=" VALUES(DEFAULT,0,0,0,null,null,null,'".$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'].",null,null)";
            }
        }
        else
        {
            if (empty($mRow['current_location_id']))
            {
                $mDataQuery .=" VALUES(DEFAULT,0,0,0,null,null,null,'".$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'].")";
            }
            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)
        {
            error_log($e->getMessage() . '-' . $mDataQuery);
            // exit ("FAIL-".$e."-".$mDataQuery);
        }
        $mInvId=mysqli_insert_id($mConnection);
    }
    else
    {
        list($mInvId) = mysqli_fetch_row($mData);
    }
//  exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
    if (!empty($mOrigInvId))
    {
        $mDataQuery = "UPDATE pick_detail SET inventory_master_id=".$mOrigInvId.",serial_reference='".$mSerialReference."' WHERE pick_detail.id=".$mAllocationId." LIMIT 1";
    }
    else
    {
        $mDataQuery = "UPDATE pick_detail SET serial_reference='".$mSerialReference."' WHERE pick_detail.id=".$mAllocationId." LIMIT 1";
    }
    try
    {
        mysqli_query($mConnection,$mDataQuery);
    }
    catch (Exception $e)
    {
        exit ("FAIL-".$e."-".$mDataQuery);
    }
    mysqli_close($mConnection);
//	error_log("picking.php-Not Full-box".$mDataQuery," ".$mQuantity." ".$mRow['inventory_qty']." ".$mRow['full_box_pick']);
    exit ("DATA:serialReference:".$mSerialReference);
}
