<?php
//
// VIMS RDT Receiving Processing
// ----------------------------------------------------------------------------------------
// Modified 2020-03-23 - Initial KUK Version
// 2020-12-02 - completeCase - Send message to service via curl.
// 2020-12-02 - completeCase - set status to complete not closed.
// 2021-04-13 - checkcase - check for 'closed' or 'transmitted'
// ----------------------------------------------------------------------------------------
// error_reporting(E_ALL);
// ini_set('display_errors', 1);

// Enable exceptions for MySQLi errors
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// ----------------------------------------------------------------------------
// Includes and Requires
// ----------------------------------------------------------------------------
// use classes\Printer;
// use classes\MysqliVeu;

$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$ip = $_SERVER['HTTP_HOST'];
$baseUrl = $protocol.$ip;

$root = $_SERVER['DOCUMENT_ROOT'];
if (empty($root))
{
    $root = (__DIR__);
}

$root = str_replace("\\","/",$root);
$dir = (dirname(__FILE__));
$dir = str_replace("\\","/",$dir);

// get Base Directory
$baseDir = $dir;
for ($i=0;$i<10;$i++)
{
    $testDir = dirname($baseDir);
    $testDir = str_replace("\\","/",$testDir);
    
    $baseDir = str_replace("\\","/",$baseDir);
    if ($baseDir == $root)
    {
        break;
    }
    if ($testDir == $root)
    {
        break;
    }
    $baseDir = dirname($baseDir);
}
require_once __DIR__ . '/./helpers.php';
include_once __DIR__ . '/./connect.php';

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

// Database Connection
$conn = dbConnection();

// validaterdt - VIMS Server Validation
$mFilter = "";
$mFunction          = $_GET['function'];
$mConnect           = $_GET['connection'];
$mUser              = $_GET['user'];
$mPwd               = $_GET['pword'];
$mHost              = $_GET['host'];
$mDbName            = $_GET['dbase'];
$mTableName         = $_GET['table'];
$mReturnFields      = $_GET['returnfields'];
$mFilter            = $_GET['filter'];

$mHost = $conn['host'] ?? '';
$mUser = $conn['user'] ?? '';
$mPwd = $conn['pwd'] ?? '';
$mDbName = $conn['dbase'] ?? '';
$mConnect = $conn['path'] ?? '';

// ----------------------------------------------------------------------------
// Get Input Parameters from POST or GET
// ----------------------------------------------------------------------------

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

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

$mSQLData = array();

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

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


// ----------------------------------------------------------------------------
// Router Functions
// ----------------------------------------------------------------------------

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


// Get list of QA locations
if (($mFunction != null) && (strtolower($mFunction) == 'getqalocations'))
{
//  echo("FAIL-TEST2");
    $mErrMsg = '';
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace('=', ':', $mFilter);
    $mFilter = str_replace('&', ',', $mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(',', $mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach ($mArray1 as $k1 => $v1)
    {
        list($k2, $v2) = explode(':', $mArray1[$k1]);
        if ($k2 == 'loctype')
        {
            $mLocType = trim(strtoupper($v2));
        }
        elseif ($k2 == 'currentUser')
        {
            $mCurrentUser = trim($v2);
        }
    }

    $mStatus = getLocList($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mLocType);
    echo $mStatus;
    return;
}


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


elseif (($mFunction != null) && (strtolower($mFunction) == "validaterts"))
{
//  echo("FAIL-TEST2");
    $mErrMsg = "";
    $mSerialReference = null;
    $mPartNumber = null;
    $mFromLoc = null;
    $mToLoc = null;
// 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 == "allocationid")
        {
            $mRtsDtlId = trim($v2);
        }
        elseif ($k2 == "fromlocation")
        {
            $mFromLoc = trim($v2);
        }
        elseif ($k2 == "serialreference")
        {
            $mSerialReference = trim($v2);
        }
        elseif ($k2 == "partnumber")
        {
            $mPartNumber = trim($v2);
        }
        elseif ($k2 == "tolocation")
        {
            $mToLoc = trim($v2);
        }
        elseif ($k2 == "currentUser")
        {
            $mCurrentUser = trim($v2);
        }
        elseif ($k2 == "transactionType")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
        elseif ($k2 == "transactionTypeId")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
    }
    $mStatus = validateRts($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mRtsDtlId, $mSerialReference, $mPartNumber, $mFromLoc, $mToLoc, $mTransactionTypeId);
    echo $mStatus;
    return;
}


elseif (($mFunction != null) && (strtolower($mFunction) == "postrts"))
{
//  echo("FAIL-TEST2");
    $mRtsDtlId = "";
    $mErrMsg = "";
    $mSerialReference = null;
    $mPartNumber = null;
    $mFromLoc = null;
    $mToLoc = null;
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=", ":", $mFilter);
    $mFilter = str_replace("&", ",", $mFilter);
//    print_r("FAIL-TEST-".$mFilter);
//    return;
// 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 == "allocationid")
        {
            $mRtsDtlId = trim($v2);
        }
        elseif ($k2 == "fromlocation")
        {
            $mFromLoc = trim($v2);
        }
        elseif ($k2 == "serialreference")
        {
            $mSerialReference = trim($v2);
        }
        elseif ($k2 == "partnumber")
        {
            $mPartNumber = trim($v2);
        }
        elseif ($k2 == "tolocation")
        {
            $mToLoc = trim($v2);
        }
        elseif ($k2 == "vldtolocationcode")
        {
            $mVldToLocCode = trim($v2);
        }
        elseif ($k2 == "currentUser")
        {
            $mCurrentUser = trim($v2);
        }
        elseif ($k2 == "transactionType")
        {
            $mTransactionTypeId = strtoupper(trim($v2));
        }
    }

    $mStatus = postRts($mConnect, $mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mRtsDtlId, $mSerialReference, $mPartNumber, $mFromLoc, $mToLoc, $mVldToLocCode, $mTransactionTypeId);
    echo $mStatus;
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "getserialoslist"))
{
//  echo("FAIL-TEST2");
    $mRtsDtlId = "";
    $mErrMsg = "";
    $mSerialReference = null;
    $mPartNumber = null;
    $mFromLoc = null;
    $mToLoc = null;
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=", ":", $mFilter);
    $mFilter = str_replace("&", ",", $mFilter);

    $mStatus = getSerialOsList($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mFilter);
    echo $mStatus;
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "validateserialos"))
{
//  echo("FAIL-TEST2");
    $mRtsDtlId = "";
    $mErrMsg = "";
    $mSerialReference = null;
    $mPartNumber = null;
    $mFromLoc = null;
    $mToLoc = null;
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=", ":", $mFilter);
    $mFilter = str_replace("&", ",", $mFilter);

    $mStatus = validateSerialOs($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mFilter);
    echo $mStatus;
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "validateloc"))
{
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=", ":", $mFilter);
    $mFilter = str_replace("&", ",", $mFilter);

    $mStatus = validateLoc($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser,$mFilter);
    echo $mStatus;
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "getlocpartlist"))
{
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=", ":", $mFilter);
    $mFilter = str_replace("&", ",", $mFilter);

    $mStatus = getLocPartList($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser,$mFilter);
    echo $mStatus;
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "getmarloc"))
{
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=", ":", $mFilter);
    $mFilter = str_replace("&", ",", $mFilter);

    $mStatus = getMarLoc($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser,$mFilter);
    echo $mStatus;
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "postinvloc"))
{
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=", ":", $mFilter);
    $mFilter = str_replace("&", ",", $mFilter);

    $mStatus = postInvLoc($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser,$mFilter);
    echo $mStatus;
    return;
}

elseif (($mFunction != null) && (strtolower($mFunction) == "labelprint"))
{
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=", ":", $mFilter);
    $mFilter = str_replace("&", ",", $mFilter);

    $mStatus = labelPrint($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mFilter);
    echo $mStatus;
    return;
}
// ----------------------------------------------------------------------------
// Main Functions
// ----------------------------------------------------------------------------

/**
 * Retrieves a list of RTS references based on the given type.
 *
 * @param string $mHost The host name for the database connection.
 * @param string $mUser The username for the database connection.
 * @param string $mPwd The password for the database connection.
 * @param string $mDbName The database name for the database connection.
 * @param string $mCurrentUser The current user.
 * @param string $mRtsType The RTS type.
 * @param string|null $mKey The optional key to filter the results.
 *
 * @return string The dropdown items containing values, text, and color for each RTS reference, encoded in JSON format.
 */
function getRtsRefList($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mRtsType, $mKey = null)
{
//  echo("FAIL-TEST3");
// mysql connection - Use Passed values...
    $mConnection = mysqli_connect($mHost, $mUser, $mPwd, $mDbName) or
    exit("FAIL-Connect failed: " . mysqli_connect_errno() . " : " . mysqli_connect_error());
    $mDataQuery = "SELECT
            rts_header.id AS id,
            rts_header.order_reference AS order_reference,
            rts_header.order_type AS order_type,
            rts_header.machine_model AS machine_model,
            rts_body.part_number AS part_number,
            rts_body.baan_location AS rts_location
        FROM rts_header 
            JOIN rts_body ON rts_header.id = rts_body.rts_header_id
            JOIN rts_detail ON rts_body.id = rts_detail.rts_body_id
            LEFT JOIN document_status ON rts_detail.document_status_id = document_status.id
        WHERE 
            rts_header.order_type LIKE('{$mRtsType}%')
            AND (rts_detail.received_qty > rts_detail.qty_transacted OR rts_detail.qty_transacted IS NULL)
            AND (rts_detail.document_status_id IS NULL OR lower(document_status.document_status_code)='open')
        ORDER by rts_header.last_updated,rts_header.order_reference
        LIMIT 500";

    if (!$mData = mysqli_query($mConnection, $mDataQuery))
    {
        exit ("FAIL-" . mysqli_error($mConnection) . "-" . $mDataQuery);
    }
//  exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
    $mDropdown = array();
    while ($mRow = mysqli_fetch_assoc($mData))
    {
//      echo("FAIL-TEST-".$mPrevCase."-".$mRow['case_reference']);
        if (strpos($mRow['order_type'], 'EMER') !== false)
        {
            $mDropdown[] = array('value' => "rtsReference:" . $mRow['order_reference'] . ",partNumber:" . $mRow['part_number'], 'text' => $mRow['part_number'] . " / " . $mRow['rts_location'], 'colour' => 'RED',);
        }
        else
        {
            $mDropdown[] = array('value' => "rtsReference:" . $mRow['order_reference'] . ",partNumber:" . $mRow['part_number'], 'text' => $mRow['part_number'] . " / " . $mRow['rts_location'], 'colour' => 'WHITE',);
        }

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


/**
 * Retrieves the next task for a given order reference.
 *
 * @param string $mHost The host name for the database connection.
 * @param string $mUser The username for the database connection.
 * @param string $mPwd The password for the database connection.
 * @param string $mDbName The database name for the database connection.
 * @param string $mCurrentUser The current user.
 * @param string $mRtsRef The order reference for the task.
 * @param string $mPartNumber The part number for the task. (optional)
 * @param string $mTransactionTypeId The transaction type ID for the task. (optional)
 *
 * @return void The task details are echoed as a string in the format: "DATA:allocationId:{id},fromLocationHashCodecontent:{rts_location}::,serialReferencecontent:{rts_serial}::skip2,toLoc:::,toCase:::,partNumber:{part_number}::".
 *              If there are no available tasks, returns the string "OKMS-No available tasks".
 *              If the task retrieval is successful, returns the string "OK  -getNextRts".
 */
function getNextRts($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mRtsRef, $mPartNumber = "", $mTransactionTypeId = "")
{
// mysql connection - Use Passed values...
    $mConnection = mysqli_connect($mHost, $mUser, $mPwd, $mDbName) or
    exit("FAIL-Connect failed: " . mysqli_connect_errno() . " : " . mysqli_connect_error());
    if ($mPartNumber != "")
    {
        $mDataQuery = "SELECT
                rts_detail.id AS id,
                rts_detail.part_number AS part_number,
                rts_detail.serial_reference AS rts_serial,
                rts_body.baan_location AS rts_location
            FROM rts_detail
                JOIN rts_body ON rts_detail.rts_body_id = rts_body.id
                JOIN rts_header ON rts_body.rts_header_id = rts_header.id
                LEFT JOIN document_status ON rts_detail.document_status_id = document_status.id
            WHERE 
                rts_header.order_reference ='{$mRtsRef}'
                AND rts_detail.part_number='{$mPartNumber}'
                AND (rts_detail.received_qty > rts_detail.qty_transacted OR rts_detail.qty_transacted IS NULL)
            LIMIT 1";
    }
    else
    {
        $mDataQuery = "SELECT
                rts_detail.id AS id,
                rts_detail.part_number AS part_number,
                rts_detail.serial_reference AS rts_serial,
                rts_body.baan_location AS rts_location
            FROM rts_detail
                JOIN rts_body ON rts_detail.rts_body_id = rts_body.id
                JOIN rts_header ON rts_body.rts_header_id = rts_header.id
                LEFT JOIN document_status ON rts_detail.document_status_id = document_status.id
            WHERE 
                rts_header.order_reference ='{$mRtsRef}'
                AND (rts_detail.received_qty>rts_detail.qty_transacted OR rts_detail.qty_transacted IS NULL)
            LIMIT 1";
    }
    if (!$mData = mysqli_query($mConnection, $mDataQuery))
    {
        exit ("FAIL-" . mysqli_error($mConnection) . "-" . $mDataQuery);
    }
//    exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
    if (mysqli_num_rows($mData) == 0)
    {
        return "OKMS-No available tasks";
    }

    while ($mRow = mysqli_fetch_assoc($mData))
    {
        $mDtlId = $mRow['id'];
        $mDocSts = strtolower($mRow['document_status_code']);

        //Gets Value of Part Number Weight
        $mPartWeight = getPartNumberWeight($mRow['part_number'], $mConnection);

        echo("DATA:allocationId:" . $mRow['id'] . ",fromLocationHashCodecontent:" . $mRow['rts_location'] . "::,serialReferencecontent:" . $mRow['rts_serial'] . "::skip2,toLoc:::,toCase:::,partNumber:" . $mRow['part_number'] . ",partWeight:". $mPartWeight ."::");
        return;

    }

    return "OK  -getNextRts";
}


/**
 * Validates an RTS transaction based on various parameters.
 *
 * @param string $mHost The host name for the database connection.
 * @param string $mUser The username for the database connection.
 * @param string $mPwd The password for the database connection.
 * @param string $mDbName The database name for the database connection.
 * @param string $mCurrentUser The current user.
 * @param string $mRtsDtlId The ID of the RTS detail.
 * @param string $mSerialReference The serial reference.
 * @param string $mPartNumber The part number.
 * @param string $mFromLoc The from location.
 * @param string $mToLoc The to location.
 * @param string $mTransactionTypeId The transaction type ID.
 *
 * @return string The result of the validation, which can be "OK -validateRts" or an error message.
 */
function validateRts($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mRtsDtlId, $mSerialReference, $mPartNumber, $mFromLoc, $mToLoc, $mTransactionTypeId = "")
{
// mysql connection - Use Passed values...
    $mConnection = mysqli_connect($mHost, $mUser, $mPwd, $mDbName) or
    exit("FAIL-Connect failed: " . mysqli_connect_errno() . " : " . mysqli_connect_error());
//    $mDataQuery = "SELECT id FROM location WHERE location.location_hash='".$mFromLoc."' LIMIT 1";
//    if (!$mData = mysqli_query($mConnection,$mDataQuery))
//      exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
//    if (mysqli_num_rows($mData) == 0)
//        return "FAIL-Invalid From Location";
    if (empty($mRtsDtlId))
    {
        exit("FAIL-Invalid Task");
    }

    $mDataQuery = "SELECT
            rts_detail.id AS id,
            rts_detail.part_number AS part_number,
            rts_detail.serial_reference AS serial_reference,
            rts_detail.location_code AS location_code,
            rts_body.baan_location AS rts_location,
            location.location_hash AS location_hash,
            part.id AS part_id
        FROM rts_detail
            JOIN rts_body ON rts_detail.rts_body_id = rts_body.id
            LEFT JOIN location ON rts_body.baan_location = location.location_code
            LEFT JOIN part ON rts_detail.part_number = part.part_number
        WHERE rts_detail.id = {$mRtsDtlId}
        LIMIT 1";

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

    if (mysqli_num_rows($mData) == 0)
    {
        return "FAIL-Error On RTS Transaction";
    }

    $mReturn = "";
    while ($mRow = mysqli_fetch_assoc($mData))
    {
        if ($mReturn == "")
        {
            if ($mSerialReference != null)
            {
                if ($mSerialReference != $mRow['serial_reference'])
                {
                    $mReturn = "FAIL-Invalid Serial";
                }
            }
            else
            {
                $mReturn = "DATA:allocationId:" . $mRow['id'] . ",serialReference:::skip3";
            }
        }

        if ($mReturn == "")
        {
            if ($mFromLoc != null)
            {
                if ($mFromLoc != $mRow['location_hash'])
                {
                    if ($mFromLoc != $mRow['rts_location'])
                    {
                        $mReturn = "FAIL-Invalid From Location";
                    }
                }
            }
            else
            {
                $mReturn = "DATA:allocationId:" . $mRow['id'] . ",fromLocationHashCode:::skip2";
            }
        }

        if ($mReturn == "")
        {
            if (empty($mToLoc))
            {
                $mDataQuery = "SELECT location.location_code AS location_code
                                FROM part
                                LEFT JOIN site ON part.site_id=site.id
                                LEFT JOIN location ON location.id=site.default_location_id
                                WHERE part.part_number = '$mPartNumber'
                                LIMIT 1";
                if (!$mData = mysqli_query($mConnection,$mDataQuery))
                    exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
                $mLocation = "";
                if (mysqli_num_rows($mData) > 0)
                {
                    list($mLocation) = mysqli_fetch_row($mData);
                }
                if (empty($mLocation))
                {
             
                    if ($mTransactionTypeId == "RTSE")
                    {
//                      $mLocation = getNextLocation($mRow['part_id'],'',1,'',0,01,$mHost,$mUser,$mPwd,$mDbName,$mTransactionTypeId,'');
                        $mDataQuery = "SELECT
                            location.location_code AS location_code 
                            FROM location
                            JOIN location_type ON location_type.id = location.location_type_id
                            WHERE
                            location_type.location_type_code = 'qa'
                            ORDER BY location_code
                            LIMIT 1";
                        if (!$mData = mysqli_query($mConnection,$mDataQuery))
                            exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
                        $mLocation = "";
                        if (mysqli_num_rows($mData) > 0)
                        {
                            list($mLocation) = mysqli_fetch_row($mData);
                        } 
                    }
                    else
                    {
                        include_once ('location.php');
                        $mLocation = getNextLocation($mRow['part_id'],'',1,'',0,00,$mHost,$mUser,$mPwd,$mDbName,$mTransactionTypeId,'');
                    }
                }
                $mReturn = "DATA:allocationId:".$mRow['id'].",toLocationHashCodecontent:".$mLocation;
            }
        }
    }

    if ($mReturn != "")
    {
        return $mReturn;
    }
    else
    {
        return "OK  -validateRts";
    }
}


/**
 * Posts the RTS transaction.
 *
 * @param string $mConnect The connect parameter.
 * @param string $mHost The host name for the database connection.
 * @param string $mUser The username for the database connection.
 * @param string $mPwd The password for the database connection.
 * @param string $mDbName The database name for the database connection.
 * @param string $mCurrentUser The current user.
 * @param int $mRtsDtlId The RTS detail ID.
 * @param string $mSerialReference The serial reference.
 * @param string $mPartNumber The part number.
 * @param string $mFromLoc The from location.
 * @param string $mToLoc The to location.
 * @param string $mVldToLocCode The validated to location code.
 * @param string $mTransactionTypeId The transaction type ID.
 *
 * @return string The status of the RTS transaction.
 */
function postRts($mConnect, $mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mRtsDtlId, $mSerialReference, $mPartNumber, $mFromLoc, $mToLoc, $mVldToLocCode = '', $mTransactionTypeId = "RTS")
{
    // Updates Value 
    if ($mTransactionTypeId === 'RTSE')
    {
        $mVldToLocCode = $mToLoc;
    }

    $mJsonArray = array();
    $mQty = 1;

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

// Checks if $mToLoc is a QA location
    if (!checkLocationType($mToLoc, 'QA', $mConnection))
    {
//        return 'FAIL- To Location Invalid - It must be QA.';
    }

// Get id for document status
    $mDocStsId = 0;
    $mDocCmpId = 0;
    $mDataQuery = "SELECT
            id AS id,
            document_status_code AS document_status_code
        FROM document_status";

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

    $mData = (mysqli_query($mConnection, $mDataQuery));
    while ($mRow = mysqli_fetch_assoc($mData))
    {
        if (strtolower($mRow['document_status_code']) == "open")
        {
            $mDocStsId = ($mRow['id']);
        }
        if (strtolower($mRow['document_status_code']) == "complete")
        {
            $mDocCmpId = ($mRow['id']);
        }
    }

    if ($mDocCmpId == null)
    {
        $mDocCmpId = 1;
    }

    $mVldLocArea = "";
    if (!empty($mVldToLocCode))
    {
        $mDataQuery = "SELECT
                location_type.location_area AS location_area
            FROM location
            LEFT JOIN location_type ON location.location_type_id = location_type.id
            WHERE location.location_hash='{$mVldToLocCode}'
            LIMIT 1";

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

        if (mysqli_num_rows($mData) == 0)
        {
            return "FAIL-Invalid Location-" . $mVldToLocCode;
        }

        list($mVldLocArea) = mysqli_fetch_row($mData);
    }

    $mLocArea = "";
    $mDataQuery = "SELECT
            location.id AS id,
            location.location_code AS location_code,
            location.location_hash AS location_hash,
            location_type.location_area AS location_area
        FROM location 
            LEFT JOIN location_type ON location.location_type_id = location_type.id
        WHERE location.location_hash='{$mToLoc}' 
        LIMIT 1";

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

    if (mysqli_num_rows($mData) == 0)
    {
        return "FAIL-Invalid Location-" . $mToLoc;
    }

    list($mToLocId, $mToLocCode, $mToLocHash, $mLocArea) = mysqli_fetch_row($mData);

    if (!empty($mVldLocArea) && strtolower($mVldLocArea) == 'work')
    {
        if ($mVldLocArea != $mLocArea)
        {
            return "FAIL-Invalid location type";
        }
    }

    $mDataQuery = "SELECT
            rts_detail.id AS id,
            rts_detail.part_number AS part_number,
            rts_detail.serial_reference AS serial_reference,
            rts_detail.location_code AS location_code,
            rts_detail.received_qty AS received_qty,
            rts_header.id AS rts_header_id,rts_header.order_reference AS order_reference,
            rts_body.id AS rts_body_id,rts_body.baan_location AS rts_location,
            location.location_code,
            location.location_hash AS location_hash
        FROM rts_detail
            JOIN rts_body ON rts_detail.rts_body_id = rts_body.id
            JOIN rts_header ON rts_body.rts_header_id = rts_header.id
            LEFT JOIN location ON rts_body.baan_location = location.location_code
        WHERE rts_detail.id = {$mRtsDtlId}
        LIMIT 1";

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

    if (mysqli_num_rows($mData) == 0)
    {
        return "FAIL-Error On RTS Transaction";
    }

    $mReturn = "";
    while ($mRow = mysqli_fetch_assoc($mData))
    {
        $mRtsHdrId = $mRow['rts_header_id'];
        $mRtsBdyId = $mRow['rts_body_id'];

        if ($mReturn == "")
        {
            if ($mSerialReference != $mRow['serial_reference'])
            {
                $mReturn = "FAIL-Invalid Serial";
            }
        }

        if ($mReturn == "")
        {
            if ($mFromLoc != $mRow['location_hash'])
            {
                if ($mFromLoc != $mRow['rts_location'])
                {
                    $mReturn = "FAIL-Invalid From Location";
                }
            }
        }

        if ($mReturn == "")
        {
            $mJsonArray['serialreference'] = $mSerialReference;
            $mJsonArray['partnumber'] = $mRow['part_number'];
            $mJsonArray['quantity'] = $mRow['received_qty'];
            $mJsonArray['transactiontypeid'] = $mTransactionTypeId;
            $mJsonArray['fromlocationcode'] = $mRow['rts_location'];
            $mJsonArray['tolocationcode'] = $mToLocCode;
            $mJsonArray['rtsreference'] = $mRow['order_reference'];
            $mJsonArray['currentuser'] = $mCurrentUser;

            $mRtsArray = array();
            $mRtsArray['partNumber'] = $mRow['part_number'];
            $mRtsArray['orderReference'] = $mRow['order_reference'];
            $mRtsArray['quantity'] = $mRow['received_qty'];
            $mRtsArray['user'] = $mCurrentUser;
            $mRtsArray['type'] = 'RTS';
        }
    }

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

// POST Operation
    try
    {
        include_once('transaction.php');
        $mStatus = postTransaction($mJsonObject, $mConnect, $mHost, $mUser, $mPwd, $mDbName);
        if (substr($mStatus, 0, 2) == "FA")
        {
            return "FAIL-" . $mStatus . "-" . $mJsonObject;
        }
    } catch (Exception $e)
    {
        exit("FAIL-Connection Error at - " . $mConnect . $mFilter . ":" . $e);
    }

// Update RTS status detail
    $mDataQuery = "UPDATE rts_detail
        SET qty_transacted = {$mJsonArray['quantity']},
            location_code = '{$mToLocCode}',
            last_updated = now(),
            last_updated_by = '{$mCurrentUser}',
            document_status_id = {$mDocCmpId}
        WHERE rts_detail.id = {$mRtsDtlId}
        LIMIT 1";
    if (!$mData = mysqli_query($mConnection, $mDataQuery))
    {
        exit ("FAIL-" . mysqli_error($mConnection) . "-" . $mDataQuery);
    }

// Update RTS status body
    $mDataQuery = "UPDATE rts_body
        SET
            qty_transacted = CASE WHEN qty_transacted IS NULL THEN {$mJsonArray['quantity']} ELSE qty_transacted + {$mJsonArray['quantity']} END,
            last_updated = now(),
            last_updated_by = '{$mCurrentUser}',
            document_status_id = CASE WHEN qty_transacted >= qty_received THEN {$mDocCmpId} ELSE {$mDocStsId} END
        WHERE rts_body.id = {$mRtsBdyId}
        LIMIT 1";
    if (!$mData = mysqli_query($mConnection, $mDataQuery))
    {
        exit ("FAIL-" . mysqli_error($mConnection) . "-" . $mDataQuery);
    }

// Update RTS Header
    $mDataQuery = "SELECT id
        FROM rts_body
        WHERE 
            rts_header_id = {$mRtsHdrId}
            AND document_status_id={$mDocStsId}
        LIMIT 1";
    if (!$mData = mysqli_query($mConnection, $mDataQuery))
    {
        exit ("FAIL-" . mysqli_error($mConnection) . "-" . $mDataQuery);
    }

    if (mysqli_num_rows($mData) == 0)
    {
        $mDataQuery = "UPDATE rts_header
            SET
                is_processed = 1,
                document_status_id = {$mDocCmpId},
                last_updated = now(),
                last_updated_by = '{$mCurrentUser}'
            WHERE rts_header.id={$mRtsHdrId}
            LIMIT 1";
    }

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

//  mysqli_close($mConnection);

// Send RTS Message    
    /*
        http://van-kuk-test:8093/vantec/writeRTSReturnMessage
        Request object :
        {
            "partNumber": "22U0152191NK",
            "quantity": 1.0,
            "user": "admin",
            "orderReference":"AC0021568",
            "type":"RTS"
        }
    */
// Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mRtsArray, JSON_FORCE_OBJECT);
    } catch (Exception $e)
    {
        exit("FAIL-Json Error");
    }

// Replace default Server Tomcat Service
    $mConnectp = str_replace(":8081/vantec", "/8093/vantec", $mConnect);
    if ($mConnectp == $mConnect)
    {
        $e = strpos($mConnect, ":8081");
        $mConnectp = substr($mConnect, 0, $e) . ":8093/vantec/";
    }
    $ch = curl_init();
    try
    {
        $mUrl = "writeRTSReturnMessage";
        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
        {
            // Updates inspect flag on Inventory master for stock with given serial number
            if ($mTransactionTypeId === 'RTSE')
            {
                $query = "UPDATE inventory_master
                    SET requires_inspection = 1
                    WHERE serial_reference = ?";
                $stmt = $mConnection->prepare($query);
                $stmt->bind_param('s', $mSerialReference);
                if (!$stmt->execute())
                {
                    exit('FAIL-' . $mConnection->error . ' - ' . $query);
                }
                $stmt->close();
            }
            $mErrMsg = "OK  - Post Complete";
        }
    } catch (Exception $e)
    {
        exit("FAIL-Connection Error at - " . $mConnect . $mFilter . ":" . $e);
    }

    if ($mReturn != "")
    {
        return $mReturn;
    }
    else
    {
        return "OK  -postRts";
    }
}


/**
 * Retrieves a list of locations based on the given type.
 *
 * @param string $mHost The host name for the database connection.
 * @param string $mUser The username for the database connection.
 * @param string $mPwd The password for the database connection.
 * @param string $mDbName The database name for the database connection.
 * @param string $mCurrentUser The current user.
 * @param string $mLocType The location type.
 *
 * @return string The JSON encoded dropdown items containing values, text, and color for each location.
 */
function getLocList($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $mLocType)
{
// 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.location_code AS location_code,
            location.location_hash AS location_hash 
        FROM location
            JOIN location_type ON location_type.id = location.location_type_id
        WHERE
            location_type.location_type_code = ?
        ORDER BY location_code
        LIMIT 100";

    $stmt = $mConnection->prepare($mDataQuery);
    $stmt->bind_param('s', $mLocType);
    if (!$stmt->execute())
    {
        exit ('FAIL-' . mysqli_error($mConnection) . '-' . $mDataQuery);
    }
    $result = $stmt->get_result();

    $mDropdown = [];
    while ($mRow = $result->fetch_assoc())
    {
        $mDropdown[] = [
            //'value' => 'toLocationHashCode:' . $mRow['location_hash'],
            'value' => 'toLocationHashCode:' . strtoupper($mRow['location_code']),
            'text' => strtoupper($mRow['location_code'])
        ];

//      echo("FAIL-TEST-".$mPrevCase."-".$mRow['case_reference']);
//         if (strpos($mRow['order_type'], 'EMER') !== false)
//         {
//             $mDropdown[] = array('value' => 'rtsReference:' . $mRow['order_reference'] . ',partNumber:' . $mRow['part_number'], 'text' => $mRow['part_number'] . ' / ' . $mRow['rts_location'], 'colour' => 'RED',);
//         }
//         else
//         {
//             $mDropdown[] = array('value' => 'rtsReference:' . $mRow['order_reference'] . ',partNumber:' . $mRow['part_number'], 'text' => $mRow['part_number'] . ' / ' . $mRow['rts_location'], 'colour' => 'WHITE',);
//         }
    }

    $result->free();
    $stmt->close();
    $mConnection->close();
    return 'DROP-' . json_encode($mDropdown);
}

/**
 * Checks if a location matches a specific type exists with the given location hash.
 *
 * @param string $mLocationHash The location hash to check.
 * @param string $mLocType The location type to check.
 * @param mysqli $mConnection The mysqli database connection.
 *
 * @return bool Returns true if a location of the specified type is found with the given location hash, otherwise false.
 */
function checkLocationType(string $mLocationHash, string $mLocType, mysqli $mConnection): bool
{
    $query = "SELECT location.id AS id
        FROM location
            JOIN location_type ON location_type.id = location.location_type_id
        WHERE 
            location.location_hash = ?
            AND location_type.location_type_code = ?
        LIMIT 1";
    $stmt = $mConnection->prepare($query);
    $stmt->bind_param('ss', $mLocationHash, $mLocType);
    if (!$stmt->execute())
    {
        exit ('FAIL-' . mysqli_error($mConnection) . '-' . $query);
    }
    $result = $stmt->get_result();
    $rowNum = $result->num_rows;

    $result->free();
    $stmt->close();

    return $rowNum > 0;
}

/**
 * Retrieves a list of inventory_master serials based on the given type.
 *
 * @param string $mHost The host name for the database connection.
 * @param string $mUser The username for the database connection.
 * @param string $mPwd The password for the database connection.
 * @param string $mDbName The database name for the database connection.
 * @param string $mCurrentUser The current user.
 * @param string $mLocType The location type.
 *
 * @return string The JSON encoded dropdown items containing values, text, and color for each location.
 */
function getSerialOsList($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $post)
{
    $mReturn = "";
    $now = date('Y-m-d H:i:s');
    $date = date('Ymd');
    $time = date('His');
    
// Explode Input String Into Array - Separated by ,
    $params = explode(",", $post);
// Create Associative Array by Exploding Array Elements on :
    for ($i = 0; $i < count($params); $i++)
    {
        $s = 0;
        $e = 0;
        $param = $params[$i];
        $s = strpos($param, ":");
        if ($s >= 0)
        {
            $key = substr($param, 0, $s);
            $val = substr($param, $s + 1);
        }
        if (strtolower($key) == "locationcode")
            $mLocationCode = strtoupper($val);
        elseif (strtolower($key) == "type")
            $mType = strtolower($val);
        elseif (strtolower($key) == "key")
            $mKey = strtoupper($val);
        elseif (strtolower($key) == "currentuser")
            $mCurrentUser = strtoupper($val);
        elseif ($key == "transactionType")
            $mTransactionTypeId = strtoupper($val);
    }
    if (empty($mTransactionTypeId))
    {
        $mTransactionTypeId = "RTSOS";
    }
// mysql connection - Use Passed values...
    $mConnection = mysqli_connect($mHost, $mUser, $mPwd, $mDbName) or
    exit('FAIL-Connect failed: ' . mysqli_connect_errno() . ' : ' . mysqli_connect_error());

    $mDataQuery = "SELECT
            inventory_master.serial_reference AS serial_reference,inventory_master.part_number AS part_number,inventory_master.location_code AS location_code
        FROM inventory_master
        JOIN location ON inventory_master.current_location_id=location.id
        WHERE
            inventory_qty=available_qty";
    if (!empty($mLocationCode))
    {
        $mDataQuery .=" AND location.location_code='$mLocationCode' OR location.location_hash='$mLocationCode'";
    }
    $mDataQuery .=" ORDER BY location_code, part_number, serial_reference
        LIMIT 1000";

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

    $mDropdown = array();
    while ($mRow = mysqli_fetch_assoc($mData))
    {
        if ($mType == "list")
        {
            $mDropdown[] = array('value' => $mRow['serial_reference'], 'text' => $mRow['location_code']." / ".$mRow['part_number']." / ".$mRow['serial_reference']);
        }
        else
        {
            $mDropdown[] = array('Part' => $mRow['part_number'], 'Serial' => $mRow['serial_reference']);
        }
    }
    if (mysqli_num_rows($mData) == 0)
    {
        $mDropdown[] = array('value' => "No Results", 'text' => "No Results");
    }
    
    $mConnection->close();
    if ($mType == "list")
    {
        return 'LIST:serialReference:'.json_encode($mDropdown);
    }
    else
    {
        return 'TABLE:serialReference:'.json_encode($mDropdown);
    }
}

function validateLoc($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $post)
{
    $mReturn = "";
    $now = date('Y-m-d H:i:s');
    $date = date('Ymd');
    $time = date('His');
    
// Explode Input String Into Array - Separated by ,
    $params = explode(",", $post);
// Create Associative Array by Exploding Array Elements on :
    for ($i = 0; $i < count($params); $i++)
    {
        $s = 0;
        $e = 0;
        $param = $params[$i];
        $s = strpos($param, ":");
        if ($s >= 0)
        {
            $key = substr($param, 0, $s);
            $val = substr($param, $s + 1);
        }
        if (strtolower($key) == "locationcode")
            $mLocationCode = strtoupper($val);
        elseif (strtolower($key) == "key")
            $mKey = strtoupper($val);
        elseif (strtolower($key) == "currentuser")
            $mCurrentUser = strtoupper($val);
        elseif ($key == "transactionType")
            $mTransactionTypeId = strtoupper($val);
    }
    if (empty($mTransactionTypeId))
    {
        $mTransactionTypeId = "";
    }
// mysql connection - Use Passed values...
    $mConnection = mysqli_connect($mHost, $mUser, $mPwd, $mDbName) or
    exit('FAIL-Connect failed: ' . mysqli_connect_errno() . ' : ' . mysqli_connect_error());

    $mDataQuery = "SELECT
            location.id, location_type.location_type_code, location.location_code
        FROM location
        JOIN location_type ON location.location_type_id=location_type.id";
    $mDataQuery .=" WHERE
        location.location_code='$mLocationCode' OR location.location_hash='$mLocationCode'";
    $mDataQuery ."
        LIMIT 1";

    if (!$mData = mysqli_query($mConnection, $mDataQuery))
    {
        exit("FAIL-" . mysqli_error($mConnection) . "-" . $mDataQuery);
    }
    
    if (mysqli_num_rows($mData) == 0)
    {
        $mReturn = "FAIL-Invalid Location";
    }
    if (empty($mReturn))
    {
        list($mId,$mLocType,$mLocationCode) = mysqli_fetch_row($mData);
        if (!empty($mKey))
        {
            if ($mKey != $mLocType)
            {
                $mReturn = "FAIL-Wrong Location Type";
            }
        }
    }
    
    $mConnection->close();
    
    if (empty($mReturn))
    {
        $mReturn = "OK  -validateLoc";
    }
    return $mReturn;
}

function getMarLoc($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $post)
{
    $mReturn = "";
    $now = date('Y-m-d H:i:s');
    $date = date('Ymd');
    $time = date('His');
    
// Explode Input String Into Array - Separated by ,
    $params = explode(",", $post);
// Create Associative Array by Exploding Array Elements on :
    for ($i = 0; $i < count($params); $i++)
    {
        $s = 0;
        $e = 0;
        $param = $params[$i];
        $s = strpos($param, ":");
        if ($s >= 0)
        {
            $key = substr($param, 0, $s);
            $val = substr($param, $s + 1);
        }
        if (strtolower($key) == "locationcode")
            $mLocationCode = strtoupper($val);
        elseif (strtolower($key) == "key")
            $mKey = strtoupper($val);
        elseif (strtolower($key) == "currentuser")
            $mCurrentUser = strtoupper($val);
        elseif ($key == "transactionType")
            $mTransactionTypeId = strtoupper($val);
    }
    if (empty($mTransactionTypeId))
    {
        $mTransactionTypeId = "";
    }
// mysql connection - Use Passed values...
    $mConnection = mysqli_connect($mHost, $mUser, $mPwd, $mDbName) or
    exit('FAIL-Connect failed: ' . mysqli_connect_errno() . ' : ' . mysqli_connect_error());

    $mDataQuery = "SELECT
            location.id, location.location_code
        FROM location";
    $mDataQuery .=" WHERE
        location.location_code='$mLocationCode' OR location.location_hash='$mLocationCode'";
    $mDataQuery ."
        LIMIT 1";

    if (!$mData = mysqli_query($mConnection, $mDataQuery))
    {
        exit("FAIL-" . mysqli_error($mConnection) . "-" . $mDataQuery);
    }
    
    if (mysqli_num_rows($mData) == 0)
    {
        $mReturn = "FAIL-Invalid Location";
    }
    list($mid,$mLocationCode) = mysqli_fetch_row($mData);
    if (empty($mReturn))
    {
        $mDataQuery = "SELECT
            location.id AS id, location.location_code AS location_code
            FROM zone_destination
            LEFT JOIN location ON zone_destination.marshall_id=location.id";
        $mDataQuery .=" WHERE
            zone_destination.zone_destination='$mLocationCode'";
        $mDataQuery ."
            LIMIT 1";
        
        if (!$mData = mysqli_query($mConnection, $mDataQuery))
        {
            exit("FAIL-" . mysqli_error($mConnection) . "-" . $mDataQuery);
        }
        if (mysqli_num_rows($mData) == 0)
        {
            $mReturn = "FAIL-Invalid Zone";
        }
        else
        {
            list($mId,$mToLocCode) = mysqli_fetch_row($mData);
            if (!empty($mToLocCode))
            {
                $mReturn = "DATA:toLocationHashCode:".$mToLocCode."::skiptoLocationHashCode";
            }
        }
        error_log("return.php-".$mDataQuery." ".$mLocationCode);
    }
    $mConnection->close();
    
    if (empty($mReturn))
    {
        $mReturn = "OK  -validateLoc";
    }
    return $mReturn;
}

function validateSerialOs($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $post)
{
    $mReturn = "";
    $now = date('Y-m-d H:i:s');
    $date = date('Ymd');
    $time = date('His');
    
// Explode Input String Into Array - Separated by ,
    $params = explode(",", $post);
// Create Associative Array by Exploding Array Elements on :
    for ($i = 0; $i < count($params); $i++)
    {
        $s = 0;
        $e = 0;
        $param = $params[$i];
        $s = strpos($param, ":");
        if ($s >= 0)
        {
            $key = substr($param, 0, $s);
            $val = substr($param, $s + 1);
        }
        if (strtolower($key) == "locationcode")
            $mLocationCode = strtoupper($val);
        elseif (strtolower($key) == "serialreference")
            $mSerialReference = strtoupper($val);
        elseif (strtolower($key) == "partnumber")
            $mPartNumber = strtoupper($val);
        elseif (strtolower($key) == "currentuser")
            $mCurrentUser = strtoupper($val);
        elseif ($key == "transactionType")
            $mTransactionTypeId = strtoupper($val);
    }
    if (empty($mTransactionTypeId))
    {
        $mTransactionTypeId = "RTSOS";
    }
    
    if (empty($mLocationCode))
    {
        return "DATA:fromLocHashCode:::skipfromLocHashCode";
    }
// 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.id, location.location_code,location_type.location_type_code
        FROM location
        JOIN location_type ON location.location_type_id=location_type.id";
    $mDataQuery .=" WHERE
        location.location_code='$mLocationCode' OR location.location_hash='$mLocationCode'";
    $mDataQuery ."
        LIMIT 1";

    if (!$mData = mysqli_query($mConnection, $mDataQuery))
    {
        exit("FAIL-" . mysqli_error($mConnection) . "-" . $mDataQuery);
    }
    
    if (mysqli_num_rows($mData) == 0)
    {
        $mReturn = "FAIL-Invalid Location";
    }
    if (empty($mReturn))
    {
        list($mId,$mLocationCode,$mLocType) = mysqli_fetch_row($mData);
        if (!empty($mKey))
        {
            if ($mKey != $mLocType)
            {
                $mReturn = "FAIL-Wrong Location Type";
            }
        }
    }
    if (empty($mReturn))
    {
        if (empty($mSerialReference))
        {
            $mReturn = "DATA:serialReference:::skipserialReference";
        }
    }
    if (empty($mReturn))
    {
        $mDataQuery = "SELECT inventory_master.id AS id,inventory_master.part_number AS part_number,inventory_master.location_code AS location_code,
                        inventory_master.allocated_qty AS allocated_qty, inventory_master.picked_qty AS picked_qty
                        FROM inventory_master
                        WHERE serial_reference='$mSerialReference'";
        if (!empty($mPartNumber))
        {
            $mDataQuery .=" AND part_number='$mPartNumber'";
        }
        $mDataQuery .=" LIMIT 2";

        if (!$mData = mysqli_query($mConnection, $mDataQuery))
        {
            exit("FAIL-" . mysqli_error($mConnection) . "-" . $mDataQuery);
        }
        error_log("return.php-".$mDataQuery);
        if (mysqli_num_rows($mData) == 0)
        {
            $mReturn = "FAIL-Invalid Serial";
        }
        elseif (mysqli_num_rows($mData) > 1)
        {
            $mReturn = "DATA:partNumber:::skippartNumber";
        }
        else
        {
            list($mInvId,$mPartNumber,$mInvLoc,$mAlcQty,$mPkdQty) = mysqli_fetch_row($mData);
            if ($mLocationCode != $mInvLoc)
            {
                $mReturn = "FAIL-Invalid Location / Serial ";
            }
            elseif($mAlcQty > 0)
            {
                $mReturn = "FAIL-Serial is Allocated";
            }
            elseif($mPkdQty > 0)
            {
                $mReturn = "FAIL-Serial is Picked";
            }
        }
    }
    $mConnection->close();
    if (empty($mReturn))
    {
//        $mReturn = "OK  -validateSerial";
        $mReturn = "DATA:partNumber:".$mPartNumber;
    }
    return $mReturn;
}

function getLocPartList($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $post)
{
    $mLocationCode = "";
    $mPartNumber = "";
    $now = date('Y-m-d H:i:s');
    $date = date('Ymd');
    $time = date('His');
    $mType = "DROP";
    
// Explode Input String Into Array - Separated by ,
    $params = explode(",", $post);
// Create Associative Array by Exploding Array Elements on :
    for ($i = 0; $i < count($params); $i++)
    {
        $s = 0;
        $e = 0;
        $param = $params[$i];
        $s = strpos($param, ":");
        if ($s >= 0)
        {
            $key = substr($param, 0, $s);
            $val = substr($param, $s + 1);
        }
        if (strtolower($key) == "locationcode")
            $mLocationCode = strtoupper($val);
        if (strtolower($key) == "partnumber")
            $mPartNumber = strtoupper($val);
        elseif (strtolower($key) == "type")
            $mType = strtoupper($val);
        elseif (strtolower($key) == "currentuser")
            $mCurrentUser = strtoupper($val);
        elseif ($key == "transactionType")
            $mTransactionTypeId = strtoupper($val);
    }
    if (empty($mTransactionTypeId))
    {
        $mTransactionTypeId = "";
    }
// mysql connection - Use Passed values...
    $mConnection = mysqli_connect($mHost, $mUser, $mPwd, $mDbName) or
    exit('FAIL-Connect failed: ' . mysqli_connect_errno() . ' : ' . mysqli_connect_error());

    $mDataQuery = "SELECT
            inventory_master.part_number AS part_number,max(location.location_code) AS location_code, sum(inventory_master.available_qty) AS available_qty
        FROM inventory_master
        JOIN location ON inventory_master.current_location_id=location.id
        WHERE
            inventory_master.available_qty>0";
        if (!empty($mLocationCode))
        {
            $mDataQuery .=" AND (location.location_code='$mLocationCode' OR location.location_hash='$mLocationCode')";
        }
        if (!empty($mPartNumber))
        {
            $mDataQuery .=" AND inventory_master.part_number='$mPartNumber'";
        }
            
        $mDataQuery .=" GROUP BY inventory_master.part_number ORDER BY inventory_master.part_number
        LIMIT 100";

    if (!$mData = mysqli_query($mConnection, $mDataQuery))
    {
        exit("FAIL-" . mysqli_error($mConnection) . "-" . $mDataQuery);
    }
    error_log("return.php-".$mDataQuery." ".mysqli_num_rows($mData)." ".$mType);
    $mDropdown = array();
    while ($mRow = mysqli_fetch_assoc($mData))
    {
        if (strtoupper($mType) == "DROP")
        {
            $mDropdown[] = array('value' => "partNumber:" . $mRow['part_number'], 'text' => $mRow['part_number']." (".$mRow['available_qty'].")");
        }
        elseif(strtoupper($mType) == "LIST")
        {
            $mDropdown[] = array('value' => $mRow['part_number'], 'text' => $mRow['available_qty']);
        }
    }
    $mConnection->close();
    if (strtoupper($mType) == "VAL")
    {
        if (mysqli_num_rows($mData) == 0)
        {
            $mPartNumber='';
            return "DATA:toLocationHashCode:*,partNumber:*::skippartNumber";
        }
        else
        {
            return "OK  -getLocPartList";
        }
    }
    if (strtoupper($mType) == "LIST")
    {
        return $mType.':partNumber:'.json_encode($mDropdown);
    }
    else
    {
        return $mType."-".json_encode($mDropdown);
    }
}

function postInvLoc($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $post)
{
    $mJsonArray = array();
    $mReturn = "";
    $now = date('Y-m-d H:i:s');
    $date = date('Ymd');
    $time = date('His');
    
// Explode Input String Into Array - Separated by ,
    $params = explode(",", $post);
// Create Associative Array by Exploding Array Elements on :
    for ($i = 0; $i < count($params); $i++)
    {
        $s = 0;
        $e = 0;
        $param = $params[$i];
        $s = strpos($param, ":");
        if ($s >= 0)
        {
            $key = substr($param, 0, $s);
            $val = substr($param, $s + 1);
        }
        if (strtolower($key) == "fromlocationhashcode")
            $mFromLocationCode = strtoupper($val);
        elseif (strtolower($key) == "partnumber")
            $mPartNumber = strtoupper($val);
        if (strtolower($key) == "tolocationhashcode")
            $mToLocationCode = strtoupper($val);
        elseif (strtolower($key) == "currentuser")
            $mCurrentUser = strtoupper($val);
        elseif ($key == "transactionTypeId")
            $mTransactionTypeId = strtoupper($val);
            
        if ((strtolower($key) == "quantity") || (strtolower($key) == "countqty"))
            $mJsonArray[strtolower($key)] = floatval($val);
        elseif (strtolower($key) == "jserialreference")
            $mJsonArray['serialreference'] = $val;
        else
            $mJsonArray[strtolower($key)] = $val;
    }
    if (empty($mTransactionTypeId))
    {
        $mTransactionTypeId = "LSTM";
    }
// mysql connection - Use Passed values...
    $mConnection = mysqli_connect($mHost, $mUser, $mPwd, $mDbName) or
    exit('FAIL-Connect failed: ' . mysqli_connect_errno() . ' : ' . mysqli_connect_error());

    $mDataQuery = "SELECT
            inventory_master.* 
        FROM inventory_master
        JOIN location ON inventory_master.current_location_id=location.id";
    $mDataQuery .=" WHERE
            inventory_master.part_number='$mPartNumber' AND
            (location.location_code='$mFromLocationCode' OR location.location_hash='$mFromLocationCode')
            AND inventory_master.available_qty>0";
    $mDataQuery ."
        LIMIT 1000";

    if (!$mData = mysqli_query($mConnection, $mDataQuery))
    {
        exit("FAIL-" . mysqli_error($mConnection) . "-" . $mDataQuery);
    }
    
    if (mysqli_num_rows($mData) == 0)
    {
        $mReturn = "FAIL-Invalid Part / Location";
    }
    include_once ('transaction.php');
    while ($mRow = mysqli_fetch_assoc($mData))
    {
        $mJsonArray['serialreference'] = $mRow['serial_reference'];
// Convert Array to Json Object
    try
    {
        $mJsonObject = json_encode($mJsonArray, JSON_FORCE_OBJECT);
    }
    catch(Exception $e)
    {
        exit("FAIL-Json Error");
    }
    $mStatus = postRcts($mJsonObject,$mConnect,$mHost,$mUser,$mPwd,$mDbName);
    echo($mStatus);
    return;
    }
    $mConnection->close();
    if (empty($mReturn))
    {
        $mReturn = "OK  -postInvLoc";
    }
    return $mReturn;
}

function labelPrint($mHost, $mUser, $mPwd, $mDbName, $mCurrentUser, $post)
{
    global $baseDir;
    require_once $baseDir.'/rdtvims/rdtphp/classes/MysqliVeu.php';
    
    $mReturn = "";
    $now = date('Y-m-d H:i:s');
    $date = date('Ymd');
    $time = date('His');
    
// Explode Input String Into Array - Separated by ,
    $params = explode(",", $post);
// Create Associative Array by Exploding Array Elements on :
    for ($i = 0; $i < count($params); $i++)
    {
        $s = 0;
        $e = 0;
        $param = $params[$i];
        $s = strpos($param, ":");
        if ($s >= 0)
        {
            $key = substr($param, 0, $s);
            $val = substr($param, $s + 1);
        }
        if (strtolower($key) == "location")
            $mLocationCode = strtoupper($val);
        elseif (strtolower($key) == "partnumber")
            $mPartNumber = strtoupper($val);
        elseif (strtolower($key) == "printer")
            $mPrinter = strtoupper($val);
        elseif (strtolower($key) == "currentuser")
            $mCurrentUser = strtoupper($val);
        elseif ($key == "transactionType")
            $mTransactionTypeId = strtoupper($val);
    }
    if (empty($mTransactionTypeId))
    {
        $mTransactionTypeId = "";
    }
    $db = new classes\MysqliVeu($mHost,$mUser,$mPwd,$mDbName);
    
    $sql = "SELECT printer_address 
            FROM printer_mapping
            WHERE printer_code=:ref OR printer_address=:ref
            LIMIT 1";
    $params = "ref:".$mPrinter;
    $result = $db->queryParamsJson($sql, $params);
    try
    {
        $result = json_decode($result,true);
    }
    catch (Exception $e)
    {
    }
    $message = $result['message'];
    $numRows = $result['numrows'];
    $rows = $result['data'];
    $mPrinter = $rows[0]['printer_address'];
//    $printer = new Printer($mPrinter);
    
    // Label Layout
/*
$mLabel = "
HEADER
^XA
~JSN
^LT0
^MTD
^PON
^PMN
^LH0,0
^JMA
^PR5,5
~SD10
^JUS
^LRN
^CI27
^PA0,1,1,0
^XZ
^XA
^MMR
^LS0
LABEL1
^FO56,965^GFA,745,2400,12,:Z64:eJy9VUFq5DAQbDuYCYIQ8gAzIadhPpFc9glhT/7DHhb2ErAwhCx5hcnJ6BXzhLkEcohgn+C9r/Gq1S11D0zYGTZJMwOiXGpVl1oSAMAFFBfAse5Ll8bNpvBp7AJuedxuilnz7ZH8T8vvvfBDZP48C1/hh/LTuPb+NY2NwhfzPKZx6VwPe+KnxR/FD4CvOX93Kfrvt6LncRA9D6Po6XrRv8Pv9/MD/v75f+/15zP91/hbcbuRsd6V9peM1wpv/od/gP6P9qd5vv2S+cPp6VH6FX4sX0ep9FRKv67r+sP9aYX/dHX1L/0H7u+Q+fMcv1ySnrjsTdRD7bmKfKLfRT5dD2uL/D7nblg9UpP69k/4j6lWm/U0fpP1rMMEpFvO/R2gINzh2sZGvrdBU83a+4A54qMYuj/Je7o/2csm4ZbkRu/DhEXCg9SS8+fD6Nj8xG+zTnEN+dWr4F2qF/eWJ8R1ueCohyfE9Hz9Uy+0wmeHSP/ZVnDjhC/1Jh+QH1atLefv0bdVrreAb6w/fO8G4qNB1ZZxnDBQL2Py61H4WDP2/kvIM42QmsdEL6h5lrElqHnIowrTF95jBYb0k3fYy0t+YWJHMH4W+JOfYsUG/WE81LqY04sU/Mx7UMciIh9MJ3tTID29YE7tWT2FYNwo/ETxS4Wr/LlZYogempBPUtIPsHvCzndf1IwXkl+OGMZS+OwzT5gEB4XDUuFG4ZXkB1A49kOOFbwZfwGCahVQ:C84C
^FO46,40^GB727,1135,2^FS
^FT169,1163^A0B,25,25^FH\^CI28^FDPart Number:^FS^CI27
^FT249,1148^A0B,56,46^FH\^CI28^FDpart_number^FS^CI27
^BY3,3,125^FT282,675^BCB,,N,N,,A
^FDPpart_number^FS
^FO298,40^GB0,1135,2^FS
^FT327,1163^A0B,26,25^FH\^CI28^FDQTY:^FS^CI27
^FT428,1148^A0B,102,84^FH\^CI28^FDavailable_qty^FS^CI27
^BY3,3,125^FT440,675^BCB,,N,N,,A
^FDQavailable_qty^FS
^FO140,40^GB0,1135,2^FS
^FT485,1163^A0B,26,25^FH\^CI28^FDSerial Number:^FS^CI27
^FT576,1148^A0B,79,66^FH\^CI28^FDserial_reference^FS^CI27
^BY3,3,125^FT598,675^BCB,,N,N,,A
^FDSserial_reference^FS
^FO456,40^GB0,1135,2^FS
^FO613,40^GB0,1135,2^FS
^PQ1,,,Y
FOOTER
^XZ
";
*/

$mLabel = "
HEADER
^XA
LABEL1
^PR2
^FO30,90^A0,30^FDFLDDT^FS
^FO30,180^A0,50^FDpart_number^FS
^FO460,180^A0,30^FDQty:^FS
^FO505,180^A0,40^FDavailable_qty^FS
^FO40,230^A0,30^FDpart_description^FS
^FO40,260^BY2^B3N,N,90,N,N^FDSserial_reference^FS
^FO200,360^A0,30^FDserial_reference^FS
FOOTER
^XZ
";

// Add NewLine Characters
    $lines=explode(PHP_EOL,$mLabel);

// No, Labels to a row (0=single label, 1=double labels)
    $mLabelsAcross = 0;
    $mHeaders = array();
    $mContent1 = "";
    $mContent2 = "";
    $mFooters = array();
    $c = 0;
    $i = 0;
    
// Build label from template
    foreach($lines as $line)
    {
        if ($line == "HEADER")
        {
            $c = 0;
            continue;
        }
        if ($line == "LABEL1")
        {
            $c = 1;
            continue;
        }
        if ($line == "LABEL2")
        {
            $c = 2;
            continue;
        }
        if ($line == "FOOTER")
        {
            $c = 9;
            continue;
        }
        if ($c == 0)
            $mHeader .= $line."\n";
        if ($c == 1)
            $mContent1 .= $line."\n";
        if ($c == 2)
            $mContent2 .= $line."\n";
        if ($c == 9)
            $mFooter .= $line."\n";
    }
// Label Data
    $mLabelContent1 = $mContent1;
    $mLabelContent2 = $mContent2;

    $sql = "SELECT
            inventory_master.*,
            DATE_FORMAT(now(),'%d/%m/%Y %H:%i') AS FLDDT,
            part.part_description AS part_description
        FROM inventory_master
        JOIN location ON inventory_master.current_location_id=location.id
        LEFT JOIN part ON inventory_master.part_id=part.id";
    $sql .=" WHERE
            inventory_master.part_number=:part AND
            (location.location_code=:loc OR location.location_hash=:loc)";
    $sql ."
        LIMIT 1000";
    $params = "part:".$mPartNumber.",loc:".$mLocationCode;
    $result = $db->queryParamsJson($sql, $params);
    try
    {
        $result = json_decode($result,true);
    }
    catch (Exception $e)
    {
    }
    $message = $result['message'];
    $numRows = $result['numrows'];
    $rows = $result['data'];
// Populate Label with data `
    $c = 0;
    foreach($rows as $row)
    {
        $i = 0;
        foreach($row as $k=>$v)
        {
// Replace Template placeholder with Value
            if ($c == 0)
                $mLabelContent1 = str_replace($k,$v,$mLabelContent1);
            else
                $mLabelContent2 = str_replace($k,$v,$mLabelContent2);
            $i++;
        }
        $c++;
        if ($c > $mLabelsAcross)
        {
// Send Label to Printer
            $fp = fsockopen($mPrinter, 9100, $errno, $errstr, 30);
			if ($fp !== false)
			{
				if (!empty($mHeader))
				{
					fwrite ($fp,$mHeader.'\n');
				}
				else
				{
					fwrite ($fp,"\x02L\n");
					fwrite ($fp,"H08\n");
					fwrite ($fp,"D11\n");
				}
				fwrite($fp,$mLabelContent1.$mLabelContent2);
				if (!empty($mFooter))
				{
					fwrite ($fp,$mFooter.'\n');
				}
				else
				{
					fwrite ($fp,"E\n"); 
				}
				fclose($fp);
            }
// Restore Print Layout for next labels
            $mLabelContent1 = $mContent1;
            $mLabelContent2 = $mContent2;
            $c = 0;
        }
    }
    return "OKMS-labels Printed to ".$mPrinter;
}
