<?php
/*=======================================================================
 *
 * import_HHA.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/

include_once ("../import/import.php");

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

// Get the rights of the employee logged in and check the accessibility
authCheckEmployeeRights($emp_id, "22", "1");

// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "statusMessage", "importFile", "executeImportProcess", "deactivateMenu"));


getLanguage(__FILE__);

$deactivateMenuStatic = "1";
$pageTitel = getLngt("IMPORT HHA");
include_once ("../admin/menu.php");
include_once ("../illt/inc_serviceunit.inc.php");
include_once ("../include/inc_stock.inc.php");
include_once ("../include/html.inc.php");
getCurrentScript(__FILE__);

if ($f_act != "executeImport" || $executeImportProcess != "1") : $executeImportProcess = ""; endif;    // Execute import after check run
$showExecutionProcessButton = true;
$outReportArray = array();
$closeWindow = "0";
$refreshParent = "0";
$delimiter = ";";

$fire = getParameterValue("0", "MASK_SU_IMPORT_ACTIVATED", $hq_id);
if ($fire == "1") : $fire = true; else : $fire = false; endif;

$flushActivated = true;
$flushEachLine = true;


// 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")) :
     $retBool = false;
  endif;  
  if ($retBool && $f_serial_no != "" && ($f_serial_no >= "100" && $f_serial_no <= "220")) :
     // $retBool = false;
  endif;  
  return $retBool;
}

// Current file to be imported
$posLastSlash = strripos($importFile, "/");
$posLastSlash++;
$pathname = substr($importFile, 0, $posLastSlash);
$filename = substr($importFile, $posLastSlash);
$outText = "<span class=\"f10bp1_blue\">" . getLngt("IMPORTDATEI:") . "</span>&nbsp;" . $filename . "<br><br>";

if ($executeImportProcess == "1") :

   if ($importFile != "") : 
   
      $importFile = urldecode($importFile);
   
      if (file_exists($importFile)) :
   
         set_time_limit(30000);  // Execution-Time for script
         $currentTime = getDateTime("0");

         $outReportArray[] = $outText;


         // *************************
         // * IMPORT FILE (PTCU_GB) *
         // *************************
         if (!(strpos($filename, "(PTCU_GB)") === false)) :

            // Activate buffering
            if ($flushActivated) :
               ob_start();
            endif;

            $rowToImport = array();
            /*
            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
            */
            $rowToImport[0]   = "f_md";
            $rowToImport[1]   = "f_vu";
            $rowToImport[2]   = "f_at_match";
            $rowToImport[3]   = "f_serial_no";
            $rowToImport[4]   = "f_timestamp_raw";
            $rowToImport[5]   = "f_gb_type";
            $rowToImport[6]   = "f_gb_serialno";
            $rowToImport[7]   = "f_dummy_1";
            $rowToImport[8]   = "f_pos";
            $rowToImport[9]   = "f_currency";
            $rowToImport[10]  = "f_quality_rating";
            $rowToImport[11]  = "f_amount_debit";   // SOLL
            $rowToImport[12]  = "f_amount_actual";  // IST !!!
            $rowToImport[13]  = "f_dummy_2";
            $rowToImport[14]  = "f_dummy_3";
            $rowToImport[15]  = "f_dummy_4";
            $rowToImport[16]  = "f_dummy_5";
            $rowToImport[17]  = "f_timestamp_raw_2";
            $rowToImport[18]  = "f_dummy";

            $rowToImportLen = count($rowToImport);

            // Get num of lines in the file
            $numOfLines = getNumOfLinesOfFile($importFile);

            // Compute chunks with max. 5000 lines
            $chunkSize = 5000;
            $numOfFileChunks = getChunksOfFile($importFile, $chunkSize);
            
            if ($flushActivated) :
               echo "numOfLines: " . $numOfLines . "<br>";
               echo "chunkSize: " . $chunkSize . "<br>";
               echo "numOfFileChunks: " . $numOfFileChunks . "<br>";
            endif;

            // Iterate chunks
            for ($c = 1; $c <= $numOfFileChunks; $c++) :

                // Read file to import
                $lineFrom = (($c - 1) * $chunkSize);
                $lineTo = ($c * $chunkSize) - 1;

                if ($flushActivated) :
                    echo "interval: " . $lineFrom . " - " . $lineTo . "<br><br>";
                endif;

                $data = importCSV($importFile,$delimiter,"",$lineFrom,$lineTo);
                $dataLen = count($data);

                $startlineOfChunk = 0;
                if ($c == 1) : $startlineOfChunk = 1; endif;

                // Loop all rows
                // Ignore header in first row, start with $j = 1
                for ($j = $startlineOfChunk; $j < $dataLen; $j++) :
                
                   if ($flushActivated && $flushEachLine) :
                      echo pad(($j + $lineFrom),5) . ".: ";
                   endif;
                
                   // Loop for all fields of $fields of the row
                   for ($i = 0; $i < $rowToImportLen; $i++) {
                       ${$rowToImport[$i]} = $data[$j][$i];
                       if ($flushActivated && $flushEachLine) :
                          echo $data[$j][$i] . "|";
                       endif;
                   }
                   if ($flushActivated && $flushEachLine) :
                      echo "<br>";
                      ob_flush(); flush();
                   endif;
                
                   $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_stk_name = trim($f_stk_name);
                   $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);
                
                   // Remove leading zeros
                   while (substr($f_serial_no, 0, 1) == "0"):
                         $f_serial_no = substr($f_serial_no, 1);
                   endwhile;
                
                   // 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_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";
                      
                      // 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;
                
                               // *** START DATABASE ACCESS ***
                               if ($fire) :
                                  TA("B");

                                  // writeToFile("../log/runtime.log", $j);
                                  if (false && $flushActivated) :
                                     if (($j % 100) == 0) :
                                        echo "Datasets executed: " . $j . "<br>";
                                        ob_flush(); flush();
                                     endif;
                                  endif;

                                  // 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), "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));
                
                                  TA("C");
                                  TA("E");
                               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;  // $doImport
                endfor;  // Rows
            endfor;  // Chunks

            // After the data are imported, compute the major probability regarding the service intervals
            // Do this here and store the current states into "articleitem", because a realtime computation is not to be recommended
            if ($fire) :
               $rootStockSU = getParameterValue("0", "SU_STK_ROOT", $hq_id);    // Get root stock where all service units belong to
               if ($rootStockSU != "" && is_numeric($rootStockSU)) :
                  $suSerialNoArray = getColVectorFromDB2ArrayByClause("phoenix.articleitem", "ati_serialno", "", "", "");
                  $suSerialNoArrayLen = count($suSerialNoArray);
                  for ($i = 0; $i < $suSerialNoArrayLen; $i++) :
                      // $probabilityToNextServiceMax = getSuHistoryData("2", "AND stk.stk_pre_id = '" . $rootStockSU . "' AND atih.atih_serialno = '" . $suSerialNoArray[$i] . "'");
                      // updateStmt("phoenix.articleitem", "ati_serialno", $suSerialNoArray[$i], array("ati_data_18", $probabilityToNextServiceMax));
                      // // $outReportArray[] = $suSerialNoArray[$i] . " <- Serviceinterval neu berechnet: " . $probabilityToNextServiceMax;

                      $serviceStatisticDataArray = getSuHistoryData("2", "AND stk.stk_pre_id = '" . $rootStockSU . "' AND atih.atih_serialno = '" . $suSerialNoArray[$i] . "'", "", "2");
                      $probabilityToNextServiceMax = $serviceStatisticDataArray[0];
                      $averageIncreaseValues = implode(",", $serviceStatisticDataArray[1]);
                      updateStmt("phoenix.articleitem", "ati_serialno", $suSerialNoArray[$i], array("ati_data_18", $probabilityToNextServiceMax, "ati_data_26", $averageIncreaseValues));
                  endfor;
               endif;
            endif;

            if (!$fire) :
               $outReportArray[] = getLngt("Der Importprozess für die Ereignisse ist derzeit ausgeschaltet!");
            else :
               $outReportArray[] = getLngt("Anzahl importierter Automatenzustandsdaten:") . " " . ($dataLen - 1) . " [Datei: " . $importFile . "]";
               // Remove file after import
               unlink($importFile);
               $refreshParent = "1";
            endif;
            
            // Deactivate buffering and flush data
            if ($flushActivated) :
               ob_end_flush();
            endif;


         // *************************
         // * IMPORT FILE (PTCU_GS) *
         // *************************
         elseif (!(strpos($filename, "(PTCU_GS)") === false)) :

            $rowToImport = array();
            /*
            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
            */
            $rowToImport[0]   = "f_md";
            $rowToImport[1]   = "f_vu";
            $rowToImport[2]   = "f_at_match";
            $rowToImport[3]   = "f_serial_no";
            $rowToImport[4]   = "f_timestamp_raw";            
            $rowToImport[5]   = "f_gs_prio";
            $rowToImport[6]   = "f_gs_x1";
            $rowToImport[7]   = "f_gs_x2";
            $rowToImport[8]   = "f_gs_prio_bm";
            $rowToImport[9]  = "f_dummy";
            
            $rowToImportLen = count($rowToImport);
            
            // Read file to import
            $data = importCSV($importFile,$delimiter);
            $dataLen = count($data);

            // Loop all rows
            // Ignore header in first row, start with $j = 1
            for ($j = 1; $j < $dataLen; $j++) :
            
               // Loop for all fields of $fields of the row
               for ($i = 0; $i < $rowToImportLen; $i++) {
                   ${$rowToImport[$i]} = $data[$j][$i];
               }
            
               $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_stk_name = trim($f_stk_name);
               $f_gs_prio = trim($f_gs_prio);
               $f_gs_prio_bm = trim($f_gs_prio_bm);

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

               // 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_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_gs_prio != "" && $f_gs_prio_bm != "") :
                  
                           // *** START DATABASE ACCESS ***
                           if ($fire) :
                              TA("B");
                  
                              // Get current field values regarding the article message (error) level
                              $currGsPrio   = getFieldValueFromClause("phoenix.articleitem", "ati_data_15", "stk_id = '" . $f_stk_id . "' AND at_id = '" . $f_at_id . "' AND ati_serialno = '" . $f_serial_no . "'");
                              if ($currGsPrio == "") : $currGsPrio = "0"; endif;
                              $currGsPrioBM = getFieldValueFromClause("phoenix.articleitem", "ati_data_16", "stk_id = '" . $f_stk_id . "' AND at_id = '" . $f_at_id . "' AND ati_serialno = '" . $f_serial_no . "'");
                              if ($currGsPrioBM == "") : $currGsPrioBM = "0"; endif;
                              $currGsDate   = getFieldValueFromClause("phoenix.articleitem", "ati_data_17", "stk_id = '" . $f_stk_id . "' AND at_id = '" . $f_at_id . "' AND ati_serialno = '" . $f_serial_no . "'");
                  
                              // Update prio state of the serviceunit in table "articleitem" if the persistent value is lower than the current value
                              if ($f_gs_prio > $currGsPrio || $currGsDate == "") :
                                 // updateStmt("phoenix.articleitem", "ati_serialno", $f_serial_no, array("ati_data_15", $f_gs_prio, "ati_data_16", $f_gs_prio_bm, "ati_data_17", $f_timestamp), "at_id = '" . $f_at_id . "' AND stk_id = '" . $f_stk_id . "'");
                                 updateStmt("phoenix.articleitem", "ati_serialno", $f_serial_no, array("ati_data_16", $f_gs_prio . "|" . $f_gs_prio_bm . "|" . $f_timestamp), "at_id = '" . $f_at_id . "' AND stk_id = '" . $f_stk_id . "'");
                              endif;
                  
                              TA("C");
                              TA("E");
                           endif;
                        else :
                           $outReportArray[] = getLngt("Es existiert kein Wert für die Prio der Betriebsmeldung!") . " [" . $f_at_match . " " . $f_serial_no . " " . $f_timestamp . " " . $f_gs_prio . " " . $f_gs_prio_bm . "]";
                        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;
            
            if (!$fire) :
               $outReportArray[] = getLngt("Der Importprozess für die Gerätestatus ist derzeit ausgeschaltet!");
            else :
               $outReportArray[] = getLngt("Anzahl importierter Automatenmeldungen über den Status:") . " " . ($dataLen - 1) . " [Datei: " . $importFile . "]";
               // Remove file after import
               unlink($importFile);
               $refreshParent = "1";
            endif;


         // **************************
         // * IMPORT FILE (PTCG_GM) *
         // **************************
         elseif (!(strpos($filename, "(PTCG_GM)") === false)) :

            $rowToImport = array();
            /*
            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	;
            */
            $rowToImport[0]   = "f_md";
            $rowToImport[1]   = "f_vu";
            $rowToImport[2]   = "f_at_match";
            $rowToImport[3]   = "f_atm_code";
            $rowToImport[4]   = "f_atm_desc";
            $rowToImport[5]   = "f_atm_text";
            $rowToImport[6]   = "f_dummy_1";
            $rowToImport[7]   = "f_dummy_2";
            $rowToImport[8]   = "f_atm_prio";
            $rowToImport[9]   = "f_dummy_3";
            
            $rowToImportLen = count($rowToImport);
            
            // Read file to import
            $data = importCSV($importFile,$delimiter);
            $dataLen = count($data);
            
            // Loop all rows
            // Ignore header in first row, start with $j = 1
            for ($j = 1; $j < $dataLen; $j++) :
            
               // Loop for all fields of $fields of the row
               for ($i = 0; $i < $rowToImportLen; $i++) {
                   ${$rowToImport[$i]} = $data[$j][$i];
               }

               $f_md = trim($f_md);
               $f_vu = trim($f_vu);
               $f_at_match = trim($f_at_match);
               $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,"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!");
                           endif;
                        else :
                           $outReportArray[] = getLngt("Die Automatentyp ") . $f_at_match . getLngt(" existiert nicht!");
                        endif;

                        TA("C");
                        TA("E");
                     endif;
                  endif;
               endif;
            endfor;
            
            if (!$fire) :
               $outReportArray[] = getLngt("Der Importprozess für die Gerätestatus ist derzeit ausgeschaltet!");
            else :
               $outReportArray[] = getLngt("Anzahl importierter Automatenmeldungen über den Status:") . " " . ($dataLen - 1) . " [Datei: " . $importFile . "]";
               // Remove file after import
               unlink($importFile);
               $refreshParent = "1";
            endif;


         // **************************
         // * IMPORT FILE (PTCU_BM2) *
         // **************************
         elseif (!(strpos($filename, "(PTCU_BM2)") === false)) :

            // Clean up all persistent message codes in "articleitem"
            if ($fire) :
               updateStmt("phoenix.articleitem", "", "", array("ati_data_17", ''), "ati_data_17 != ''");
            endif;

            $rowToImport = array();
            /*
            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;"";;""
            */
            $rowToImport[0]   = "f_md";
            $rowToImport[1]   = "f_vu";
            $rowToImport[2]   = "f_at_match";
            $rowToImport[3]   = "f_serial_no";
            $rowToImport[4]   = "f_timestamp_raw";
            $rowToImport[5]   = "f_atm_code";
            $rowToImport[6]   = "f_atm_desc";
            $rowToImport[7]   = "f_atm_text";
            $rowToImport[8]   = "f_atm_text2";
            $rowToImport[9]   = "f_dummy_1";
            $rowToImport[10]  = "f_dummy_2";
            $rowToImport[11]  = "f_service_usr_name";
            $rowToImport[12]  = "f_servicedatetime_raw";
            $rowToImport[13]  = "f_dummy_3";
            $rowToImport[14]  = "f_dummy_4";
            $rowToImport[15]  = "f_dummy_5";
            $rowToImport[16]  = "f_dummy_6";
            $rowToImport[17]  = "f_dummy_7";
            
            $rowToImportLen = count($rowToImport);
            
            // Read file to import
            $data = importCSV($importFile,$delimiter);
            $dataLen = count($data);
            
            // Loop all rows
            // Ignore header in first row, start with $j = 1
            for ($j = 1; $j < $dataLen; $j++) :
            
               // Loop for all fields of $fields of the row
               for ($i = 0; $i < $rowToImportLen; $i++) {
                   ${$rowToImport[$i]} = $data[$j][$i];
               }

               $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_stk_name = trim($f_stk_name);
               $f_atm_code = trim($f_atm_code);
               $f_service_usr_name = trim($f_service_usr_name);

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

               // 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_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)
                              $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 . "'");
                  
                              // 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("Die 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;
            
            if (!$fire) :
               $outReportArray[] = getLngt("Der Importprozess für die Gerätestatus ist derzeit ausgeschaltet!");
            else :
               $outReportArray[] = getLngt("Anzahl importierter Automatenmeldungen über den Status:") . " " . ($dataLen - 1) . " [Datei: " . $importFile . "]";
               // Remove file after import
               unlink($importFile);
               $refreshParent = "1";
            endif;


         // *************************
         // * IMPORT FILE (PTCG_G) *
         // *************************
         elseif (!(strpos($filename, "(PTCG_G)") === false)) :
         
            $rowToImport = array();
            /*
            MANDANT;VU;GERAETEART;GERAET;HALTESTELLE;STANDORT
            */
            $rowToImport[0]   = "f_md";
            $rowToImport[1]   = "f_vu";
            $rowToImport[2]   = "f_at_match";
            $rowToImport[3]   = "f_serial_no";      // Seriennr. FA
            $rowToImport[4]   = "f_stk_name";       // Lagerortname (Baumwall, etc)
            $rowToImport[5]   = "f_ati_data_01";    // Standorttext (Ausgang A, etc.)

            $rowToImport[6]  = "f_dummy";
            /*
            $rowToImport[6]   = "f_com_mode";       // Kommunikationsmodus (F = Offline, L = Online)
            $rowToImport[7]   = "f_tgn";            // Techn. Identifikation. 
            $rowToImport[8]   = "f_tga";            // Technische Geräteart
            $rowToImport[9]   = "f_state_target";   // Sollzustand
            $rowToImport[10]  = "f_timestamp_raw";  // Zeitstempel
            $rowToImport[11]  = "f_dummy";
            */

            $rowToImportLen = count($rowToImport);

            // Read file to import
            $data = importCSV($importFile,$delimiter);
            $dataLen = count($data);

            // Loop all rows
            // Ignore header in first row, start with $j = 1
            for ($j = 1; $j < $dataLen; $j++) :

               // Loop for all fields of $fields of the row
               for ($i = 0; $i < $rowToImportLen; $i++) {
                   ${$rowToImport[$i]} = $data[$j][$i];
               }

               $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_stk_name = trim($f_stk_name);
               $f_ati_data_01 = trim($f_ati_data_01);
               $f_com_mode = trim($f_com_mode);
               $f_tgn = trim($f_tgn);
               $f_tga = trim($f_tga);
               $f_state_target = trim($f_state_target);
               $f_timestamp_raw = trim($f_timestamp_raw);

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

               // 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) :
                  $currAtiId = getFieldValueFromClause("phoenix.articleitem", "ati_id", "ati_serialno = '" . $f_serial_no . "'");
                  if ($currAtiId != "") :
                     $doImport = false;
                     // $outReportArray[] = getLngt("Der Automat mit der Nummer") . " " . $f_serial_no . " " . getLngt("existiert schon!");
                  endif;
               endif;

               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";

                  // 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);
                  $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.)

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

                     // 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;

                     // 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;
            
            if (!$fire) :
               $outReportArray[] = getLngt("Der Importprozess für die Gerätestatus ist derzeit ausgeschaltet!");
            else :
               $outReportArray[] = getLngt("Anzahl geprüfter Datensätze:") . " " . ($dataLen - 1) . " [Datei: " . $importFile . "]";
               // Remove file after import
               unlink($importFile);
               $refreshParent = "1";
            endif;


         // *************************
         // * IMPORT FILE (PTCU_XX) *
         // *************************
         elseif (!(strpos($filename, "(PTCU_XX)") === false)) :



         endif;
      else :
         $statusMessage .= getLngt("Die angegebene Datei existiert nicht!");
      endif;
   else :
      $statusMessage .= getLngt("Es wurde keine Datei spezifiziert!");
   endif;
endif;


// Output report entries and system messages
$outReport = "";
$outReportArrayLen = count($outReportArray);
if ($outReportArrayLen > 0) :
   $maskDisplay00Switch = "1";   // Activate output if there is at least one message to be displayed
   $outReport .= "<table width=\"100%\" border=\"0\">";
   for ($j = 0; $j < $outReportArrayLen; $j++) :
       $outReport .= "<tr><td><span class=\"f8np1_red\">" . $outReportArray[$j] . "</span></td></tr>";
   endfor;
   $outReport .= "</table>";
endif;
?>

<html>
<head>
<title><?php echo $pageTitel ?></title>
<link rel="stylesheet" type="text/css" href="../css/phoenix.css">
<style type="text/css">
  <?php include_once ("../css/navigation.css.php"); ?>
</style>

<?php include_once ("../include/js_framework.inc.php"); ?>

<script type="text/javascript">
<!--
// NAVIGATION
<?php echo $jsMenuOut; ?>

/*
function finishPageExecuteImportProcess(f_act) {  
  document.forms[0].f_act.value=f_act;
  document.forms[0].executeImportProcess.value = '1';
  document.forms[0].submit();
};
*/

function onBodyLoad() {
	displayStatusMessage();
	var closeWindow = '<?php echo $closeWindow ?>';
	if (closeWindow == '1') {
     opener.document.forms[0].submit();
     window.close();
  };
	var refreshParent = '<?php echo $refreshParent ?>';
	if (refreshParent == '1') {
     opener.document.forms[0].submit();
  };
};

function finishPageExecuteImportProcess(f_act, button_name) {
  notDisabled = checkButtonIsDisabled(button_name);
  if (notDisabled) {
  	 disabledButtons = new Array('action_import','action_close');
     document.forms[0].f_act.value=f_act;
     document.forms[0].executeImportProcess.value = '1';
     document.forms[0].submit();
  }
};

function finishPageCloseWindow(button_name) {
  notDisabled = checkButtonIsDisabled(button_name);
  if (notDisabled) {
  	 disabledButtons = new Array('action_import','action_close');
     window.close();
  }
}
-->
</script>

</head>

<body onLoad="<?php echo $phpCurrentNavigationOnLoad ?>onBodyLoad();">

<?php echo $phpMenuOut ?>
<?php echo $phpReducedMenuOut ?>
<?php echo $phpPageTitelOut ?>

<div class="maincontent" name="maincontent" id="maincontent">

  <div>
    <form name="import_form" action="../import/import_HHA.php" method="post">
      <input type="hidden" name="f_act" value="">
      <?php echo $phpCurrentNavigationInputHidden ?>
      <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">
      <input type="hidden" name="importFile" value="<?php echo $importFile; ?>">
      <input type="hidden" name="executeImportProcess" value="<?php echo $executeImportProcess; ?>">

      <?php echo htmlDivLineSpacer("10px"); ?>

      <?php
        if ($showExecutionProcessButton && $executeImportProcess != "1") :
           echo "<div>" . $outText . "</div>";
           echo htmlDivLineSpacer("10px");
           echo defineButtonType10(getLngt("Import starten"), "action_import", "finishPageExecuteImportProcess('executeImport','action_import');", "200");
           echo htmlDivLineSpacer("5px");
           echo defineButtonType10(getLngt("Schließen"), "action_close", "finishPageCloseWindow('action_close');", "200");
           echo htmlDivLineSpacer("5px");
        endif;
      ?>

       <?php echo htmlDivLineSpacer("20px"); ?>

      <div>
        <table border="0" margin="10" padding="10">
        	<tr>
        		<td style="vertical-align:top;">
              <?php echo $outReport ?>
            </td>
          </tr>
        </table>    
      </div>
    </form>
  </div>

</div>

</body>

</html>