<?php

// CALL BY CRON: 
// php soap.php acapella7890 1 0    # HHA, State data
// php soap.php acapella7890 1 1    # HHA, Master data


include_once ("../include/mcglobal.inc.php");
include_once ("../include/inc_parseXML.inc.php");
include_once ("../illt/inc_serviceunit.inc.php");
include_once ("../include/inc_stock.inc.php");

ini_set('soap.wsdl_cache_enabled', '0');
ini_set('soap.wsdl_cache_ttl', '0'); 
ini_set('memory_limit', '512M');

// Execution-Time for script
set_time_limit(600);


// Write response log
function ptNovaLogFile ($msg, $logLevel = 0) {
  XMLRequestLogFile($msg, $logLevel, $logFile = "pt_nova.log");
}


function convert($size) {
    $unit=array('b','kb','mb','gb','tb','pb');
    return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
}


// Check filters of service units (e.g. range of serial numbers) deciding the data will be imported
function checkFilterForImport ($f_serial_no, $f_vu, $f_at_match) {
	$retBool = true;
  if ($f_vu != "HHA" && $f_vu != "HDAG") :
     $retBool = false;
  endif;
  if ($retBool && ($f_at_match != "H+W" && $f_at_match != "HUW" && $f_at_match != "H&W" && $f_at_match != "H&WB" && $f_at_match != "HWB" && $f_at_match != "STU" && $f_at_match != "STH" && $f_at_match != "STB" && $f_at_match != "CAGU" && $f_at_match != "STVS")) :
     $retBool = false;
  endif;  
  if ($retBool && $f_serial_no != "" && ($f_serial_no >= "100" && $f_serial_no <= "220")) :
     // $retBool = false;
  endif;  
  return $retBool;
}


// OrgunhdIdPrK  DevtyhdIdK  Bemerkung
// HDAG          HUW         Hadag Fahrscheinautomaten
// HHA           H&W         HOCHBAHN
// HHA           H&WB        HOCHBAHN
// HHA           HWB         HOCHBAHN
// HHA           STU         HOCHBAHN :: Selfservice-Terminal
// HHA           STH         HOCHBAHN :: Selfservice-Terminal
// HHA           STB         HOCHBAHN :: Selfservice-Terminal
// HHA           CAGU        HOCHBAHN :: Cash Recycler
// HHA           STVS        HOCHBAHN :: Cashless Terminal
function generateRequestPTnova ($timestamp, $mode = "0") {
  $request = "";

  if ($timestamp != "") :

     if ($mode == "0") :

        // STATE DATA
        /*    SOAP 1.1
        $request = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:urn="urn:sap-com:document:sap:soap:functions:mc-style">
                       <soap:Header/>
                       <soap:Body>
                          <urn:ZRstTestStatusdataWs01>
                             <ItDevicetype>
                                <!--Zero or more repetitions:-->
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>HUW</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>H&amp;W</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>H&amp;WB</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>HWB</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>STU</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>STH</DevtyhdIdK>
                                </item>
                             </ItDevicetype>
                             <IvActualFg>X</IvActualFg>
                             <IvTimestamp>' . $timestamp . '</IvTimestamp>
                          </urn:ZRstTestStatusdataWs01>
                       </soap:Body>
                    </soap:Envelope>';
        */
        $request = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:sap-com:document:sap:soap:functions:mc-style">
                       <soapenv:Header/>
                       <soapenv:Body>
                          <urn:ZPtnWstpStatusdata>
                             <ItDevicetype>
                                <!--Zero or more repetitions:-->
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>HUW</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>H&amp;W</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>H&amp;WB</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>HWB</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>STU</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>STH</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>STB</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>CAGU</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>STVS</DevtyhdIdK>
                                </item>
                             </ItDevicetype>
                             <IvActualFg>X</IvActualFg>
                             <IvTimestamp>' . $timestamp . '</IvTimestamp>
                          </urn:ZPtnWstpStatusdata>
                       </soapenv:Body>
                    </soapenv:Envelope>';

     elseif ($mode == "1") :

        // MASTER DATA
        /*    SOAP 1.1
        $request = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:urn="urn:sap-com:document:sap:soap:functions:mc-style">
                       <soap:Header/>
                       <soap:Body>
                          <urn:ZRstTestMasterdataWs01>
                             <ItDevicetype>
                                <!--Zero or more repetitions:-->
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>HUW</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>H&amp;W</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>H&amp;WB</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>HWB</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>STU</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>STH</DevtyhdIdK>
                                </item>
                             </ItDevicetype>
                             <IvTimestamp>' . $timestamp . '</IvTimestamp>
                          </urn:ZRstTestMasterdataWs01>
                       </soap:Body>
                    </soap:Envelope>';
        */
        $request = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:sap-com:document:sap:soap:functions:mc-style">
                       <soapenv:Header/>
                       <soapenv:Body>
                          <urn:ZPtnWstpMasterdata>
                             <ItDevicetype>
                                <!--Zero or more repetitions:-->
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>HUW</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>H&amp;W</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>H&amp;WB</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>HWB</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>STU</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>STH</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>STB</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>CAGU</DevtyhdIdK>
                                </item>
                                <item>
                                   <OrgunhdIdPrK>HHA</OrgunhdIdPrK>
                                   <DevtyhdIdK>STVS</DevtyhdIdK>
                                </item>
                             </ItDevicetype>
                             <IvTimestamp>' . $timestamp . '</IvTimestamp>
                          </urn:ZPtnWstpMasterdata>
                       </soapenv:Body>
                    </soapenv:Envelope>';
     endif;
  endif;

  return $request;
}


// Sends SOAP request by CURL
function sendCurlSoapRequestPTnova ($timestamp, $mode = "0") {
  global $debug, $httpStatus;

  $response = "";
  // $soapUrl = "https://HHASAP007SPS.hhasap.local:44300/sap/bc/srt/rfc/sap/zptn_ws_tourenplanung/100/zptnwstourenplanung/zptnwstourenplanungbnd";  // 128.8.106.109
  // $soapUrl = "https://HHASAP012vm.hhasap.local:44300/sap/bc/srt/rfc/sap/zptn_ws_tourenplanung/100/zptnwstourenplanung/zptnwstourenplanungbnd";
  // $soapUrl = "https://hhasap4033.quovadiscorp.de:44300/sap/bc/srt/rfc/sap/zptn_ws_tourenplanung/100/zptnwstourenplanung/zptnwstourenplanungbnd";  // 10.192.22.68
  // $soapUrl = "https://hhasap6009.quovadiscorp.de:8805/sap/bc/srt/rfc/sap/zptn_ws_tourenplanung/100/zptnwstourenplanung/zptnwstourenplanungbnd";  // 10.192.66.124
  $soapUrl = "https://hhasap0009.corp.hochbahn.de:8806/sap/bc/srt/rfc/sap/zptn_ws_tourenplanung/100/zptnwstourenplanung/zptnwstourenplanungbnd";  // 10.192.34.180
  if ($debug) :
     // echo $soapUrl . "<br><br>";
  endif;

  $soapUser = "ASSECUT_EXT";  //  username
  $soapPassword = "tUHRenplan"; // password

  $xml_post_string = generateRequestPTnova($timestamp, $mode);
  ptNovaLogFile("SYSTEM.REQUEST:");
  ptNovaLogFile($xml_post_string);

  if ($debug) :
     // echo $xml_post_string . "<br><br>";
  endif;

  if ($xml_post_string != "") :

     // "SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice", 
     if ($mode == "1") :
        $soapAction = "SOAPAction: urn:sap-com:document:sap:soap:functions:mc-style:ZPTN_WS_TOURENPLANUNG:ZPtnWstpMasterdataRequest";
     else :
        $soapAction = "SOAPAction: urn:sap-com:document:sap:soap:functions:mc-style:ZPTN_WS_TOURENPLANUNG:ZPtnWstpStatusdataRequest";
     endif;

     $headers = array(
                  "Content-type: text/xml;charset=\"utf-8\"",
                  "Accept: text/xml",
                  "Cache-Control: no-cache",
                  "Pragma: no-cache",
                  $soapAction,
                  "Content-length: " . strlen($xml_post_string),
              );

     // PHP cURL  for https connection with auth
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
     curl_setopt($ch, CURLOPT_URL, $soapUrl);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // Username and password - declared at the top of the doc
     curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
     curl_setopt($ch, CURLOPT_TIMEOUT, 300);
     curl_setopt($ch, CURLOPT_POST, true);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // The SOAP request
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
     if ($debug) :
        // curl_setopt($ch, CURLINFO_HEADER_OUT, true);
     endif;

     // converting
     $response = curl_exec($ch); 

     if ($debug) :
        // $info = $httpStatus = curl_getinfo($ch);
        // print_r($info); echo "<br><br>";
     endif;
     $errNo = curl_errno($ch);
     $errMsg = curl_error($ch);
     $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);     
     ptNovaLogFile("HTTP-STATUS: " . $httpStatus);
     ptNovaLogFile("CURL.ERR.NO: " . $errNo);
     ptNovaLogFile("CURL.ERR.MSG: " . $errMsg);

     // fclose($fh);
     curl_close($ch);

     return $response;
  endif;
}


// ***************************************************************************
// **** START ****************************************************************
// ***************************************************************************

$fire = true;  // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$debug = true;
$getResponseFromServer = true;
$getResponseFromFile = false;
$fileMasterData = "../temp/HHA_Request_20270710_MASTER.xml";
$fileStatusData = "../temp/HHA_Request_20270710_STATE.xml";

// Init
if (!isset($hq_id)) : $hq_id = ""; endif;
$errMsg = "";
$mode = "";
$response = "";
$httpStatus = "";
$wsdl = "https://HHASAP007SPS.hhasap.local:44300/sap/bc/srt/wsdl/flv_10002A111AD1/bndg_url/sap/bc/srt/rfc/sap/zptn_ws_tourenplanung/100/zptnwstourenplanung/zptnwstourenplanungbnd?sap-client=100";

if (!isset($argv[1]) || $argv[1] == "") :
   $isCron = false;
//   include_once ("../include/auth.inc.php");
   getSecHttpVars("1",array("code", "hq_id", "mode", "timestamp"));
   $execute = true;
//   $usrAccessArray["hq"] = "1"; $usrAccessArray["cs"] = "1";
//   authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
//   authCheckEmployeeRights($emp_id, "1", "1");
else :
   $isCron = true;
   if ($argv[1] == "acapella7890") : $execute = true; endif;
   if ($execute) :
      if (isset($argv[2]) && $argv[2] != "") : $hq_id = $argv[2]; endif;
      if (isset($argv[3]) && $argv[3] != "") : $mode = $argv[3]; endif;
      if (isset($argv[4]) && $argv[4] != "") : $timestamp = $argv[4]; endif;
   endif;
endif;

if (!$getResponseFromServer && !$getResponseFromFile) :
   $errMsg = "PT_NOVA call failed by deactivation of all response modes!";
endif;

if ($errMsg == "" && !$execute) :
   $errMsg = "PT_NOVA call failed by authentication!";
endif;

// Check for existimg headquarters
if ($errMsg == "" && ($hq_id == "" || !is_numeric($hq_id))) :
   $errMsg = "PT_NOVA call failed by missing headquarters!";
endif;

// Check for call for master data ["1"] or status data ["0"]
if ($errMsg == "" && ($mode != "0" && $mode != "1")) :
   $errMsg = "PT_NOVA call failed by missing or wrong argument for request mode!";
endif;

if ($errMsg != "") :
   ptNovaLogFile("SYSTEM.PROCESS.STATE: NOT_OK [" . $errMsg . "]");
   sendInternalMail($errMsg);
   die();   
endif;

// Define global parameters
defineGlobalParameters($hq_id);

$currentTime = getDateTime("0");       // 2003-03-10 17:16:17
$currentTimestamp = getDateTime("6");  // 20170711112233
$currentDate = getDateTime("1");       // 20170711

$usedFallbackTimestamp = false;
if (!isset($timestamp) || $timestamp == "") :
   // Init
   $fallbackTimestamp = getDateTime("date_plus_offset", array(0,-1,0), "YmdHis");
   // Check timestamp of the current day
   $gdcContentPtNova = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'hq' AND gdc_obj_id = '" . $hq_id . "' AND gdc_gen_fieldname = 'pt_nova' AND gdc_context = '" . $mode . "'");
   if ($gdcContentPtNova != "" && $gdcContentPtNova > $fallbackTimestamp) :
      // if (substr($gdcContentPtNova,0,8) == $currentDate) :
         $timestamp = $gdcContentPtNova;
      // endif;
   else :
      $timestamp = $fallbackTimestamp;
      $usedFallbackTimestamp = true;
   endif;
endif;
if ($debug) :
   ptNovaLogFile("=> DEBUG.MODE: START TIMESTAMP: " . $timestamp . " | FALLBACK USED: " . ($usedFallbackTimestamp ? "YES" : "NO"));
endif;

// Response by FILE
if ($getResponseFromFile) :
   $response = file_get_contents($fileMasterData);
   $response = urldecode($response);
   $response = str_replace("'", "", $response);
   $response = mcEncode($response);
   $response = str_replace("'", "", $response);
endif;

// Write request to log
ptNovaLogFile("SYSTEM.DATETIME.SCRIPT_EXEC_START: " . $currentTime);
ptNovaLogFile("SYSTEM.DATETIME.REQUEST_FROM: " . $timestamp);
ptNovaLogFile("SYSTEM.CALLMODE: " . ($mode == "1" ? "MASTER DATA" : "STATE DATA"));

// Response by CURL
if ($getResponseFromServer) :   
   $response = sendCurlSoapRequestPTnova($timestamp, $mode);
endif;

// Write response to log
ptNovaLogFile("SYSTEM.RESPONSE:");
ptNovaLogFile($response);

$responseArr = xml2array($response);

if ($debug) :
   $memUsageTotal = convert(memory_get_usage(true));
   $memUsage = convert(memory_get_usage());
   // echo "<br><br><br><br>Speicherverbrauch: " . $memUsageTotal . " | "  . $memUsage;
   // echo "<br><br>" . memory_get_usage();
   ptNovaLogFile("DEBUG.MEMORY.USAGE: " . $memUsageTotal . " | "  . $memUsage);
   // print_r($responseArr); echo "<br><br><br>\n\n\n";
endif;


// MASTER DATA
if ($mode == "1") :

   if ($debug) :
      ptNovaLogFile("=> DEBUG.MODE: MASTER_DATA.PREPARE_ARRAY.START");
   endif;

   $masterDataArray = array();
   $deviceType = &$responseArr["soap-env:Envelope"]["soap-env:Body"]["n0:ZPtnWstpMasterdataResponse"]["EsMasterdata"]["Devicetypes"];
   $numOfDeviceType = count($deviceType);
   if ($numOfDeviceType > 0) :
      $hasMoreElements = false;
      $numOfDeviceTypeItems = 1;
      if ($deviceType["item"]["0"] != "") : 
         $hasMoreElements = true;
         $numOfDeviceTypeItems = count($deviceType["item"]);
      endif;
      for ($i = 0; $i < $numOfDeviceTypeItems; $i++) :
          if ($hasMoreElements) : 
             $deviceTypeItem = &$deviceType["item"][$i];
          else :
             $deviceTypeItem = &$deviceType["item"];
          endif;
   
          $masterDataArray[$i]["OrgunhdIdPr"]  = convertSpecial($deviceTypeItem["OrgunhdIdPr"]);
          $masterDataArray[$i]["DevtyhdId"]    = convertSpecial($deviceTypeItem["DevtyhdId"]);
          $masterDataArray[$i]["Description"]  = convertSpecial($deviceTypeItem["Description"]);
          $masterDataArray[$i]["DevmfhdId"]    = convertSpecial($deviceTypeItem["DevmfhdId"]);
          $masterDataArray[$i]["DevmflinId"]   = convertSpecial($deviceTypeItem["DevmflinId"]);
          $masterDataArray[$i]["TstmpCreated"] = convertSpecial($deviceTypeItem["TstmpCreated"]);
          $masterDataArray[$i]["TstmpChanged"] = convertSpecial($deviceTypeItem["TstmpChanged"]);
          $masterDataArray[$i]["ArchiveStat"]  = convertSpecial($deviceTypeItem["ArchiveStat"]);
          $masterDataArray[$i]["MdLcycleStat"] = convertSpecial($deviceTypeItem["MdLcycleStat"]);
   
          // Devices
          $hasMoreElements2 = false;
          $numOfDeviceTypeItemDeviceItems = 1;
          if ($deviceTypeItem["Devices"]["item"]["0"] != "") : 
             $hasMoreElements2 = true;
             $numOfDeviceTypeItemDeviceItems = count($deviceTypeItem["Devices"]["item"]);
          endif;
          for ($j = 0; $j < $numOfDeviceTypeItemDeviceItems; $j++) :
              if ($hasMoreElements2) : 
                 $deviceTypeItemDeviceItem = &$deviceTypeItem["Devices"]["item"][$j];
              else :
                 $deviceTypeItemDeviceItem = &$deviceTypeItem["Devices"]["item"];
              endif;
   
              // $masterDataArray[$i]["Devices"]["item"][$j]["DevichdId"]     = convertSpecial($deviceTypeItemDeviceItem["DevichdId"]);
              // ....
              // Wenn ["item"] entfernen nicht möglich, dann rückgängig, wie vorige Zeilen (!!!!)
              $masterDataArray[$i]["Devices"][$j]["DevichdId"]     = convertSpecial($deviceTypeItemDeviceItem["DevichdId"]);
              $masterDataArray[$i]["Devices"][$j]["OnlineState"]   = convertSpecial($deviceTypeItemDeviceItem["OnlineState"]);
              $masterDataArray[$i]["Devices"][$j]["NetelhdIdO"]    = convertSpecial($deviceTypeItemDeviceItem["NetelhdIdO"]);
              $masterDataArray[$i]["Devices"][$j]["YearConstruct"] = convertSpecial($deviceTypeItemDeviceItem["YearConstruct"]);
              $masterDataArray[$i]["Devices"][$j]["DevCondition"]  = convertSpecial($deviceTypeItemDeviceItem["DevCondition"]);
              $masterDataArray[$i]["Devices"][$j]["TechnicalId"]   = convertSpecial($deviceTypeItemDeviceItem["TechnicalId"]);
              $masterDataArray[$i]["Devices"][$j]["DevSerial"]     = convertSpecial($deviceTypeItemDeviceItem["DevSerial"]);
              $masterDataArray[$i]["Devices"][$j]["ProductiveFg"]  = convertSpecial($deviceTypeItemDeviceItem["ProductiveFg"]);
              $masterDataArray[$i]["Devices"][$j]["Description"]   = convertSpecial($deviceTypeItemDeviceItem["Description"]);
              $masterDataArray[$i]["Devices"][$j]["TstmpCreated"]  = convertSpecial($deviceTypeItemDeviceItem["TstmpCreated"]);
              $masterDataArray[$i]["Devices"][$j]["TstmpChanged"]  = convertSpecial($deviceTypeItemDeviceItem["TstmpChanged"]);
              $masterDataArray[$i]["Devices"][$j]["ArchiveStat"]   = convertSpecial($deviceTypeItemDeviceItem["ArchiveStat"]);
              $masterDataArray[$i]["Devices"][$j]["MdLcycleStat"]  = convertSpecial($deviceTypeItemDeviceItem["MdLcycleStat"]);
          endfor;
   
          // Softwarereleases
          $hasMoreElements2 = false;
          $numOfDeviceTypeItemSwrItems = 1;
          if ($deviceTypeItem["Swreleases"]["item"]["0"] != "") : 
             $hasMoreElements2 = true;
             $numOfDeviceTypeItemSwrItems = count($deviceTypeItem["Swreleases"]["item"]);
          endif;
          for ($j = 0; $j < $numOfDeviceTypeItemSwrItems; $j++) :
              if ($hasMoreElements2) : 
                 $deviceTypeItemSwrItem = &$deviceTypeItem["Swreleases"]["item"][$j];
              else :
                 $deviceTypeItemSwrItem = &$deviceTypeItem["Swreleases"]["item"];
              endif;
   
              // $masterDataArray[$i]["Swreleases"]["item"][$j]["DevsrhdId"]    = convertSpecial($deviceTypeItemSwrItem["DevsrhdId"]);
              // ....
              // Wenn ["item"] entfernen nicht möglich, dann rückgängig, wie vorige Zeilen (!!!!)
              $masterDataArray[$i]["Swreleases"][$j]["DevsrhdId"]    = convertSpecial($deviceTypeItemSwrItem["DevsrhdId"]);
              $masterDataArray[$i]["Swreleases"][$j]["Description"]  = convertSpecial($deviceTypeItemSwrItem["Description"]);
              $masterDataArray[$i]["Swreleases"][$j]["ReleaseTstmp"] = convertSpecial($deviceTypeItemSwrItem["ReleaseTstmp"]);
              $masterDataArray[$i]["Swreleases"][$j]["TstmpCreated"] = convertSpecial($deviceTypeItemSwrItem["TstmpCreated"]);
              $masterDataArray[$i]["Swreleases"][$j]["ActiveFg"]     = convertSpecial($deviceTypeItemSwrItem["ActiveFg"]);
              $masterDataArray[$i]["Swreleases"][$j]["ArchiveStat"]  = convertSpecial($deviceTypeItemSwrItem["ArchiveStat"]);
              $masterDataArray[$i]["Swreleases"][$j]["MdLcycleStat"] = convertSpecial($deviceTypeItemSwrItem["MdLcycleStat"]);
   
              // Messages
              $hasMoreElements3 = false;
              $numOfDeviceTypeItemSwrItemMsgItem = 1;
              if ($deviceTypeItemSwrItem["Messages"]["item"]["0"] != "") : 
                 $hasMoreElements3 = true;
                 $numOfDeviceTypeItemSwrItemMsgItem = count($deviceTypeItemSwrItem["Messages"]["item"]);
              endif;
              for ($k = 0; $k < $numOfDeviceTypeItemSwrItemMsgItem; $k++) :
                  if ($hasMoreElements3) : 
                     $deviceTypeItemSwrItemMsgItem = $deviceTypeItemSwrItem["Messages"]["item"][$k];
                  else :
                     $deviceTypeItemSwrItemMsgItem = $deviceTypeItemSwrItem["Messages"]["item"];
                  endif;
   
                  // $masterDataArray[$i]["Swreleases"]["item"][$j]["Messages"][$k]["DevsrmsgId"]   = convertSpecial($deviceTypeItemSwrItemMsgItem["DevsrmsgId"]);
                  // ....
                  // Wenn ["item"] entfernen nicht möglich, dann rückgängig, wie vorige Zeilen (!!!!)
                  $masterDataArray[$i]["Swreleases"][$j]["Messages"][$k]["DevsrmsgId"]   = convertSpecial($deviceTypeItemSwrItemMsgItem["DevsrmsgId"]);
                  $masterDataArray[$i]["Swreleases"][$j]["Messages"][$k]["Description"]  = convertSpecial($deviceTypeItemSwrItemMsgItem["Description"]);
                  $masterDataArray[$i]["Swreleases"][$j]["Messages"][$k]["Msgtext"]      = convertSpecial($deviceTypeItemSwrItemMsgItem["Msgtext"]);
                  $masterDataArray[$i]["Swreleases"][$j]["Messages"][$k]["Msgparam"]     = convertSpecial($deviceTypeItemSwrItemMsgItem["Msgparam"]);
                  $masterDataArray[$i]["Swreleases"][$j]["Messages"][$k]["SeverityCode"] = convertSpecial($deviceTypeItemSwrItemMsgItem["SeverityCode"]);
                  $masterDataArray[$i]["Swreleases"][$j]["Messages"][$k]["NodeDate"]     = convertSpecial($deviceTypeItemSwrItemMsgItem["NodeDate"]);
              endfor;
          endfor;
      endfor;
   endif;

   if ($debug) :
      // echo "<br><br>\n\nMASTER-DATA-ARRAY<br><br>\n\n";
      // print_r($masterDataArray);
      // echo "<br><br><br>\n\n\n";
      ptNovaLogFile("=> DEBUG.MODE: MASTER_DATA.PREPARE_ARRAY.END");
   endif;
endif;


if ($getResponseFromFile) :
   $response2 = file_get_contents($fileStatusData);
   $response2 = urldecode($response2);
   $response2 = str_replace("'", "", $response2);
   $response2 = mcEncode($response2);
   $response = str_replace("'", "", $response2);
   if ($debug) :
      // echo $response2 . "<br><br><br>\n\n\n";
   endif;
   $responseArr = xml2array($response2);
   if ($debug) :
      // print_r($responseArr); echo "<br><br><br>\n\n\n";
   endif;
endif;

// STATUS DATA
if ($mode == "0") :

   if ($debug) :
      ptNovaLogFile("=> DEBUG.MODE: MASTER_DATA.PREPARE_ARRAY.START");
   endif;

   $statusDataArray = array();
   $statusData = &$responseArr["soap-env:Envelope"]["soap-env:Body"]["n0:ZPtnWstpStatusdataResponse"]["EsStatusdata"]["Statusdata"];
   $numOfStatusData = count($statusData);
   if ($numOfStatusData > 0) :
      $hasMoreElements = false;
      $numOfStatusDataItems = 1;
      if ($statusData["item"]["0"] != "") : 
         $hasMoreElements = true;
         $numOfStatusDataItems = count($statusData["item"]);
      endif;
      for ($i = 0; $i < $numOfStatusDataItems; $i++) :
          if ($hasMoreElements) : 
             $statusDataItem = $statusData["item"][$i];
          else :
             $statusDataItem = $statusData["item"];
          endif;
   
          $statusDataArray[$i]["DevsthdNo"]    = convertSpecial($statusDataItem["DevsthdNo"]);
          $statusDataArray[$i]["OrgunhdIdPr"]  = convertSpecial($statusDataItem["OrgunhdIdPr"]);
          $statusDataArray[$i]["DevtyhdId"]    = convertSpecial($statusDataItem["DevtyhdId"]);
          $statusDataArray[$i]["DevichdId"]    = convertSpecial($statusDataItem["DevichdId"]);
          $statusDataArray[$i]["TstmpDevsthd"] = convertSpecial($statusDataItem["TstmpDevsthd"]);
          $statusDataArray[$i]["SevCodeHd"]    = convertSpecial($statusDataItem["SevCodeHd"]);
          $statusDataArray[$i]["SevCodeOpn"]   = convertSpecial($statusDataItem["SevCodeOpn"]);
          $statusDataArray[$i]["IsActual"]     = convertSpecial($statusDataItem["IsActual"]);
          $statusDataArray[$i]["IsInService"]  = convertSpecial($statusDataItem["IsInService"]);
          $statusDataArray[$i]["IsMnyVltd"]    = convertSpecial($statusDataItem["IsMnyVltd"]);
          $statusDataArray[$i]["IsMatVltd"]    = convertSpecial($statusDataItem["IsMatVltd"]);
          $statusDataArray[$i]["NoOpnFg"]      = convertSpecial($statusDataItem["NoOpnFg"]);
   
          // Devstopn
          $hasMoreElements2 = false;
          $numOfStatusDataItemSubItems = 1;
          if ($statusDataItem["Devstopn"]["item"]["0"] != "") : 
             $hasMoreElements2 = true;
             $numOfStatusDataItemSubItems = count($statusDataItem["Devstopn"]["item"]);
          endif;
          for ($j = 0; $j < $numOfStatusDataItemSubItems; $j++) :
              if ($hasMoreElements2) : 
                 $statusDataItemDeviceItem = &$statusDataItem["Devstopn"]["item"][$j];
              else :
                 $statusDataItemDeviceItem = &$statusDataItem["Devstopn"]["item"];
              endif;
   
              // $statusDataArray[$i]["Devstopn"]["item"][$j]["DevichdId"]     = convertSpecial($statusDataItemDeviceItem["DevichdId"]);
              // ....
              // Wenn ["item"] entfernen nicht möglich, dann rückgängig, wie vorige Zeilen (!!!!)
              $statusDataArray[$i]["Devstopn"][$j]["DevsthdNo"]    = convertSpecial($statusDataItemDeviceItem["DevsthdNo"]);
              $statusDataArray[$i]["Devstopn"][$j]["DevstopnNo"]   = convertSpecial($statusDataItemDeviceItem["DevstopnNo"]);
              $statusDataArray[$i]["Devstopn"][$j]["DevsrhdId"]    = convertSpecial($statusDataItemDeviceItem["DevsrhdId"]);
              $statusDataArray[$i]["Devstopn"][$j]["DevsrmsgId"]   = convertSpecial($statusDataItemDeviceItem["DevsrmsgId"]);
              $statusDataArray[$i]["Devstopn"][$j]["DevCatMf"]     = convertSpecial($statusDataItemDeviceItem["DevCatMf"]);
              $statusDataArray[$i]["Devstopn"][$j]["DevCmpMf"]     = convertSpecial($statusDataItemDeviceItem["DevCmpMf"]);
              $statusDataArray[$i]["Devstopn"][$j]["DevCmpinsMf"]  = convertSpecial($statusDataItemDeviceItem["DevCmpinsMf"]);
              $statusDataArray[$i]["Devstopn"][$j]["OpNotifApdx"]  = convertSpecial($statusDataItemDeviceItem["OpNotifApdx"]);
              $statusDataArray[$i]["Devstopn"][$j]["OpNotifText"]  = convertSpecial($statusDataItemDeviceItem["OpNotifText"]);
              $statusDataArray[$i]["Devstopn"][$j]["TstmpProcss"]  = convertSpecial($statusDataItemDeviceItem["TstmpProcss"]);
              $statusDataArray[$i]["Devstopn"][$j]["DoorState"]    = convertSpecial($statusDataItemDeviceItem["DoorState"]);
              $statusDataArray[$i]["Devstopn"][$j]["TstmpIncdt"]   = convertSpecial($statusDataItemDeviceItem["TstmpIncdt"]);
              $statusDataArray[$i]["Devstopn"][$j]["TstmpFinishd"] = convertSpecial($statusDataItemDeviceItem["TstmpFinishd"]);
              $statusDataArray[$i]["Devstopn"][$j]["SevCodeOpn"]   = convertSpecial($statusDataItemDeviceItem["SevCodeOpn"]);
          endfor;
   
          // Devstmny
          $hasMoreElements2 = false;
          $numOfStatusDataItemSubItems = 1;
          if ($statusDataItem["Devstmny"]["item"]["0"] != "") : 
             $hasMoreElements2 = true;
             $numOfStatusDataItemSubItems = count($statusDataItem["Devstmny"]["item"]);
          endif;
          for ($j = 0; $j < $numOfStatusDataItemSubItems; $j++) :
              if ($hasMoreElements2) : 
                 $statusDataItemSwrItem = &$statusDataItem["Devstmny"]["item"][$j];
              else :
                 $statusDataItemSwrItem = &$statusDataItem["Devstmny"]["item"];
              endif;
   
              // $statusDataArray[$i]["Devstmny"]["item"][$j]["DevsrhdId"]    = convertSpecial($statusDataItemSwrItem["DevsrhdId"]);
              // ....
              // Wenn ["item"] entfernen nicht möglich, dann rückgängig, wie vorige Zeilen (!!!!)
              $statusDataArray[$i]["Devstmny"][$j]["DevsthdNo"]    = convertSpecial($statusDataItemSwrItem["DevsthdNo"]);
              $statusDataArray[$i]["Devstmny"][$j]["DevstmnyNo"]   = convertSpecial($statusDataItemSwrItem["DevstmnyNo"]);
              $statusDataArray[$i]["Devstmny"][$j]["CashboxType"]  = convertSpecial($statusDataItemSwrItem["CashboxType"]);
              $statusDataArray[$i]["Devstmny"][$j]["CashboxNo"]    = convertSpecial($statusDataItemSwrItem["CashboxNo"]);
              $statusDataArray[$i]["Devstmny"][$j]["CbxSerialNo"]  = convertSpecial($statusDataItemSwrItem["CbxSerialNo"]);
              $statusDataArray[$i]["Devstmny"][$j]["PositionDesc"] = convertSpecial($statusDataItemSwrItem["PositionDesc"]);
              $statusDataArray[$i]["Devstmny"][$j]["Currency"]     = convertSpecial($statusDataItemSwrItem["Currency"]);
              $statusDataArray[$i]["Devstmny"][$j]["FaceValue"]    = convertSpecial($statusDataItemSwrItem["FaceValue"]);
              $statusDataArray[$i]["Devstmny"][$j]["NominalQnty"]  = convertSpecial($statusDataItemSwrItem["NominalQnty"]);
              $statusDataArray[$i]["Devstmny"][$j]["NominalAmnt"]  = convertSpecial($statusDataItemSwrItem["NominalAmnt"]);
              $statusDataArray[$i]["Devstmny"][$j]["NominalCapct"] = convertSpecial($statusDataItemSwrItem["NominalCapct"]);
              $statusDataArray[$i]["Devstmny"][$j]["Threshold"]    = convertSpecial($statusDataItemSwrItem["Threshold"]);
              $statusDataArray[$i]["Devstmny"][$j]["Measurand"]    = convertSpecial($statusDataItemSwrItem["Measurand"]);
              $statusDataArray[$i]["Devstmny"][$j]["Direction"]    = convertSpecial($statusDataItemSwrItem["Direction"]);
              $statusDataArray[$i]["Devstmny"][$j]["TstmpMeasure"] = convertSpecial($statusDataItemSwrItem["TstmpMeasure"]);
              $statusDataArray[$i]["Devstmny"][$j]["IsViolated"]   = convertSpecial($statusDataItemSwrItem["IsViolated"]);
          endfor;
   
          // Devstmat
          $hasMoreElements2 = false;
          $numOfStatusDataItemSubItems = 1;
          if ($statusDataItem["Devstmat"]["item"]["0"] != "") : 
             $hasMoreElements2 = true;
             $numOfStatusDataItemSubItems = count($statusDataItem["Devstmat"]["item"]);
          endif;
          for ($j = 0; $j < $numOfStatusDataItemSubItems; $j++) :
              if ($hasMoreElements2) : 
                 $statusDataItemSwrItem = &$statusDataItem["Devstmat"]["item"][$j];
              else :
                 $statusDataItemSwrItem = &$statusDataItem["Devstmat"]["item"];
              endif;
   
              // $statusDataArray[$i]["Devstmat"]["item"][$j]["DevsrhdId"]    = convertSpecial($statusDataItemSwrItem["DevsrhdId"]);
              // ....
              // Wenn ["item"] entfernen nicht möglich, dann rückgängig, wie vorige Zeilen (!!!!)
              $statusDataArray[$i]["Devstmat"][$j]["DevsthdNo"]    = convertSpecial($statusDataItemSwrItem["DevsthdNo"]);
              $statusDataArray[$i]["Devstmat"][$j]["DevstmatNo"]   = convertSpecial($statusDataItemSwrItem["DevstmatNo"]);
              $statusDataArray[$i]["Devstmat"][$j]["MatHopperId"]  = convertSpecial($statusDataItemSwrItem["MatHopperId"]);
              $statusDataArray[$i]["Devstmat"][$j]["MaterialId"]   = convertSpecial($statusDataItemSwrItem["MaterialId"]);
              $statusDataArray[$i]["Devstmat"][$j]["NominalStock"] = convertSpecial($statusDataItemSwrItem["NominalStock"]);
              $statusDataArray[$i]["Devstmat"][$j]["MatUnitExt"]   = convertSpecial($statusDataItemSwrItem["MatUnitExt"]);
              $statusDataArray[$i]["Devstmat"][$j]["MatUnit"]      = convertSpecial($statusDataItemSwrItem["MatUnit"]);
              $statusDataArray[$i]["Devstmat"][$j]["MeasureMeth"]  = convertSpecial($statusDataItemSwrItem["MeasureMeth"]);
              $statusDataArray[$i]["Devstmat"][$j]["Threshold"]    = convertSpecial($statusDataItemSwrItem["Threshold"]);
              $statusDataArray[$i]["Devstmat"][$j]["TstmpMeasure"] = convertSpecial($statusDataItemSwrItem["TstmpMeasure"]);
              $statusDataArray[$i]["Devstmat"][$j]["IsViolated"]   = convertSpecial($statusDataItemSwrItem["IsViolated"]);
          endfor;
   
          // Devstswr
          $hasMoreElements2 = false;
          $numOfStatusDataItemSubItems = 1;
          if ($statusDataItem["Devstswr"]["item"]["0"] != "") : 
             $hasMoreElements2 = true;
             $numOfStatusDataItemSubItems = count($statusDataItem["Devstswr"]["item"]);
          endif;
          for ($j = 0; $j < $numOfStatusDataItemSubItems; $j++) :
              if ($hasMoreElements2) : 
                 $statusDataItemSwrItem = &$statusDataItem["Devstswr"]["item"][$j];
              else :
                 $statusDataItemSwrItem = &$statusDataItem["Devstswr"]["item"];
              endif;
   
              // $statusDataArray[$i]["Devstswr"]["item"][$j]["DevsrhdId"]    = convertSpecial($statusDataItemSwrItem["DevsrhdId"]);
              // ....
              // Wenn ["item"] entfernen nicht möglich, dann rückgängig, wie vorige Zeilen (!!!!)
              $statusDataArray[$i]["Devstswr"][$j]["DevsthdNo"]    = convertSpecial($statusDataItemSwrItem["DevsthdNo"]);
              $statusDataArray[$i]["Devstswr"][$j]["DevstswrNo"]   = convertSpecial($statusDataItemSwrItem["DevstswrNo"]);
              $statusDataArray[$i]["Devstswr"][$j]["SoftwareCat"]  = convertSpecial($statusDataItemSwrItem["SoftwareCat"]);
              $statusDataArray[$i]["Devstswr"][$j]["Version"]      = convertSpecial($statusDataItemSwrItem["Version"]);
              $statusDataArray[$i]["Devstswr"][$j]["Description"]  = convertSpecial($statusDataItemSwrItem["Description"]);
              $statusDataArray[$i]["Devstswr"][$j]["TstmpUpdate"]  = convertSpecial($statusDataItemSwrItem["TstmpUpdate"]);
              $statusDataArray[$i]["Devstswr"][$j]["ValidFrom"]    = convertSpecial($statusDataItemSwrItem["ValidFrom"]);
              $statusDataArray[$i]["Devstswr"][$j]["ValidTo"]      = convertSpecial($statusDataItemSwrItem["ValidTo"]);
              $statusDataArray[$i]["Devstswr"][$j]["TstmpMeasure"] = convertSpecial($statusDataItemSwrItem["TstmpMeasure"]);
              $statusDataArray[$i]["Devstswr"][$j]["IsActive"]     = convertSpecial($statusDataItemSwrItem["IsActive"]);
          endfor;
   
          // Devstloc
          $hasMoreElements2 = false;
          $numOfStatusDataItemSubItems = 1;
          if ($statusDataItem["Devstloc"]["item"]["0"] != "") : 
             $hasMoreElements2 = true;
             $numOfStatusDataItemSubItems = count($statusDataItem["Devstloc"]["item"]);
          endif;
          for ($j = 0; $j < $numOfStatusDataItemSubItems; $j++) :
              if ($hasMoreElements2) : 
                 $statusDataItemSwrItem = &$statusDataItem["Devstloc"]["item"][$j];
              else :
                 $statusDataItemSwrItem = &$statusDataItem["Devstloc"]["item"];
              endif;
   
              // $statusDataArray[$i]["Devstloc"]["item"][$j]["DevsrhdId"]    = convertSpecial($statusDataItemSwrItem["DevsrhdId"]);
              // ....
              // Wenn ["item"] entfernen nicht möglich, dann rückgängig, wie vorige Zeilen (!!!!)
              $statusDataArray[$i]["Devstloc"][$j]["DevsthdNo"]    = convertSpecial($statusDataItemSwrItem["DevsthdNo"]);
              $statusDataArray[$i]["Devstloc"][$j]["DevstlocNo"]   = convertSpecial($statusDataItemSwrItem["DevstlocNo"]);
              $statusDataArray[$i]["Devstloc"][$j]["DevstlocCat"]  = convertSpecial($statusDataItemSwrItem["DevstlocCat"]);
              $statusDataArray[$i]["Devstloc"][$j]["DevstlocId"]   = convertSpecial($statusDataItemSwrItem["DevstlocId"]);
              $statusDataArray[$i]["Devstloc"][$j]["Description"]  = convertSpecial($statusDataItemSwrItem["Description"]);
              $statusDataArray[$i]["Devstloc"][$j]["TstmpMeasure"] = convertSpecial($statusDataItemSwrItem["TstmpMeasure"]);
          endfor;
      endfor;
   endif;

   if ($debug) :
      // echo "<br><br>\n\nSTATUS-DATA-ARRAY<br><br>\n\n";
      // print_r($statusDataArray);
      // echo "<br><br><br>\n\n\n";
      ptNovaLogFile("=> DEBUG.MODE: MASTER_DATA.PREPARE_ARRAY.END");
   endif;
endif;


// ***************************************************************************************
// **** START IMPORT PROCESS *************************************************************
// ***************************************************************************************

// IMPORT MASTER DATA
if ($mode == "1") :

   if ($debug) :
      ptNovaLogFile("=> DEBUG.MODE: MASTER_DATA.IMPORT.START");
   endif;

   $masterDataArrayLen = count($masterDataArray);
   for ($i = 0; $i < $masterDataArrayLen; $i++) :

       $f_vu             = $masterDataArray[$i]["OrgunhdIdPr"];
       $f_at_match       = $masterDataArray[$i]["DevtyhdId"];
       $f_description    = $masterDataArray[$i]["Description"];
       $f_devmfhd_id     = $masterDataArray[$i]["DevmfhdId"];
       $f_devmflin_id    = $masterDataArray[$i]["DevmflinId"];
       $f_tstmp_created  = $masterDataArray[$i]["TstmpCreated"];
       $f_tstmp_changed  = $masterDataArray[$i]["TstmpChanged"];
       $f_archive_stat   = $masterDataArray[$i]["ArchiveStat"];
       $f_md_lcycle_stat = $masterDataArray[$i]["MdLcycleStat"];

       if ($debug) :
          /*
          echo "f_vu :" . $f_vu . "<br>";
          echo "f_at_match :" . $f_at_match . "<br>";
          echo "f_description :" . $f_description . "<br>";
          echo "f_devmfhd_id :" . $f_devmfhd_id . "<br>";
          echo "f_devmflin_id :" . $f_devmflin_id . "<br>";
          echo "f_tstmp_created :" . $f_tstmp_created . "<br>";
          echo "f_tstmp_changed :" . $f_tstmp_changed . "<br>";
          echo "f_archive_stat :" . $f_archive_stat . "<br>";
          echo "f_md_lcycle_stat :" . $f_md_lcycle_stat . "<br>";
          echo "<br><br>";
          */
       endif;

       $numOfItems = count($masterDataArray[$i]["Devices"]);
       for ($j = 0; $j < $numOfItems; $j++) :

           $f_serial_no      = $masterDataArray[$i]["Devices"][$j]["DevichdId"];
           $f_online_state   = $masterDataArray[$i]["Devices"][$j]["OnlineState"];
           $f_netelhd_id_o   = $masterDataArray[$i]["Devices"][$j]["NetelhdIdO"];
           $f_year_construct = $masterDataArray[$i]["Devices"][$j]["YearConstruct"];
           $f_dev_condition  = $masterDataArray[$i]["Devices"][$j]["DevCondition"];
           $f_technical_id   = $masterDataArray[$i]["Devices"][$j]["TechnicalId"];
           $f_dev_serial     = $masterDataArray[$i]["Devices"][$j]["DevSerial"];
           $f_productive_fg  = $masterDataArray[$i]["Devices"][$j]["ProductiveFg"];
           $f_stk_name       = $masterDataArray[$i]["Devices"][$j]["Description"];
           $f_tstmp_created  = $masterDataArray[$i]["Devices"][$j]["TstmpCreated"];
           $f_tstmp_changed  = $masterDataArray[$i]["Devices"][$j]["TstmpChanged"];
           $f_archive_stat   = $masterDataArray[$i]["Devices"][$j]["ArchiveStat"];
           $f_md_lcycle_stat = $masterDataArray[$i]["Devices"][$j]["MdLcycleStat"];

           $f_serial_no = trim($f_serial_no);
           $f_stk_name = trim($f_stk_name);

           // Remove leading zeros
           if ($f_serial_no != "") :
              while (substr($f_serial_no, 0, 1) == "0"):
                    $f_serial_no = substr($f_serial_no, 1);
              endwhile;
           endif;

           if ($debug) :
              /*
              echo " f_serial_no :" . $f_serial_no . "<br>";
              echo " f_technical_id :" . $f_technical_id . "<br>";
              echo " f_stk_name :" . $f_stk_name . "<br>";
              */
           endif;

           $doImportLocal = false;
           if ($f_serial_no != "") :
              $currAtiId = getFieldValueFromClause("phoenix.articleitem", "ati_id", "ati_serialno = '" . $f_serial_no . "'");
              if ($currAtiId == "") :
                 $doImportLocal = true;
                 // $outReportArray[] = getLngt("Der Automat mit der Nummer") . " " . $f_serial_no . " " . getLngt("existiert schon!");
              else :
                 $currStkId = getFieldValueFromClause("phoenix.articleitem", "stk_id", "ati_serialno = '" . $f_serial_no . "'");
                 $currStkName = getFieldValueFromClause("phoenix.stock", "stk_name", "stk_id = '" . $currStkId . "'");
                 if (strtolower($currStkName) != strtolower($f_stk_name)) :

                    if ($debug) :
                       // echo " => currStkName :" . $currStkName . "<br>";
                    endif;
                 endif; 
              endif;
           endif;

           if ($debug) :
              // echo "<br><br>";
           endif;

           if ($doImportLocal) :

              // There could be defined a special stock being parent stock for all service unit (article item) stocks.
              // Otherwise every service unit will be associated to a special root stock (!!!!)
              $suStockIdParentDefault = getParameterValue("0", "SERVICEUNIT_STOCK_PARENT_ID", $hq_id);
              if ($suStockIdParentDefault == "" || !is_numeric($suStockIdParentDefault)) :
                 $suStockIdParentDefault = getParameterValue("0", "SERVICEUNIT_STOCK_PARENT_ID", "0");
                 if ($suStockIdParentDefault == "" || !is_numeric($suStockIdParentDefault)) :
                    $suStockIdParentDefault = "0";
                 endif;
              endif;

              // Wrap parameters because of copied values from adminstration of the service units (!!!!)
              $f_su_admin_ati_serialno = $f_serial_no;
              $f_su_admin_ati_data_01  = trim($f_ati_data_01);  // Not defined in PT-Nova
              $f_su_admin_ati_data_02  = trim($f_su_admin_ati_data_02);
              $f_su_admin_ati_data_03  = trim($f_su_admin_ati_data_03);

              // Check existence
              $f_su_admin_at_id = getFieldValueFromClause("phoenix.article", "at_id", "at_match = '" . $f_at_match . "'");  // Automatentyp (H&W, etc.)
              $f_su_admin_stk_id = getFieldValueFromClause("phoenix.stock", "stk_id", "stk_name = '" . $f_stk_name . "'");  // Haltestelle (Baumwall, etc.)
// [CONTAINER-HALTESTELLE] !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$f_su_admin_stk_id = "1000";
// $f_stk_name = "[CONTAINER-HALTESTELLE]";
              // *** START DATABASE ACCESS ***
              if ($fire) :
                 TA("B");
if (false) :
                 // Insert new stock if does not exist
                 if ($f_su_admin_stk_id == "") :

                    // $f_stk_barcode = trim($f_stk_barcode);
                    $f_stk_barcode = "";
                    // $f_ad_street = trim($f_ad_street);
                    // $f_ad_zipcode = trim($f_ad_zipcode);
                    // $f_ad_city = trim($f_ad_city);
                    // $f_stk_hsno = trim($f_stk_hsno);
                    // if ($f_stk_hsno == "") : $f_stk_hsno = "."; endif;
                    // if ($f_ad_country == "") : $f_ad_country = "DE"; endif;

                    // Check for empty entries in address-fields
                    // if ($f_ad_street != "" && $f_ad_zipcode != "" && $f_ad_city != "" && $f_ad_country != "") :
                    if (true) :
                       // Check zipcode and city
                       // $addressValidityArray = checkCityZipcode($f_ad_zipcode, $f_ad_city, $f_ad_street);
                       // if ($noValidationOfAddress || $addressValidityArray[0] >= 1) :
                       if (true) :
                          TA("B");
                          if ($f_stk_name != "") :

                             $rootStockSU = getParameterValue("0", "SU_STK_ROOT", $hq_id);    // Get root stock where all service units belong to
                             if ($rootStockSU != "" && is_numeric($rootStockSU)) :

                                // Check for existing entry in address (because of redundance)
                                // $tmpArray = insertAddress($f_ad_street, $f_ad_zipcode, $f_ad_city, "", $f_ad_country, true);
                                // $ad_id_new = $tmpArray[0];
                                $ad_id_new = "0";
                                // if ($ad_id_new != "" && is_numeric($ad_id_new)) :
                                if (true) :
                                   // Get current timestamp
                                   // $currentTime = getDateTime("0");      
                                   // Check for selection of a service unit item

                                   if (!existsEntry("phoenix.stock",array("stk_name",$f_stk_name))) :
                                      // Get complete path of $rootStockSU. $rootStockSU can have a parent which can be a sub stock, too
                                      $newStkPath = "//" . $rootStockSU . "//";
                                      $tmpStkPath = getFieldValueFromId("stock", "stk_id", $rootStockSU, "stk_path");
                                      if ($tmpStkPath != "") :
                                         $newStkPath = substr($tmpStkPath,0,-2) . $newStkPath;
                                      endif;
                                      // * INSERT *
                                      insertStmt("phoenix.stock", array("hq_id", $hq_id, "stk_name",$f_stk_name, "stk_pre_id", $rootStockSU, "stk_path", $newStkPath, "ad_id", $ad_id_new,"stk_barcode",$f_stk_barcode,"stk_modifytime", $currentTime, "stk_visible", "1"));
                                      $outReportArray[] = getLngt("Der neue Standort wurde angelegt!");
                                   // else :
                                   //    $outReportArray[] = getLngt("Dieser Standort existiert schon! Schauen Sie bitte in der Auswahl!");
                                   endif;
                                // else :
                                //    $outReportArray[] = getLngt("Die Generierung der Adresse hat nicht funktioniert!");
                                endif;
                             else :
                                $outReportArray[] = getLngt("KRITISCH: Kein Root-Stock für die Haltestellen definiert!!!!");
                             endif;
                          else :
                             $outReportArray[] = getLngt("Die Standortangabe ist leer!");
                          endif;
                          TA("C");    
                          TA("E");
                       // else :
                       //   $outReportArray[] = getLngt("Die Postleitzahl passt nicht zu dem angegebenen Ort!");
                       endif;

                       // Get NEW stock ID
                       $f_su_admin_stk_id = getFieldValueFromClause("phoenix.stock", "stk_id", "stk_name = '" . $f_stk_name . "'");  // Haltestelle (Baumwall, etc.)
                    else :
                       $outReportArray[] = getLngt("Bitte geben Sie die Addressdaten vollständig an!");
                    endif;
                 endif;
endif;
                 // Insert new service unit
                 // $currentTime = getDateTime("0");
                 if ($f_su_admin_at_id != "" && is_numeric($f_su_admin_at_id)) :
                    if ($f_su_admin_stk_id != "" && is_numeric($f_su_admin_stk_id)) :
                       $doModifyStockarticle = false;

                       // Vector of predefined vehicles of days of the week
                       // $f_su_admin_ati_data_21 = $f_su_admin_ati_data_21_1 . "," . $f_su_admin_ati_data_21_2 . "," . $f_su_admin_ati_data_21_3 . "," . $f_su_admin_ati_data_21_4 . ","
                       //                         . $f_su_admin_ati_data_21_5 . "," . $f_su_admin_ati_data_21_6 . "," . $f_su_admin_ati_data_21_7;
                       $f_su_admin_ati_data_21 = "";

                       // There could be defined a special stock being parent stock for all service unit (article item) stocks.
                       // Otherwise every service unit will be associated to a special root stock (!!!!)
                       $suStockIdParent = $suStockIdParentDefault;

                       $atiLastInsertId = dbInsert("phoenix.articleitem", array("at_id", $f_su_admin_at_id, "stk_id", $f_su_admin_stk_id, "ati_serialno", $f_su_admin_ati_serialno, "ati_data_01", $f_su_admin_ati_data_01, "ati_data_02", $f_su_admin_ati_data_02, "ati_data_03", $f_su_admin_ati_data_03, "ati_data_04", $currentTime, "ati_data_21", $f_su_admin_ati_data_21));
                       if ($atiLastInsertId != "" && is_numeric($atiLastInsertId) && $atiLastInsertId > 0) :
                          // $outReportArray[] = getLngt("Die neuen Automatendaten wurden angelegt!");
                          $doModifyStockarticle = true;                     

                          // Item is a service unit. Insert stock associated to this item if does not exist
                          $opVal = objectInsertStock("ati", $atiLastInsertId, $suStockIdParent, "SYSTEM-SERVICEUNIT", getLngt("FA") . $f_su_admin_ati_serialno, $dbConnection);
   
                          if ($opVal == "-1") :
                             $outReportArray[] = getLngt("Es wurde kein spezielles Objekt bzw. dessen Typ spezifiziert!");
                          elseif ($opVal == "-2") :
                             $outReportArray[] = getLngt("ACHTUNG! Es existiert kein notwendiges Hauptlager! Bitte den Administrator kontaktieren!");
                          elseif ($opVal == "-3") :
                             $outReportArray[] = getLngt("ACHTUNG! Die Anlage des Lagerortes konnte nicht durchgeführt werden! Bitte wiederholen bzw. den Administrator kontaktieren!");
                          endif;
                       else :
                          $outReportArray[] = getLngt("ACHTUNG! Die Anlage des Automats hat nicht geklappt! Bitte wiederholen bzw. den Administrator kontaktieren!");
                       endif;

                       if ($doModifyStockarticle) :

                          // *** Update stock quantity from target stock ***
                          if ($f_su_admin_stk_id > "0") :
                             // Get current item quantity of the specified article and target stock
                             $stkatItemQuantity = getFieldValueFromClause("stockarticle", "stkat_itemquantity", "stk_id = '" . $f_su_admin_stk_id . "' AND at_id = '" . $f_su_admin_at_id . "'");
                             if ($stkatItemQuantity != "") : 
                                $stkatItemQuantity = $stkatItemQuantity + 1;
                             endif;
                             if (existsEntry("phoenix.stockarticle",array("stk_id",$f_su_admin_stk_id,"at_id",$f_su_admin_at_id))) :
                                updateStmt("phoenix.stockarticle","stk_id",$f_su_admin_stk_id,array("stkat_quantity",$stkatItemQuantity,"stkat_itemquantity",$stkatItemQuantity),"at_id = '".$f_su_admin_at_id."'");
                             else :
                                insertStmt("phoenix.stockarticle",array("stk_id",$f_su_admin_stk_id,"at_id",$f_su_admin_at_id,"stkat_quantity","1","stkat_itemquantity","1"));
                             endif;
                          endif;
                       endif;

                       $outReportArray[] = getLngt("Der Automat mit der Nummer") . " " . $f_serial_no . " " . getLngt("wurde angelegt!");
                    else :
                       $outReportArray[] = $f_serial_no . ": " . getLngt("Es existiert kein Standort!");
                    endif;
                 else :
                    $outReportArray[] = $f_serial_no . ": " . getLngt("Es existiert kein Automatentyp!");
                 endif;

                 TA("C");
                 TA("E");
              endif;
           endif;          
       endfor;

       $numOfItems = count($masterDataArray[$i]["Swreleases"]);
       for ($j = 0; $j < $numOfItems; $j++) :
           $f_devsrhd_id     = $masterDataArray[$i]["Swreleases"][$j]["DevsrhdId"];
           $f_description    = $masterDataArray[$i]["Swreleases"][$j]["Description"];
           $f_release_tstmp  = $masterDataArray[$i]["Swreleases"][$j]["ReleaseTstmp"];
           $f_tstmp_created  = $masterDataArray[$i]["Swreleases"][$j]["TstmpCreated"];
           $f_active_fg      = $masterDataArray[$i]["Swreleases"][$j]["ActiveFg"];
           $f_archive_stat   = $masterDataArray[$i]["Swreleases"][$j]["ArchiveStat"];
           $f_md_lcycle_stat = $masterDataArray[$i]["Swreleases"][$j]["MdLcycleStat"];
   
           $numOfSubItems = count($masterDataArray[$i]["Swreleases"][$j]["Messages"]);
           for ($k = 0; $k < $numOfSubItems; $k++) :
               $f_atm_code      = $masterDataArray[$i]["Swreleases"][$j]["Messages"][$k]["DevsrmsgId"];
               $f_atm_desc      = $masterDataArray[$i]["Swreleases"][$j]["Messages"][$k]["Description"];
               $f_atm_text      = $masterDataArray[$i]["Swreleases"][$j]["Messages"][$k]["Msgtext"];
               $f_msgparam      = $masterDataArray[$i]["Swreleases"][$j]["Messages"][$k]["Msgparam"];
               $f_severity_code = $masterDataArray[$i]["Swreleases"][$j]["Messages"][$k]["SeverityCode"];
               $f_node_date     = $masterDataArray[$i]["Swreleases"][$j]["Messages"][$k]["NodeDate"];

               $f_atm_code = trim($f_atm_code);
               $f_atm_desc = trim($f_atm_desc);
               $f_atm_text = trim($f_atm_text);
               $f_atm_prio = trim($f_atm_prio);

               // Check filters of service units (e.g. range of serial numbers) deciding the data will be imported
               $doImport = checkFilterForImport("", $f_vu, $f_at_match);

               if ($doImport) :
                  if ($f_at_match != "" && $f_atm_code != "" && $f_atm_desc != "") :

                     // *** START DATABASE ACCESS ***
                     if ($fire) :
                        TA("B");

                        // Get "at_id" by "at_match" value
                        $atId = getFieldValueFromClause("phoenix.article", "at_id", "at_match = '" . $f_at_match . "'");

                        // Get current field values regarding the article message (error code)
                        // $f_atm_desc = getFieldValueFromClause("phoenix.articlemessage", "atm_desc", "at_id = '" . $f_at_id . "' AND atm_code = '" . $f_atm_code . "'");
                        // $f_atm_text = getFieldValueFromClause("phoenix.articlemessage", "atm_text", "at_id = '" . $f_at_id . "' AND atm_code = '" . $f_atm_code . "'");

                        if ($atId != "") :
                           if (existsEntry("phoenix.articlemessage",array("at_id",$atId,"atm_code",$f_atm_code))) :
                              updateStmt("phoenix.articlemessage", "atm_code", $f_atm_code, array("atm_desc", $f_atm_desc, "atm_text", $f_atm_text), "at_id = '" . $atId . "'");
                           else :
                              insertStmt("phoenix.articlemessage", array("at_id",$atId,"atm_code",$f_atm_code,"atm_desc",$f_atm_desc,"atm_text",$f_atm_text,"atm_prio",$f_atm_prio));
                              $outReportArray[] = getLngt("Die Betriebsmeldung ") . $f_atm_code . getLngt(" für den Automatentyp ") . $f_at_match . getLngt(" wurde angelegt!");
                           endif;
                           /*                        
                           if (!existsEntry("phoenix.articlemessage",array("at_id",$atId,"atm_code",$f_atm_code,"atm_desc",$f_atm_desc))) :
                              insertStmt("phoenix.articlemessage", array("at_id",$atId,"atm_code",$f_atm_code,"atm_desc",$f_atm_desc,"atm_text",$f_atm_text,"atm_prio",$f_atm_prio));
                              $outReportArray[] = getLngt("Die Betriebsmeldung ") . $f_atm_code . getLngt(" für den Automatentyp ") . $f_at_match . getLngt(" wurde angelegt!");
                           else :
                              updateStmt("phoenix.articlemessage", "atm_code", $f_atm_code, array($dbFieldAmount_atih, $f_amount_actual, "atih_createtime", $currentTime), "at_id = '" . $atId . "'");
                           endif;
                           */
                        else :
                           $outReportArray[] = getLngt("Die Automatentyp ") . $f_at_match . getLngt(" existiert nicht!");
                        endif;

                        TA("C");
                        TA("E");
                     endif;
                  endif;
               endif;
           endfor;
       endfor;
   endfor;

   if ($debug) :
      ptNovaLogFile("=> DEBUG.MODE: MASTER_DATA.IMPORT.END");
   endif;
endif;


// IMPORT STATUS DATA
if ($mode == "0") :

   if ($debug) :
      ptNovaLogFile("=> DEBUG.MODE: STATUS_DATA.IMPORT.START");
   endif;

   $statusDataArrayLen = count($statusDataArray);
   for ($i = 0; $i < $statusDataArrayLen; $i++) :
   
       $f_md            = "";
       $f_devsthd_no    = $statusDataArray[$i]["DevsthdNo"];
       $f_vu            = $statusDataArray[$i]["OrgunhdIdPr"];
       $f_at_match      = $statusDataArray[$i]["DevtyhdId"];
       $f_serial_no     = $statusDataArray[$i]["DevichdId"];
       $f_timestamp_raw = $statusDataArray[$i]["TstmpDevsthd"];
       $f_gs_prio       = $statusDataArray[$i]["SevCodeHd"];
       $f_gs_prio_bm    = $statusDataArray[$i]["SevCodeOpn"];
       $f_gs_x1         = $statusDataArray[$i]["IsActual"];
       $f_gs_x2         = $statusDataArray[$i]["IsInService"];
       $f_is_mny_vltd   = $statusDataArray[$i]["IsMnyVltd"];
       $f_is_mat_vltd   = $statusDataArray[$i]["IsMatVltd"];
       $f_no_opn_fg     = $statusDataArray[$i]["NoOpnFg"];
   
   
       $f_devsthd_no = trim($f_devsthd_no);
       // $f_md = trim($f_md);
       $f_vu = trim($f_vu);
       $f_at_match = trim($f_at_match);
       $f_serial_no = trim($f_serial_no);
       $f_timestamp_raw = trim($f_timestamp_raw);
       $f_timestamp_raw_2 = $f_timestamp_raw;  // Init

       // Remove leading zeros
       if ($f_serial_no != "") :
          while (substr($f_serial_no, 0, 1) == "0"):
                $f_serial_no = substr($f_serial_no, 1);
          endwhile;
       endif;

       if ($debug) :
          /*
          echo "f_md :" . $f_md . "<br>";
          echo "f_devsthd_no :" . $f_devsthd_no . "<br>";
          echo "f_vu :" . $f_vu . "<br>";
          echo "f_at_match :" . $f_at_match . "<br>";
          echo "f_serial_no :" . $f_serial_no . "<br>";
          echo "f_timestamp_raw :" . $f_timestamp_raw . "<br>";
          echo "f_gs_prio :" . $f_gs_prio . "<br>";
          echo "f_gs_prio_bm :" . $f_gs_prio_bm . "<br>";
          echo "f_gs_x1 :" . $f_gs_x1 . "<br>";
          echo "f_gs_x2 :" . $f_gs_x2 . "<br>";
          echo "f_is_mny_vltd :" . $f_is_mny_vltd . "<br>";
          echo "f_is_mat_vltd :" . $f_is_mat_vltd . "<br>";
          echo "f_no_opn_fg :" . $f_no_opn_fg . "<br>";
          echo "<br>";
          */
       endif;
   
       // Check filters of service units (e.g. range of serial numbers) deciding the data will be imported
       $doImport = checkFilterForImport($f_serial_no, $f_vu, $f_at_match);
   
       if ($doImport && $f_serial_no != "") :

          $f_stk_id = "";
          $f_at_id = getFieldValueFromId("articleitem", "ati_serialno", $f_serial_no, "at_id");
          if ($f_at_id != "") :
             // Get stock of the serviceunit
             $f_stk_id = getFieldValueFromId("articleitem", "ati_serialno", $f_serial_no, "stk_id");
             if ($f_stk_id != "") :
                updateStmt("phoenix.articleitem", "ati_serialno", $f_serial_no, array("ati_data_17", "", "ati_data_29", ""), "at_id = '" . $f_at_id . "' AND stk_id = '" . $f_stk_id . "'");
             endif;
          endif;

          $numOfItems = count($statusDataArray[$i]["Devstopn"]);
          for ($j = 0; $j < $numOfItems; $j++) :
              $f_devsthd_no          = $statusDataArray[$i]["Devstopn"][$j]["DevsthdNo"];
              $f_devstopn_no         = $statusDataArray[$i]["Devstopn"][$j]["DevstopnNo"];
              $f_devsrhd_id          = $statusDataArray[$i]["Devstopn"][$j]["DevsrhdId"];
              $f_atm_code            = $statusDataArray[$i]["Devstopn"][$j]["DevsrmsgId"];
              $f_atm_desc            = $statusDataArray[$i]["Devstopn"][$j]["DevCatMf"];
              $f_atm_text            = $statusDataArray[$i]["Devstopn"][$j]["DevCmpMf"];
              $f_atm_text2           = $statusDataArray[$i]["Devstopn"][$j]["DevCmpinsMf"];
              $f_dummy_1             = $statusDataArray[$i]["Devstopn"][$j]["OpNotifApdx"];
              $f_dummy_2             = $statusDataArray[$i]["Devstopn"][$j]["OpNotifText"];
              $f_service_usr_name    = "";
              $f_servicedatetime_raw = $statusDataArray[$i]["Devstopn"][$j]["TstmpProcss"];
              $f_dummy_3             = $statusDataArray[$i]["Devstopn"][$j]["DoorState"];
              $f_atm_incident_start  = $statusDataArray[$i]["Devstopn"][$j]["TstmpIncdt"];
              $f_dummy_5             = "";
              $f_atm_incident_end    = $statusDataArray[$i]["Devstopn"][$j]["TstmpFinishd"];
              $f_dummy_7             = "";
              $f_gs_prio_bm          = $statusDataArray[$i]["Devstopn"][$j]["SevCodeOpn"];
     
     
              $f_atm_code = trim($f_atm_code);
              // $f_service_usr_name = trim($f_service_usr_name);
              
              if ($f_atm_incident_end == "00000000000000") :
                 $f_atm_incident_end = "";
              endif;

              // writeToFile("../log/debug_MC_atm.log", $f_serial_no . " - " . $f_atm_code . " - S:" . $f_atm_incident_start . " - E:" . $f_atm_incident_end);
              if ($debug) :
                 /*
                 echo "&nbsp;&nbsp; f_devsthd_no :" . $f_devsthd_no . "<br>";
                 echo "&nbsp;&nbsp; f_devstopn_no :" . $f_devstopn_no . "<br>";
                 echo "&nbsp;&nbsp; f_devsrhd_id :" . $f_devsrhd_id . "<br>";
                 echo "&nbsp;&nbsp; f_atm_code :" . $f_atm_code . "<br>";
                 echo "&nbsp;&nbsp; f_atm_desc :" . $f_atm_desc . "<br>";
                 echo "&nbsp;&nbsp; f_atm_text :" . $f_atm_text . "<br>";
                 echo "&nbsp;&nbsp; f_atm_text2 :" . $f_atm_text2 . "<br>";
                 echo "&nbsp;&nbsp; f_dummy_1 :" . $f_dummy_1 . "<br>";
                 echo "&nbsp;&nbsp; f_dummy_2 :" . $f_dummy_2 . "<br>";
                 echo "&nbsp;&nbsp; f_service_usr_name :" . $f_service_usr_name . "<br>";
                 echo "&nbsp;&nbsp; f_servicedatetime_raw :" . $f_servicedatetime_raw . "<br>";
                 echo "&nbsp;&nbsp; f_dummy_3 :" . $f_dummy_3 . "<br>";
                 echo "&nbsp;&nbsp; f_atm_incident_start :" . $f_atm_incident_start . "<br>";
                 echo "&nbsp;&nbsp; f_dummy_5 :" . $f_dummy_5 . "<br>";
                 echo "&nbsp;&nbsp; f_atm_incident_end :" . $f_atm_incident_end . "<br>";
                 echo "&nbsp;&nbsp; f_dummy_7 :" . $f_dummy_7 . "<br>";
                 echo "&nbsp;&nbsp; f_gs_prio_bm :" . $f_gs_prio_bm . "<br>";
                 echo "-------------------------<br>";
                 */
              endif;

              if ($doImport && $f_atm_incident_end == "") :
                 $f_timestamp = substr($f_timestamp_raw,0,4) . "-" . substr($f_timestamp_raw,4,2) . "-" . substr($f_timestamp_raw,6,2) . " 03:00:00";
                 $f_timestamp_2 = substr($f_timestamp_raw_2,0,4) . "-" . substr($f_timestamp_raw_2,4,2) . "-" . substr($f_timestamp_raw_2,6,2) . " 03:00:00";

                 // Check for existence of the service unit
                 // $f_stk_id = "";
                 // $f_at_id = getFieldValueFromId("articleitem", "ati_serialno", $f_serial_no, "at_id");
                 if ($f_at_id != "") :
                    // Get stock of the serviceunit
                    // $f_stk_id = getFieldValueFromId("articleitem", "ati_serialno", $f_serial_no, "stk_id");
                    if ($f_stk_id != "") :
                       if ($f_atm_code != "") :
   
                          // *** START DATABASE ACCESS ***
                          if ($fire) :
                             TA("B");
   
                             // Get current field values regarding the article message (error code)
                             if ($f_atm_desc == "" || $f_atm_desc == "keine Angabe") :
                                $f_atm_desc = getFieldValueFromClause("phoenix.articlemessage", "atm_desc", "at_id = '" . $f_at_id . "' AND atm_code = '" . $f_atm_code . "'");
                             endif;
                             if ($f_atm_text == "" || $f_atm_text == "keine Angabe") :
                                $f_atm_text = getFieldValueFromClause("phoenix.articlemessage", "atm_text", "at_id = '" . $f_at_id . "' AND atm_code = '" . $f_atm_code . "'");
                             endif;
   
                             // Init field for status messages of the current service unit
                             // if ($j == 0) :
                             //    updateStmt("phoenix.articleitem", "ati_serialno", $f_serial_no, array("ati_data_17", ""), "at_id = '" . $f_at_id . "' AND stk_id = '" . $f_stk_id . "'");
                             // endif;
   
                             // Update prio state of the serviceunit in table "articleitem" if the persistent value is lower than the current value
                             if ($f_atm_desc != "") :
                                $tmpMsgCodes = getFieldValueFromClause("phoenix.articleitem", "ati_data_17", "at_id = '" . $f_at_id . "' AND stk_id = '" . $f_stk_id . "' AND ati_serialno = '" . $f_serial_no . "'");
                                $tmpMsgCodes = trim($tmpMsgCodes);
                                $doUpdate = true;
                                if ($tmpMsgCodes != "") :
                                   $tmpMsgCodesArray = spliti(",", $tmpMsgCodes);
                                   $tmpSearch = array_search($f_atm_code, $tmpMsgCodesArray);
                                   if (!($tmpSearch === FALSE)) :
                                      $doUpdate = false;
                                   endif;
                                   $tmpMsgCodes .= ",";
                                endif;
                                if ($doUpdate) :
                                   updateStmt("phoenix.articleitem", "ati_serialno", $f_serial_no, array("ati_data_17", $tmpMsgCodes . $f_atm_code), "at_id = '" . $f_at_id . "' AND stk_id = '" . $f_stk_id . "'");
                                endif;
                             else :
                                $outReportArray[] = getLngt("Der Betriebsmeldungscode ") . $f_atm_code . getLngt(" wurde nicht gefunden!");
                             endif;
   
                             TA("C");
                             TA("E");
                          endif;
                       endif;
                    else :
                       $outReportArray[] = getLngt("Standortzuordnungsfehler! Wahrscheinlich liegt eine Dateninkonsistenz vor! Bitte unverzüglich melden!");
                    endif;
                 else :
                    $outReportArray[] = getLngt("Der Automat mit der Nummer") . " " . $f_serial_no . " " . getLngt("wurde nicht gefunden!") . " [" . $f_at_match . " " . $f_serial_no . " " . $f_timestamp . " " . $f_gs_prio . " " . $f_gs_prio_bm . "]";
                 endif;
              endif;
          endfor;

          $numOfItems = count($statusDataArray[$i]["Devstloc"]);
          for ($j = 0; $j < $numOfItems; $j++) :
              $f_devsthd_no      = $statusDataArray[$i]["Devstloc"][$j]["DevsthdNo"];
              $f_devstloc_no     = $statusDataArray[$i]["Devstloc"][$j]["DevstlocNo"];
              $f_devstloc_cat    = $statusDataArray[$i]["Devstloc"][$j]["DevstlocCat"];
              $f_ati_data_01     = $statusDataArray[$i]["Devstloc"][$j]["DevstlocId"];
              $f_description     = $statusDataArray[$i]["Devstloc"][$j]["Description"];
              $f_timestamp_raw_2 = $statusDataArray[$i]["Devstloc"][$j]["TstmpMeasure"];
   
              $f_stk_name = trim($f_description);  // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
              $f_ati_data_01 = trim($f_ati_data_01);

              if ($debug) :
                 /*
                 echo "&nbsp;&nbsp; f_devsthd_no :" . $f_devsthd_no . "<br>";
                 echo "&nbsp;&nbsp; f_devstloc_no :" . $f_devstloc_no . "<br>";
                 echo "&nbsp;&nbsp; f_devstloc_cat :" . $f_devstloc_cat . "<br>";
                 echo "&nbsp;&nbsp; f_ati_data_01 :" . $f_ati_data_01 . "<br>";
                 echo "&nbsp;&nbsp; f_description :" . $f_description . "<br>";
                 echo "&nbsp;&nbsp; f_timestamp_raw_2 :" . $f_timestamp_raw_2 . "<br>";
                 echo "&nbsp;&nbsp; f_stk_name :" . $f_stk_name . "<br>";
                 echo "<br>";
                 */
              endif;
   
              // !!!!!!!!! f_ati_data_01 eintragen !!!!!!!!!
              
          endfor;

          $numOfItems = count($statusDataArray[$i]["Devstmny"]);
          for ($j = 0; $j < $numOfItems; $j++) :
              $f_devsthd_no      = $statusDataArray[$i]["Devstmny"][$j]["DevsthdNo"];
              $f_devstmny_no     = $statusDataArray[$i]["Devstmny"][$j]["DevstmnyNo"];
              $f_gb_type         = $statusDataArray[$i]["Devstmny"][$j]["CashboxType"];
              $f_gb_serialno     = $statusDataArray[$i]["Devstmny"][$j]["CashboxNo"];
              $f_dummy_1         = $statusDataArray[$i]["Devstmny"][$j]["CbxSerialNo"];
              $f_pos             = $statusDataArray[$i]["Devstmny"][$j]["PositionDesc"];
              $f_currency        = $statusDataArray[$i]["Devstmny"][$j]["Currency"];
              $f_quality_rating  = $statusDataArray[$i]["Devstmny"][$j]["FaceValue"];
              $f_amount_debit    = $statusDataArray[$i]["Devstmny"][$j]["NominalQnty"];
              $f_amount_actual   = $statusDataArray[$i]["Devstmny"][$j]["NominalAmnt"];
              $f_dummy_2         = $statusDataArray[$i]["Devstmny"][$j]["NominalCapct"];
              $f_dummy_3         = $statusDataArray[$i]["Devstmny"][$j]["Threshold"];
              $f_dummy_4         = $statusDataArray[$i]["Devstmny"][$j]["Measurand"];
              $f_dummy_5         = $statusDataArray[$i]["Devstmny"][$j]["Direction"];
              $f_timestamp_raw_2 = $statusDataArray[$i]["Devstmny"][$j]["TstmpMeasure"];
              $f_is_violated     = $statusDataArray[$i]["Devstmny"][$j]["IsViolated"];
   
   
              $f_gb_type = trim($f_gb_type);
              $f_gb_serialno = trim($f_gb_serialno);
              $f_pos = trim($f_pos);
              $f_currency = trim($f_currency);
              $f_quality_rating = trim($f_quality_rating);    $f_quality_rating = str_replace (",", ".", $f_quality_rating);
              $f_amount_debit = trim($f_amount_debit);        $f_amount_debit = str_replace (",", ".", $f_amount_debit);
              $f_amount_actual = trim($f_amount_actual);      $f_amount_actual = str_replace (",", ".", $f_amount_actual);
              $f_timestamp_raw_2 = trim($f_timestamp_raw_2);

              if ($debug) :
                 /*
                 echo "&nbsp;&nbsp; f_devsthd_no :" . $f_devsthd_no . "<br>";
                 echo "&nbsp;&nbsp; f_devstmny_no :" . $f_devstmny_no . "<br>";
                 echo "&nbsp;&nbsp; f_gb_type :" . $f_gb_type . "<br>";
                 echo "&nbsp;&nbsp; f_gb_serialno :" . $f_gb_serialno . "<br>";
                 echo "&nbsp;&nbsp; f_dummy_1 :" . $f_dummy_1 . "<br>";
                 echo "&nbsp;&nbsp; f_pos :" . $f_pos . "<br>";
                 echo "&nbsp;&nbsp; f_currency :" . $f_currency . "<br>";
                 echo "&nbsp;&nbsp; f_quality_rating :" . $f_quality_rating . "<br>";
                 echo "&nbsp;&nbsp; f_amount_debit :" . $f_amount_debit . "<br>";
                 echo "&nbsp;&nbsp; f_amount_actual :" . $f_amount_actual . "<br>";
                 echo "&nbsp;&nbsp; f_dummy_2 :" . $f_dummy_2 . "<br>";
                 echo "&nbsp;&nbsp; f_dummy_3 :" . $f_dummy_3 . "<br>";
                 echo "&nbsp;&nbsp; f_dummy_4 :" . $f_dummy_4 . "<br>";
                 echo "&nbsp;&nbsp; f_dummy_5 :" . $f_dummy_5 . "<br>";
                 echo "&nbsp;&nbsp; f_timestamp_raw_2 :" . $f_timestamp_raw_2 . "<br>";
                 echo "&nbsp;&nbsp; f_is_violated :" . $f_is_violated . "<br>";
                 echo "<br>";
                 */
              endif;

              if ($doImport) :
                 // $f_timestamp = substr($f_timestamp_raw,0,4) . "-" . substr($f_timestamp_raw,4,2) . "-" . substr($f_timestamp_raw,6,2) . " " . substr($f_timestamp_raw,8,2) . ":" . substr($f_timestamp_raw,10,2) . ":" . substr($f_timestamp_raw,12,2);
                 $f_timestamp = substr($f_timestamp_raw,0,4) . "-" . substr($f_timestamp_raw,4,2) . "-" . substr($f_timestamp_raw,6,2) . " 03:00:00";
                 // $f_timestamp_2 = substr($f_timestamp_raw_2,0,4) . "-" . substr($f_timestamp_raw_2,4,2) . "-" . substr($f_timestamp_raw_2,6,2) . " " . substr($f_timestamp_raw_2,8,2) . ":" . substr($f_timestamp_raw_2,10,2) . ":" . substr($f_timestamp_raw_2,12,2);
                 $f_timestamp_2 = substr($f_timestamp_raw_2,0,4) . "-" . substr($f_timestamp_raw_2,4,2) . "-" . substr($f_timestamp_raw_2,6,2) . " 03:00:00";

                 if ($debug) :
                    /*
                    echo "&nbsp;&nbsp; f_timestamp :" . $f_timestamp . "<br>";
                    echo "&nbsp;&nbsp; f_timestamp_2 :" . $f_timestamp_2 . "<br>";
                    echo "<br>";
                    */
                 endif;

                 // Check for existence of the service unit
                 // $f_stk_id = "";
                 // $f_at_id = getFieldValueFromId("articleitem", "ati_serialno", $f_serial_no, "at_id");
                 if ($f_at_id != "") :
                    // Get stock of the serviceunit
                    // $f_stk_id = getFieldValueFromId("articleitem", "ati_serialno", $f_serial_no, "stk_id");
                    if ($f_stk_id != "") :
                       if ($f_gb_type != "" && $f_pos != "") :
                          $dbFieldAmount = "";
                          $dbFieldAmount_atih = "";
                          if ($f_gb_type == "BEK") :
                             $dbFieldAmount = "ati_data_05";
                             $dbFieldAmount_atih = "atih_data_05";
                          elseif ($f_gb_type == "MEK") :
                                 $dbFieldAmount = "ati_data_06";
                                 $dbFieldAmount_atih = "atih_data_06";
                          elseif ($f_gb_type == "ZGS" && $f_pos == "0") :
                                 $dbFieldAmount = "ati_data_07";
                                 $dbFieldAmount_atih = "atih_data_07";
                          elseif ($f_gb_type == "ZGS" && $f_pos == "1") :
                                 $dbFieldAmount = "ati_data_08";
                                 $dbFieldAmount_atih = "atih_data_08";
                          elseif ($f_gb_type == "ZGS" && $f_pos == "2") :
                                 $dbFieldAmount = "ati_data_09";
                                 $dbFieldAmount_atih = "atih_data_09";
                          elseif ($f_gb_type == "RGS" && $f_pos == "10") :
                                 $dbFieldAmount = "ati_data_10";
                                 $dbFieldAmount_atih = "atih_data_10";
                          elseif ($f_gb_type == "RGS" && $f_pos == "11") :
                                 $dbFieldAmount = "ati_data_11";
                                 $dbFieldAmount_atih = "atih_data_11";
                          elseif ($f_gb_type == "RGS" && $f_pos == "12") :
                                 $dbFieldAmount = "ati_data_12";
                                 $dbFieldAmount_atih = "atih_data_12";
                          elseif ($f_gb_type == "RGS" && $f_pos == "13") :
                                 $dbFieldAmount = "ati_data_13";
                                 $dbFieldAmount_atih = "atih_data_13";
                          elseif ($f_gb_type == "RGS" && $f_pos == "14") :
                                 $dbFieldAmount = "ati_data_14";
                                 $dbFieldAmount_atih = "atih_data_14";
                          elseif ($f_gb_type == "RGS" && $f_pos == "15") :
                                 $dbFieldAmount = "ati_data_15";
                                 $dbFieldAmount_atih = "atih_data_15";
                          endif;

                          if ($fire) :
                             // Update current event state of the serviceunit in table "articleitem"
                             if ($dbFieldAmount != "") :
                                updateStmt("phoenix.articleitem", "ati_serialno", $f_serial_no, array("ati_data_04", $f_timestamp, $dbFieldAmount, $f_amount_actual, "ati_data_30", ""), "at_id = '" . $f_at_id . "' AND stk_id = '" . $f_stk_id . "'");
                             endif;

                             // Set quantities in "stockarticle"
                             /*
                             if (existsEntry("phoenix.stockarticle",array("at_id",$f_at_id,"stk_id",$f_stk_id))) :
                                $stkatItemQuantity = getFieldValueFromClause("stockarticle", "stkat_itemquantity", "stk_id = '" . $f_stk_id . "' AND at_id = '" . $f_at_id . "'");
                                $stkatItemQuantity++;
                                updateStmt("phoenix.stockarticle","stk_id",$f_stk_id,array("stkat_quantity",$stkatItemQuantity,"stkat_itemquantity",$stkatItemQuantity),"at_id = '" . $f_at_id . "'");
                             else :
                                insertStmt("phoenix.stockarticle", array("at_id", $f_at_id, "stk_id", $f_stk_id, "stkat_maxquantity", "0", "stkat_quantity", "1", "stkat_itemquantity", "1"));
                             endif;

                             // Mapping: ati_data_05 = BEK, ati_data_06 = MEK, ati_data_07 = Hopper 1, ati_data_08 = Hopper 2, ati_data_09 = Hopper 3
                             if (existsEntry("phoenix.articleitem",array("at_id",$f_at_id,"stk_id",$f_stk_id,"ati_serialno",$f_serial_no))) :
                                // Update current event state of the serviceunit in table "articleitem"
                                updateStmt("phoenix.articleitem", "ati_serialno", $f_serial_no, array("ati_data_04", $f_timestamp, "ati_data_05", $f_bek, "ati_data_06", $f_mek, "ati_data_07", $f_hopper_1, "ati_data_08", $f_hopper_2, "ati_data_09", $f_hopper_3), "at_id = '" . $f_at_id . "' AND stk_id = '" . $f_stk_id . "'");
                             else :
                               // Insert current event state AND article and new stock of the serviceunit into table "articleitem"
                                insertStmt("phoenix.articleitem", array("at_id", $f_at_id, "stk_id", $f_stk_id, "ati_serialno", $f_serial_no, "ati_data_01", $f_data_01, "ati_data_02", "", "ati_data_03", "", "ati_data_04", $f_timestamp, 
                                                                        "ati_data_05", $f_bek, "ati_data_06", $f_mek, "ati_data_07", $f_hopper_1, "ati_data_08", $f_hopper_2, "ati_data_09", $f_hopper_3));
                             endif;
                             */

                             // Write current event state of the serviceunit into table "articleitemhistory"
                             if ($dbFieldAmount_atih != "") :
                                // USE SPECIAL INDEX FOR OPZIMIZATION
                                $forceIndex = " FORCE INDEX (serialno_atid_data04) ";

                                if (existsEntry("phoenix_log.articleitemhistory" . $forceIndex,array("at_id",$f_at_id,"stk_id",$f_stk_id,"atih_serialno",$f_serial_no,"atih_data_04",$f_timestamp))) :
                                   updateStmt("phoenix_log.articleitemhistory" . $forceIndex, "atih_serialno", $f_serial_no, array($dbFieldAmount_atih, $f_amount_actual, "atih_createtime", $currentTime), "at_id = '" . $f_at_id . "' AND stk_id = '" . $f_stk_id . "' AND atih_data_04 = '" . $f_timestamp . "'");
                                else :
                                   insertStmt("phoenix_log.articleitemhistory", array("at_id", $f_at_id, "stk_id", $f_stk_id, "atih_createtime", $currentTime, "atih_serialno", $f_serial_no, "atih_data_01", "", "atih_data_02", "", "atih_data_03", "", "atih_data_04", $f_timestamp, $dbFieldAmount_atih, $f_amount_actual));
                                endif;
                             endif;

                             // Write current event state of the serviceunit into table "log"
                             // insertStmt("phoenix_log.log", array("logo_id", "1000", "log_createtime", $f_timestamp, "hq_id", $hq_id, "at_id", $f_at_id, "stk_id", $f_stk_id, "id_01", $f_serial_no, "logo_description", $f_bek . ";" . $f_mek . ";" . $f_hopper_1 . ";" . $f_hopper_2 . ";" . $f_hopper_3));
                          endif;
                       else :
                          $outReportArray[] = getLngt("Der Kassettentyp konnte nicht zugeordnet werden!") . " [" . $f_at_match . " " . $f_serial_no . " " . $f_timestamp . " " . $f_gb_type . " " . $f_gb_serialno . " " . $f_pos . " " . $f_currency . " " . $f_quality_rating . " " . $f_amount_debit .  " " . $f_amount_actual .  " " . $f_timestamp_2 . "]";
                       endif;
                    else :
                       $outReportArray[] = getLngt("Standortzuordnungsfehler! Wahrscheinlich liegt eine Dateninkonsistenz vor! Bitte unverzüglich melden!");
                    endif;
                 else :
                    $outReportArray[] = getLngt("Der Automat mit der Nummer") . " " . $f_serial_no . " " . getLngt("wurde nicht gefunden!") . " [" . $f_at_match . " " . $f_serial_no . " " . $f_timestamp . " " . $f_gb_type . " " . $f_gb_serialno . " " . $f_pos . " " . $f_currency . " " . $f_quality_rating . " " . $f_amount_debit .  " " . $f_amount_actual .  " " . $f_timestamp_2 . "]";
                 endif;
              endif;
          endfor;
      
          $numOfItems = count($statusDataArray[$i]["Devstmat"]);
          for ($j = 0; $j < $numOfItems; $j++) :
                                 $statusDataArray[$i]["Devstmat"][$j]["DevsthdNo"];
                                 $statusDataArray[$i]["Devstmat"][$j]["DevstmatNo"];
                                 $statusDataArray[$i]["Devstmat"][$j]["MatHopperId"];
                                 $statusDataArray[$i]["Devstmat"][$j]["MaterialId"];
              $f_nominal_stock = $statusDataArray[$i]["Devstmat"][$j]["NominalStock"];
              $f_mat_unit_ext  = $statusDataArray[$i]["Devstmat"][$j]["MatUnitExt"];
                                 $statusDataArray[$i]["Devstmat"][$j]["MatUnit"];
                                 $statusDataArray[$i]["Devstmat"][$j]["MeasureMeth"];
                                 $statusDataArray[$i]["Devstmat"][$j]["Threshold"];
                                 $statusDataArray[$i]["Devstmat"][$j]["TstmpMeasure"];
                                 $statusDataArray[$i]["Devstmat"][$j]["IsViolated"];
              
              if ($doImport) :
                 // $f_timestamp = substr($f_timestamp_raw,0,4) . "-" . substr($f_timestamp_raw,4,2) . "-" . substr($f_timestamp_raw,6,2) . " 03:00:00";
                 // $f_timestamp_2 = substr($f_timestamp_raw_2,0,4) . "-" . substr($f_timestamp_raw_2,4,2) . "-" . substr($f_timestamp_raw_2,6,2) . " 03:00:00";

                 if ($debug) :
                    echo "&nbsp;&nbsp; f_timestamp :" . $f_timestamp . "<br>";
                    echo "&nbsp;&nbsp; f_timestamp_2 :" . $f_timestamp_2 . "<br>";
                    echo "&nbsp;&nbsp; $f_nominal_stock :" . $f_nominal_stock . "<br>";
                    echo "&nbsp;&nbsp; $f_mat_unit_ext :" . $f_mat_unit_ext . "<br>";
                    echo "<br>";
                 endif;

                 // Check for existence of the service unit
                 // $f_stk_id = "";
                 // $f_at_id = getFieldValueFromId("articleitem", "ati_serialno", $f_serial_no, "at_id");
                 if ($f_at_id != "") :
                    // Get stock of the serviceunit
                    // $f_stk_id = getFieldValueFromId("articleitem", "ati_serialno", $f_serial_no, "stk_id");
                    if ($f_stk_id != "") :
                       if (($f_at_match == "STU" || $f_at_match == "STH" || $f_at_match == "STB" || $f_at_match == "STVS") && $f_mat_unit_ext == "KARTEN") :
                          // Special treatment for prepaid cards to be stored and displayed in column "H3"
                          $dbFieldAmount = "ati_data_09";
                          $dbFieldAmount_atih = "atih_data_09";

                          if ($fire) :
                             // Update current unit
                             if ($dbFieldAmount != "") :
                                updateStmt("phoenix.articleitem", "ati_serialno", $f_serial_no, array($dbFieldAmount, $f_nominal_stock), "at_id = '" . $f_at_id . "' AND stk_id = '" . $f_stk_id . "'");
                             endif;

                             // Write current event state of the serviceunit into table "articleitemhistory"
                             if ($dbFieldAmount_atih != "") :
                                // USE SPECIAL INDEX FOR OPZIMIZATION
                                $forceIndex = " FORCE INDEX (serialno_atid_data04) ";

                                if (existsEntry("phoenix_log.articleitemhistory" . $forceIndex,array("at_id",$f_at_id,"stk_id",$f_stk_id,"atih_serialno",$f_serial_no,"atih_data_04",$f_timestamp))) :
                                   updateStmt("phoenix_log.articleitemhistory" . $forceIndex, "atih_serialno", $f_serial_no, array($dbFieldAmount_atih, $f_nominal_stock), "at_id = '" . $f_at_id . "' AND stk_id = '" . $f_stk_id . "' AND atih_data_04 = '" . $f_timestamp . "'");
                                // else :
                                //    insertStmt("phoenix_log.articleitemhistory", array("at_id", $f_at_id, "stk_id", $f_stk_id, "atih_createtime", $currentTime, "atih_serialno", $f_serial_no, "atih_data_01", "", "atih_data_02", "", "atih_data_03", "", "atih_data_04", $f_timestamp, $dbFieldAmount_atih, $f_amount_actual));
                                endif;
                             endif;

                             // Write current event state of the serviceunit into table "log"
                             // insertStmt("phoenix_log.log", array("logo_id", "1000", "log_createtime", $f_timestamp, "hq_id", $hq_id, "at_id", $f_at_id, "stk_id", $f_stk_id, "id_01", $f_serial_no, "logo_description", $f_bek . ";" . $f_mek . ";" . $f_hopper_1 . ";" . $f_hopper_2 . ";" . $f_hopper_3));
                          endif;
                       endif;
                    else :
                       $outReportArray[] = getLngt("Standortzuordnungsfehler! Wahrscheinlich liegt eine Dateninkonsistenz vor! Bitte unverzüglich melden!");
                    endif;
                 else :
                    $outReportArray[] = getLngt("Der Automat mit der Nummer") . " " . $f_serial_no . " " . getLngt("wurde nicht gefunden!") . " [" . $f_at_match . " " . $f_serial_no . " " . $f_timestamp . " " . $f_gb_type . " " . $f_gb_serialno . " " . $f_pos . " " . $f_currency . " " . $f_quality_rating . " " . $f_amount_debit .  " " . $f_amount_actual .  " " . $f_timestamp_2 . "]";
                 endif;
              endif;
          endfor;
      
          $numOfItems = count($statusDataArray[$i]["Devstswr"]);
          for ($j = 0; $j < $numOfItems; $j++) :
              $statusDataArray[$i]["Devstswr"][$j]["DevsthdNo"];
              $statusDataArray[$i]["Devstswr"][$j]["DevstswrNo"];
              $statusDataArray[$i]["Devstswr"][$j]["SoftwareCat"];
              $statusDataArray[$i]["Devstswr"][$j]["Version"];
              $statusDataArray[$i]["Devstswr"][$j]["Description"];
              $statusDataArray[$i]["Devstswr"][$j]["TstmpUpdate"];
              $statusDataArray[$i]["Devstswr"][$j]["ValidFrom"];
              $statusDataArray[$i]["Devstswr"][$j]["ValidTo"];
              $statusDataArray[$i]["Devstswr"][$j]["TstmpMeasure"];
              $statusDataArray[$i]["Devstswr"][$j]["IsActive"];
          endfor;

       endif;  // $doImport
   endfor;

   if ($debug) :
      ptNovaLogFile("=> DEBUG.MODE: STATUS_DATA.IMPORT.END");
   endif;
endif;

if ($debug) :
   // echo "hq_id :" . $hq_id . "<br>";
   // echo "mode :" . $mode . "<br>";
   // echo "currentTimestamp :" . $currentTimestamp . "<br>";
   // echo "<br>";
   ptNovaLogFile("=> DEBUG.MODE: hq_id :" . $hq_id . " | mode :" . $mode . " | currentTimestamp :" . $currentTimestamp);
endif;

if ($httpStatus == "200") :
   if (existsEntry("genericdatacontainer",array("gdc_obj_type","hq","gdc_obj_id",$hq_id,"gdc_gen_fieldname","pt_nova","gdc_context",$mode))) :
      updateStmt("genericdatacontainer","gdc_obj_type","hq",array("gdc_content", $currentTimestamp),"gdc_obj_id = '" . $hq_id . "' AND gdc_gen_fieldname = 'pt_nova' AND gdc_context = '" . $mode . "'");
   else :
      insertStmt("genericdatacontainer", array("gdc_obj_type", "hq", "gdc_obj_id", $hq_id, "gdc_gen_fieldname", "pt_nova", "gdc_content", $currentTimestamp, "gdc_context", $mode));
   endif;
   ptNovaLogFile("SYSTEM.PROCESS.STATE: OK!");
else : 
   ptNovaLogFile("SYSTEM.PROCESS.STATE: NOT OK!");
endif;


ptNovaLogFile("SYSTEM.DATETIME.SCRIPT_EXEC_END: " . getDateTime("0"));
ptNovaLogFile("___________________________________________________________________________________");


// Finally call script to update iverage increase values
if ($mode == "0") :
   $path = getAbsoluteSystemPath();
   $mcDebugAverageIncreaseErrLogFile = $path . "/log/average_increase_err.stdout+err";
   $cmd = "php " . $path . "/illt/average_increase.php acapella7890 " . $hq_id . " " . $currentTimestamp . " > " . $mcDebugAverageIncreaseErrLogFile . " 2>&1 &";
   system($cmd);
endif;

/*
IMPORT FILE (PTCU_GB) <=> Devstmny
            MANDANT;VU;GERAETEART;GERAET;ZEITPUNKT;GELDBEHAELTERART;GELDBEHAELTER;SERIENNUMMERGB;POSITION;WAEHRUNG;WERTIGKEIT;SOLLANZAHL;SOLLBETRAG;SOLLVOLUMEN;SCHWELLWERT;SCHWELLWERTMESSGR;SCHWELLWERTRICHTG;ZEITSTEMPEL
            "111";"HHA";"H&W";"00092845";20120423041547;"BEK";"71207410";"";"20";"EUR";;116;955;;;"";"";20120423030451
            "111";"HHA";"H&W";"00092845";20120423041547;"MEK";"70009001";"";"21";"EUR";;511;464,9;;;"";"";20120423030451
            "111";"HHA";"H&W";"00092845";20120423041547;"RGS";"60004425";"";"10";"EUR";2;35;70;;;"";"";20120423030451
            "111";"HHA";"H&W";"00092845";20120423041547;"RGS";"61201595";"";"11";"EUR";1;50;50;;;"";"";20120423030451
            "111";"HHA";"H&W";"00092845";20120423041547;"RGS";"62201556";"";"12";"EUR";0,5;48;24;;;"";"";20120423030451
            "111";"HHA";"H&W";"00092845";20120423041547;"RGS";"63201178";"";"14";"EUR";0,1;5;0,5;;;"";"";20120423030451
            "111";"HHA";"H&W";"00092845";20120423041547;"RGS";"64202022";"";"15";"EUR";0,05;5;0,25;;;"";"";20120423030451
            "111";"HHA";"H&W";"00092845";20120423041547;"RGS";"67201578";"";"13";"EUR";0,2;47;9,4;;;"";"";20120423030451
            "111";"HHA";"H&W";"00092845";20120423041547;"ZGS";"50000592";"";"0";"EUR";2;227;454;;;"";"";20120423030451
            "111";"HHA";"H&W";"00092845";20120423041547;"ZGS";"53200253";"";"1";"EUR";0,1;1491;149,1;;;"";"";20120423030451
            "111";"HHA";"H&W";"00092845";20120423041547;"ZGS";"54000064";"";"2";"EUR";0,05;1092;54,6;;;"";"";20120423030451
                        
                                 ----                  DevsthdNo          [PTnova-interne laufende Nummer des Gerätestatus]
                                 ----                  DevstmnyNo         [PTnova-interne laufende Nummer des Geldbestandes unterhalb des Gerätestatus]
            MANDANT              f_md                  ----
            VU                   f_vu                  OrgunhdIdPr        
            GERAETEART           f_at_match            DevtyhdId
            GERAET               f_serial_no           DevichdId
            ZEITPUNKT            f_timestamp_raw       TstmpDevsthd   
            GELDBEHAELTERART     f_gb_type             CashboxType        [Gibt die Art des Geldbehälters an]
            GELDBEHAELTER        f_gb_serialno         CashboxNo          [Gibt die eindeutige Identifikation des Geldbehälters an]
            SERIENNUMMERGB       f_dummy_1             CbxSerialNo        [Gibt die Seriennummer des Geldbehälters an]
            POSITION             f_pos                 PositionDesc       [Gibt die Position des Geldbehälters im Gerät an]
            WAEHRUNG             f_currency            Currency           [Gibt die Währung von dem Geld an]
            WERTIGKEIT           f_quality_rating      FaceValue          [Wertigkeit der Münzen bzw. Banknoten in der angegebenen Währung. 
                                                                           Beispiele: Münze/Note	Wertigkeit 10-Cent-Münze	0,10, 50-Cent-Münze	0,50, 10-Euro-Note	10,00, 20-Euro-Note	20,00]
            SOLLANZAHL           f_amount_debit        NominalQnty        [Gibt die vom Gerät ermittelte Anzahl an Münzen oder Noten an]
            SOLLBETRAG           f_amount_actual       NominalAmnt        [Gibt den vom Gerät ermittelten Wert der Münzen oder Noten an ]
            SOLLVOLUMEN          f_dummy_2             NominalCapct       [Gibt das Volumen des Geldes in dem Geldbehälter an]
            SCHWELLWERT          f_dummy_3             Threshold          [Gibt den Schwellwert an, bei dessen Erreichen eine Meldung ausgelöst werden soll]       
            SCHWELLWERTMESSGR    f_dummy_4             Measurand          [Schwellwertmessgröße]
            SCHWELLWERTRICHTG    f_dummy_5             Direction          [Schwellwertrichtung]
            ZEITSTEMPEL          f_timestamp_raw_2     TstmpMeasure       [Gibt den Zeitpunkt an, wann der Bestand gemessen wurde]
            ----                                       IsViolated         [Kennzeichen, ob Schwellverletzung vorliegt. 'X' – Schwellwertverletzung liegt vor, ' ' – keine Schwellwertverletzung]
            
                                    
IMPORT FILE (PTCU_GS) <=> Statusdata
            MANDANT;VU;GERAETEART;GERAET;ZEITPUNKT;SCHWEREGRAD;KZAKTUELL;KZIMSERVICE;SCHWEREGRADBM
            "111";"HDAG";"HUW";"00000215";20120514020437;0;0;0;20
            "111";"HDAG";"HUW";"00000215";20120514020440;0;0;0;20
            "111";"HDAG";"HUW";"00000106";20120514020445;10;0;0;40
            "111";"HDAG";"HUW";"00000106";20120514020448;10;0;0;40
            "111";"HDAG";"HUW";"00000203";20120514020449;30;0;0;40
            "111";"HDAG";"HUW";"00000215";20120514020450;0;0;0;20
            "111";"HDAG";"HUW";"00000203";20120514020451;30;0;0;40
            "111";"HDAG";"HUW";"00000106";20120514020457;10;0;0;40
            "111";"HDAG";"HUW";"00000106";20120514020500;10;0;0;40
            
                                 ----                  DevsthdNo          [PTnova-interne laufende Nummer des Gerätestatus]
            MANDANT              f_md                  ----
            VU                   f_vu                  OrgunhdIdPr        
            GERAETEART           f_at_match            DevtyhdId
            GERAET               f_serial_no           DevichdId
            ZEITPUNKT            f_timestamp_raw       TstmpDevsthd
            SCHWEREGRAD          f_gs_prio             SevCodeHd
            KZAKTUELL            f_gs_x1               IsActual
            KZIMSERVICE          f_gs_x2               IsInService
            SCHWEREGRADBM        f_gs_prio_bm          SevCodeOpn
                                 ----                  IsMnyVltd          [Kennzeichen, ob Schwellwertverletzung bei Geldbeständen vorhanden. 'X' – Schwellwertverletzung vorhanden, ' ' – keine Schwellwertverletzung vorhanden]
                                 ----                  IsMatVltd          [In PT-COM nicht vorhanden, Kennzeichen, ob Schwellwertverletzung bei Materialbeständen vorhanden. 'X' – Schwellwertverletzung vorhanden, ' ' – keine Schwellwertverletzung vorhanden]
                                 ----                  NoOpnFg            [In PT-COM nicht vorhanden, Kennzeichen, ob Meldungen vorhanden. 'X' – keine Meldungen vorhanden, ' ' – Meldungen vorhanden]



IMPORT FILE (PTCG_GM)
            MANDANT;VU;GERAETEART;CODE;MNEMONIK;TEXT;DUMMY;DUMMY;PRIO;
            111 ;HHA	 ;HWB  ;7000030D ;POWERGENERALOUTOFORDER ;Stromversorgung: ausser Betrieb   ; ;Hft&Wessel ;40	;
            111 ;HHA	 ;H&W  ;7000030D ;POWERGENERALOUTOFORDER ;Stromversorgung: ausser Betrieb   ; ;Wartung    ;40	;
            111 ;HHA	 ;H&WB ;7000030D ;POWERGENERALOUTOFORDER ;Stromversorgung: ausser Betrieb   ; ;Wartung    ;40	;
            111 ;HDAG  ;HUW	 ;7000030D ;POWERGENERALOUTOFORDER ;Stromversorgung: ausser Betrieb   ; ;Hˆft&Wesse ;40	;
            111 ;HHA	 ;HWB	 ;8003030C ;CASEALARMBURGLARY      ;Geh‰use: Alarm Einbruch           ; ;Hft&Wessel ;40	;
            111 ;HHA	 ;H&W	 ;8003030C ;CASEALARMBURGLARY      ;Geh‰use: Alarm Einbruch           ; ;Hft&Wessel ;40	;
            111 ;HHA	 ;H&WB ;8003030C ;CASEALARMBURGLARY      ;Geh‰use: Alarm Einbruch           ; ;Hft&Wessel ;40	;
            111 ;HDAG  ;HUW	 ;8003030C ;CASEALARMBURGLARY      ;Geh‰use: Alarm Einbruch           ; ;Hˆft&Wesse ;40	;
            111 ;HHA	 ;HWB  ;A2000000 ;GUIGENERALOK           ;Automat: (wieder) in Ordnung      ; ;Hft&Wessel ;0	;
            111 ;HHA	 ;H&W  ;A2000000 ;GUIGENERALOK           ;Automat: (wieder) in Ordnung      ; ;Hft&Wessel ;0	;
            111 ;HHA	 ;H&WB ;A2000000 ;GUIGENERALOK           ;Automat: (wieder) in Ordnung      ; ;Hft&Wessel ;0	;
            111 ;HDAG  ;HUW  ;A2000000 ;GUIGENERALOK           ;Automat: (wieder) in Ordnung      ; ;Hˆft&Wesse ;0	;
            111 ;HHA	 ;HWB  ;A2000300 ;GUIGENERALERROR        ;Automat: genereller Fehlerzustand ; ;Hft&Wessel ;40	;
            111 ;HHA	 ;H&W  ;A2000300 ;GUIGENERALERROR        ;Automat: genereller Fehlerzustand ; ;Hft&Wessel ;40	;
            111 ;HHA	 ;H&WB ;A2000300 ;GUIGENERALERROR        ;Automat: genereller Fehlerzustand ; ;Hft&Wessel ;40	;
            111 ;HDAG  ;HUW  ;A2000300 ;GUIGENERALERROR        ;Automat: genereller Fehlerzustand ; ;Hˆft&Wesse ;40	;

                                 ----                  DevsthdNo          [PTnova-interne laufende Nummer des Gerätestatus]
            MANDANT              f_md                  ----
            VU                   f_vu                  OrgunhdIdPr        
            GERAETEART           f_at_match            DevtyhdId
            CODE                 f_atm_code
            MNEMONIK             f_atm_desc
            TEXT                 f_atm_text
            DUMMY                f_dummy_1
            DUMMY                f_dummy_2
            PRIO                 f_atm_prio
                                 


IMPORT FILE (PTCU_BM2) <=> Devstopn
            MANDANT;VU;GERAETEART;GERAET;ZEITPUNKT;GERAETEMELDUNG;GERAETEKLASSE;KOMPONENTE;KOMPONENTENINSTANZ;ZUSATZINFORMATION;ZUSATZTEXT;BEARBEITETVON;BEARBEITETAM;TUERSTATUS;ZEITSTEMPEL;ERLEDIGTVON;ERLEDIGTAM;STOERFALL
            "111";"HDAG";"HUW";"00000104";20120423031530;"40140202";"keine Angabe";"keine Angabe";"keine Angabe";"";"";"krafzigt";20120423042117;"2";20120422133123;"krafzigt";20120423042117;""
            "111";"HDAG";"HUW";"00000107";20120423020435;"61010301";"keine Angabe";"keine Angabe";"keine Angabe";"";"";"PtcDKM";20120423020438;"2";20120418170904;"";;""
            "111";"HDAG";"HUW";"00000107";20120423020435;"6102030F";"keine Angabe";"keine Angabe";"keine Angabe";"";"";"PtcDKM";20120423020438;"2";20120418170907;"";;""
            "111";"HDAG";"HUW";"00000107";20120423020438;"61010301";"keine Angabe";"keine Angabe";"keine Angabe";"";"";"PtcDKM";20120423020457;"2";20120418170904;"";;""
            "111";"HDAG";"HUW";"00000107";20120423020438;"6102030F";"keine Angabe";"keine Angabe";"keine Angabe";"";"";"PtcDKM";20120423020457;"2";20120418170907;"";;""
            "111";"HDAG";"HUW";"00000107";20120423020457;"61010301";"keine Angabe";"keine Angabe";"keine Angabe";"";"";"PtcDKM";20120423020501;"2";20120418170904;"";;""
            "111";"HDAG";"HUW";"00000107";20120423020457;"6102030F";"keine Angabe";"keine Angabe";"keine Angabe";"";"";"PtcDKM";20120423020501;"2";20120418170907;"";;""
            "111";"HDAG";"HUW";"00000107";20120423020501;"61010301";"keine Angabe";"keine Angabe";"keine Angabe";"";"";"PtcDKM";20120423033030;"2";20120418170904;"";;""
            "111";"HDAG";"HUW";"00000107";20120423020501;"6102030F";"keine Angabe";"keine Angabe";"keine Angabe";"";"";"PtcDKM";20120423033030;"2";20120418170907;"";;""
            
                                 ----                  DevsthdNo          [PTnova-interne laufende Nummer des Gerätestatus]
                                 ----                  DevstopnNo         [PTnova-interne laufende Nummer der Meldung unterhalb des Gerätestatus]
                                 ----                  DevsrhdId          [Softwarestand, bzw. Softwareversion, der die Meldung in den Stammdaten zugeordnet ist. Siehe Stammdaten]
                                 ----                  SevCodeOpn         [In PT-COM nicht vorhanden. Schweregrad der Betriebsmeldung]
            MANDANT              f_md                  ----
            VU                   f_vu                  OrgunhdIdPr        
            GERAETEART           f_at_match            DevtyhdId
            GERAET               f_serial_no           DevichdId
            ZEITPUNKT            f_timestamp_raw       TstmpDevsthd
            GERAETEMELDUNG       f_atm_code            DevsrmsgId         [ID der Gerätemeldung]
            GERAETEKLASSE        f_atm_desc            DevCatMf           [Gibt die Klasse an, zu der das Gerät gehört. Vorgabe, wenn kein Wert geliefert wird, ist „keine Angabe“]
            KOMPONENTE           f_atm_text            DevCmpMf           [Gibt die Komponente im Gerät an, die die Mel-dung erzeugt hat. Vorgabe, wenn kein Wert geliefert wird, ist „keine Angabe“]
            KOMPONENTENINSTANZ   f_atm_text2           DevCmpinsMf        [Gibt die genaue Instanz der erzeugenden Komponente an. Vorgabe, wenn kein Wert geliefert wird, ist „keine Angabe“]
            ZUSATZINFORMATION    f_dummy_1             OpNotifApdx        [Numerische Zusatzinformation zur aufgetretenen Meldung. Beispiel: Anzahl der noch druckbaren Tickets bei drohendem Papiermangel]
            ZUSATZTEXT           f_dummy_2             OpNotifText        [Alphanumerische Zusatzinformation zur aufgetretenen Meldung]
            BEARBEITETVON        f_service_usr_name    ----
            BEARBEITETAM         f_servicedatetime_raw TstmpProcss
            TUERSTATUS           f_dummy_3             DoorState          [In PT-COM nicht vorhanden, Zeitstempel Änderung. Werte: '1' - Tür offen, '2' - Tür geschlossen]
            ZEITSTEMPEL          f_atm_incident_start  TstmpIncdt         [Meldungszeitpunkt.  Gibt den Zeitpunkt an, wann die Meldung eingetreten ist]
            ERLEDIGTVON          f_dummy_5             ----
            ERLEDIGTAM           f_atm_incident_end    TstmpFinishd       [Gibt an, wann die Meldung als erledigt gekennzeichnet wurde]
            STOERFALL            f_dummy_7          
            

IMPORT FILE (PTCG_G)
            MANDANT;VU;GERAETEART;GERAET;HALTESTELLE;STANDORT
           
            MANDANT              f_md                  ----
            VU                   f_vu                  OrgunhdIdPr        
            GERAETEART           f_at_match            DevtyhdId 
            GERAET               f_serial_no           DevichdId    (Seriennr. FA)
            HALTESTELLE          f_stk_name                         (Lagerortname (Baumwall, etc.))
            STANDORT             f_ati_data_01         DevstlocId   (Standorttext (Ausgang A, etc.))  [Gibt den Standort an.]
            SOLLZUSTAND          ----                  DevCondition       [Sollzustand des Gerätes mit folgenden Ausprägungen:
                                                                             '<leer>' – undefiniert
                                                                             'P' – position / aufgestellt (PT-COM: 'A')
                                                                             'O' – operation / funktionsbereit (PT-COM: 'F')
                                                                             'D' – disassemble / abgebaut (PT-COM: 'X')
                                                                             'R' – repair / in Reparatur (PT-COM: 'R')
                                                                             Bitte die unterschiedlichen Werte beachten.]
            Standorttyp (Neu!)   ----                  DevstlocCat        [Standorttyp der gemeldet wurde, z.B. Fahrzeug, Haltestelle, Serviceplatz]
           

-----------------------------------------------------------------------------------------------------
// KOMMENTARE, TOOLS !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

// $soap = new SoapClient(null, array("location" => "soap_server.php", "uri" => "http://test-uri", "soap_version" => SOAP_1_1, "trace" => 1));
// $soap = new SoapClient(null, array("location" => "http://127.0.0.1/votian/sysadmin/soap_server.php", "uri" => "http://test-uri", "soap_version" => SOAP_1_1, "trace" => 1));
// $soap = new SoapClient("math.wsdl", array("location" => "http://127.0.0.1/votian/sysadmin/soap_server.php", "uri" => "http://test-uri", "trace" => 1));
// $soap = new SoapClient(null, array("location" => "http://127.0.0.1/votian/sysadmin/soap_server.php", "uri" => "http://test-uri"));
// var_dump($soap->__soapCall("add", array(3,4)));
// var_dump($soap->add(3,4));


try
 {
     // $client = new SoapClient("http://127.0.0.1/votian/sysadmin/webservice1.wsdl");
     // $client = new SoapClient("127.0.0.1/votian/sysadmin/webservice1.wsdl");
     $client = new SoapClient("webservice1.wsdl");
     print($client->getServerTime());
 }
 catch (SoapFault $e)
 {
     print($e);
 }

*/
?>
