<?php
/*=======================================================================
 *
 * import_saturn.php
 *
 * Autor: Marc Vollmann, Carsten Annacker
 *
 * ToDoS :
 * [1] Configuration in php.ini: 
 *     "file_uploads", "upload_max_filesize", "upload_tmp_dir", "post_max_size"
 * [2] Change tables "tour" and "tourhistory"
 *     ALTER TABLE `tour` ADD `tr_cs_freetext` TEXT;
 *     ALTER TABLE `tourhistory` ADD `tr_cs_freetext` TEXT;
 * [3] Create table "import_log"
 *     CREATE TABLE import (imp_id int(10) NOT NULL default '0',imp_pos smallint(6) NOT NULL default '0', imp_createtime timestamp(14) NOT NULL, jb_id int(10) NOT NULL default '0', UNIQUE KEY imp_id_pos (imp_id,imp_pos)) TYPE=MyISAM;
 * [4] Exportcategoryfields have to be inserted
 *     DELETE FROM `exportcategoryfields` WHERE expc_id = '110'
 *     => Start Insert-Script
 *
 * - Ablauf: Erst Rollkarte, dann Tourenplanung importieren; von letzterer wird nur das ausführende Fahrzeug, der vollständige Name des Kunden
 *   (zusätzlich der Vorname vorhanden), der auftraggebende Saturn-Markt, das ausführendes Fahrzeug, die Kundennummer des Kunden bei Saturn
 *    übernommen und anhand der Belegnummer der bestehenden Rollkartenstation zugeordnet
 * - Nur eine Datei pro Upload möglich, bearbeitete Datei wird gelöscht --> ok so?
 * - Tourenplanung enthält weniger Belege als Rollkarte, d.h einige Stationen verbleiben ohne vollständigen Namen in der Adresse
 * --> unvollständige Stationen verbleiben, wenn das normal ist, dann muss jb_incomplete gepflegt werden
 * - Welche Bedeutung haben die auftraggebenden Märkte für die Tourenplanung?
=======================================================================*/

include_once ("import.php");
include_once ("xServer.inc.php");

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

$importPath = "../import/upload_saturn/";
$tempPath = "../temp/upload_saturn/";

// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "statusMessage", "f_importFile", "f_uploadFile"));

// Select user-type for mode of security check 
$userType = getFieldValueFromId("user","usr_id",$usr_id,"usr_type");
$userTypeName = getUserTypeName($userType);

// Get the rights of the employee logged in and check the accessibility
if (!authCheckEmployeeRights($emp_id, "7")) : die ("$PHP_SELF: Access denied!"); endif;

$statusMessage = "";
$importFileStatusMsg = "";
$jbIdNew = "";

// Get number of files in the upload folder
$numOfFiles = getNumOfFilesInFolder($importPath);

// Process uploaded file
if ($f_act == "uploadFile") :

   if ($numOfFiles < 1) :

      if ($_FILES['f_uploadFile']['size'] <= 2000000) :

         if (!move_uploaded_file($_FILES['f_uploadFile']['tmp_name'], $importPath . $_FILES['f_uploadFile']['name'])) :
            $statusMessage .= "Die Datei wurde leider nicht hochgeladen!";
         endif;
      else :
         $statusMessage .= "Die Datei ist für den Upload zu groß!";
      
         // Delete real file if does exist
         $retVal = removeFile($_FILES['f_uploadFile']['name'], $importPath, $pathSeparator); 
      endif;
      
      // Delete temp file if does exist
      $retVal = removeFile($_FILES['f_uploadFile']['tmp_name'], $tempPath, $pathSeparator); 
   else :
      $statusMessage .= "Bevor eine weitere Datei hochgeladen werden kann, muss das Verzeichnis geleert werden!";
   endif;
endif;

// Manually removal of a specified importfile
if ($f_act == "removeImportfile") :

   // Remove import file
   $retVal = removeFile($f_importFile, $importPath, $pathSeparator);
   
   if ($retVal == "0") :
         
   elseif ($retVal == "-1") :
     $statusMessage = "Es liegt kein Dateiname vor!";
   elseif ($retVal == "-2") :
     $statusMessage = "Die Datei befindet sich nicht mehr in dem Verzeichnis!";
   elseif ($retVal == "") :
     $statusMessage = "Es fand keine Löschung statt!";
   endif;
endif;


// Import process
if ($f_act == "goImport") :

//   if ($numOfFiles == 1) :

/**************************************************
 * Read csv
 **************************************************/
 
      $importFileStatusMsg .= "<br><br><br><br><span class=\"f12bp1_red\" colspan=\"2\">Verarbeitungsprotokoll:</span><br><br>\n";
      $importFileStatusMsg .= "Import-Datei: " . $f_importFile . "<br><br>\n";
  
      // read file to import
      $data = importCSV($importPath . $f_importFile);
      $dataLen = count($data);
      $impType = 0;
      // find out whether current file ist Rollkarte oder Tourenplanung
      if (count($data[0]) == 12): // Rollkarte
        $impType = 1;
        $impName = "Rollkarte";
      elseif (count($data[0]) == 19): // Tourenplanung
        $impType = 2;
        $impName = "Tourenplanung";
      else:
        die('Fehler: Importdatei hat ungültige Anzahl von Spalten.');
      endif;

/**************************************************
 * aggregate lines to stops
 **************************************************/

      $file_csv = file_get_contents($importPath . $f_importFile);
      writeLog($f_importFile . "\n" . $file_csv, "import_saturn_csv");

//print_r($data); die();
      $tourA = array();
      // loop all rows
      $j = 0;
      $i = 0;
      $cr_sids = array(); // nur Tourenplanung
      $f_hq_id = "102";   // Hamburg
      $trCscIdRoot = "44540";   // Hauptkostenstelle Kunde "Extern"
      
      while ($j < $dataLen):
        if ($impType == 1): // Rollkarte
          // get current documentnumber
          $cur_documentnumber = $data[$j][3];
          $i++;
          while (trim($data[$j][3]) == $cur_documentnumber && $j < $dataLen):
            // loop for all fields of $fields of the row
//            $tourA[$i]["f_jb_ordertime"] = trim($data[$j][1]);                                    // delivery date
//            $tourA[$i]["f_tr_ware_from_to"] = trim($data[$j][2]);                                 // time-limit: G=0=full-time, V=1=ante meridiem, N=2=post meridiem
            $tourA[$i]["f_tr_person"] = trim($data[$j][3]);                                       // documentnumber (Belegnummer) Saturn (stored in tr_persopn because of searchability)
            $tourA[$i]["f_tr_remark"] .= str_replace("\\\\", "|", trim($data[$j][4]) . " " . trim($data[$j][5]) . " " . trim($data[$j][6])) . "\n";
                                                                                                  // arcticlenumber Saturn, arcticledescription1 Saturn, arcticledescription2 Saturn
            $tourA[$i]["f_tr_remark1"] = str_replace("\\\\", "|", trim($data[$j][11]));                                     // rest of description
//            $tourA[$i]["f_tr_comp"] = trim($data[$j][7]);                                       // name of customer
            $tourA[$i]["f_ad_street"] = trim($data[$j][8]);                                       // delivery/street
            $tourA[$i]["f_ad_zipcode"] = trim($data[$j][9]);                                     // delivery/zipCode
            $tourA[$i]["f_ad_city"] = (trim($data[$j][10]) == "HH" ? "HAMBURG" : trim($data[$j][10])); // delivery/city
            $j++;
            // rest dummy
            // ignore garbage lines (i.e. no documentnumber)
            while (trim($data[$j][3]) == "" && $j < $dataLen):
              $tourA[$i]["f_tr_remark1"] .= " " . str_replace("\\\\", "|", trim($data[$j][0]));  // rest of previous remarkline
              $j++;
            endwhile;
          endwhile;
        elseif ($impType == 2): // Tourenplanung
          // get current documentnumber
          $cur_documentnumber = $data[$j][6];
          $i++;
          while (trim($data[$j][6]) == $cur_documentnumber && $j < $dataLen):
            // loop for all fields of $fields of the row, negative numbers are ignored
            if (trim($data[$j][10]) != "-1"):
              $tourA[$i]["f_jb_ordertime"] = trim($data[$j][0]);                        // delivery date
              $tourA[$i]["f_tr_ware_from_to"] = trim($data[$j][1]);                     // time-limit: G=0=full-time, V=1=ante meridiem, N=2=post meridiem
              $tourA[$i]["f_tr_mediationarea_name"] = trim($data[$j][2]);               // Auftraggebender Saturn-Markt
              $cr_sid_parts = explode(" ", trim($data[$j][4]));                         // ausführendes Fahrzeug in brauchbare cr_sid verwandeln...
              $tourA[$i]["f_jb_cr_sid"] = "HH" . $cr_sid_parts[count($cr_sid_parts) - 1];
              $tourA[$i]["f_jb_cr_id"] = getFieldValueFromId("couriervehicle", "crvh_sid", $tourA[$i]["f_jb_cr_sid"], "cr_id");
              $tourA[$i]["f_jb_vht_id"] = getFieldValueFromId("couriervehicle", "crvh_sid", $tourA[$i]["f_jb_cr_sid"], "vht_id");
              $tourA[$i]["f_tr_comp2"] = trim($data[$j][5]);                            // Kundennummer des Kunden bei Saturn
              $tourA[$i]["f_tr_person"] = trim($data[$j][6]);                           // Beleggnummer Saturn
              $tourA[$i]["f_tr_comp"] = trim($data[$j][7]) . ", " . trim($data[$j][8]); // Nachname, Vorname des Kunden
              // rest dummy
              // ignore garbage lines (i.e. no documentnumber)
            endif;
            $j++;
            while (trim($data[$j][6]) == "" && $j < $dataLen): $j++; endwhile;
          endwhile;
        else:
          die('Fehler: Ungültiger Importtyp.');
        endif;
      endwhile;
//print_r($tourA); die();

/**************************************************
 * write stops to job and tour
 **************************************************/

      $allCoords = array();
      $doPlan = array();
      TA("BEGIN");
      foreach ($tourA AS $tour) {
         // Check import log table in db according to the unique key "f_tr_person"
         $logJbId = getFieldValueFromClause("phoenix_log.import","jb_id","imp_id = '" . $tour["f_tr_person"] . $impType . "'");

         if ($logJbId == "" && $tour["f_tr_person"] != "Beleg-Nr.") :

            if ($impType == 1): // Rollkarte

              // find corresponding Tourenplanung
              $jbIdNew = getFieldValueFromClause("phoenix_log.import","jb_id","imp_id = '" . $tour["f_tr_person"] . 2 . "'");
//                  writeToLogDB("55", $hq_id, $jbIdNew, $usr_id, $tour["f_jb_cr_id"], $tour["f_jb_cr_sid"], $csId, "Import Rollkarte");

              if ($jbIdNew != ''):
                // Get address id
                $tour["f_ad_street"] = str_replace(".", ". ", $tour["f_ad_street"]);
                $f_ad_street_parts = explode(" ", $tour["f_ad_street"]);
                $f_ad_street = $f_ad_street_parts[0];
                $f_tr_hsno = "";
                if (count($f_ad_street_parts) > 1):            
                  $f_tr_hsno = $f_ad_street_parts[1];
                  if (count($f_ad_street_parts) > 2):
                    if (strlen($f_ad_street_parts[count($f_ad_street_parts) - 1]) == 1):
                      if (ord(strtoupper($f_ad_street_parts[count($f_ad_street_parts) - 1])) >= ord("A")
                        && ord(strtoupper($f_ad_street_parts[count($f_ad_street_parts) - 1])) <= ord("Z")):
                        $f_tr_hsno = $f_ad_street_parts[count($f_ad_street_parts) - 2] . " " . $f_ad_street_parts[count($f_ad_street_parts) - 1];
                        for ($k = 1; $k < count($f_ad_street_parts) - 2; $k++)
                          $f_ad_street .= " " . $f_ad_street_parts[$k];
                      else:
                        for ($k = 1; $k < count($f_ad_street_parts) - 1; $k++)
                          $f_ad_street .= " " . $f_ad_street_parts[$k];
                        $f_tr_hsno = $f_ad_street_parts[count($f_ad_street_parts) - 1];
                      endif;
                    else:
                      for ($k = 1; $k < count($f_ad_street_parts) - 1; $k++)
                        $f_ad_street .= " " . $f_ad_street_parts[$k];
                      $f_tr_hsno = $f_ad_street_parts[count($f_ad_street_parts) - 1];
                    endif;
                  endif;
                endif;
$txt = "Suche Koordinaten für Adresse " . $tour["f_ad_zipcode"] . " " . $tour["f_ad_city"] . " " . $f_ad_street . " " . $f_tr_hsno . " ...";
echo $txt; flush();
writeLog($txt, "import_saturn");
                $coords = XSfindAddress("D", $tour["f_ad_zipcode"], $tour["f_ad_city"], $f_ad_street, $f_tr_hsno);
                $invalidAddressCur = 1;
                if ($coords[0][0] != 100) {
$txt = " kein exakter Match<br>\n";
echo $txt; flush();
writeLog($txt, "import_saturn");
                  $importFileStatusMsg .= "Fehlerhafte Adresse in Belegnummer [" . $tour["f_tr_person"] . "]: [" .
                    $tour["f_ad_zipcode"] . " " . $tour["f_ad_city"] . " " . $f_ad_street . " " . $f_tr_hsno . "]. <b>Routenoptmierung nicht möglich!</b><br>\n";
                  $invalidAddressCur = -1;
                } else {
$txt = " ok<br>\n";
echo $txt; flush();
writeLog($txt, "import_saturn");
                  $allCoords[] = array($coords[0][1], $coords[0][2]);
                  $f_tr_cs_freetext = $coords[0][1]  . "," . $coords[0][2];
                }
                $tmpArray = insertAddress($f_ad_street, $tour["f_ad_zipcode"], $tour["f_ad_city"], "", "", true);
                $ad_id_new = $tmpArray[0];
              endif;
            elseif  ($impType == 2): // Tourenplanung
               // nur ein Auftrag pro Fahrer!
              $jbIdNew = "";
              $fTrSort = 2;
              $f_jb_ordertime = substr($tour["f_jb_ordertime"],6,4) . "-" . substr($tour["f_jb_ordertime"],3,2) . "-" . substr($tour["f_jb_ordertime"],0,2) . " 08:00:00";
              if (!(array_key_exists($tour["f_jb_cr_sid"], $cr_sids))):
                // check, whether jobs have already been created today in a previous import
writeLog("SELECT jb_id FROM phoenix_log.log WHERE cr_sid = '" . $tour["f_jb_cr_sid"] . "' AND logo_description = 'Import Tourenplanung $f_jb_ordertime'", "import_saturn");
                $jb_id_tmp = $db->getOne("SELECT jb_id FROM phoenix_log.log WHERE cr_sid = '" . $tour["f_jb_cr_sid"] . "' AND logo_description = 'Import Tourenplanung $f_jb_ordertime'");
                if ($jb_id_tmp > 0):
                  $tr_sort_tmp = $db->getOne("SELECT MAX(tr_sort) FROM tour WHERE jb_id = $jb_id_tmp");
                  $cr_sids[$tour["f_jb_cr_sid"]][0] = $jb_id_tmp;
                  $cr_sids[$tour["f_jb_cr_sid"]][1] = $tr_sort_tmp + 2;
                  $jbIdNew = $jb_id_tmp;
                  $fTrSort = $tr_sort_tmp + 1;
writeLog("jbIdNew = $jbIdNew, fTrSort = $fTrSort", "import_saturn");
                else:
                  $cr_sids[$tour["f_jb_cr_sid"]][0] = 0;
                  $cr_sids[$tour["f_jb_cr_sid"]][1] = 3;
                endif;
              elseif ($cr_sids[$tour["f_jb_cr_sid"]][0] > 0):
                $jbIdNew = $cr_sids[$tour["f_jb_cr_sid"]][0];
                $fTrSort = $cr_sids[$tour["f_jb_cr_sid"]][1]++;
//echo "$jbIdNew, $fTrSort<br>\n";
              endif;
            else:
              die('Fehler: Ungültiger Importtyp.');
            endif;

/**************************************************
 * write data to db
 **************************************************/
 
            // Get the current time
            $currentTime = getDateTime("0");

            // Insert job data
            if ($jbIdNew == "" && $impType == 2):

               $jbStatus = "9";
               $jbType = "2";    // "G"
               $csInvmod = "";
               
               $price = 0;
               if (!isset($f_tax_value) || $f_tax_value == ""):                
                  $f_tax_value = getFieldValueFromId("tax","tx_id","4","tx_value");
                  if ($f_tax_value == ""):
                     $f_tax_value = "19.00"; 
                  endif;
               endif;
               $txSign = "V";
 
               $f_price = $price;
               $f_cs_eid_payer = "HTHH30794";

               $csId = getFieldValueFromId("customer","cs_eid",$f_cs_eid_payer,"cs_id");
               $f_csc_id_payer = getFieldValueFromId("customer","cs_eid",$f_cs_eid_payer,"csc_id");
                 // if ($isCashPayerTour): $cscIdRoot = $cscIdCashPayer; endif;
               $csInvmode = getFieldValueFromId("customer","cs_eid",$f_cs_eid_payer,"cs_invmode");
               $cmpPostage = getFieldValueFromId("customer","cs_eid",$f_cs_eid_payer,"cmp_id");
                 if ($cmpPostage == "") : $cmpPostage = "0.00"; endif;
               // Check for absolute customer discount
               $csDiscountAbsolute = getFieldValueFromId("customer", "cs_id", $csId, "cs_discount");
               $useDiscountDisabled = getParameterValue("0", "JB_EDITBATCH_DISCOUNT_DISABLED");
               if ($useDicountDisabled == "1") :
                  $csDiscountAbsolute = 0;
               endif;

               insertStmt("job", array("hq_id", $f_hq_id, "vht_id", $f_vht_id, "csc_id_payer", $f_csc_id_payer, "jb_payment", "0",
                                       "jb_ordertime", $f_jb_ordertime, "jb_reserv", "1", "cr_id", $tour["f_jb_cr_id"], "cr_sid", $tour["f_jb_cr_sid"], "cr_id_order", $tour["f_jb_cr_id"],
                                       "jb_taketime", "", "jb_status", $jbStatus, "jb_autoranking", "0", "jb_type", $jbType, "jb_incomplete", "0", "jb_globaljob", 0,
                                       "jb_tourname", "", "emp_id", $usr_id, "jb_fixprice", $f_price, "jb_totalprice", $f_price,
                                       "jb_postage", $cmpPostage, "jb_invmode", $csInvmode, "jb_freetext_1", "",
                                       "jb_sales_tax_rate", $f_tax_value, "jb_sales_tax_rate_sign", $txSign,));
//               print_r( array("hq_id", $f_hq_id, "vht_id", $f_vht_id, "csc_id_payer", $f_csc_id_payer, "jb_payment", "0",
//                                       "jb_ordertime", $f_jb_ordertime, "jb_reserv", "1", "cr_id", $tour["f_jb_cr_id"], "cr_sid", $tour["f_jb_cr_sid"], "cr_id_order", $tour["f_jb_cr_id"],
//                                       "jb_taketime", "", "jb_status", $jbStatus, "jb_autoranking", "0", "jb_type", $jbType, "jb_tourname", "",
//                                       "emp_id", $usr_id, "jb_fixprice", $f_price, "jb_totalprice", $f_price,
//                                       "jb_postage", $cmpPostage, "jb_invmode", $csInvmode, "jb_freetext_1", "",
//                                       "jb_sales_tax_rate", $f_tax_value, "jb_sales_tax_rate_sign", $txSign,));

               $jbIdNew = getLastInsertId();
               $cr_sids[$tour["f_jb_cr_sid"]][0] = $jbIdNew;


//               $coords = XSfindAddress("D", "22848", "Norderstedt", "Niendorfer Str.", 172);
//               $coords = XSfindAddress("D", "20537", "Hamburg", "Sorbenstr.", 22);
//               $f_tr_cs_freetext = $coords[0][1]  . "," . $coords[0][2];
               // insert first station
               insertStmt("tour", array("jb_id", $jbIdNew, "tr_sort", 1, "ad_id", 117135 /*2229*/, "tr_hsno", 22 /*172*/, "csc_id", $trCscIdRoot, 
                 "tr_remark", "", "tr_cs_freetext", "1003996, 5354938" /*"997928.0000000017,5366139.000000002"*/,
                 "tr_mediationarea_name", "", "tr_comp2", "", "tr_comp", "Master-Express" /*"Haase Logistik GmbH"*/,
                 "tr_commission_no", "07 - 09 Uhr", "tr_ware_from_to", 0, "tr_person", ""));                 

               // Insert tourservice data
               insertStmt("tourservice", array("jb_id", $jbIdNew, "csc_id", $f_csc_id_payer, "tr_sort", "0", 
                                               "srv_id", "0", "trs_srv_name", "Fixpreis", "srvt_id", "0", "trs_srvt_name", "", 
                                               "trs_price", $price, "trs_discount", $csDiscountAbsolute));
//               print_r(array("jb_id", $jbIdNew, "csc_id", $f_csc_id_payer, "tr_sort", "0", 
//                                               "srv_id", "0", "trs_srv_name", "Fixpreis", "srvt_id", "0", "trs_srvt_name", "", 
//                                               "trs_price", $price, "trs_discount", $csDiscountAbsolute));

               // Write logdata into log database
               writeToLogDB("55",$hq_id,$jbIdNew,$usr_id,$tour["f_jb_cr_id"],$tour["f_jb_cr_sid"],$csId, "Import Tourenplanung $f_jb_ordertime");
            endif;

            if ($impType == 1):                
              if ($jbIdNew != ''):              
                updateStmt("tour","jb_id", $jbIdNew, array("ad_id", $ad_id_new, "tr_hsno", $f_tr_hsno, "csc_id", $trCscIdRoot, 
                  "tr_remark", $tour["f_tr_remark"] . $tour["f_tr_remark1"], "tr_cs_freetext", $f_tr_cs_freetext), "tr_person = " . $tour["f_tr_person"]);
                $importFileStatusMsg .= "$impName zu Belegnummer <i>" . $tour["f_tr_person"] . "</i> wurde importiert in Auftrag Nr. <i>" . $jbIdNew . "</i>.<br>\n";
                if ($invalidAddressCur == 1)
                  insertStmt("phoenix_log.import", array("imp_id", ($tour["f_tr_person"] * $invalidAddressCur). $impType, "imp_pos", $fTrSort, "imp_createtime", $currentTime, "jb_id", $jbIdNew));
//                print_r(array("imp_id", $tour["f_tr_person"], "imp_pos", $fTrSort, "imp_createtime", $currentTime, "jb_id", $jbIdNew));
                if (!(array_key_exists($jbIdNew, $doPlan))):
                  $doPlan[$jbIdNew] = 1;
                endif;
                if ($invalidAddressCur != 1):
                  $doPlan[$jbIdNew] = 0;
                endif;
              else:
                $importFileStatusMsg .= "$impName zu Belegnummer <i>" . $tour["f_tr_person"] . "</i> wurde <b>nicht</b> importiert, weil <b>entsprechende Tourenplanung noch nicht vorhanden.</b><br>\n";
              endif;                

            elseif ($impType == 2):
            
              $doNotImport = false;
              $f_tr_commission_no = "";
              // time-limit: G=0=full-time, V=1=ante meridiem, N=2=post meridiem
              switch ($tour["f_tr_ware_from_to"]) {
              case 'G':
                $f_tr_commission_no = "08 - 19 Uhr"; break;
              case 'V':
                $f_tr_commission_no = "08 - 14 Uhr"; break;
              case 'N':
                $f_tr_commission_no = "13 - 19 Uhr"; break;
              case 'E':
                $f_tr_commission_no = "16 - 20 Uhr"; break;
              default:
                $importFileStatusMsg .= "$impName zu Belegnummer <i>" . $tour["f_tr_person"] . "</i> wurde <b>nicht</b> importiert. ";
                $importFileStatusMsg .= "Fehlerhaftes Zeitfenster: [" . $tour["f_tr_ware_from_to"] . "]. Erlaubt sind nur [G], [V], [N], und [E].</b><br>\n";
                $doNotImport = true;
              } 
              
              if (!$doNotImport):
                // Insert tour data for station
                insertStmt("tour", array("jb_id", $jbIdNew, "tr_sort", $fTrSort,
                  "tr_mediationarea_name", $tour["f_tr_mediationarea_name"], "tr_comp2", $tour["f_tr_comp2"], "tr_comp", $tour["f_tr_comp"],
                  "tr_commission_no", $f_tr_commission_no, "tr_ware_from_to", 1, "tr_person", $tour["f_tr_person"]));
                $importFileStatusMsg .= "$impName zu Belegnummer <i>" . $tour["f_tr_person"] . "</i> wurde importiert in Auftrag Nr. <i>" . $jbIdNew . "</i>.<br>\n";
                // Insert into import log table
                insertStmt("phoenix_log.import", array("imp_id", $tour["f_tr_person"] . $impType, "imp_pos", $fTrSort, "imp_createtime", $currentTime, "jb_id", $jbIdNew));
//                print_r(array("imp_id", $tour["f_tr_person"], "imp_pos", $fTrSort, "imp_createtime", $currentTime, "jb_id", $jbIdNew));
              endif;

            else:
              die('Fehler: Ungültiger Importtyp.');
            endif;

         else :
           if ($tour["f_tr_person"] != "Beleg-Nr.")
             $importFileStatusMsg .= "$impName zu Belegnummer <i>" . $tour["f_tr_person"] . "</i> wurde <b>nicht</b> importiert, weil bereits vorhanden in Auftrag Nr. <i>" . $logJbId . "</i>.<br>\n";
         endif;
      }

/**************************************************
 * Plan tour
 **************************************************/

//      if ($doPlan && !$invalidAddress) {
//        $planTour = XSplanTour($allCoords);
//        for ($i = 0; $i < count($planTour); $i++) {
//          updateStmt("tour", "jb_id", $jbIdNew, array("tr_sort", $i + 1), "tr_sort = " . (100 + $planTour[$i]));
//        }
//      }
      TA("COMMIT");
//      $importFileStatusMsg .= "Datei wurde erfolgreich importiert.<br>";
//      if (!$invalidAddress) {
//      } else {
//        TA("ROLLBACK");
//        deleteStmt("phoenix_log.import", "jb_id = $jbIdNew");
//        writeToLogDB("55", $hq_id, $jbIdNew, $usr_id, $tour["f_jb_cr_id"], $tour["f_jb_cr_sid"], $csId, "Import abgebrochen aufgrund fehlerhafter Adresse(n)");
//        $importFileStatusMsg .= "<i>Datei wurde aufgrund fehlerhafter Adresse(n) <b>nicht</b> importiert.</i><br>";
//        $importFileStatusMsg .= "<i>Datei wurde aufgrund fehlerhafter Adresse(n) <b>nicht</b> importiert.</i><br>";
//      }
      TA("END");

      foreach ($doPlan AS $jb_id_plan => $doit) {
        if ($doit == 1):
$txt = "Auftrag $jb_id_plan wird optimiert...";
echo $txt; flush();
writeLog($txt, "import_saturn");
          if (XSplanTourJob($jb_id_plan, 1)):
$txt = " ok!<br>\n";
echo $txt; flush();
writeLog($txt, "import_saturn");
          else:
$txt = " fehlgeschlagen!<br>\n";
echo $txt; flush();
writeLog($txt, "import_saturn");
          endif;
        else:
$txt = "Auftrag $jb_id_plan wird nicht optimiert...<br>\n";
echo $txt; flush();
writeLog($txt, "import_saturn");
        endif;
      }
      
      // Remove import file
      $retVal = removeFile($f_importFile, $importPath, $pathSeparator);
//   else :
//      $importFileStatusMsg .= "Der Import konnte nicht vollzogen werden, da noch mindestens eine andere Importdatei existiert!<br>";
//   endif;

  writeLog($importFileStatusMsg, "import_saturn");
endif;


// **************************************************
// * Read all of the local filenames to be imported *
// **************************************************
if ($userTypeName == "hq") :

   // Get filenames
   $fileNames = getFilenamesInFolder($importPath);

   $storedImportFiles .= "<table>";
   $storedImportFiles .= "<tr><td class=\"f12bp1_red\" colspan=\"2\">Auftragsimport</td></tr>";
   $storedImportFiles .= "<tr><td colspan=\"2\"><br><br></td></tr>";
   // Define table header
   $storedImportFiles .= "<tr><td>Dateiname&nbsp;&nbsp;&nbsp;&nbsp;</td><td>Löschen</td></tr>";
   $storedImportFiles .= "<tr><td colspan=\"2\"><br></td></tr>";

   // Define table body from array
   $fileNamesLen = count($fileNames);
   for ($j = 0; $j < $fileNamesLen; $j++) :
         $storedImportFiles .= "<tr>";
         $storedImportFiles .= "<td><a href=\"javascript:importImportfile('" . $fileNames[$j] . "');\">" . $fileNames[$j] . 
                                   "</a>" . "&nbsp;&nbsp;&nbsp;&nbsp;</td>";
         $storedImportFiles .= "<td align=\"center\"><a href=\"javascript:removeImportfile('" . $fileNames[$j] . "');\">"
                                    . "<img src=\"../images/trash.jpg\" border=\"0\" height=\"13\" width=\"8\">" 
                                    . "</a>" . "&nbsp;&nbsp;&nbsp;&nbsp;</td>";                                   
         $storedImportFiles .= "</tr>";
   endfor;   
   $storedImportFiles .= "</table>";
endif;
?>


<html>
<head>
<title>AUFTRAGSIMPORT</title>
<link rel="stylesheet" type="text/css" href="../css/phoenix.css"> 

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

function displayStatusMessage() {
 if (statusMessage != "") {
    alert(statusMessage);
 }
};

function finishPage(f_act_value) {  
  document.forms[0].f_act.value=f_act_value;
  document.forms[0].submit();
};

function removeImportfile(fileName) {
  if (confirm('Importdatei ' + fileName + ' entfernen?')) {
     document.forms[0].f_importFile.value = fileName;
     finishPage('removeImportfile');
  };
};

function importImportfile(fileName) {
  if (confirm('Importdatei ' + fileName + ' jetzt importieren?')) {
     document.forms[0].f_importFile.value = fileName;
     finishPage('goImport');
  };
};

function finishPageUpload(f_act_value) {  
  document.forms[1].f_act.value=f_act_value;
  document.forms[1].submit();
};
-->
</script>

</head>

<body onLoad="displayStatusMessage();">

  <form name="import_form" action="../import/import_saturn.php" method="post">
    <input type="hidden" name="f_act" value="">
    <input type="hidden" name="f_importFile" value="">    

    <?php echo $storedImportFiles; ?>
  </form>
  
  <br><br>
  
  <form name="upload_file" action="../import/import_saturn.php" enctype="multipart/form-data" method="post">
  <!--  <form name="upload_file" action="../import/upload_file.php" enctype="multipart/form-data" method="post"> -->
    <input type="hidden" name="f_act" value="">
    <p>W&auml;hlen Sie die Auftragsdateidatei von Ihrem Rechner aus:<br>
      <input type="hidden" name="MAX_FILE_SIZE" value="2000000">
      <input name="f_uploadFile" type="file" size="50" accept="text/*">
      <input type="button" value="Upload" onClick="finishPageUpload('uploadFile');">
    </p>
    <br><br>
    <?php echo $importFileStatusMsg; ?>
  </form>

</body>

</html>