<?php
// Putaway Locate Processing
// ----------------------------------------------------------------------------------------
// Modified 2019-12-20 - getNextLocation - Change logic for pick-face putaway
//          2020-01-21 - getNextLocation - Temp. Remove some pick-face calcs.
//          2021-04-28 - getNextLocation - Overbooking Processing
//          2021-04-29 - getNextLocation - Big Part Processing
//          2021-07-26 - getNextLocation - weight processing
// ----------------------------------------------------------------------------------------
header('Cache-Control: no-cache, no-store, must-revalidate');   
header('Expires: 0');
// Header to allow Cross-Server AJAX Connection
header('Access-Control-Allow-Origin: *');
set_time_limit(0);
// Enable exceptions for MySQLi errors
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

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

// function getNextLocation($mPartNumber,$mPlt="",$mDbHost=null,$mDbUser=null,$mDbPwd=null,$mDbName=null)
function getNextLocation($mPartId,$mProductType,$mMultiPart,$mPlt,$mPrufCube,$mRequiresInspection,$mHost,$mUser,$mPwd,$mDbName,$mTransactionTypeId="",$mSerialReference="",$mInvId=null)
{
//  exit("FAIL-TEST1-".$mRequiresInspection);
    if ($mPartId == null || $mPartId == "")
        return "FAIL-Invalid Part Number";
        
    $mPickFace = "";
    $mLocId = "";
// FQA - Ignore 'requires inspection'
    if ($mTransactionTypeId == "FQA")
    {
        if (strlen($$mRequiresInspection) <=1)
            $mRequiresInspection = "0";
        else
            $mRequiresInspection = "0"+substr($mRequiresInspection,1);
    }
// mysql connection - Use Passed values...
    $mConnection=mysqli_connect($mHost,$mUser,$mPwd,$mDbName) or
        exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());

// Get Company Settings
    $mDataQuery = "SELECT company.to_qa AS to_qa FROM company LIMIT 1";
// Validate QRY
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection).$mDataQuery);
// Run QRY
    $mData = mysqli_query($mConnection,$mDataQuery);
    $i = 0;
    $mCompanyToQa = "";
    $mRow = mysqli_fetch_assoc($mData);
    if ($mRow['to_qa'] == "1")
        $mCompanyToQa = "1";

// Select location-Type & zone-type, from part, based on input part_number  
    $mDataQuery = "SELECT part.part_number AS part_number, part.fixed_location_type_id AS location_type_id, part.fixed_sub_type_id AS sub_type_id, part.is_big_part AS big_part, part.weight AS weight";
    $mDataQuery .=",location_type.location_type_code AS location_type_code, location_type.drop_zone_location_id AS zone_type_id, location_type.to_qr,location_type.to_inspect,location_type.locate_overbooking";
    $mDataQuery .=" FROM part";
    $mDataQuery .=" JOIN location_type ON part.fixed_location_type_id=location_type.id";
    $mDataQuery .=" WHERE part.id = ".$mPartId." LIMIT 1";
// Validate QRY
    if (!mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection).$mDataQuery);
// Run QRY
    $mData = mysqli_query($mConnection,$mDataQuery);
    $i = 0;
    $mLocTypeId = "";
    $mZoneTypeId = 0;
    $mPartNumber = "";
    $mLocTypeCode = "";
    $mBigPart = 0;
    $mPartWeight = 0;
    $mToQr = 0;
    $mToInsp = 0;
    $mOvrBook = 0;
    while($mRow = mysqli_fetch_assoc($mData))
    {
        $mLocTypeId = ($mRow['location_type_id']);
        $mLocSubTypeId = ($mRow['sub_type_id']);
        $mZoneTypeId = ($mRow['zone_type_id']);
        $mPartNumber = ($mRow['part_number']);
        $mLocTypeCode = ($mRow['location_type_code']);
        $mBigPart = ($mRow['big_part']);
        $mPartWeight = ($mRow['weight']);
        $mToQr = $mRow['to_qr'];
        $mToInsp = $mRow['to_inspect'];
        $mOvrBook = $mRow['locate_overbooking'];
        $i++;
    }
    if (empty($mPartWeight))
    {
        $mPartWeight = 99999;
    }
/*
// locate_overbookung over-rides inspection
    if (($mOvrBook=="1" && $mToQr=="1" && $mToInsp=="1"))
    {
        
    }
    elseif ($mOvrBook == "1")
    {
        if (strlen($mRequiresInspection) > 1)
            $mRequiresInspection = "0".substr($mRequiresInspection,1);
        else
            $mRequiresInspection = "0";
    }
    elseif ($mToQr == "1")
    {
        if (strlen($mRequiresInspection) > 1)
            substr($mRequiresInspection,0,1)."1";
        else
            $mRequiresInspection = "01";
    }
*/
    if ($i ==0)
    {
        return "FAIL-The scanned part number does not exist.";
    }
    if ($mZoneTypeId == null)
        $mZoneTypeId = 0;

// Test for Free Locate Part
    if ((($mLocTypeId == null) || ($mLocTypeId == "")) && (($mRequiresInspection == "") || substr($mRequiresInspection,0,1) == "0" || (substr($mRequiresInspection,0,1) == "1" && $mCompanyToQa == "")))
    {
        return "";
    }
// Test for Free Locate Part
    if ((($mLocTypeId == null) || ($mLocTypeId == "")) && (($mZoneTypeId == null) || ($mZoneTypeId == "")))
    {
        return "";
    }
    
// Get id for inventory status
    $mInvStsId = 0;
    $mInvRcvId = 0;
    $mInvPckId = 0;
    $mInvPltId = 0;
    $mInvQaId = 0;
    $mInvOvrId = 0;
    $mDataQuery = "SELECT id AS id, inventory_status_code AS inventory_status_code FROM inventory_status";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;
    $mData = (mysqli_query($mConnection,$mDataQuery));
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        if (strtolower($mRow['inventory_status_code']) == "ok")
            $mInvStsId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "rcv")
            $mInvRcvId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "pkd")
            $mInvPkdId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "plt")
            $mInvPltId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "qa")
            $mInvQaId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "qtine")
            $mInvQaId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "overbooking")
            $mInvOvrId = ($mRow['id']);
    }
    if ($mInvPkdId == null && $mInvPltId != null)
        $mInvPkdId = $mInvPltId;
        
// If Inventory Id supplied - get inventory_master inventory_status
    $mInvInvStsId = "";
    if ($mInvId != null)
    {
        $mDataQuery = "SELECT inventory_master.inventory_status_id AS inventory_status_id";
        $mDataQuery .=" FROM inventory_master";
        $mDataQuery .=" WHERE inventory_master.id=".$mInvId;
        $mDataQuery .=" LIMIT 1";
        $mData = mysqli_query($mConnection,$mDataQuery);
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mInvInvStsId = $mRow['inventory_status_id'];
        }   
    }
//    return "FAIL-TEST1-".$mRequiresInspection;
// Standard Parts
    if ($mBigPart != "1")
    {
        $i = 0;
// Is serial flagged for inspect?
        if (substr($mRequiresInspection,0,1)=="1")
        {
            if ($mToInsp == "0" && $mInvInvStsId != $mInvQaId)
            {
                $mRequiresInspection = "0".substr($mRequiresInspection,1);
                $i = 1;
            }
            else
            {
                $i = 1;
            }
        }
// was the receiving overbooked?
        if ($i == 0)
        {
            if ($mInvInvStsId==$mInvOvrId)
            {
                if ($mOverBook == "0")
                {
                    $mRequiresInspection = "01";
                    $i = 1;
                }
            }
        }
        if ($i == 0)
        {
            if ($mInvInvStsId==$mInvQaId)
            {
                if ($mToQr == "1")
                {
                    $mRequiresInspection = "01";
                    $i = 1;
                }
                else
                {
                    $mRequiresInspection = "00";
                    $i = 1;
                }    
            }
            else
            {
                if (strlen($mRequiresInspection)>0)
                    $mRequiresInspection = substr($mRequiresInspection,0,1)."0";
                else
                    $mRequiresInspection = "00";
            }
        }
    }
    else
    {
        $mRequiresInspection = "00";
    }
//    exit("FAIL-TEST2-".$mRequiresInspection."-".$mInvInvStsId."-".$mInvQaId);
//    return "FAIL-TEST2-".$mRequiresInspection."-".$mInvStsId."-".$mToQr;
// Return first matching location code for the specified part Location_type & zone_type - Unless 'qa' transaction   
    if ($mPlt == "")
    {
        $i = 0;
// Only If Not Flagged for Inspection or Flagged for Inspection & Company 'Move To Inspection" is not set.
        if (((substr($mRequiresInspection,0,1) != "1") || (substr($mRequiresInspection,0,1) == "1" && $mCompanyToQa != "1")) && (substr($mRequiresInspection,1,1) != "1"))
        {
// Only if not To-QA transaction
            if ($mTransactionTypeId != "TQA")
            {
                if ($mPickFace == "")
                {
// Look for free locations with matching Fixed Part Number
                    $mDataQuery = "SELECT location.id AS id, CASE WHEN location.max_pick_face_qty IS null THEN 'Y' WHEN location.max_pick_face_qty=0 THEN 'Y' WHEN location.max_pick_face_qty > (SELECT COUNT(id) FROM inventory_master WHERE inventory_master.current_location_id=location.id AND inventory_master.inventory_status_id IN(".$mInvStsId.",".$mInvRcvId.")) THEN 'Y' ELSE 'N' END AS pick_face";
                    $mDataQuery .= " FROM location";
                    $mDataQuery .= " LEFT JOIN location_filling_status ON location.filling_status_id=location_filling_status.id";
                    $mDataQuery .= " LEFT JOIN location_type ON location.location_type_id=location_type.id";
                    $mDataQuery .= " WHERE";
                    $mDataQuery .=" location.pick_group_id IS NOT null AND";
                    $mDataQuery .=" location.part_number='".$mPartNumber."'";
                    $mDataQuery .= " AND (location.filling_status_id IS null OR 
                    (location_filling_status.putaway=1 AND (LOWER(location_filling_status.filling_code) = 'empty' OR LOWER(location_filling_status.filling_code) = 'filling')))";
                    if ($mPartWeight >0)
                    {
                        $mDataQuery .= " AND location.max_weight > ".$mPartWeight."+(SELECT max(part.weight*inventory_master.inventory_qty) FROM part JOIN inventory_master ON part.id=inventory_master.part_id WHERE inventory_master.current_location_id=location.id)";
                    }
// Overbooked Inventory cannot go to 'SS' type location
                    if ($mInvInvStsId == $mInvOvrId)
                    {
                        $mDataQuery .= " AND location_type.locate_overbooking=1";
                    }
                    $mDataQuery .= " ORDER BY location.max_pick_face_qty LIMIT 100";
                    if (!mysqli_query($mConnection,$mDataQuery))
                        return("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
                    $mData = mysqli_query($mConnection,$mDataQuery);
                
//              return("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
                
                    $i = mysqli_num_rows($mData);
                    while($mRow = mysqli_fetch_assoc($mData)) 
                    {
                        $mPickFace = $mRow['pick_face'];
                        if ($mPickFace == "Y")
                        {
                            $mLocId = $mRow['id'];
                            break;
                        }
                    }
                }
// Check if there is a pick face location for the part type
                if ($mPickFace == "")
                {
                    if (empty($mLocTypeId))
                        $mLocTypeId = 0;
                    $mDataQuery = "SELECT location.id AS id FROM location";
                    $mDataQuery .= " LEFT JOIN location_filling_status ON location.filling_status_id=location_filling_status.id";
                    $mDataQuery .= " LEFT JOIN location_type ON location.location_type_id=location_type.id";
                    $mDataQuery .= " WHERE location.location_type_id=".$mLocTypeId;
                    if (!empty($mLocSubTypeId))
                    {
                        $mDataQuery .= " AND location.location_sub_type_id=".$mLocSubTypeId;
                    }
                    $mDataQuery .= " AND location.pick_group_id IS NOT null";
                    $mDataQuery .= " AND (location.filling_status_id IS null OR (location_filling_status.putaway=1 AND (LOWER(location_filling_status.filling_code) = 'empty' OR LOWER(location_filling_status.filling_code) = 'filling')))";
                    if ($mPartWeight >0)
                    {
                        $mDataQuery .= " AND location.max_weight > ".$mPartWeight."+(SELECT max(weight) FROM part WHERE EXISTS(SELECT id FROM inventory_master WHERE part.id=inventory_master.part_id AND inventory_master.current_location_id=location.id))";
//                        $mDataQuery .= " AND location.max_weight > ".$mPartWeight."+(SELECT max(part.weight*inventory_master.inventory_qty) FROM part JOIN inventory_master ON part.id=inventory_master.part_id WHERE inventory_master.current_location_id=location.id)";
                    }
// Overbooked Inventory cannot go to 'SS' type location
                    if ($mInvInvStsId == $mInvOvrId)
                    {
                        $mDataQuery .= " AND location_type.locate_overbooking=1";
                    }
                    $mDataQuery .= " LIMIT 1";
//                  exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
                    if (!mysqli_query($mConnection,$mDataQuery))
                        return("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
                    $mData = mysqli_query($mConnection,$mDataQuery);
                    
//                  return("FAIL-".mysqli_error($mConnection)."-".$mDataQuery."-".mysqli_num_rows($mData));
                    
                    if (mysqli_num_rows($mData) == 0)
                    {
                        $mPickFace = "N";
                    }
                }
                if ($mPickFace == "")
                {
// If no Pick Face stock - set pickface flag
                    $mDataQuery = "SELECT inventory_master.id AS id, inventory_master.part_id AS part_id FROM inventory_master JOIN part ON inventory_master.part_id=part.id JOIN location ON inventory_master.current_location_id=location.id WHERE part.part_number='".$mPartNumber."' AND inventory_master.inventory_status_id IN(".$mInvStsId.",".$mInvRcvId.") AND location.pick_group_id IS NOT null LIMIT 1";
                    if (!mysqli_query($mConnection,$mDataQuery))
                        return("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
                    $mData = mysqli_query($mConnection,$mDataQuery);
                    $i = mysqli_num_rows($mData);
// If no inventory - set pickface flag.
//                  if ($i == 0)
//                  {
//                      $mPickFace = "Y";
//                  }
                }
// If Part exists in available pickface Location - set pickface flag
                if ($mPickFace == "")
                {
                    $mRow = mysqli_fetch_assoc($mData);
                    if (!empty($mRow['part_id']))
                        $mPartId = $mRow['part_id'];
                    $mDataQuery = "SELECT inventory_master.current_location_id AS current_location_id";
                    $mDataQuery .= " FROM inventory_master";
                    $mDataQuery .= " JOIN location ON inventory_master.current_location_id=location.id";
                    $mDataQuery .= " LEFT JOIN location_filling_status ON location.filling_status_id=location_filling_status.id";
                    $mDataQuery .= " LEFT JOIN location_type ON location.location_type_id=location_type.id";
                    $mDataQuery .= " WHERE inventory_master.part_number='".$mPartNumber."' AND location.location_type_id=".$mLocTypeId." AND location.location_sub_type_id=".$mLocSubTypeId;
                    $mDataQuery .= " AND inventory_master.inventory_status_id IN(".$mInvStsId.",".$mInvRcvId.") AND location.pick_group_id IS NOT null";
                    $mDataQuery .= " AND (location.filling_status_id IS null OR (location_filling_status.putaway=1 AND (LOWER(location_filling_status.filling_code) = 'empty' OR LOWER(location_filling_status.filling_code) = 'filling')))";
                    if ($mPartWeight >0)
                    {
                        $mDataQuery .= " AND location.max_weight > ".$mPartWeight."+(SELECT max(weight) FROM part WHERE EXISTS(SELECT id FROM inventory_master WHERE part.id=inventory_master.part_id AND inventory_master.current_location_id=location.id))";
//                        $mDataQuery .= " AND location.max_weight > ".$mPartWeight."+(SELECT max(part.weight*inventory_master.inventory_qty) FROM part JOIN inventory_master ON part.id=inventory_master.part_id WHERE inventory_master.current_location_id=location.id)";
                    }
// Overbooked Inventory cannot go to 'SS' type location
                    if ($mInvInvStsId == $mInvOvrId)
                    {
                        $mDataQuery .= " AND location_type.locate_overbooking=1";
                    }
                    $mDataQuery .= " ORDER BY inventory_master.current_location_id";
                    if (!$mData = mysqli_query($mConnection,$mDataQuery))
                        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
                    $i = 0;
                    while($mRow = mysqli_fetch_assoc($mData)) 
                    {
                        $mDataLocQuery = "SELECT location.id AS id, CASE WHEN location.max_pick_face_qty IS null THEN 'Y' WHEN location.max_pick_face_qty=0 THEN 'Y' WHEN location.max_pick_face_qty > (SELECT COUNT(id) FROM inventory_master WHERE inventory_master.current_location_id=location.id AND inventory_master.inventory_status_id IN(".$mInvStsId.",".$mInvRcvId.")) THEN 'Y' ELSE 'N' END AS pick_face FROM location WHERE location.pick_group_id IS NOT null AND location.id=".$mRow['current_location_id']." LIMIT 1";
//                      $mDataLocQuery = "SELECT location.id AS id, CASE WHEN location.max_pick_face_qty IS null THEN 'Y' WHEN location.max_pick_face_qty=0 THEN 'Y' WHEN location.max_pick_face_qty > (SELECT COUNT(id) FROM inventory_master WHERE inventory_master.current_location_id=location.id AND inventory_master.inventory_status_id IN(".$mInvStsId.",".$mInvRcvId.")) THEN 'Y' ELSE 'N' END AS pick_face FROM location WHERE location.id=".$mRow['current_location_id']." LIMIT 1";
                        if (!mysqli_query($mConnection,$mDataLocQuery))
                            return("FAIL-".mysqli_error($mConnection)."-".$mDataLocQuery);
                        $mLocData = mysqli_query($mConnection,$mDataLocQuery);
                        $i = mysqli_num_rows($mLocData);
                        if ($i > 0)
                        {
                            $mLocRow = mysqli_fetch_assoc($mLocData);
                            
                            $mPickFace = $mLocRow['pick_face'];
                            if ($mPickFace == "Y")
                            {
                                $mLocId = $mLocRow['id'];
                                break;
                            }
                        }
                    }
                }
// Look for Stores Location with matching Inventory Parts
                if ($mPickFace != "Y")
                {
                    $mPickFace = "";
                    $mDataQuery = "SELECT current_location_id FROM inventory_master JOIN location ON inventory_master.current_location_id=location.id LEFT JOIN location_filling_status ON location.filling_status_id=location_filling_status.id LEFT JOIN location_type ON location.location_type_id=location_type.id JOIN part ON inventory_master.part_id=part.id WHERE part.part_number ='".$mPartNumber."'";
                    if ($mSerialReference != "")
                        $mDataQuery .= " AND inventory_master.serial_reference <> '".$mSerialReference."'";
                    $mDataQuery .= " AND (location.pick_group_id IS null OR location.pick_group_id='')";
                    $mDataQuery .= " AND lower(location_type.location_area)='storage'";
                    $mDataQuery .= " AND (location.part_number='".$mPartNumber."'";
                    $mDataQuery .= " OR ((location.part_number = '' OR location.part_number IS null)";
                    $mDataQuery .= " AND location.location_type_id=".$mLocTypeId;
                    if (!empty($mLocSubTypeId))
                    {
                        $mDataQuery .= " AND location.location_sub_type_id=".$mLocSubTypeId;
                    }
                    $mDataQuery .= "))";
                    $mDataQuery .= " AND (location.filling_status_id IS null OR (location_filling_status.putaway=1 AND (LOWER(location_filling_status.filling_code) = 'empty' OR LOWER(location_filling_status.filling_code) = 'filling')))";   
                    $mDataQuery .= " AND inventory_master.inventory_status_id IN(".$mInvStsId.",".$mInvRcvId.")";
                    if ($mPartWeight >0)
                    {
//                        $mDataQuery .= " AND location.max_weight > ".$mPartWeight."+(SELECT max(weight) FROM part WHERE EXISTS(SELECT id FROM inventory_master WHERE part.id=inventory_master.part_id AND inventory_master.current_location_id=location.id))";
                        $mDataQuery .= " AND location.max_weight > ".$mPartWeight."+(SELECT max(part.weight*inventory_master.inventory_qty) FROM part JOIN inventory_master ON part.id=inventory_master.part_id WHERE inventory_master.current_location_id=location.id)";
                    }
                    $mDataQuery .= " 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)) 
                    {
                        $mLocId = $mRow['current_location_id'];
                        $i++;
                    }
//                  echo ("FAIL-TEST1-".mysqli_error($mConnection)."-".$mDataQuery."-".$i);
                }
            }
        }
// Otherwise get details of Matching Location Type
        $mDataQuery = "SELECT 
          location.location_code AS toLocationHashCode,
          location.location_hash AS hash_code,
          SUBSTRING(location.location_code, 1, 1) AS aisle_code,
          SUBSTRING(location.location_code, 2, 1) AS rack_code,
          SUBSTRING(location.location_code, 3, 3) AS column_code,
          SUBSTRING(location.location_code, 6, 1) AS row_code,
          CASE 
            WHEN location_rack.priority_row_column = 'C' THEN location_column.filling_priority
            ELSE location_row.filling_priority
          END AS seq1,
          CASE 
            WHEN location_rack.priority_row_column <> 'C' THEN location_column.filling_priority
            ELSE location_row.filling_priority
          END AS seq2,
          location_type.location_type_code AS location_type_code,
          location_type.locate_overbooking AS locate_overbooking,
          COALESCE(SUM(part.weight * (inventory_master.inventory_qty/part.conversion_factor)), 0) AS loc_weight
        FROM 
          location
          LEFT JOIN location_aisle ON SUBSTRING(location.location_code, 1, 1) = location_aisle.aisle_code
          LEFT JOIN location_rack ON SUBSTRING(location.location_code, 2, 1) = location_rack.rack_code
          LEFT JOIN location_column ON SUBSTRING(location.location_code, 3, 3) = location_column.column_code
          LEFT JOIN location_row ON SUBSTRING(location.location_code, 6, 1) = location_row.row_code
          LEFT JOIN location_filling_status ON location.filling_status_id = location_filling_status.id
          LEFT JOIN location_type ON location.location_type_id = location_type.id
          LEFT JOIN inventory_master ON inventory_master.current_location_id = location.id
          LEFT JOIN part ON part.id = inventory_master.part_id";
        if ($mLocId != "")
        {
            $mDataQuery .= " WHERE location.id=".$mLocId." LIMIT 1";
        }
        else
        {       
            if (($mBigPart != 1 && (substr($mRequiresInspection,0,1) == "1" AND $mCompanyToQa == "1") || ($mTransactionTypeId == "TQA")))
                if (strtolower($mLocTypeCode) != "bp")
                    $mDataQuery .= " WHERE lower(location_type_code) = 'qa'";
                else
                    $mDataQuery .= " WHERE lower(location_type_code) in ('qa','bp')";
            elseif (strlen($mRequiresInspection)>1 && substr($mRequiresInspection,1,1) == 1)
                    $mDataQuery .= " WHERE lower(location_type_code) in ('qr','qr')";
            elseif ($mBigPart != 1 && $mPrufCube != "")
                $mDataQuery .= " WHERE lower(location_type.location_area)='storage'";
            else
            {
                if ($mLocTypeId != null)
                    $mDataQuery .= " WHERE (location.location_type_id IS null OR location.location_type_id = ".$mLocTypeId.") AND lower(location_type.location_area)='storage'";
                else
                    $mDataQuery .= " WHERE (location.location_type_id IS null) AND lower(location_type.location_area)='storage'";
                $mDataQuery .= " AND (location.part_number = '' OR location.part_number IS null";
                if ($mPartNumber != "" && $mPartNumber != null)
                        $mDataQuery .= " OR location.part_number = '".$mPartNumber."'";
                $mDataQuery .= ")";
                $mDataQuery .= " AND (location.max_pick_face_qty IS null OR location.max_pick_face_qty=0 OR location.max_pick_face_qty > (SELECT COUNT(id) FROM inventory_master WHERE inventory_master.current_location_id=location.id AND inventory_master.inventory_status_id IN(".$mInvStsId.",".$mInvOvrId.",".$mInvQaId.")))";               
                if ($mLocSubTypeId != "")
                    $mDataQuery .= " AND location.location_sub_type_id=".$mLocSubTypeId;
                else
                    $mDataQuery .= " AND location.location_sub_type_id IS null";
//                if ($mPickFace == "Y")
//                    $mDataQuery .= " AND location.pick_group_id IS NOT null";
//                else
//                    $mDataQuery .= " AND location.pick_group_id IS null";
// Overbooked Inventory cannot go to 'SS' location
                if ($mInvInvStsId == $mInvOvrId)
                {
                    $mDataQuery .= " AND location_type.locate_overbooking=1";
                }
            }
            if ($mPartWeight >0)
            {
                $mDataQuery .= " AND location.max_weight >= ".$mPartWeight."+(SELECT case WHEN max(part.weight*(inventory_master.inventory_qty/part.conversion_factor)) IS null THEN 0 ELSE max(part.weight*(inventory_master.inventory_qty/part.conversion_factor)) END AS loc_weight FROM part JOIN inventory_master ON part.id=inventory_master.part_id WHERE inventory_master.current_location_id=location.id)";
            }

            $mDataQuery .= " 
                AND (
                        location.filling_status_id IS null 
                        OR 
                        (   
                            location_filling_status.putaway=1
                            AND 
                            (
                                LOWER(location_filling_status.filling_code) = 'empty'
                                OR 
                                (
                                    LOWER(location_filling_status.filling_code) = 'filling' AND location.multi_part_location=1
                                    OR 
                                    (
                                        CASE WHEN '$mTransactionTypeId' = 'FQA'
                                        THEN
                                            LOWER(location_filling_status.filling_code)='filling' AND location.multi_part_location=0 AND EXISTS(SELECT id FROM inventory_master WHERE inventory_master.location_id=location.id AND inventory_master.part_number='$mPartNumber' AND inventory_master.inventory_status_id IN($mInvStsId,$mInvOvrId,$mInvQaId))
                                        ELSE
                                            LOWER(location_filling_status.filling_code)='filling' AND location.multi_part_location=0 AND EXISTS(SELECT id FROM inventory_master WHERE inventory_master.location_id=location.id AND inventory_master.part_number='$mPartNumber' AND inventory_master.inventory_status_id IN($mInvStsId,$mInvOvrId))
                                        END
                                    )
                                )
                            )
                        )
                    )";
            $mDataQuery .=" GROUP BY
              location.location_code,
              location.location_hash,
              location_aisle.aisle_code,
              location_rack.rack_code,
              location_column.column_code,
              location_row.row_code,
              location_rack.priority_row_column,
              location_column.filling_priority,
              location_row.filling_priority,
              location_type.location_type_code,
              location_type.locate_overbooking"; 
            if (substr($mRequiresInspection,0,1) == 1)
            {
                $mDataQuery .=" ORDER BY location.id";
            }
            else
            {
                $mDataQuery .= " ORDER BY location_aisle.filling_priority,location_aisle.aisle_code, location_rack.filling_priority,location_rack.rack_code, seq1, seq2,location.location_code";            
            }
            $mDataQuery .= " LIMIT 50";
            $mTest = "TEST2";
        }
//      return "FAIL-TEST2".$mDataQuery;
    }

// Pallet Locate
    else
    {
        $mPartWeight = 0;
        $mDataQuery = "SELECT sum(part.weight) AS weight FROM part";
        $mDataQuery .=" WHERE EXISTS(SELECT id FROM inventory_master WHERE part.id=inventory_master.part_id AND inventory_master.id='".$mInvId."')";
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            return("FAIL-".mysqli_error($mConnection)."-".$mDataQuery); 
        if (mysqli_num_rows($mData) > 0)
        {
            list($mPartWeight) = mysqli_fetch_row($mData); 
        }
        if (empty($mPartWeight))
            $mPartWeight = 99999;

// force to drop zone
        if ($mZoneTypeId > 0)
        {
// Check current location type
            $mDataQuery = "SELECT location_type_code FROM location_type";
            $mDataQuery .=" WHERE EXISTS(SELECT id FROM location WHERE location.location_type_id=location_type.id";
            $mDataQuery .=" AND EXISTS(SELECT id FROM inventory_master WHERE location.id=inventory_master.current_location_id AND inventory_master.id='".$mInvId."'))";
            $mDataQuery .=" LIMIT 1";
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                return("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    //        return "FAIL-TEST-".$mDataQuery."-".mysqli_num_rows($mData);
            if (mysqli_num_rows($mData) > 0)
            {
                list($mLocType) = mysqli_fetch_row($mData);
                if (strToUpper($mLocType) != "DZ")
                {
//        return "FAIL-TEST-".$mDataQuery."-".mysqli_num_rows($mData)."-".$mLocType;
                    $mDataQuery = "SELECT location.id AS id FROM location";
                    $mDataQuery .= " LEFT JOIN location_filling_status ON location.filling_status_id=location_filling_status.id";
                    $mDataQuery .= " LEFT JOIN location_type ON location.location_type_id=location_type.id";
                    $mDataQuery .= " WHERE location.id=".$mZoneTypeId;
                    $mDataQuery .= " LIMIT 1";
                    if (!$mData = mysqli_query($mConnection,$mDataQuery))
                        return("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);             
                    if (mysqli_num_rows($mData) > 0)
                    {
                        list($mLocId) = mysqli_fetch_row($mData); 
                        $mPickFace = "Z";
                    }
                }
            }
        }
        $mDataQuery = "SELECT 
          location.location_code AS toLocationHashCode,
          location.location_hash AS hash_code,
          SUBSTRING(location.location_code, 1, 1) AS aisle_code,
          SUBSTRING(location.location_code, 2, 1) AS rack_code,
          SUBSTRING(location.location_code, 3, 3) AS column_code,
          SUBSTRING(location.location_code, 6, 1) AS row_code,
          CASE 
            WHEN location_rack.priority_row_column = 'C' THEN location_column.filling_priority
            ELSE location_row.filling_priority
          END AS seq1,
          CASE 
            WHEN location_rack.priority_row_column <> 'C' THEN location_column.filling_priority
            ELSE location_row.filling_priority
          END AS seq2,
          location_type.location_type_code AS location_type_code,
          location_type.locate_overbooking AS locate_overbooking,
          COALESCE(SUM(part.weight * (inventory_master.inventory_qty/part.conversion_factor)), 0) AS loc_weight
        FROM 
          location
          LEFT JOIN location_aisle ON SUBSTRING(location.location_code, 1, 1) = location_aisle.aisle_code
          LEFT JOIN location_rack ON SUBSTRING(location.location_code, 2, 1) = location_rack.rack_code
          LEFT JOIN location_column ON SUBSTRING(location.location_code, 3, 3) = location_column.column_code
          LEFT JOIN location_row ON SUBSTRING(location.location_code, 6, 1) = location_row.row_code
          LEFT JOIN location_filling_status ON location.filling_status_id = location_filling_status.id
          LEFT JOIN location_type ON location.location_type_id = location_type.id
          LEFT JOIN inventory_master ON inventory_master.current_location_id = location.id
          LEFT JOIN part ON part.id = inventory_master.part_id";
        if ($mLocId != "")
        {
            $mDataQuery .= " WHERE location.id=".$mLocId." LIMIT 1";
        }
        else
        {       
            if (($mBigPart != 1 && (substr($mRequiresInspection,0,1) == "1" AND $mCompanyToQa == "1") || ($mTransactionTypeId == "TQA")))
                if (strtolower($mLocTypeCode) != "bp")
                    $mDataQuery .= " WHERE lower(location_type_code) = 'qa'";
                else
                    $mDataQuery .= " WHERE lower(location_type_code) in ('qa','bp')";
            elseif (strlen($mRequiresInspection)>1 && substr($mRequiresInspection,1,1) == 1)
                    $mDataQuery .= " WHERE lower(location_type_code) in ('qr','qr')";
            elseif ($mBigPart != 1 && $mPrufCube != "")
                $mDataQuery .= " WHERE lower(location_type.location_type_code)='pc' AND lower(location_type.location_area)='storage'";
            else
            {
                if ($mLocTypeId != null)
                    $mDataQuery .= " WHERE (location.location_type_id IS null OR location.location_type_id = ".$mLocTypeId.") AND lower(location_type.location_area)='storage'";
                else
                    $mDataQuery .= " WHERE (location.location_type_id IS null) AND lower(location_type.location_area)='storage'";
                $mDataQuery .= " AND (location.part_number = '' OR location.part_number IS null)";
                $mDataQuery .= " AND (location.max_pick_face_qty IS null OR location.max_pick_face_qty=0 OR location.max_pick_face_qty > (SELECT COUNT(id) FROM inventory_master WHERE inventory_master.current_location_id=location.id AND inventory_master.inventory_status_id IN(".$mInvStsId.",".$mInvOvrId.",".$mInvQaId.")))";               
                if ($mLocSubTypeId != "")
                    $mDataQuery .= " AND location.location_sub_type_id=".$mLocSubTypeId;
                else
                    $mDataQuery .= " AND location.location_sub_type_id IS null";
                if ($mPickFace == "Y")
                    $mDataQuery .= " AND location.pick_group_id IS NOT null";
                if ($mMultiPart == "1")
                    $mDataQuery .=" AND location.multi_part_location=1";
// Overbooked Inventory cannot go to 'SS' location
                if ($mInvInvStsId == $mInvOvrId)
                {
                    $mDataQuery .= " AND location_type.locate_overbooking=1";
                }
            }
            if ($mPartWeight >0)
            {
                $mDataQuery .= " AND location.max_weight >= ".$mPartWeight."+(SELECT case WHEN max(part.weight*(inventory_master.inventory_qty/part.conversion_factor)) IS null THEN 0 ELSE max(part.weight*(inventory_master.inventory_qty/part.conversion_factor)) END AS loc_weight FROM part JOIN inventory_master ON part.id=inventory_master.part_id WHERE inventory_master.current_location_id=location.id)";
            }
            $mDataQuery .= " 
                AND (
                        location.filling_status_id IS null 
                        OR 
                        (   
                            location_filling_status.putaway=1
                            AND 
                            (
                                LOWER(location_filling_status.filling_code) = 'empty'
                                OR 
                                (
                                    LOWER(location_filling_status.filling_code) = 'filling' AND location.multi_part_location=1
                                    OR 
                                    (
                                        CASE WHEN '$mTransactionTypeId' = 'FQA'
                                        THEN
                                            LOWER(location_filling_status.filling_code)='filling' AND location.multi_part_location=0 AND EXISTS(SELECT id FROM inventory_master WHERE inventory_master.location_id=location.id AND inventory_master.part_number='$mPartNumber' AND inventory_master.inventory_status_id IN($mInvStsId,$mInvOvrId,$mInvQaId))
                                        ELSE
                                            LOWER(location_filling_status.filling_code)='filling' AND location.multi_part_location=0 AND EXISTS(SELECT id FROM inventory_master WHERE inventory_master.location_id=location.id AND inventory_master.part_number='$mPartNumber' AND inventory_master.inventory_status_id IN($mInvStsId,$mInvOvrId))
                                        END
                                    )
                                )
                            )
                        )
                    )";
            $mDataQuery .= " GROUP BY
              location.location_code,
              location.location_hash,
              location_aisle.aisle_code,
              location_rack.rack_code,
              location_column.column_code,
              location_row.row_code,
              location_rack.priority_row_column,
              location_column.filling_priority,
              location_row.filling_priority,
              location_type.location_type_code,
              location_type.locate_overbooking"; 
            if (substr($mRequiresInspection,0,1) == 1)
            {
                $mDataQuery .=" ORDER BY location.id";
            }
            else
            {
                $mDataQuery .= " ORDER BY location_aisle.filling_priority,location_aisle.aisle_code, location_rack.filling_priority,location_rack.rack_code, seq1, seq2,location.location_code";            
            }            $mDataQuery .= " LIMIT 50";
        }
        $mTest = "TEST3";
    }
//  exit("FAIL-".$mTest."-".$mDataQuery);
//      exit ("FAIL-TEST2-".$mDataQuery."-".$mPartWeight);
// validate QRY
    if (!$mData = mysqli_query($mConnection,$mDataQuery))
        exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
//    exit ("FAIL-TEST2-".$mDataQuery."-".mysqli_error($mConnection)."-".$mPartWeight);

// Pick Face with no available pick face location
    if ((mysqli_num_rows($mData) ==0) && ($mPickFace == "Y"))
    {
        $mDataQuery = "SELECT 
          location.location_code AS toLocationHashCode,
          location.location_hash AS hash_code,
          SUBSTRING(location.location_code, 1, 1) AS aisle_code,
          SUBSTRING(location.location_code, 2, 1) AS rack_code,
          SUBSTRING(location.location_code, 3, 3) AS column_code,
          SUBSTRING(location.location_code, 6, 1) AS row_code,
          CASE 
            WHEN location_rack.priority_row_column = 'C' THEN location_column.filling_priority
            ELSE location_row.filling_priority
          END AS seq1,
          CASE 
            WHEN location_rack.priority_row_column <> 'C' THEN location_column.filling_priority
            ELSE location_row.filling_priority
          END AS seq2,
          location_type.location_type_code AS location_type_code,
          location_type.locate_overbooking AS locate_overbooking,
          COALESCE(SUM(part.weight * (inventory_master.inventory_qty/part.conversion_factor)), 0) AS loc_weight
        FROM 
          location
          LEFT JOIN location_aisle ON SUBSTRING(location.location_code, 1, 1) = location_aisle.aisle_code
          LEFT JOIN location_rack ON SUBSTRING(location.location_code, 2, 1) = location_rack.rack_code
          LEFT JOIN location_column ON SUBSTRING(location.location_code, 3, 3) = location_column.column_code
          LEFT JOIN location_row ON SUBSTRING(location.location_code, 6, 1) = location_row.row_code
          LEFT JOIN location_filling_status ON location.filling_status_id = location_filling_status.id
          LEFT JOIN location_type ON location.location_type_id = location_type.id
          LEFT JOIN inventory_master ON inventory_master.current_location_id = location.id
          LEFT JOIN part ON part.id = inventory_master.part_id";
        if (($mBigPart != 1 && (substr($mRequiresInspection,0,1) == "1" AND $mCompanyToQa == "1") || ($mTransactionTypeId == "TQA")))
            if (strtolower($mLocTypeCode) != "bp")
                $mDataQuery .= " WHERE lower(location_type_code) = 'qa'";
            else
                $mDataQuery .= " WHERE lower(location_type_code) in ('qa','bp')";
            elseif (strlen($mRequiresInspection)>1 && substr($mRequiresInspection,1,1) == 1)
                    $mDataQuery .= " WHERE lower(location_type_code) in ('qr','qr')";
            elseif ($mBigPart != 1 && $mPrufCube != "")
                $mDataQuery .= " WHERE lower(location_type.location_type_code)='pc' AND lower(location_type.location_area)='storage'";
        else
        {
            if ($mLocTypeId != null)
                $mDataQuery .= " WHERE (location.location_type_id IS null OR location.location_type_id = ".$mLocTypeId.") AND lower(location_type.location_area)='storage'";
            else
                $mDataQuery .= " WHERE (location.location_type_id IS null) AND lower(location_type.location_area)='storage'";
            $mDataQuery .= " AND (location.part_number = '' OR location.part_number IS null)";
            $mDataQuery .= " AND (location.max_pick_face_qty IS null OR location.max_pick_face_qty=0 OR location.max_pick_face_qty+0 > (SELECT COUNT(id) FROM inventory_master WHERE inventory_master.current_location_id=location.id AND inventory_master.inventory_status_id IN(".$mInvStsId.",".$mInvOvrId.")))";                
            if ($mLocSubTypeId != "")
                $mDataQuery .= " AND location.location_sub_type_id=".$mLocSubTypeId;
            else
                $mDataQuery .= " AND location.location_sub_type_id IS null";                
            $mDataQuery .= " AND location.pick_group_id IS null";
            $mDataQuery .= " AND (location.filling_status_id IS null OR (location_filling_status.putaway=1 
            AND (LOWER(location_filling_status.filling_code) = 'empty' OR (LOWER(location_filling_status.filling_code) = 'filling' AND location.multi_part_location=1)
//            OR (LOWER(location_filling_status.filling_code)='filling' AND location.multi_part_location=0 AND EXISTS* SELECT id FROM inventory_master WHERE inventory_master.location.id=location.id AND inventory_master.part_number='".$mPartNumber."' AND inventory_master.inventory_status_id=".$mInvStsId.")))))
            "; 
            if ($mMultiPart == "1")
                $mDataQuery .=" AND location.multi_part_location=1";
            if ($mPartWeight >0)
            {
                $mDataQuery .= " AND location.max_weight > ".$mPartWeight."+(SELECT max(weight) FROM part WHERE EXISTS(SELECT id FROM inventory_master WHERE part.id=inventory_master.part_id AND inventory_master.current_location_id=location.id))";
            }
            $mDataQuery .=" GROUP BY
              location.location_code,
              location.location_hash,
              location_aisle.aisle_code,
              location_rack.rack_code,
              location_column.column_code,
              location_row.row_code,
              location_rack.priority_row_column,
              location_column.filling_priority,
              location_row.filling_priority,
              location_type.location_type_code,
              location_type.locate_overbooking"; 
            $mDataQuery .= " ORDER BY location_aisle.filling_priority,location_aisle.aisle_code, location_rack.filling_priority,location_rack.rack_code, seq1, seq2,location.location_code";
            $mDataQuery .= " LIMIT 1";
            $mTest = "TEST4";
        }
// validate QRY
        if (!$mData = mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
    }
    
 //   return "FAIL-TEST2".mysqli_num_rows($mData)."-".$mDataQuery."-".mysqli_error($mConnection)."-".$mTest;
    
    $i = 0;
    $mId = "";
    $mSeq1 = "";
    $mLocs = array();
    $mNextLoc = "";
    $mPrvCode = null;
// Retrieve Location_Code
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
//      $mNextLoc = ($mRow['toLocationHashCode'])."-".($mRow['location_type_code']);
        if ((strtolower($mRow['location_type_code']) != "qtine") && (strtolower($mRow['location_type_code']) != "bp"))
        {
            $mNextLoc = ($mRow['toLocationHashCode']);
            break;
        }
        if ($mRow['location_type_code'] != $mPrvCode)
        {
            if ($i==0)
                $mNextLoc = ($mRow['toLocationHashCode']);
            else
                $mNextLoc .= " ".$mRow['toLocationHashCode'];
            $mPrvCode = $mRow['location_type_code'];
            $i++;
            if ($i >1)
                break;
        }
    }
//  mysqli_close($mConnection);
    if ($mNextLoc == "")
    {
        if ($mInvInvStsId == $mInvOvrId)
        {
            $mNextLoc = "FAIL-No Available Locations - Serial is Overbooked";
        }
        else
        {
            $mNextLoc = "FAIL-No Available Locations ".$mPickFace;
        }
    }
//  exit ("FAIL-".$mDataQuery);
//  exit("FAIL-".$mTest."-".$mLocTypeId."-".$mRequiresInspection."-".$mDataQuery."-".$i.":".$mNextLoc);
// Return Location_Code to calling program
    return $mNextLoc;
}

// validate Putaway Location based on Company Rules
function validateCompanyPutawayLocation($mUser,$mPart,$mHashCode,$mLocationCode,$mSerialReference,$mPlt,$mDbHost=null,$mDbUser=null,$mDbPwd=null,$mDbName=null,$mTransactionTypeId="",$mReplace="")
{
    $mDataStr = "";
// mysql connection
        $mConnection=mysqli_connect($mDbHost,$mDbUser,$mDbPwd,$mDbName) or
            exit ("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Check Location Code
    $mDataQuery = "SELECT location.id AS id , location.location_code AS location_code, location.location_type_id AS location_type_id FROM location LEFT JOIN location_filling_status ON location.filling_status_id=location_filling_status.id WHERE location.location_hash='".$mHashCode."' AND lower(location_filling_status.filling_code) IN('filling','empty') LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery."-".$mDbHost."-".$mDbUser."-".$mDbPwd."-".$mDbName;
    $mData = mysqli_query($mConnection,$mDataQuery);
    if (mysqli_num_rows($mData) == 0)
    {
        $mDataStr = "FAIL-Invalid Location Code";
        return $mDataStr;
    }
// No Results Found
    $i = 0;
    $mLocId = "";
    $mLocation = "";
    $mLocTypeId = "";
// Retrieve Location_Code
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mLocId = ($mRow['id']);
        $mLocation = ($mRow['location_code']);
        $mLocTypeId = ($mRow['location_type_id']);
        $i++;
    }
// get Company Settings
    $mDataQuery = "SELECT company.forced_locate AS forced_locate, company.to_qa AS to_qa FROM company WHERE id=1 LIMIT 1";
// validate QRY
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery."-".$mDbHost."-".$mDbUser."-".$mDbPwd."-".$mDbName;
// Run QRY
    $mData = mysqli_query($mConnection,$mDataQuery);
    $i = 0;
    $mForceLoc = "";
    $mToQa = "";
    
// Retrieve Location_Code
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mForceLoc = ($mRow['forced_locate']);
        if ($mRow['to_qa'] == "1")
            $mToQa = "1";
        $i++;
    }
// Force Locate - Prompted Loc must match scanned Loc.
    if ($mForceLoc == "1")
    {
// Invalid Prompted Location
        if (substr($mLocationCode,0,4)=="FAIL")
            $mLocationCode=$mLocation;
        $pos = strpos($mLocationCode, $mLocation);
        if ($pos === false)
        {
            $mDataStr = "FAIL-Not Fixed Location";
            return $mDataStr;
        }
    }
    else
    {
        if ($mPlt != "PTS")
        {
// Check for matching Product / Zone / filling Types
            $mDataQuery = "SELECT part.id AS id, part.fixed_location_type_id AS location_type_id, part.fixed_sub_type_id AS zone_type_id,location_type.location_area AS location_area FROM part LEFT JOIN location_type ON part.fixed_location_type_id=location_type.id WHERE part_number = '".$mPart."' AND now() BETWEEN effective_from AND effective_to LIMIT 1";
// validate QRY
            if (!mysqli_query($mConnection,$mDataQuery))
                return "FAIL-".mysqli_error($mConnection).$mDataQuery;
// Run QRY
            $mData = mysqli_query($mConnection,$mDataQuery);
            $i = 0;
            $mId = "";
            $mPartLocation = "";
            $mPartZone = "";
            $mPartArea = "";
// Retrieve Location_Code
            while($mRow = mysqli_fetch_assoc($mData)) 
            {
                $mId = ($mRow['id']);
                $mPartLocation = ($mRow['location_type_id']);
                $mPartZone = ($mRow['zone_type_id']);
                $mPartArea = ($mRow['location_area']);
                $i++;
            }
            if ($i == 0)
            {
                $mDataStr = "FAIL-Invalid Part Number";
            }
        }
        if (!empty($mDataStr) && $mTransactionTypeId == "FQA")
        {
            if ($mPartLocation != $mLocTypeId)
            {
                $mDataStr = "FAIL-Invalid Location_type";
                return $mDataStr;
            }
        }
// No Errors
        if ($mDataStr == "" && $mTransactionTypeId != "FQA")
        {
// Check for Pruf-Cube Serial
            if ($mPlt == "PTS")
            {
                $mDataQuery = "SELECT inventory_master.pruf_cube AS pruf_cube, inventory_master.requires_inspection AS requires_inspection";
                $mDataQuery .=",part.is_big_part AS is_big_part";
                $mDataQuery .=" FROM inventory_master";
                $mDataQuery .=" JOIN part ON inventory_master.part_id=part.id";
                $mDataQuery .=" JOIN tag ON inventory_master.parent_tag_id=tag.id";
                $mDataQuery .=" WHERE tag.tag_reference = '".$mSerialReference."' AND inventory_master.inventory_qty > 0";
                $mDataQuery .=" ORDER BY tag.tag_reference, inventory_master.part_id";
                $mDataQuery .=" LIMIT 50";
            }
            else
            {
                $mDataQuery = "SELECT inventory_master.pruf_cube AS pruf_cube, inventory_master.requires_inspection AS requires_inspection";
                $mDataQuery .=",part.is_big_part AS is_big_part";
                $mDataQuery .=" FROM inventory_master";
                $mDataQuery .=" JOIN part ON inventory_master.part_id=part.id";
                $mDataQuery .=" WHERE inventory_master.part_id=".$mId." AND inventory_master.serial_reference='".$mSerialReference."' AND inventory_master.inventory_qty > 0";
                $mDataQuery .=" LIMIT 1";
            }
// validate QRY
            if (!mysqli_query($mConnection,$mDataQuery))
                return "FAIL-".mysqli_error($mConnection).$mDataQuery;
// Run QRY
            $mData = mysqli_query($mConnection,$mDataQuery);
            $mPrufCube = "";
            $mRequiresInspection = "";
            $mBigPart = 0;
            while($mRow = mysqli_fetch_assoc($mData)) 
            {
                if(($mRow['pruf_cube']) == "1")
                    $mPrufCube="1";
                if ($mRow['requires_inspection'] == "1")
                    $mRequiresInspection = "1";
                if ($mRow['is_big_part'] == "1")
                    $mBigPart = "1";
                
            }
            if ($mTransactionTypeId == "TQA")
                $mRequiresInspection = "1";
            if ($mToQa == "1" && $mRequiresInspection == "1")
                $mDataQuery = "SELECT location.id AS id, location.inventory_disposition_id AS product_type_id, location.multi_part_location AS multi_part, location.location_type_id AS location_type_id, location.location_sub_type_id AS zone_type_id, location_type.location_type_code AS location_type_code, location.part_number AS part_number, location_type.location_area AS location_area FROM location JOIN location_type ON location.location_type_id=location_type.id WHERE location.location_hash='".$mHashCode."' AND LOWER(location_type.location_area) in('storage','work')";
            else                
                $mDataQuery = "SELECT location.id AS id, location.inventory_disposition_id AS product_type_id, location.multi_part_location AS multi_part, location.location_type_id AS location_type_id, location.location_sub_type_id AS zone_type_id, location_type.location_type_code AS location_type_code, location.part_number AS part_number, location_type.location_area AS location_area FROM location JOIN location_type ON location.location_type_id=location_type.id WHERE location.location_hash='".$mHashCode."' AND LOWER(location_type.location_area) in('storage','work')";
//          if ($mPlt == "PTS")
//              $mDataQuery .= " AND location_filling_status.filling_code='Empty'";
            $mDataQuery .= " LIMIT 1";
// validate QRY
            if (!mysqli_query($mConnection,$mDataQuery))
                return "FAIL-".mysqli_error($mConnection).$mDataQuery;
// Run QRY
            $mData = mysqli_query($mConnection,$mDataQuery);
            $i = 0;
            $mLocId = "";
            $mLocLocation = "";
            $mLocZone = "";
            $mLocMultiPart = "";
            $mLocTypeCode = "";
            $mLocPartNumber = "";
            $mLocArea = "";
// Retrieve Location_Code
            while($mRow = mysqli_fetch_assoc($mData)) 
            {
                $mLocId = ($mRow['id']);
                $mLocLocation = ($mRow['location_type_id']);
                $mLocZone = ($mRow['zone_type_id']);
                $mLocMultiPart = ($mRow['multi_part']);
                $mLocTypeCode = ($mRow['location_type_code']);
                $mLocPartNumber = ($mRow['part_number']);
                $mLocArea = ($mRow['location_area']);
                $i++;
            }
            if ($i > 0)
            {
                if ($mPartLocation == null)
                    $mPartLocation = $mLocLocation;
                if ($mPartZone == null)
                    $mPartZone = $mLocZone;
            }
// No Matching Location Type
            if ($i == 0)
            {
                $mDataStr = "FAIL-Scanned Location is not a Matching Putaway Location ".$mDataQuery;
            }
// Test for Inspection Part
            if ($mDataStr == "" && $mTransactionTypeId == "TQA") 
                if (strtolower($mLocTypeCode) != 'qa')
                    $mDataStr = "FAIL-This Serial must go to Inspection.";
                else
                    $mDataStr = "OK  -insp";
/*
// Test for Inspection Part
            if ($mDataStr == "" && $mToQa == "1"  && $mRequiresInspection == "1" && $mBigPart == 0 && $mTransactionTypeId != "FQA")
            {
                if (strtolower($mLocTypeCode) != 'qa')
                    $mDataStr = "FAIL-This Serial must go to Inspection.";
                else
                    $mDataStr = "OK  -insp";
            }
*/
// Test for Pruf Cube
            if ($mDataStr == "" && $mPrufCube == "1")
            {
                if (strtolower($mLocTypeCode) != 'pc')
                    $mDataStr = "FAIL-This Serial is Pruf Cube only.";
                else
                    $mDataStr = "OK  -pruf";
            }
// Test matching Part / Location zone settings
            if ($mDataStr == "") 
            {
// Test for Matching Part Number
                if ($mLocPartNumber != $mPart)
                {
                    if (($mPartLocation != $mLocLocation) || ($mPartZone != $mLocZone))
                    {
/*
                        if ($mPartArea != $mLocArea)
                            $mReplace = "";
                        if (strtolower($mReplace) != "y")
                        {
                            if (($mPartLocation != $mLocLocation) && ($mPartZone != $mLocZone))
                                $mDataStr = "FAIL-Scanned Location Type and Zone do not match.";
                            elseif ($mPartLocation != $mLocLocation)
                                $mDataStr = "FAIL-Scanned Location is not allowed for this Part.";
                            else
                                $mDataStr = "FAIL-Scanned Location Zone is not allowed for this Part.";
                        }
                        else
                        {
                            $mDataQuery = "UPDATE location SET last_updated=now(),last_updated_by='".$mUser."_RCTS',location_type_id=".$mPartLocation.",location_sub_type_id=".$mPartZone." WHERE id=".$mLocId." LIMIT 1";
                            if (!mysqli_query($mConnection,$mDataQuery))
                            return "FAIL-".mysqli_error($mConnection).$mDataQuery;
                        }
*/
                    }
                }
                else
                    $mDataStr = "";
            }
        }
// Test for Single Part Location
        if ($mDataStr == "")
        {
            $mDataQuery = "SELECT location.multi_part_location AS multi_part FROM location WHERE location.location_hash='".$mHashCode."' LIMIT 1";
// validate QRY
            if (!$mData = mysqli_query($mConnection,$mDataQuery))
                return "FAIL-".mysqli_error($mConnection).$mDataQuery;
// Run QRY
//          $mData = mysqli_query($mConnection,$mDataQuery);
            $i = 0;
            $mLocMultiPart = "";
// Retrieve First Part on Pallet
            while($mRow = mysqli_fetch_assoc($mData)) 
            {
                $mLocMultiPart = ($mRow['multi_part']);
                $i++;
            }
            if ($mLocMultiPart == 0)
            {
// Test for Mixed-Pallet
                if ($mPlt == "PTS")
                {
                    $mDataQuery = "SELECT inventory_master.part_id AS part_id FROM inventory_master JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE tag.tag_reference = '".$mSerialReference."' AND inventory_master.inventory_qty > 0 ORDER BY tag.tag_reference, inventory_master.part_id LIMIT 1";
// validate QRY
                    if (!mysqli_query($mConnection,$mDataQuery))
                        return "FAIL-".mysqli_error($mConnection).$mDataQuery;
// Run QRY
                    $mData = mysqli_query($mConnection,$mDataQuery);
                    $i = 0;
                    $mPartId1 = "";
// Retrieve First Part on Pallet
                    while($mRow = mysqli_fetch_assoc($mData)) 
                    {
                        $mPartId1 = ($mRow['part_id']);
                        $i++;
                    }
                    $mDataQuery = "SELECT inventory_master.part_id AS part_id FROM inventory_master JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE tag.tag_reference = '".$mSerialReference."' AND inventory_master.inventory_qty > 0 ORDER BY tag.tag_reference, inventory_master.part_id DESC LIMIT 1";
// validate QRY
                    if (!mysqli_query($mConnection,$mDataQuery))
                        return "FAIL-".mysqli_error($mConnection).$mDataQuery;
// Run QRY
                    $mData = mysqli_query($mConnection,$mDataQuery);
                    $i = 0;
                    $mPartId2 = "";
// Retrieve Last Part on Pallet
                    while($mRow = mysqli_fetch_assoc($mData)) 
                    {
                        $mPartId2 = ($mRow['part_id']);
                        $i++;
                    }
                    if ($mPartId1 != $mPartId2)
                        $mDataStr = "FAIL-Mixed Pallets Are Not Allowed";
                }
                else
                {
// Test for different Part in Location
                    $mDataQuery = "SELECT inventory_master.id AS id FROM inventory_master JOIN location ON inventory_master.current_location_id=location.id JOIN part ON inventory_master.part_id=part.id LEFT JOIN location_filling_status ON location.filling_status_id=location_filling_status.id LEFT JOIN inventory_status ON inventory_master.inventory_status_id=inventory_status.id WHERE location.location_hash='".$mHashCode."' AND part.part_number<>'".$mPart."' AND inventory_qty > 0 AND lower(inventory_status.inventory_status_code) NOT IN('plt','pkd')";
//                  $mDataQuery .= " AND lower(location_filling_status.filling_code) IN('filling','closed')";
                    $mDataQuery .= " LIMIT 1";
// validate QRY
                    if (!mysqli_query($mConnection,$mDataQuery))
                        return "FAIL-".mysqli_error($mConnection).$mDataQuery;
// Run QRY
                    $mData = mysqli_query($mConnection,$mDataQuery);
                    $i = 0;
                    $mInvId = "";
// Retrieve Location_Code
                    while($mRow = mysqli_fetch_assoc($mData)) 
                    {
                        $mInvId = ($mRow['id']);
                        $i++;
                    }
                    if ($i > 0)
                        $mDataStr = "FAIL-Different Part Exists in This Location";
                }
            }
        }
        if ($mDataStr == "")
        {
            $mDataStr = "OK  -";
        }
    }
//  mysqli_close($mConnection);
    
    if ($mDataStr == "")
    {
        $mDataStr = "OK  -".$mDataQuery."-".mysqli_error($mConnection);
    }
    
    return $mDataStr;
}

function postCts($mSerialReference,$mPartNumber,$mToLocHash,$mCurrentUser,$mDbHost=null,$mDbUser=null,$mDbPwd=null,$mDbName=null)
{
// mysql connection - Use Passed values...
    if (($mDbHost != null) && ($mDbHost != ""))
        $mConnection=mysqli_connect($mDbHost,$mDbUser,$mDbPwd,$mDbName) or
            exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// ... or get defaults from function defaultDbConnection
    else
        $mConnection =defaultDbConnection();
    
    $mDataQuery = "SELECT id AS id, location_code AS location_code FROM location WHERE location.location_hash='".$mToLocHash."' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;
    $mData = (mysqli_query($mConnection,$mDataQuery));
    if (mysqli_num_rows($mData) == 0)
        return "FAIL-Invalid Location Code.";
    $mRow = mysqli_fetch_assoc($mData);
    $mToLocId = ($mRow['id']);
    $mToLocCode = ($mRow['location_code']);
    
    $mDataQuery = "SELECT inventory_master.id AS id, part.part_number AS part_number, inventory_master.serial_reference AS serial_reference, inventory_master.ran_or_order AS ran_order, inventory_master.inventory_qty AS inventory_qty, tag.tag_reference AS plt_number, location.location_code AS location_code FROM inventory_master JOIN part ON inventory_master.part_id=part.id LEFT JOIN location ON inventory_master.current_location_id=location.id LEFT JOIN inventory_status ON inventory_master.current_inventory_status_id=inventory_status.id LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE part.part_number='".$mPartNumber."' AND inventory_master.serial_reference='".$mSerialReference."' AND inventory_qty>0 LIMIT 1";  
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;
    $mData = (mysqli_query($mConnection,$mDataQuery));
    if (mysqli_num_rows($mData) == 0)
        return "FAIL-No inventory exists for this serial reference.";
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mInvId = ($mRow['id']);
        $mTranQuery = "INSERT INTO transaction_history (id,short_code,part_number,serial_reference,ran_or_order,txn_qty,source_tag,from_location_code,to_location_code,date_created,last_updated,last_updated_by,transaction_reference_code) VALUES(DEFAULT,'CTS','".($mRow['part_number'])."','".($mRow['serial_reference'])."','".($mRow['ran_order'])."',".($mRow['inventory_qty']).",'".($mRow['plt_number'])."','".($mRow['location_code'])."','".$mToLocCode."',now(),now(),'".$mCurrentUser."','CTS')";  
        if (!mysqli_query($mConnection,$mTranQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mTranQuery;  
    }
    
    $mDataQuery = "UPDATE inventory_master SET current_location_id=".$mToLocId.",last_updated=now(),last_updated_by='".$mCurrentUser."' WHERE id=".$mInvId." LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;

    return("OKMS-locate Complete");
}

function postFqa($mSerialReference,$mPartNumber,$mToLocHash,$mCurrentUser,$mDbHost=null,$mDbUser=null,$mDbPwd=null,$mDbName=null)
{
// mysql connection - Use Passed values...
    if (($mDbHost != null) && ($mDbHost != ""))
        $mConnection=mysqli_connect($mDbHost,$mDbUser,$mDbPwd,$mDbName) or
            exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// ... or get defaults from function defaultDbConnection
    else
        $mConnection =defaultDbConnection();
    
// Get id for inventory status
    $mInvStsId = 0;
    $mInvRcvId = 0;
    $mInvPckId = 0;
    $mInvPltId = 0;
    $mInvQaId = 0;
    $mDataQuery = "SELECT id AS id, inventory_status_code AS inventory_status_code FROM inventory_status";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;
    $mData = (mysqli_query($mConnection,$mDataQuery));
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        if (strtolower($mRow['inventory_status_code']) == "ok")
            $mInvStsId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "rcv")
            $mInvRcvId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "pkd")
            $mInvPkdId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "plt")
            $mInvPltId = ($mRow['id']);
        elseif (strtolower($mRow['inventory_status_code']) == "qtine")
            $mInvQaId = ($mRow['id']);
    }
    if ($mInvPkdId == null && $mInvPltId != null)
        $mInvPkdId = $mInvPltId;
        
    $mDataQuery = "SELECT id AS id, location_code AS location_code FROM location WHERE location.location_hash='".$mToLocHash."' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;
    $mData = (mysqli_query($mConnection,$mDataQuery));
    if (mysqli_num_rows($mData) == 0)
        return "FAIL-Invalid Location Code.";
    $mRow = mysqli_fetch_assoc($mData);
    $mToLocId = ($mRow['id']);
    $mToLocCode = ($mRow['location_code']);
    
    $mDataQuery = "SELECT inventory_master.id AS id, part.part_number AS part_number, inventory_master.serial_reference AS serial_reference, inventory_master.ran_or_order AS ran_order, inventory_master.inventory_qty AS inventory_qty, tag.tag_reference AS plt_number, location.location_code AS location_code FROM inventory_master JOIN part ON inventory_master.part_id=part.id LEFT JOIN location ON inventory_master.current_location_id=location.id LEFT JOIN inventory_status ON inventory_master.current_inventory_status_id=inventory_status.id LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE part.part_number='".$mPartNumber."' AND inventory_master.serial_reference='".$mSerialReference."' AND inventory_qty>0 LIMIT 1";  
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;
    $mData = (mysqli_query($mConnection,$mDataQuery));
    if (mysqli_num_rows($mData) == 0)
        return "FAIL-No inventory exists for this serial reference.";
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mInvId = ($mRow['id']);
        $mTranQuery = "INSERT INTO transaction_history (id,short_code,part_number,serial_reference,ran_or_order,txn_qty,source_tag,from_location_code,to_location_code,date_created,last_updated,last_updated_by,transaction_reference_code) VALUES(DEFAULT,'FQA','".($mRow['part_number'])."','".($mRow['serial_reference'])."','".($mRow['ran_order'])."',".($mRow['inventory_qty']).",'".($mRow['plt_number'])."','".($mRow['location_code'])."','".$mToLocCode."',now(),now(),'".$mCurrentUser."','FQA')";
        if (!mysqli_query($mConnection,$mTranQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mTranQuery;  
    }
    
    $mDataQuery = "UPDATE inventory_master SET current_location_id=".$mToLocId.", inventory_status_id=".$mInvStsId.", requires_inspection=0, last_updated=now(),last_updated_by='".$mCurrentUser."' WHERE id=".$mInvId." LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;

    return("OKMS-locate Complete");
}

function postPts($mPltNumber,$mPartNumber,$mToLocHash,$mCurrentUser,$mDbHost=null,$mDbUser=null,$mDbPwd=null,$mDbName=null)
{
// mysql connection - Use Passed values...
    if (($mDbHost != null) && ($mDbHost != ""))
        $mConnection=mysqli_connect($mDbHost,$mDbUser,$mDbPwd,$mDbName) or
            exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// ... or get defaults from function defaultDbConnection
    else
        $mConnection =defaultDbConnection();
    
    $mDataQuery = "SELECT id AS id, location_code AS location_code FROM location WHERE location.location_hash='".$mToLocHash."' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;
    $mData = (mysqli_query($mConnection,$mDataQuery));
    if (mysqli_num_rows($mData) == 0)
        return "FAIL-Invalid Location Code.";
    $mRow = mysqli_fetch_assoc($mData);
    $mToLocId = ($mRow['id']);
    $mToLocCode = ($mRow['location_code']);
    
    $mDataQuery = "SELECT inventory_master.id AS id, part.part_number AS part_number, inventory_master.serial_reference AS serial_reference, inventory_master.ran_or_order AS ran_order, inventory_master.inventory_qty AS inventory_qty, tag.tag_reference AS plt_number, location.location_code AS location_code FROM inventory_master JOIN part ON inventory_master.part_id=part.id LEFT JOIN location ON inventory_master.current_location_id=location.id LEFT JOIN inventory_status ON inventory_master.current_inventory_status_id=inventory_status.id LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE part.part_number='".$mPartNumber."' AND (tag.tag_reference='".$mPltNumber."' OR inventory_master.serial_reference = '".$mPltNumber."') AND inventory_qty>0";  
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;
    $mData = (mysqli_query($mConnection,$mDataQuery));
    if (mysqli_num_rows($mData) == 0)
        return "FAIL-No inventory exists for this pallet or serial reference.";
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mInvId = ($mRow['id']);
        $mTranQuery = "INSERT INTO transaction_history (id,short_code,part_number,serial_reference,ran_or_order,txn_qty,source_tag,from_location_code,to_location_code,date_created,last_updated,last_updated_by,transaction_reference_code) VALUES(DEFAULT,'PTS','".($mRow['part_number'])."','".($mRow['serial_reference'])."','".($mRow['ran_order'])."',".($mRow['inventory_qty']).",'".($mRow['plt_number'])."','".($mRow['location_code'])."','".$mToLocCode."',now(),now(),'".$mCurrentUser."','PTS')";  
        if (!mysqli_query($mConnection,$mTranQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mTranQuery;  
        
        $mTranQuery = "UPDATE inventory_master SET current_location_id=".$mToLocId.",last_updated=now(),last_updated_by='".$mCurrentUser."' WHERE id=".$mInvId." LIMIT 1";
        if (!mysqli_query($mConnection,$mTranQuery))
            return "FAIL-".mysqli_error($mConnection).$mTranQuery;
    }
    return("OKMS-locate Complete");
}

function processTtm($mFromLocId,$mToLocId,$mFromLocCode,$mToLocCode,$mCurrentUser,$mDbHost=null,$mDbUser=null,$mDbPwd=null,$mDbName=null)
{
// mysql connection - Use Passed values...
    if (($mDbHost != null) && ($mDbHost != ""))
        $mConnection=mysqli_connect($mDbHost,$mDbUser,$mDbPwd,$mDbName) or
            exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// ... or get defaults from function defaultDbConnection
    else
        $mConnection =defaultDbConnection();
    
    $mDataQuery = "SELECT inventory_master.id AS id,part.part_number AS part_number, inventory_master.serial_reference AS serial_reference, inventory_master.ran_or_order AS ran_order, inventory_master.inventory_qty AS inventory_qty,inventory_master.picked_qty AS picked_qty, tag.tag_reference AS plt_number FROM inventory_master JOIN part ON inventory_master.part_id=part.id LEFT JOIN inventory_status ON inventory_master.current_inventory_status_id=inventory_status.id LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE location_id=".$mFromLocId;  
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;
    $mData = (mysqli_query($mConnection,$mDataQuery));
    if (mysqli_num_rows($mData) == 0)
        return "FAIL-No Parts to Relocate from ".$mFromLocCode;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        if ($mRow['picked_qty']>=$mRow['inventory_qty'])
        {
            try
            {

               $mTranQuery = "DELETE FROM inventory_master WHERE id>0 AND id=".$mRow['id']." LIMIT 1"; 
               if (!mysqli_query($mConnection,$mTranQuery))
                    return "FAIL-".mysqli_error($mConnection)."-".$mTranQuery;
            }
            catch(Exception $e)
            {
                $mTranQuery = "UPDATE inventory_master SET inventory_qty=0, allocated_qty=0 WHERE id = ".$mRow['id']." LIMIT 1";
                if (!mysqli_query($mConnection,$mTranQuery))
                    return "FAIL-".mysqli_error($mConnection)."-".$mTranQuery;
            }
            $mTranQuery = "INSERT INTO transaction_history (id,short_code,transaction_reference_code,part_number,serial_reference,ran_or_order,txn_qty,from_plt,from_location_code,to_location_code,created_by,date_created,last_updated,last_updated_by) VALUES(DEFAULT,'TTM','TTM','".($mRow['part_number'])."','".($mRow['serial_reference'])."','".($mRow['ran_order'])."',".($mRow['inventory_qty']).",'".($mRow['plt_number'])."','".$mFromLocCode."','".$mToLocCode."','".$mCurrentUser."',now(),now(),'".$mCurrentUser."')";    
            if (!mysqli_query($mConnection,$mTranQuery))
                return "FAIL-".mysqli_error($mConnection)."-".$mTranQuery;
        }
        else
        {
            $mTranQuery = "UPDATE inventory_master SET location_id=".$mToLocId.",current_location_id=".$mToLocId.",location_code='$mToLocCode',inventory_qty=inventory_qty-picked_qty,picked_qty=0,parent_tag_id=null,last_updated=now(),last_updated_by='".$mCurrentUser."' WHERE location_id=".$mFromLocId." AND (current_inventory_status_id IS null OR EXISTS(SELECT id FROM inventory_status WHERE inventory_master.current_inventory_status_id=inventory_status.id AND lower(inventory_status.inventory_status_code) <> 'pkd'))";
            if (!mysqli_query($mConnection,$mTranQuery))
                return "FAIL-".mysqli_error($mConnection)."-".$mTranQuery;
            $mTranQuery = "INSERT INTO transaction_history (id,short_code,transaction_reference_code,part_number,serial_reference,ran_or_order,txn_qty,from_plt,from_location_code,to_location_code,created_by,date_created,last_updated,last_updated_by) VALUES(DEFAULT,'TTM','TTM','".($mRow['part_number'])."','".($mRow['serial_reference'])."','".($mRow['ran_order'])."',".($mRow['inventory_qty']-$mRow['picked_qty']).",'".($mRow['plt_number'])."','".$mFromLocCode."','".$mToLocCode."','".$mCurrentUser."',now(),now(),'".$mCurrentUser."')";    
            if (!mysqli_query($mConnection,$mTranQuery))
                return "FAIL-".mysqli_error($mConnection)."-".$mTranQuery;
        }
    }

    return("OKMS-Relocate Complete");
}
/*
function processLocToLoc($mFromLocId,$mToLocId,$mFromLocCode,$mToLocCode,$mCurrentUser,$mDbHost=null,$mDbUser=null,$mDbPwd=null,$mDbName=null)
{
// mysql connection - Use Passed values...
    if (($mDbHost != null) && ($mDbHost != ""))
        $mConnection=mysqli_connect($mDbHost,$mDbUser,$mDbPwd,$mDbName) or
            exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// ... or get defaults from function defaultDbConnection
    else
        $mConnection =defaultDbConnection();
    
    $mDataQuery = "SELECT part.part_number AS part_number, inventory_master.serial_reference AS serial_reference, inventory_master.ran_or_order AS ran_order, inventory_master.inventory_qty AS inventory_qty,inventory_master.picked_qty AS picked_qty, tag.tag_reference AS plt_number FROM inventory_master JOIN part ON inventory_master.part_id=part.id LEFT JOIN inventory_status ON inventory_master.current_inventory_status_id=inventory_status.id LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE location_id=".$mFromLocId." AND (inventory_master.current_inventory_status_id IS null OR lower(inventory_status.status_code) <> 'pkd')";  
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;
    $mData = (mysqli_query($mConnection,$mDataQuery));
    if (mysqli_num_rows($mData) == 0)
        return "FAIL-No Parts to Relocate from ".$mFromLocCode;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mTranQuery = "INSERT INTO transaction_history (id,short_code,part_number,serial_reference,ran_or_order,txn_qty,from_plt,from_location_code,to_location_code,created_by,date_created,last_updated,last_updated_by) VALUES(DEFAULT,'LTL','".($mRow['part_number'])."','".($mRow['serial_reference'])."','".($mRow['ran_order'])."',".($mRow['inventory_qty']).",'".($mRow['plt_number'])."','".$mFromLocCode."','".$mToLocCode."','".$mCurrentUser."',now(),now(),'".$mCurrentUser."')"; 
        if (!mysqli_query($mConnection,$mTranQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mTranQuery;  
    }
    $mDataQuery = "UPDATE inventory_master SET location_id=".$mToLocId.",parent_tag_id=null,last_updated=now(),last_updated_by='".$mCurrentUser."' WHERE location_id=".$mFromLocId." AND (current_inventory_status_id IS null OR EXISTS(SELECT id FROM inventory_status WHERE inventory_master.current_inventory_status_id=inventory_status.id AND lower(inventory_status.status_code) <> 'pkd'))";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;

    return("OKMS-Relocate Complete");
}
*/
/*
function processLocToPlt($mFromLocId,$mToPlt,$mFromLocCode,$mCurrentUser,$mDbHost=null,$mDbUser=null,$mDbPwd=null,$mDbName=null)
{
// mysql connection - Use Passed values...
    if (($mDbHost != null) && ($mDbHost != ""))
        $mConnection=mysqli_connect($mDbHost,$mDbUser,$mDbPwd,$mDbName) or
            exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// ... or get defaults from function defaultDbConnection
    else
        $mConnection =defaultDbConnection();
    
//  $mDataQuery = "SELECT part.part_number AS part_number, inventory_master.serial_reference AS serial_reference, inventory_master.ran_order AS ran_order, inventory_master.inventory_qty AS inventory_qty, inventory_master.plt_number AS plt_number FROM inventory_master JOIN part ON inventory_master.part_id=part.id WHERE location_id=".$mFromLocId;  
    $mDataQuery = "SELECT part.part_number AS part_number, inventory_master.serial_reference AS serial_reference, inventory_master.ran_or_order AS ran_order, inventory_master.inventory_qty AS inventory_qty, tag.tag_reference AS plt_number FROM inventory_master JOIN part ON inventory_master.part_id=part.id LEFT JOIN inventory_status ON inventory_master.current_inventory_status_id=inventory_status.id LEFT JOIN tag ON inventory_master.parent_tag_id=tag.id WHERE location_id=".$mFromLocId." AND (inventory_master.current_inventory_status_id IS null OR lower(inventory_status.status_code) <> 'pkd')";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;
    $mData = (mysqli_query($mConnection,$mDataQuery));
    if (mysqli_num_rows($mData) == 0)
        return "FAIL-No Parts to Relocate for ".$mFromLocId;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
        $mTranQuery = "INSERT INTO transaction_history (id,short_code,part_number,serial_reference,ran_or_order,txn_qty,from_plt,from_location_code,to_plt,created_by,date_created,last_updated,last_updated_by) VALUES(DEFAULT,'LTL','".($mRow['part_number'])."','".($mRow['serial_reference'])."','".($mRow['ran_order'])."',".($mRow['inventory_qty']).",'".($mRow['plt_number'])."','".$mFromLocCode."','".$mToPlt."','".$mCurrentUser."',now(),now(),'".$mCurrentUser."')";   
        if (!mysqli_query($mConnection,$mTranQuery))
            return "FAIL-".mysqli_error($mConnection)."-".$mTranQuery;  
    }
    $mTagId=null;
    $mDataQuery = "SELECT tag.id AS id FROM tag WHERE tag.tag_reference='".$mToPlt."' LIMIT 1";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;
    $mData = (mysqli_query($mConnection,$mDataQuery));
    if (mysqli_num_rows($mData) == 0)
        return "FAIL-Invalid Tag - ".$mTpPlt;
    $mRow = mysqli_fetch_assoc($mData)) 
    $mTagId = ($mRow['id']);
    $mDataQuery = "UPDATE inventory_master SET parent_tag_id=".$mTagId.",last_updated=now(),last_updated_by='".$mCurrentUser."' WHERE location_id=".$mFromLocId." AND (inventory_master.current_inventory_status_id IS null OR EXISTS(SELECT id FROM inventory_status WHERE inventory_master.inventory_status_id=inventory_status.id AND lower(inventory_status.status_code) NOT IN('pkd','plt'))";
    if (!mysqli_query($mConnection,$mDataQuery))
        return "FAIL-".mysqli_error($mConnection).$mDataQuery;

    return("OKMS-Relocate Complete");
}
*/
// Return Default mySql Connection
function defaultDbConnection()
{
// get default System Settings from xml file    
    $mSystem = "DEFAULT";
// Get System Definition XML from URL
    $mData = file_get_contents("../../vimsconfig/systemsettings.xml");
// Parse XML to XML Object Array
    $xml = simplexml_load_string($mData, 'SimpleXMLElement', LIBXML_NOCDATA);
// Split-out System Definitions from XML 'fields' Nodes
    $i = 0;

    for ($i = 0; $i <= 150; $i++) 
    {           
        $mSystemId = "";
        $mPath = "";
        $mDbHost = "";
        $mDbUser = "";
        $mDbPwd = "";
        $mDbase = "";
        $mMqServer = "";
        $mCompany = "";
        if (("".$xml->systems->system[$i]->systemid."" == "") || ("".$xml->systems->system[$i]->systemid."" == false) || ("".$xml->systems->system[$i]->systemid."" == false))
            break;
        
        $mSystemId = "".$xml->systems->system[$i]->systemid."";
        if (($mSystemId == "") || ($mSystemId == false))
            break;
        
// Store System Settings from "trandef/systemsettings.xml"      
        if (strToUpper($mSystem) == strToUpper($mSystemId))
        {
            $mPath = "".$xml->systems->system[$i]->path."";
            $mDbHost = "".$xml->systems->system[$i]->dbhost."";
            $mDbUser = "".$xml->systems->system[$i]->dbuser."";
            $mDbPwd = "".$xml->systems->system[$i]->dbpwd."";
            $mDbase = "".$xml->systems->system[$i]->dbase."";
            break;
        }
        if (($mSystemId == "") || ($mSystemId == false))
            break;
    }

    $mConnection = mysqli_connect($mDbHost,$mDbUser,$mDbPwd,$mDbase)or die("FAIL-Failed to connect to Database: " . mysqli_connect_error().":".$mSystem);
    return $mConnection;
}

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

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

if (strpos($mFilter,"getnextlocation"))
{
    $mPartNumber = "";
// 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 == "function")
            $mFunction = $v2;
        elseif ($k2 == "partnumber")
            $mPartNumber = $v2;
    }   
    echo getNextLocation($mPartNumber);
}
?>