<?php
// reloc.php
// VIMS RDT Reloc Process
// ----------------------------------------------------------------------------------------
// Modified 2021-07-15 - Created.
// ----------------------------------------------------------------------------------------
header('Cache-Control: no-cache, no-store, must-revalidate');   
header('Expires: 0');
set_time_limit(0);
// Enable exceptions for MySQLi errors
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// error_reporting(E_ALL);
// ini_set('display_errors', 1);

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

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

$mSQLData = array();

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

// Get RELOC task list
if (($mFunction != null) && (strtolower($mFunction) == "getreloclist"))
{
//  echo("FAIL-TEST2");
    $mErrMsg = "";
    $mReference="";
    $mOffset=0;
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "reference")
            $mReference = trim($v2);
        elseif ($k2 == "key")
            $mKey = trim($v2);
        elseif ($k2 == "offset")
            $mOffset = trim($v2);   
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    $mStatus = getRelocList($mHost,$mUser,$mPwd,$mDbName,$mCurrentUser,$mReference,$mKey,$mOffset);
    echo $mStatus;
    return;
}
// Get Selected RELOC Task
if (($mFunction != null) && (strtolower($mFunction) == "getreloc"))
{
    $mErrMsg = "";
    $mBdyId="";
// 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 == "bdyid")
            $mBdyId = trim($v2);
        elseif ($k2 == "documentreference")
            $mDocumentReference = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionType")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    $mStatus = getReloc($mFilter,$mHost,$mUser,$mPwd,$mDbName,'',$mBdyId,$mDocumentReference);
    echo $mStatus;
    return;
}
// Get Next RELOC Task
if (($mFunction != null) && (strtolower($mFunction) == "getnextreloc"))
{
    $mErrMsg = "";
    $mStatus = getNextReloc($mFilter,$mHost,$mUser,$mPwd,$mDbName);
    echo $mStatus;
    return;
}
// Validate RELOC Task
if (($mFunction != null) && (strtolower($mFunction) == "validatereloc"))
{
    $mErrMsg = "";
    $mStatus = validateReloc($mFilter,$mHost,$mUser,$mPwd,$mDbName);
    echo $mStatus;
    return;
}
// clear RELOC Task
if (($mFunction != null) && (strtolower($mFunction) == "clearreloc"))
{
    $mErrMsg = "";
    $mStatus = clearReloc($mFilter,$mHost,$mUser,$mPwd,$mDbName);
    echo $mStatus;
    return;
}
// complete RELOC Task
if (($mFunction != null) && (strtolower($mFunction) == "completereloc"))
{
    $mErrMsg = "";
    $mStatus = completeReloc($mFilter,$mHost,$mUser,$mPwd,$mDbName);
    echo $mStatus;
    return;
}
// Missing RELOC Serial
if (($mFunction != null) && ($mFunction == "missingrelocserial"))
{
    $mErrMsg = "";
    $mStatus = missingRelocSerial($mFilter,$mHost,$mUser,$mPwd,$mDbName);
    echo $mStatus;
    return;
}
// Map Location
if (($mFunction != null) && ($mFunction == "maploc"))
{
    $mErrMsg = "";
    $mStatus = mapLoc($mFilter,$mHost,$mUser,$mPwd,$mDbName);
    echo $mStatus;
    return;
}

// Map Location
if (($mFunction != null) && ($mFunction == "moveloc"))
{
    $mErrMsg = "";
    $mStatus = moveLoc($mFilter,$mHost,$mUser,$mPwd,$mDbName);
    echo $mStatus;
    return;
}

function getRelocList($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";
    $mDataQuery .= " reloc_header.id AS header_id,reloc_header.document_reference AS document_reference,reloc_header.to_location AS to_location";
    $mDataQuery .= ",reloc_body.id AS body_id";
    $mDataQuery .= ",inventory_master.part_id AS part_id, inventory_master.current_location_id AS location_id,inventory_master.serial_reference AS serial_reference,inventory_master.inventory_qty AS inventory_qty";
    $mDataQuery .= ",location.location_code AS from_location";
    $mDataQuery .= ",part.part_number AS part_number";
    $mDataQuery .= " FROM reloc_header";
    $mDataQuery .= " JOIN reloc_body ON reloc_header.id=reloc_body.reloc_header_id";
    $mDataQuery .= " JOIN inventory_master ON reloc_body.inventory_master_id=inventory_master.id";
    $mDataQuery .= " JOIN part ON inventory_master.part_id=part.id";
    $mDataQuery .= " JOIN location ON inventory_master.current_location_id=location.id";
    $mDataQuery .= " LEFT JOIN reloc_task_type ON reloc_header.from_location=reloc_task_type.cust_from_location";
    $mDataQuery .= " WHERE (reloc_body.processed=0 OR reloc_body.processed IS null)";
    $mDataQuery .= " AND (reloc_body.in_use IS null OR reloc_body.in_use='' OR reloc_body.in_use='".$mCurrentUser."' OR (reloc_body.last_updated < DATE_SUB(NOW(), INTERVAL 10 MINUTE)))";
    $mDataQuery .= " AND NOT EXISTS(SELECT id FROM chgpno_task WHERE reloc_body.serial_reference=chgpno_task.serial_reference AND chgpno_task.processed=0)";
    $mDataQuery .= " ORDER by reloc_header.date_created LIMIT 50 OFFSET ".$mOffset;
    
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
//  exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
    $mDropdown = array();
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
//      echo("FAIL-TEST-".$mPrevCase."-".$mRow['case_reference']);
        $mDropdown[] = array('value' => "documentReference:".$mRow['document_reference'].",allocationId:".$mRow['body_id'],'text' => $mRow['part_number']." ".$mRow['from_location'],);
    }
    mysqli_close($mConnection);
    return "DROP-".json_encode($mDropdown);
}

// get selected RELOC task
function getReloc($mFilter,$mHost,$mUser,$mPwd,$mDbName,$mConnect=null,$mBdyId,$mDocumentReference='')
{
    $mReturn = "";
    $mErrMsg = "";
    $mPartNumber = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
    if (!$mConnection)
        return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
    $mDataQuery = "SELECT";
    $mDataQuery .= " reloc_header.id AS header_id";
    $mDataQuery .= ",reloc_body.id AS body_id";
    $mDataQuery .= ",inventory_master.part_id AS part_id, inventory_master.current_location_id AS location_id,inventory_master.serial_reference AS serial_reference,inventory_master.inventory_qty AS inventory_qty";
    $mDataQuery .= ",location.location_code AS from_location";
    $mDataQuery .= ",reloc_header.to_location AS to_location";
    $mDataQuery .= ",reloc_body.quantity AS reloc_qty";
    $mDataQuery .= ",part.part_number AS part_number";
    $mDataQuery .= " FROM reloc_header";
    $mDataQuery .= " JOIN reloc_body ON reloc_header.id=reloc_body.reloc_header_id";
    $mDataQuery .= " JOIN inventory_master ON reloc_body.inventory_master_id=inventory_master.id";
    $mDataQuery .= " JOIN part ON inventory_master.part_id=part.id";
    $mDataQuery .= " JOIN location ON inventory_master.current_location_id=location.id";
    $mDataQuery .= " LEFT JOIN reloc_task_type ON reloc_header.from_location=reloc_task_type.cust_from_location";
    $mDataQuery .= " WHERE reloc_header.id>0 AND reloc_header.processed =0";
    $mDataQuery .= " AND (reloc_body.processed IS null OR reloc_body.processed=0)";
    if (!empty($mBdyId))
    {
        $mDataQuery .= " AND reloc_body.id=".$mBdyId;
    }
    if (!empty($mDocumentReference))
    {
        $mDataQuery .=" AND reloc_header.document_reference='$mDocumentReference'";
    }
    $mDataQuery .= " AND NOT EXISTS(SELECT id FROM chgpno_task WHERE reloc_body.serial_reference=chgpno_task.serial_reference AND chgpno_task.processed=0)";
    $mDataQuery .= " LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    $mPartId = "";
    $mToLoc = "";
//  return("FAIL-TEST1-".$mDataQuery."-".mysqli_num_rows($mData));
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mReturn = "DATA:sequencingRequestId:".$mRow['header_id'].",allocationId:".$mRow['body_id'].",fromLocationCodecontent:".$mRow['from_location'].",serialReferencecontent:".$mRow['serial_reference'].",partNumber:".$mRow['part_number'].",quantity:".$mRow['reloc_qty'];
        $mDataQuery = "UPDATE reloc_body SET in_use='".$mCurrentUser."', last_updated=now(),last_updated_by='".$mCurrentUser."' WHERE id=".$mRow['body_id']." LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    }
    if (mysqli_num_rows($mData) == 0)
    {
        $mReturn = "FAIL-No Reloc Tasks";
    }       
    if ($mReturn == "")
        $mReturn = "OK  -getNextReloc";
//  return ("FAIL-TEST1-".$mReturn);
    return ($mReturn);
}

function getNextReloc($mFilter,$mHost,$mUser,$mPwd,$mDbName,$mConnect=null)
{
    $mReturn = "";
    $mErrMsg = "";
    $mPartNumber = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
    if (!$mConnection)
        return "FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error();
    $mDataQuery = "SELECT";
    $mDataQuery .= " reloc_header.id AS header_id,reloc_header.document_reference AS document_reference";
    $mDataQuery .= ",reloc_body.id AS body_id";
    $mDataQuery .= ",inventory_master.part_id AS part_id, inventory_master.current_location_id AS location_id,inventory_master.serial_reference AS serial_reference,inventory_master.inventory_qty AS inventory_qty";
    $mDataQuery .= ",location.location_code AS from_location";
    $mDataQuery .= ",reloc_header.to_location AS to_location";
    $mDataQuery .= ",part.part_number AS part_number";
    $mDataQuery .= " FROM reloc_header";
    $mDataQuery .= " JOIN reloc_body ON reloc_header.id=reloc_body.reloc_header_id";
    $mDataQuery .= " JOIN inventory_master ON reloc_body.inventory_master_id=inventory_master.id";
    $mDataQuery .= " JOIN part ON inventory_master.part_id=part.id";
    $mDataQuery .= " JOIN location ON inventory_master.current_location_id=location.id";
    $mDataQuery .= " LEFT JOIN reloc_task_type ON reloc_header.from_location=reloc_task_type.cust_from_location";
    $mDataQuery .= " WHERE (reloc_body.processed=0 OR reloc_body.processed IS null)";
    $mDataQuery .= " AND (reloc_body.in_use IS null OR reloc_body.in_use='' OR reloc_body.in_use='".$mCurrentUser."' OR (reloc_body.last_updated < DATE_SUB(NOW(), INTERVAL 10 MINUTE)))";
    $mDataQuery .= " AND NOT EXISTS(SELECT id FROM chgpno_task WHERE reloc_body.serial_reference=chgpno_task.serial_reference AND chgpno_task.processed=0)";
    $mDataQuery .= " LIMIT 1";
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    $mPartId = "";
    $mToLoc = "";
//  return("FAIL-TEST1-".$mDataQuery."-".mysqli_num_rows($mData));
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mReturn = "DATA:sequencingRequestId:".$mRow['header_id'].",allocationId:".$mRow['body_id'].",documentReference:".$mRow['document_reference'].",fromLocationCodecontent:".$mRow['from_location'].",serialReferencecontent:".$mRow['serial_reference'].",partNumber:".$mRow['part_number'].",quantity:".$mRow['inventory_qty'];
        $mDataQuery = "UPDATE reloc_body SET in_use='".$mCurrentUser."', last_updated=now(),last_updated_by='".$mCurrentUser."' WHERE id=".$mRow['body_id']." LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
    }
    if (mysqli_num_rows($mData) == 0)
    {
        $mReturn = "FAIL-No Reloc Tasks";
    }       
    if ($mReturn == "")
        $mReturn = "OK  -getNextReloc";
//  return ("FAIL-TEST1-".$mReturn);
    return ($mReturn);
}

// Validate Replen
function validateReloc($mFilter,$mHost,$mUser,$mPwd,$mDbName,$mConnect=null)
{
    $array = ['RTVQR' => 'RTVQR', 'INSP00' => 'INSP00'];
    $mReturn = "";
    $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 == "relocid")
            $mRelocId = trim($v2);
        elseif ($k2 == "relocbdyid")
            $mBdyId = trim($v2);
        elseif ($k2 == "fromlocation")
            $mFromLocHash = trim($v2);
        elseif ($k2 == "vldfromlocation")
            $mVldFromLoc = trim($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = trim($v2);
        elseif ($k2 == "vldserialreference")
            $mVldSerialReference = trim($v2);
        elseif ($k2 == "partnumber")
            $mPartNumber = trim($v2);
        elseif ($k2 == "vldpartnumber")
            $mVldPartNumber = trim($v2);
        elseif ($k2 == "quantity")
            $mQty = trim($v2);
        elseif ($k2 == "qty")
            $mQty = trim($v2);
        elseif ($k2 == "tolocation")
            $mToLocHash = trim($v2);
        elseif ($k2 == "vldtolocation")
            $mVldToLocCode = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    // Test for non-numeric Quantity
    if (!empty($mQty))
    {
        if(is_numeric($mQty))
        {
        }
        else
        {
            echo "FAIL-This must be a number only";
            return;
        }
    }
//  exit("FAIL0-TEST1-$mQty");
// mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    
    if (!empty($mFromLocHash))
    {
        $mDataQuery = "SELECT location.location_code AS location_code FROM location WHERE location.location_hash = '".$mFromLocHash."' LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            return("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $mData = mysqli_query($mConnection,$mDataQuery);
        $i = 0;
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mFromLocCode = ($mRow['location_code']);
            $i++;
        }
        if (($i == 0) || (strtoupper($mFromLocCode) != strtoupper($mVldFromLoc)))
        {
            echo "FAIL-Location is Incorrect";
            return;
        }
    }
    else
    {
        exit ("DATA:fromLocationCode:::skipfromLocationCode");
    }

// Check Scanned Part
    if (!empty($mPartNumber))
    {
        if (trim($mPartNumber) != trim($mVldPartNumber))
        {
            echo "FAIL-Incorrect Part Number";
            return;
        }
        
        $mDataQuery = "SELECT id AS id, part_number AS part_number FROM part WHERE upper(part_number) = '".$mPartNumber."' LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        $mData = mysqli_query($mConnection,$mDataQuery);
        $i = 0;
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mPartNumber = $mRow['part_number'];
            $i++;
        }
        
        if (($i == 0) || (strtoupper($mPartNumber) != $mVldPartNumber))
        {
            echo "FAIL-Incorrect Part Number";
            return;
        }   
                    
    }

// Validate Entered Serial  
    if (!empty($mSerialReference))
    {
        if ($mPartNumber == "")
        {
            $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_qty AS inventory_qty, inventory_master.requires_inspection AS inspect";
            $mDataQuery .=", location.location_code";
            $mDataQuery .=", part.id AS part_id, part.part_number AS part_number, part.conversion_factor AS conversion_factor,part.fixed_location_type_id AS fixed_location_type_id";
            $mDataQuery .=", tag.tag_reference AS tag_reference";
            $mDataQuery .=", location_type.location_area AS location_area";
            $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 tag ON inventory_master.parent_tag_id=tag.id";
            $mDataQuery .=" LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id";
            $mDataQuery .=" LEFT JOIN location_type ON location.location_type_id=location_type.id";
            $mDataQuery .=" WHERE UPPER(inventory_master.serial_reference)='".$mSerialReference."'";
            $mDataQuery .=" AND inventory_master.inventory_qty > 0 AND (inventory_master.inventory_status_id IS null OR LOWER(inventory_status.inventory_status_code) IN('ok','qa','qtine','overbooking','missing')) LIMIT 2";
        }
        else
        {
            $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.inventory_qty AS inventory_qty, inventory_master.requires_inspection AS inspect, location.location_code";
            $mDataQuery .=", part.id AS part_id, part.part_number AS part_number, part.conversion_factor AS conversion_factor,part.fixed_location_type_id AS fixed_location_type_id";
            $mDataQuery .=", tag.tag_reference AS tag_reference";
            $mDataQuery .=", location_type.location_area AS location_area";
            $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 tag ON inventory_master.parent_tag_id=tag.id";
            $mDataQuery .=" LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id";
            $mDataQuery .=" LEFT JOIN location_type ON location.location_type_id=location_type.id";
            $mDataQuery .=" WHERE UPPER(inventory_master.serial_reference)='".$mSerialReference."'";
            $mDataQuery .=" AND inventory_master.part_number='".$mPartNumber."'";
            $mDataQuery .=" AND inventory_master.inventory_qty > 0 AND (inventory_master.inventory_status_id IS null OR LOWER(inventory_status.inventory_status_code) IN('ok','qa','qtine','overbooking','missing')) LIMIT 2";
        }
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        
        $i = 0;
        $mInvId = "";
        $mInvQty = 0;
        $mPartConvFactor = 1;
        $mTagRef = "";
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mInvLoc = ($mRow['location_code']);
            $mInspect = ($mRow['inspect']);
            $mInvId = ($mRow['id']);
            $mInvQty = ($mRow['inventory_qty']);
            $mPartConvFactor = ($mRow['conversion_factor']);
            $mPartId = ($mRow['part_id']);
            $mPartNumber = ($mRow['part_number']);
            $mTagRef = ($mRow['tag_reference']);
            $mPartLocType = ($mRow['fixed_location_type_id']);
            $mLocArea = ($mRow['location_area']);
            $i++;
        }
        if ($i == 0)
        {
            $mErrMsg = "FAIL-Serial is Incorrect ";
            return($mErrMsg);
        }
        if ($i == 1)
        {
//          exit ("FAIL-TEST1-".$mLocArea);
            if (strtoupper(substr($mSerialReference,0,strlen($mVldSerialReference))) != strtoupper($mVldSerialReference))
            {
                $mErrMsg = "FAIL-Scanned Serial is not prompted serial";
                return($mErrMsg);
            }
            if (strtoupper($mFromLocCode) != strtoupper($mInvLoc))
            {
                $mErrMsg = "FAIL-Scanned Serial is in a different Location ".$mPartNumber."-".strtoupper($mInvLoc)."-".strtoupper($mFromLocCode);
                return($mErrMsg);
            }

            if (strtoupper($mPartNumber) != strtoupper($mVldPartNumber))
            {
                $mErrMsg = "FAIL-Incorrect Part for this Task".$mPartNumber."-".$mVldPartNumber;
                return($mErrMsg);
            }

            elseif (substr($mTagRef,0,3) == "REP")
            {
                $mErrMsg = "FAIL-Serial is already located to pallet ".$mTagRef;
                return($mErrMsg);
            }
        }
// Multiple Serials - Prompt for Part Number
        if ($i > 1)
        {
            $mErrMsg = "DATA:serialReference:".$mSerialReference."::skip3,partNumber::I";
            return($mErrMsg);
        }
        if ($mErrMsg == "")
        {
// Apply Conversion Factor
            if ($mPartConvFactor > 0)
                $mInvQty = $mInvQty / $mPartConvFactor;
        }
        if(is_numeric($mQty))
        {
            if ($mQty < $mInvQty)
            {
                $mErrMsg = "FAIL-This serial must be decanted";
                return($mErrMsg);
            }
        }
    }
    else
    {
        exit("DATA:serialReference:::skipserialReference");
    }
    if (!empty($mRelocId))
    {
        if (!empty($mToLocHash))
        {
            $mDataQuery = "SELECT location.location_code AS location_code, location_type.id AS location_type_id";
            $mDataQuery .=", location_type.location_area AS location_area";
            $mDataQuery .=" FROM location";
            $mDataQuery .=" LEFT JOIN location_type ON location.location_type_id=location_type.id";
            $mDataQuery .=" WHERE location.location_hash = '".$mToLocHash."'";
            $mDataQuery .=" LIMIT 1";
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                return("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
            list($mToLocCode,$mLocType,$mLocArea) = mysqli_fetch_row($mData);
/*
            while($mRow = mysqli_fetch_assoc($mData)) 
            {
                $mToLocCode = ($mRow['location_code']);
                $mLocType = ($mRow['location_type_id']);
                $mLocArea = ($mRow['location_area']);
            }
*/
            if (mysqli_num_rows($mData)==0)
            {
                $mErrMsg = "FAIL-Location is Incorrect";
                return $mErrMsg;
            }
            if (!empty($mPartLocType) && (trim($mPartLocType) != trim($mLocType)))
            {
                if (strtolower($mLocArea) == "storage")
                {
                    $mErrMsg = "FAIL-Location Type is Incorrect ";
                    return $mErrMsg;
                }
            }
        }
        else
        {
//          exit("DATA:toLocationCodeinput:::skiptoLocationCode");
        }
        $key = $mVldToLocCode;
        if (array_key_exists($key, $array)) 
        {
            if ($mVldToLocCode != $mToLocCode)
            {
                echo "FAIL-Not Prompted Location";
                return;
            }
        }
/*
        else
        {
            $mDataQuery = "SELECT location.location_code";
            $mDataQuery .=" FROM reloc_header";
            $mDataQuery .=" JOIN reloc_task_type ON reloc_header.to_location=reloc_task_type.cust_to_location";
            $mDataQuery .=" JOIN location ON reloc_task_type.fixed_location_id=location.id";
            $mDataQuery .=" WHERE reloc_header.id=".$mRelocId." LIMIT 1";
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
            list($mToLocCode) = mysqli_fetch_row($mData);
            if (mysqli_num_rows($mData) > 0)
            {
                $mErrMsg = "DATA:toLocationCode:".$mToLocCode;
                return $mErrMsg;
            }
            else
            {
                include_once ('location.php');
                $mToLocCode = getNextLocation($mPartId,'','Y','','','',$mHost,$mUser,$mPwd,$mDbName,$mTransactionTypeId,'');
                if ($mToLocCode != "")
                {
//                    $mErrMsg = "FAIL-Invalid To Location ".$mDataQuery;
                    $mErrMsg = "DATA:toLocationCode:".$mToLocCode;
                }
                else
                {
                    $mErrMsg = "DATA:toLocationCode:No Location Found";
                }
                return $mErrMsg;
            }
        }
*/
    }
//  mysqli_close($mConnection);
    
    if ($mErrMsg == "")
    {
        $mErrMsg = "OK  -Valid Reloc";
    }   
    return $mErrMsg;
}

// clear Reloc
function clearReloc($mFilter,$mHost,$mUser,$mPwd,$mDbName,$mConnect=null)
{
    $mReturn = "";
    $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 == "relocid")
            $mRelocId = trim($v2);
        elseif ($k2 == "relocbdyid")
            $mBdyId = trim($v2);
        elseif ($k2 == "fromlocation")
            $mFromLocHash = trim($v2);
        elseif ($k2 == "vldfromlocation")
            $mVldFromLoc = trim($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = trim($v2);
        elseif ($k2 == "vldserialreference")
            $mVldSerialReference = trim($v2);
        elseif ($k2 == "partnumber")
            $mPartNumber = trim($v2);
        elseif ($k2 == "vldpartnumber")
            $mVldPartNumber = trim($v2);
        elseif ($k2 == "quantity")
            $mQty = trim($v2);
        elseif ($k2 == "tolocation")
            $mToLocHash = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    // mysql connection
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    $mDataQuery = "UPDATE reloc_body SET in_use='', last_updated=now(),last_updated_by='".$mCurrentUser."' WHERE id=".$mRow['body_id']." LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
//    mysqli_close($mConnection);
    $mErrMsg = "OK  -clearReloc";
    return $mErrMsg;
}

// complete Reloc
function completeReloc($mFilter,$mHost,$mUser,$mPwd,$mDbName,$mConnect=null)
{
    $mReturn = "";
    $mErrMsg = "";
    $mBdyId = "";
    $mSerialReference = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "relocid")
            $mRelocId = trim($v2);
        elseif ($k2 == "relocbdyid")
            $mBdyId = trim($v2);
        elseif ($k2 == "fromlocation")
            $mFromLocHash = trim($v2);
        elseif ($k2 == "vldfromlocation")
            $mVldFromLoc = trim($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = trim($v2);
        elseif ($k2 == "vldserialreference")
            $mVldSerialReference = trim($v2);
        elseif ($k2 == "partnumber")
            $mPartNumber = trim($v2);
        elseif ($k2 == "vldpartnumber")
            $mVldPartNumber = trim($v2);
        elseif ($k2 == "quantity")
            $mQty = trim($v2);
        elseif ($k2 == "tolocationhashcode")
            $mToLocHash = trim($v2);
        elseif ($k2 == "tolocationcode")
            $mToLocHash = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
    if ($mErrMsg == "")
    {
        // mysql connection
        $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
            exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
        if ($mSerialReference != "")
        {
//            $mDataQuery = "UPDATE reloc_body SET processed=1,last_updated=now(),last_updated_by='".$mCurrentUser."' WHERE serial_reference = '".$mSerialReference."' LIMIT 20";
            $mDataQuery = "SELECT id AS id, reloc_header_id AS reloc_header_id FROM reloc_body WHERE serial_reference = '".$mSerialReference."' AND processed<>1 LIMIT 20";
        }
        elseif ($mBdyId != "")
//            $mDataQuery = "UPDATE reloc_body SET processed=1,last_updated=now(),last_updated_by='".$mCurrentUser."' WHERE id=".$mBdyId." LIMIT 1";
            $mDataQuery = "SELECT id AS id, reloc_header_id AS reloc_header_id FROM reloc_body WHERE id=".$mBdyId." LIMIT 1";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mBdyId = ($mRow['id']);
            $mHdrId = ($mRow['reloc_header_id']);
            $i++;
            $mDataQuery = "UPDATE reloc_body SET processed=1,last_updated=now(),last_updated_by='".$mCurrentUser."' WHERE id=".$mBdyId." LIMIT 1";
            if (!mysqli_query($mConnection,$mDataQuery))
                exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
            $mDataQuery = "UPDATE reloc_header SET processed=1,last_updated_date=now(),last_updated_by='".$mCurrentUser."' WHERE id=".$mHdrId." AND NOT EXISTS(SELECT id FROM reloc_body WHERE reloc_header_id=".$mHdrId." AND reloc_body.processed=0) LIMIT 1";
            if (!mysqli_query($mConnection,$mDataQuery))
                exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);

            if (empty($mToLocHash))
            {
                exit("OK  -completereloc");
            }
// Get location type (area)
            $mDataQuery = "SELECT location.inventory_status_id AS inventory_status_id, location_type.location_area AS location_area";
            $mDataQuery .=" FROM location";
            $mDataQuery .=" LEFT JOIN location_type ON location.location_type_id=location_type_id";
            $mDataQuery .=" WHERE";
            $mDataQuery .=" (location.location_code=? OR location.location_hash=?)";
            $mDataQuery .=" AND lower(location_type.location_area) = 'storage'";
            $mDataQuery .=" LIMIT 1";
            try
            {
                $mStmt = $mConnection->prepare($mDataQuery);
                $mStmt->bind_param("ss", $mToLocHash, $mToLocHash);
                $mStmt->execute();
                $mData = $mStmt->get_result();
            }
            catch (Exception $e)
            {
                exit("FAIL-".$e." ".mysqli_error($mConnection)." ".$mDataQuery);
            }            
            $mStmt->close();
// If this location isn't storage, leave.            
            if (mysqli_num_rows($mData) == 0)
            {
                exit("OK  -completereloc");
            }
            else
            {
                $mRows = $mData->fetch_all(MYSQLI_ASSOC);
                foreach ($mRows as $row)
                {
                    $mInvStsId = $row['inventory_status_id'];
                }
            }
            
// Update inventory_masster Inventory_status
            if (empty($mInvStsId))
            {
                $mDataQuery = "SELECT inventory_status.id AS id";
                $mDataQuery .=" FROM inventory_status";
                $mDataQuery .=" WHERE";
                $mDataQuery .=" inventory_status_code=?";
                $mDataQuery .=" LIMIT 1";
                
                try
                {
                    $mInvSts = "OK";
                    $mStmt = $mConnection->prepare($mDataQuery);
                    $mStmt->bind_param("s", $mInvSts);
                    $mStmt->execute();
                    $mData = $mStmt->get_result();
                }
                catch (Exception $e)
                {
                    exit("FAIL-".$e." ".mysqli_error($mConnection)." ".$mDataQuery);
                }
    // Fetch the results
                $mRows = $mData->fetch_all(MYSQLI_ASSOC);

                foreach ($results as $row)
                {
                    $mInvStsId = $row['id'];
                }

                foreach ($results as $row)
                {
                    $mInvStsId = $row['id'];
                }
            }
            $mStmt->close();
            
            if (empty($mInvStsId))
            {
                $mInvStsId = 1;
            }
            if (mysqli_num_rows($mData) > 0)
            {
                $mDataQuery = "UPDATE inventory_master";
                $mDataQuery .=" SET hold_qty=0,inventory_status_id=?, last_updated=now()";
                $mDataQuery .=" WHERE serial_reference=? AND part_number=?";
                $mDataQuery .=" LIMIT 1";
                try
                {
                    $mStmt = $mConnection->prepare($mDataQuery);
                    $mStmt->bind_param("iss", $mInvStsId,$mSerialReference, $mPartNumber);
                    $mStmt->execute();
                }
                catch (Exception $e)
                {
                    exit("FAIL-".$e." ".mysqli_error($mConnection)." ".$mDataQuery);
                }
                $mStmt->close();
            }
        }
    }
    $mErrMsg = "OK  -completeReloc-".$mDataQuery."-".mysqli_error($mConnection);
    return $mErrMsg;
}

// Missing Serial
function missingRelocSerial($mFilter,$mHost,$mUser,$mPwd,$mDbName,$mConnect=null)
{
    $mReturn = "";
    $mErrMsg = "";
    $mBdyId = "";
    $mSerialReference = "";
// Replace Chars in Input String to emulate a JSON format instead of GET format
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("&",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "relocid")
            $mRelocId = trim($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = trim($v2);
        elseif ($k2 == "partnumber")
            $mPartNumber = trim($v2);
        elseif ($k2 == "relocbodyid")
            $mBdyId = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }

    if ($mErrMsg == "")
    {

// mysql connection
        $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
            exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Get id for inventory status
        $mInvStsId = 0;
        $mInvRcvId = 0;
        $mInvPkdId = 0;
        $mInvPltId = 0;
        $mInvMisId = 0;
        $mInvOvrId = 0;
        $mInvRanId = 0;
        $mDataQuery = "SELECT id AS id, inventory_status_code AS inventory_status_code FROM inventory_status";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            return "FAIL-".mysqli_error($mConnection).$mDataQuery;
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            if (strtolower($mRow['inventory_status_code']) == "ok")
                $mInvStsId = ($mRow['id']);
            elseif (strtolower($mRow['inventory_status_code']) == "rcv")
                $mInvRcvId = ($mRow['id']);
            elseif (strtolower($mRow['inventory_status_code']) == "pkd")
                $mInvPkdId = ($mRow['id']);
            elseif (strtolower($mRow['inventory_status_code']) == "plt")
                $mInvPltId = ($mRow['id']);
            elseif (strtolower($mRow['inventory_status_code']) == "missing")
                $mInvMisId = ($mRow['id']);
            elseif (strtolower($mRow['inventory_status_code']) == "overbooking")
                $mInvOvrId = ($mRow['id']);
            elseif (strtolower($mRow['inventory_status_code']) == "noran")
                $mInvRanId = ($mRow['id']);
        }
        if ($mInvPkdId == null && $mInvPltId != null)
            $mInvPkdId = $mInvPltId;    
       
        if ($mSerialReference != "")
        {
            $mDataQuery = "UPDATE inventory_master SET inventory_status_id=".$mInvMisId.", available_qty=inventory_qty,last_updated=now(),last_updated_by='".$mCurrentUser."' WHERE serial_reference='$mSerialReference' AND part_number='$mPartNumber' LIMIT 1";
            if (!mysqli_query($mConnection,$mDataQuery))
                exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
            $mDataQuery = "UPDATE reloc_body SET processed=1,last_updated=now(),last_updated_by='".$mCurrentUser."' WHERE id=".$mBdyId." LIMIT 1";
            if (!mysqli_query($mConnection,$mDataQuery))
                exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);

            $mDataQuery = "SELECT reloc_header_id FROM reloc_body WHERE id=$mBdyId LIMIT 1";
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
            list($mRelocHdrId) = mysqli_fetch_row($mData);
            $mDataQuery = "SELECT id FROM reloc_body WHERE reloc_header_id=$mRelocHdrId AND processed=0 LIMIT 1";
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;

            if (mysqli_num_rows($mData)==0)
            {
                $mDataQuery = "UPDATE reloc_header SET processed=1,last_updated_date=now(),last_updated_by='".$mCurrentUser."' WHERE id=".$mRelocHdrId." LIMIT 1";
                if (!mysqli_query($mConnection,$mDataQuery))
                    exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
            }

// Inventory Master
            $mDataQuery = "SELECT inventory_master.ran_or_order AS ran_order, inventory_master.current_location_id AS location_id, part.part_number,part.conversion_factor, location.location_code,inventory_master.tag_reference AS plt_number, inventory_master.serial_reference AS serial_reference, inventory_master.inventory_qty AS inventory_qty, vendor.vendor_reference_code AS vendor_code,product_type.product_type_code AS product_type_code";
            $mDataQuery .=" FROM inventory_master";
            $mDataQuery .=" JOIN part ON inventory_master.part_id=part.id";
            $mDataQuery .=" JOIN location ON inventory_master.current_location_id=location.id";
            $mDataQuery .=" LEFT JOIN vendor ON part.vendor_id=vendor.id";
            $mDataQuery .=" LEFT JOIN product_type ON inventory_master.product_type_id=product_type.id";
            $mDataQuery .=" WHERE inventory_master.serial_reference='$mSerialReference' AND inventory_master.part_number='$mPartNumber' LIMIT 1";
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
            $mInvRow = array();
            if (mysqli_num_rows($mData) > 0)
            {                
                $mInvRow = mysqli_fetch_assoc($mData);
                $mDataQuery = "INSERT INTO transaction_history";
                $mDataQuery .= " (id,ran_or_order,part_number,serial_reference,short_code,txn_qty,from_location_code,to_location_code,to_plt,customer_reference,associated_document_reference,date_created,created_by,last_updated,last_updated_by,parent_tag,transaction_reference_code,comment,source_tag,conversion_factor,vendor_code,product_type_code)";
                $mDataQuery .=" VALUE(DEFAULT,'".$mInvRow['ran_order']."','".$mInvRow['part_number']."','".$mSerialReference."','RELOCMISSING',".$mInvRow['inventory_qty'].",'".$mInvRow['location_code']."','".$mInvRow['location_code']."','".$mInvRow['plt_number']."','".$mDtlRow['customer_reference']."','".$mDtlRow['document_reference']."',now(),'".$mCurrentUser."',now(),'".$mCurrentUser."','".$mInvRow['plt_number']."','MISSING','','',".$mInvRow['conversion_factor'].",'".$mInvRow['vendor_code']."','".$mInvRow['product_type_code']."')";
                if (!mysqli_query($mConnection,$mDataQuery))
                    exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
            }
        }        
//        mysqli_close($mConnection);

    }
    $mErrMsg = "OK  -missingRelocSerial";
    return $mErrMsg;
}

// Map fixed location
function mapLoc($mFilter,$mHost,$mUser,$mPwd,$mDbName,$mConnect=null)
{
    $mErrMsg = "";
    $mToLocationHash = "";
// 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 == "docref")
            $mDocumentReference = trim($v2);
        elseif ($k2 == "location")
            $mToLocationHash = trim($v2);
        elseif ($k2 == "partnumber")
            $mPartNumber = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
//  exit("FAIL-".$mFilter);
    $array = ['return' => 'RTVQR', 'inspection' => 'INSP00', 'stock' => ''];
// mysql connection
    try
    {
        $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
    }
    catch(Exception $e)
    {   
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    }
    $mDataQuery = "SELECT id,to_location FROM reloc_header WHERE document_reference='".$mDocumentReference."' LIMIT 1";
    $mToLocCode = "";
    try
    {
        $mData = mysqli_query($mConnection,$mDataQuery);
    }
    catch (Exception $e)
    {
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    }
    if (mysqli_num_rows($mData)>0)
    {
        list($mId,$mToLocCode) = mysqli_fetch_row($mData);
        $key = $mToLocCode;
        if (array_key_exists($key, $array)) 
        {
            $mToLocCode = $array[$key];
        }
        else
        {
            $mToLocCode = '';
        }
    }
    if ($mToLocCode == '')
    {
        $mDataQuery = "SELECT id FROM part WHERE part_number='".$mPartNumber."' LIMIT 1";
        $mToLocCode = "";
        try
        {
            $mData = mysqli_query($mConnection,$mDataQuery);
        }
        catch (Exception $e)
        {
            return "FAIL-".mysqli_error($mConnection)."-".$mDataQuery;
        }
        list($mPartId) = mysqli_fetch_row($mData);
        include_once('location.php');
        $mToLocCode = getNextLocation($mPartId,'','Y','','','',$mHost,$mUser,$mPwd,$mDbName,$mTransactionTypeId,'');
    }
    exit("DATA:toLocationCodecontent:".$mToLocCode);
}

// Check CTS Loc.
function moveLoc($mFilter,$mHost,$mUser,$mPwd,$mDbName,$mConnect=null)
{
    $mErrMsg = "";
    $mToLocationHash = "";
// 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 == "location")
            $mToLocationHash = trim($v2);
        elseif ($k2 == "partnumber")
            $mPartNumber = trim($v2);
        elseif ($k2 == "serialreference")
            $mSerialReference = trim($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = trim($v2);
        elseif ($k2 == "transactionTypeId")
            $mTransactionTypeId = strtoupper(trim($v2));
    }
//  exit("FAIL-".$mFilter);
// mysql connection
    try
    {
        $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName);
    }
    catch(Exception $e)
    {   
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
    }
    $mDataQuery = "SELECT reloc_body.id AS id,reloc_header.to_location AS to_location";
    $mDataQuery .=" FROM reloc_header";
    $mDataQuery .=" JOIN reloc_body ON reloc_header.id=reloc_body.reloc_header_id";
    $mDataQuery .=" WHERE reloc_body.serial_reference='".$mSerialReference."'";
    $mDataQuery .=" AND reloc_body.processed=0";
    $mDataQuery .=" AND reloc_header.to_location<>'stock'";
    $mDataQuery .=" LIMIT 1";
    try
    {
        $mData = mysqli_query($mConnection,$mDataQuery);
    }
    catch (Exception $e)
    {
        exit ("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    }
//      exit("FAIL-TEST1-".$mDataQuery." ".mysqli_num_rows($mData));
    if (mysqli_num_rows($mData)>0)
    {
        exit("FAIL-Outstanding RELOC. This serial cannot be moved");
    }
    exit("OK  -moveLoc");
}
?>
