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


// $doNotIncludeGeocode = true;
include_once ("../import/import.php");
include_once ("../include/services_func.inc.php");
include_once ("../include/inc_vehicle.inc.php");
include_once ("../include/inc_job.inc.php");
// include_once ("../include/inc_parseXML.inc.php");


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


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


getLanguage(__FILE__);

$deactivateMenuStatic = "1";
$pageTitel = getLngt("IMPORT AUFTRÄGE");
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");
getCurrentScript(__FILE__);

// Check for authentication access
$usrAccessArray["hq"] = "1";
authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
if (!(authCheckEmployeeRights($emp_id, "22"))) : gotoReferer("1"); endif;

$empHasAdminRights = false;
$empIdRootAdmin = getEmpIdOfRootAdmin($userTypeName);
if ($empIdRootAdmin != "" && $emp_id == $empIdRootAdmin) : 
   $empHasAdminRights = true;
endif;
$debug = false;
if ($empIdRootAdmin == $emp_id) :
   $debug = false;
endif;


// Writes a string to a file optional with or without linefeed
function writeToLogFile($fileName, $stringToOperate, $mode = 'a', $noLf = "") {
  $fileHandle = fopen($fileName, $mode);
  if ($noLf == "") : $stringToOperate .= "\n"; endif;
  $opCode = fwrite($fileHandle, $stringToOperate);
  fclose($fileHandle);
  return $opCode;
}
$logFilename = "import_toom.log";


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

$currentDate = getDateTime(3);
$currentShortDate = getDateTime(1);
$objType = strtolower($objType);


// Import for special customer ONLY !!!!
$csEid = "";
$cscIdPayer = "";
if ($objType == "cs" && $objId != "" && is_numeric($objId)) :
   $csId = $objId;
endif;
if ($objType == "csc" && $objId != "" && is_numeric($objId)) :
   $cscIdPayer = $objId;
   $csId = getFieldValueFromClause("costcenter", "cs_id", "csc_id = '" . $cscIdPayer . "'");   
endif;
if ($csId != "") : 
   $hqId = getFieldValueFromClause("customer", "hq_id", "cs_id = '" . $csId . "'");
   $csEid = getFieldValueFromClause("customer", "cs_eid", "cs_id = '" . $csId . "'");
endif;
if ($hqId == "") : 
   $hqId = $hq_id;
endif;
$cscIdPayerExtern = getParameterValue("0", "CSC_ID_PAYER_EXTERN", $hqId);

// Init
$jbIdNew = "";
$jbTourdata = "";
$jbTourdataZipcode = "";
$jbTourdataCity = "";
$jbTourdataCountry = "";

$pickUpStationFinishedByDefault = true;


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


// Mapping "tour id" to "vehicle SID"
/*
$tourVehicleArray = array();
$tourVehicleArray["294501"] = "E501";
$tourVehicleArray["294502"] = "E502";
$tourVehicleArray["294503"] = "E503";
$tourVehicleArray["294504"] = "E504";
$tourVehicleArray["294505"] = "E505";
$tourVehicleArray["294506"] = "E506";
$tourVehicleArray["294507"] = "E507";
$tourVehicleArray["294508"] = "E508";
$tourVehicleArray["294509"] = "E509";
$tourVehicleArray["294510"] = "E510";
$tourVehicleArray["294511"] = "E511";
$tourVehicleArray["294512"] = "E512";
$tourVehicleArray["294590"] = "E590";
*/

$tourCourierArray = array();
/*
$tourCourierArray["294501"] = "e8020201";
$tourCourierArray["294502"] = "e8020202";
$tourCourierArray["294503"] = "e8020203";
$tourCourierArray["294504"] = "e8020204";
$tourCourierArray["294505"] = "e8020205";
$tourCourierArray["294506"] = "e8020206";
$tourCourierArray["294507"] = "e8020207";
$tourCourierArray["294508"] = "e8020208";
$tourCourierArray["294509"] = "e8020209";
$tourCourierArray["294510"] = "e8020210";
$tourCourierArray["294511"] = "e8020211";
$tourCourierArray["294512"] = "e8020212";
$tourCourierArray["294590"] = "e8020213";
*/


function mcStrWrap($aStr)
{
	$aStr = str_replace("'", "", $aStr);
	$aStr = removeFieldSigns($aStr);
  // $aStr = str_replace("'", "\'", $aStr);
  /*
  $aStr = utf8_decode($aStr);
  $aStr = str_replace("\"", '', $aStr);
  $aStr = str_replace("ÃŸ", "ß", $aStr);
  $aStr = str_replace("Ã¤", "ä", $aStr);
  $aStr = str_replace("Ã¶", "ö", $aStr);
  $aStr = str_replace("Ã¼", "ü", $aStr);
  $aStr = str_replace("Ã„", "Ä", $aStr);
  $aStr = str_replace("Ã–", "Ö", $aStr);
  $aStr = str_replace("Ãœ", "Ü", $aStr);
  */
  return $aStr;
}


echo "importFile" . $importFile . "<br>";
echo "hqId" . $hqId . "<br>";
echo "csId" . $csId . "<br>";

if ($importFile != "" && $hqId != "" && is_numeric($hqId) && $csId != "" && is_numeric($csId)) :

   if (file_exists($importFile)) :

      $currentTime = getDateTime("0");
      
      // Get meta customer of the current customer
      $csIdParent = getFieldValueFromId("customer","cs_id",$csId,"cs_id_parent");
      $hqIdCsParent = getFieldValueFromId("customer","cs_id",$csIdParent,"hq_id");

      // The filename contains the execution day !!!!
      $tmpJbOrdertime = substr($filename,-12,8);
      $jbOrdertime = substr($tmpJbOrdertime,0,4) . "-" . substr($tmpJbOrdertime,4,2) . "-" . substr($tmpJbOrdertime,6,2) . " 08:00:00";
// echo $jbOrdertime . "<br>";
      // $jbOrdertime = checkDateTimeFormat($jbOrdertime);    // DISABLED BECAUSE OF PHP VERSION ONLY !!! ACTIVATE AFTER MIGRATION !!!
      $checkGmtdatetimeIsValid = strtotime($jbOrdertime);
// echo $checkGmtdatetimeIsValid . "<br>";
      if ($checkGmtdatetimeIsValid != "" && is_int($checkGmtdatetimeIsValid)):

         // ***********************
         // * IMPORT FILE article *
         // ***********************
         if (!(strpos($filename, $csEid . "_import_TOOM_") === false)) :

            $executionCount = 0;
            $insertCount = 0;
            $updateCount = 0;
            $failedCount = 0;

            $remTourNo = "";
            $jbIdNew = 0;
            $trSort = 0;    // Init for 1st station
            $tratSort = 1;  // Init all serial numbers !!!!

            // Array für Preis-/Leistungstypnamen
            $jbCalcNameArr = array();
            // $jbCalcNameArr["vht"] = array("LKW 1 To.", "Kran");
            $jbCalcNameArr["sz"] = "Spätzustellung";
            $jbCalcNameArr["fu"] = "Uhrzeit";
            $jbCalcNameArr["sdd"] = "same-day";
            $jbCalcNameArr["1mh"] = "Verwendungsstelle";
            $jbCalcNameArr["2mh"] = "2-Mann";

            $rowToImport = array();

            $parImportFieldsGroup == "";
            if ($groupId != "") :
               $parImportFieldsGroup = getParameterValue("0", "IMPORT_TOOM_JOB_FIELDS", "0");
            endif;
            if ($parImportFieldsGroup != "") :
               $rowToImport = spliti(",", $parImportFieldsGroup);
            else :
               /*
               Nr.	Tour Bezeichnung	Tourelement Bezeichnung	Auftrag Bemerkungen	Tourelement Position in Tour	Tourelement PLZ	Tourelement Ort	Tourelement Straße	Tourelement Hausnummer	Tourelement Ankunft	Tourelement Abfahrt	Tourelement Strecke	Auftrag Fixe Dauer
               */

               $rowToImport[0]  = "f_jb_tourname";         // A : Tour (v = vormittags, n = nachmittags)
               $rowToImport[1]  = "f_tr_sort";             // B : Lfd der Station
               $rowToImport[2]  = "f_tr_commission_no";    // C : Belegnummer
               $rowToImport[3]  = "f_tr_comp";             // D : Kunde / Frima
               $rowToImport[4]  = "f_ad_data";             // E : Adresse
               $rowToImport[5]  = "f_tr_phone";            // F : Telefon
               $rowToImport[6]  = "f_tr_mobile";           // G : Mobil
               $rowToImport[7]  = "f_tr_remark";           // H : Wareninfo
               $rowToImport[8]  = "f_palettes";            // I : Anzahl Paletten
               $rowToImport[9]  = "f_tr_remark2";          // J : Weitere Bemerkungen
               $rowToImport[10] = "f_tr_remark3";          // K : Zusatz-Leistungen
               // $rowToImport[11] = "f_jb_calculator";       // L : Calculator-Vektoren
               // $rowToImport[12] = "f_dummy_01";            // M : ?
               $rowToImport[11] = "f_vht_type";            // L : Fahrzeugtyp (1 = Kran, ansonsten "Default LKW")
               $rowToImport[12] = "f_jb_calc_sz";          // M : Calculator.Spätzustellung (1 = JA, ansonsten NEIN)
               $rowToImport[13] = "f_jb_calc_fu";          // N : Calculator.FixeUhrzeit (Format "H:i")
               $rowToImport[14] = "f_jb_calc_sdd";         // O : Calculator.SameDayDelivery (1 = JA, ansonsten NEIN)
               $rowToImport[15] = "f_jb_calc_mh";          // P : Calculator.(1|2)-MannHandling
               $rowToImport[16] = "f_dummy_01";            // Q : ?
            endif;


            $rowToImportLen = count($rowToImport);

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

            // Loop all rows (EXCEPT header row [$j = 1])
            for ($j = 0; $j < $dataLen; $j++) {

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

               $f_jb_tourname = mcStrWrap($f_jb_tourname);
               $f_daytime = "";
               if ($f_jb_tourname != "") :
                  $f_daytime = "Zeitfenster: " . $f_jb_tourname;
               endif;
               if (strtolower($f_jb_tourname) == "v") : 
                  $f_jb_tourname = "Vormittagstour";
               endif;
               if (strtolower($f_jb_tourname) == "n") : 
                  $f_jb_tourname = "Nachmittagstour";
               endif;
               $f_jb_tourname = "TOOM";

               $f_tr_sort = mcStrWrap($f_tr_sort);
               $f_tr_commission_no = mcStrWrap($f_tr_commission_no);

               // Check for existing headline
               if ($j > 0 && ($f_tr_sort != "" && is_numeric($f_tr_sort)) && $f_tr_commission_no != "") :

                  $tmpArray = spliti(":", $f_tr_commission_no);
                  $tmpRemark = $tmpArray[1];
                  $tmpRemark = trim($tmpRemark);
                  $f_tr_commission_no = $tmpArray[0];
                  $f_tr_commission_no = trim($f_tr_commission_no);
   
                  $f_tr_comp = mcStrWrap($f_tr_comp);
                  $f_tr_person = $f_tr_comp;
   
                  $f_ad_data = mcStrWrap($f_ad_data);
                  $tmpArray = spliti(",", $f_ad_data);
                  $f_ad_street = $tmpArray[0];
                  if ($f_tr_hsno == "") :
                     $f_tr_hsno = ".";
                  endif;
                  $tmpArray[1] = str_replace ("D -", "", $tmpArray[1]);
                  $tmpArray[1] = str_replace ("D-", "", $tmpArray[1]);
                  $tmpArray[1] = trim($tmpArray[1]);
                  if (!is_numeric(substr($tmpArray[1],0,1))) :
                     $pos = strpos("-",$tmpArray[1]);
                     if ($pos === false) : $pos = 0; endif;
                     $f_ad_zipcode = substr($tmpArray[1],0,($pos + 1)) . "-" . preg_replace('/[^0-9]/', '', $tmpArray[1]);
                     $f_ad_city = preg_replace('/[^a-zäöü]/i', '', substr($tmpArray[1],1));  // Without first char (being the letter for the country)
                  else :
                     $f_ad_zipcode = preg_replace('/[^0-9]/', '', $tmpArray[1]);
                     $f_ad_zipcode = substr(trim($f_ad_zipcode),0,5);
                     $f_ad_city = preg_replace('/[^a-zäöü]/i', '', $tmpArray[1]);
                  endif;
                  $f_ad_city = trim($f_ad_city);
   
                  $f_tr_phone = trim($f_tr_phone);
                  if ($f_tr_phone != "") :
                     $f_tr_phone = mcStrWrap($f_tr_phone);
                     $f_tr_phone = eregPhoneNo($f_tr_phone);
                  endif;

                  $f_tr_mobile = trim($f_tr_mobile);
                  if ($f_tr_mobile != "") :
                     $f_tr_mobile = mcStrWrap($f_tr_mobile);
                     $f_tr_mobile = eregPhoneNo($f_tr_mobile);
                  endif;
   
                  $f_tr_remark = mcStrWrap($f_tr_remark);
                  $f_palettes = mcStrWrap($f_palettes);
                  $f_tr_remark2 = mcStrWrap($f_tr_remark2);
                  $f_tr_remark3 = mcStrWrap($f_tr_remark3);

                  $f_tr_remark = $tmpRemark . ",\n" . $f_tr_remark . ",\n" . $f_tr_remark2 . ",\n" . $f_palettes . ",\n" . $f_tr_remark3;
                  if ($f_daytime != "") :
                     $f_tr_remark .= ",\n" . $f_daytime;
                  endif;

                  if ($f_tr_phone == "") : 
                     $f_tr_phone = $f_tr_mobile;
                  else :
                     if ($f_tr_mobile != "") : 
                        $f_tr_remark .= ",\n" . $f_tr_mobile;
                     endif;
                  endif;

                  // $f_jb_calculator = mcStrWrap($f_jb_calculator);
                  $f_jb_calc_sz = mcStrWrap($f_jb_calc_sz);
                  $f_jb_calc_fu = mcStrWrap($f_jb_calc_fu);
                  $f_jb_calc_sdd = mcStrWrap($f_jb_calc_sdd);
                  $f_jb_calc_mh = mcStrWrap($f_jb_calc_mh);

/*
3142 		40512 	IWV 30 km-Radius 	  	2016-09-26 16:07:13
3141 		40512 	IWV 20 km-Radius 	  	2016-09-26 16:06:45
3140 		40512 	IWV 10 km-Radius 	  	2016-09-26 16:06:16
3139 		40512 	Wartezeit / 30 Min. 	  	2016-09-26 16:05:47
3138 		40512 	Kran Mindestabrechnung 	  	2016-09-26 15:59:34
3137 		40512 	Kran Mehrstunde 	  	2016-09-26 16:00:10
3135 		40512 	same-day delivery 	  	2016-09-26 13:42:22
3134 		40512 	Fixe Uhrzeit 	  	2016-09-26 13:41:41
3133 		40512 	SpÃ¤tzustellung >17:00 Uhr 	  	2016-09-26 13:41:20
3132 		40512 	2-Mann-Handling / 30 Min. 	  	2016-09-26 13:40:40
3131 		40512 	Frei Verwendungsstelle / 30 Min. 	  	2016-09-26 13:39:56
3130 		40512 	Mehrkilometer 	  	2016-09-26 13:37:13
3129 		40512 	30 km-Radius 	  	2016-09-26 13:37:03
3128 		40512 	20 km-Radius 	  	2016-09-26 13:36:56
3127 		40512 	10 km-Radius 	  	2016-09-26 13:36:47
*/
                  $f_jb_calc_arr = array();
                  if ($f_jb_calc_sz == "1") :
                     $f_jb_calc_arr[] = "sz";
                  endif;
                  if ($f_jb_calc_fu != "") :
                     // Get start hour an start minute from fixed time
                     $tmpHour = substr($f_jb_calc_fu, 0, 2);
                     $tmpMinute = substr($f_jb_calc_fu, 3, 2);
                     if (is_numeric($tmpHour) && is_numeric($tmpMinute) && $tmpHour >= 0 && $tmpHour <= 23 && $tmpHour >= 0 && $tmpHour <= 59) :
                        $f_jb_calc_arr[] = "fu";
                        $jbOrdertime = substr($jbOrdertime, 0, 10) . " " . pad($tmpHour, 2) . ":" . pad($tmpMinute, 2) . ":" . "00";
                     endif;
                  endif;
                  if ($f_jb_calc_sdd == "1") :
                     $f_jb_calc_arr[] = "sdd";
                  endif;
                  if ($f_jb_calc_mh == "1") :
                     $f_jb_calc_arr[] = "1mh";
                  elseif ($f_jb_calc_mh == "2") :
                     $f_jb_calc_arr[] = "2mh";
                  endif;

                  $f_vht_type = mcStrWrap($f_vht_type);

                  $vhtId = "70";
                  $jbCalcNameArr["vht"] = "Fzg.";
                  if ($f_vht_type == "1") :
                    $vhtId = "990";
                    $jbCalcNameArr["vht"] = "Kran";
                  endif;

                  // Set vehicle and courier
                  $crId = "";
                  /*
                  $crSid = $tourVehicleArray[$f_jb_tourname];
                  if ($crSid != "") :
                     $crId = getFieldValueFromId("courier","cr_sid",$crSid,"cr_id");
                  endif;
   
                  $crEid = $tourCourierArray[$f_jb_tourname];
                  if ($crEid != "") :
                     $crId = getFieldValueFromId("courier","cr_eid",$crEid,"cr_id");
                  endif;
                  */

                  $jbStatus = "9";
                  $jbTaketime = "";
                  if ($crId != "" && is_numeric($crId)) :
                     $jbStatus = "1";
                     $jbTaketime = $currentTime;
                  endif;
                  $jbType = "2";
                  $jbFinishtime = "";
                  $jbRemark = "";
                  $jbCrFilter = "";
                  $sum_totalprice = 0;
                  $f_jb_cr_price = 0;
                  $jbCrvhWeight = 0;
                  $jbCrvhLength = 0;
                  $jbCrvhWidth = 0;
                  $jbCrvhHeight = 0;
                  $jbCrvhPosition = 0;

                  /*
                  echo $f_jb_tourname . ";" . $f_tr_sort . ";" . $f_tr_commission_no . ";";
                  echo $f_ad_street . ";" . $f_ad_zipcode . ";" . $f_ad_city . ";";
                  echo $f_tr_phone . ";" . $f_tr_mobile . ";" . $f_tr_remark;
                  echo "<br>";
                  */
                  echo "------------------------------------------------------<br>";
                  echo "f_jb_tourname: " . $f_jb_tourname . "<br>";
                  echo "f_tr_sort: " . $f_tr_sort . "<br>";
                  echo "f_tr_commission_no: " . $f_tr_commission_no . "<br>";
                  echo "f_ad_street: " . $f_ad_street . "<br>";
                  echo "f_ad_zipcode: " . $f_ad_zipcode . "<br>";
                  echo "f_ad_city: " . $f_ad_city . "<br>";
                  echo "f_tr_phone: " . $f_tr_phone . "<br>";
                  echo "f_tr_mobile: " . $f_tr_mobile . "<br>";
                  echo "f_tr_remark: " . $f_tr_remark . "<br>";                  
   
                  // Check for existence of the imported "tour name" AND "station number" (unique for station)
                  $gdcEntryExists = false;
                  if (existsEntry("genericdatacontainer",array("gdc_obj_type","tr","gdc_gen_fieldname","check_exist","gdc_content",$f_tr_commission_no . " " . $f_tr_sort . " " . $currentShortDate,"gdc_context","TOOM"))) :
                     $gdcEntryExists = true;
                  endif;
   
                  // Do NOT import if TOOM number does exist !!!!
                  if (!$gdcEntryExists) :
   
                     // Insert new article
                     if ($executeImportProcess == "1") :
   
                        TA("B");
   
                        if ($cscIdPayer == "") :
                           // Get root costcenter
                           $cscIdPayer = getFieldValueFromClause("costcenter", "csc_id", "cs_id = '" . $csId . "' AND (isnull(csc_pre_id) OR csc_pre_id = '')");
                        endif;
   /*             
                        $crId = "";
                        $crSid = "";
                        if ($crvhId != "") :
                           $crId = getFieldValueFromId("couriervehicle","crvh_id",$crvhId,"cr_id");
                           if ($crId != "") :
                              $crSid = $vhtPrefix . $f_crvh_sid;
                           endif;
                        endif;
   */             
                        $txValue = "4";
                        $txSign = "V";
                        $noValidationOfAddress = true;
   
                        if ($remTourNo == "" || $remTourNo == $f_jb_tourname) :
                           if ($jbTourdataZipcode != "") : $jbTourdataZipcode .= ";"; endif;
                           $jbTourdataZipcode .= $f_ad_zipcode;
                           if ($jbTourdataCity != "") : $jbTourdataCity .= ";"; endif;
                           $jbTourdataCity .= $f_ad_city;
                           if ($jbTourdataCountry != "") : $jbTourdataCountry .= ";"; endif;
                           $jbTourdataCountry .= "DE";
                        endif;
   
                        // Insert address
                        if ($f_ad_street == "" || $f_ad_zipcode == "" || $f_ad_city == "") :
                           $noValidationOfAddress = "1";
                        endif;
                        $tmpArray = insertAddress($f_ad_street, $f_ad_zipcode, $f_ad_city, "", $f_ad_country, $noValidationOfAddress);
                        $ad_id_new = $tmpArray[0];
                  
                        $outText .= "AD_ID : " . $ad_id_new . " | ";
                  
                  
                        if ($fire) :
                  
                           // Insert new job because new cartage note does begin
                           if ($remTourNo == "" || $remTourNo != $f_jb_tourname) :
   
                              // Finalize currently imported job
                              // Write "jb_tourdata" of the job currently imported
                              if ($remTourNo != "" && $jbIdNew != "" && is_numeric($jbIdNew)) :
                                 $jbTourdata = $jbTourdataZipcode . "|" . $jbTourdataCity . "|" . $jbTourdataCountry;
                                 updateStmt("job","jb_id",$jbIdNew,array("jb_tourdata",$jbTourdata));
                              endif;
   
                              // Remove existing tourname
                              updateStmt("job","jb_tourname",$f_jb_tourname,array("jb_tourname",""), "jb_tourname = '" . $f_jb_tourname . "'");
   
                              // Tour data                           
                              /*
                              if ($jbIdNew != "" && is_numeric($jbIdNew)) :
                              //    updateStmt("job","jb_id",$jbIdNew,array("jb_tourdata",$jbTourdata));
                              endif;
                              */               
   
                              $jbIdNew = "";  // Init
   
                              // Insert job
                              insertStmt("job", array("hq_id", $hqId, "csc_id", "", "vht_id", $vhtId, "csc_id_payer", $cscIdPayer, "csc_id_related", "0", "jb_payment", "0",
                                                      "jb_ordertime", $jbOrdertime, "jb_reserv", "1", "cr_id", $crId, "cr_sid", $crSid, "cr_id_order", $crId,
                                                      "jb_cr_filter", $jbCrFilter, "jb_cr_filter_opt", "", "jb_waitstorno", "0", 
                                                      "jb_taketime", $jbTaketime, "jb_status", $jbStatus, "jb_autoranking", "0", "jb_type", $jbType, 
                                                      "jb_incomplete", "0", "jb_globaljob", "0", "jb_tourname", $f_jb_tourname,
                                                      "jb_finishtime", $jbFinishtime, "emp_id", $usr_id, 
                                                      "jb_serviceprice", "0", "jb_fixprice", $sum_totalprice, "jb_totalprice", $sum_totalprice, "jb_subtotalprice", $sum_totalprice, 
                                                      "jb_cr_price", $f_jb_cr_price, "jb_cr_subprice", $f_jb_cr_price,
                                                      "jb_postage", "0", "jb_freetext_1", $jbRemark,
                                                      "jb_weight", $jbCrvhWeight, "jb_crvh_length", $jbCrvhLength, "jb_crvh_width", $jbCrvhWidth, 
                                                      "jb_crvh_height", $jbCrvhHeight, "jb_crvh_position", $jbCrvhPosition, 
                                                      "jb_tourdata", $jbTourdata, "jb_createtime", $currentTime, "jb_lockuser", "0", "jb_id_parent", "0", "jb_dispoinfo", "",
                                                      "jb_sales_tax_rate", $txValue, "jb_sales_tax_rate_sign", $txSign, "jb_timeunits", "0", 
                                                      "jb_service", "", "jb_booktime", ""));
                              $jbIdNew = getLastInsertId();                        

                              $trSort = 0;    // Init for 1st station
                              $tratSort = 1;  // Init all serial numbers !!!!
                              $remTourNo = $f_jb_tourname;
                              
                              // Init for the next job to be imported
                              $jbTourdata = "";
                              // Init with current values
                              $jbTourdataZipcode = $f_ad_zipcode;
                              $jbTourdataCity = $f_ad_city;
                              $jbTourdataCountry = "DE";                           
                           endif;
   
   
                           // Check for inserted job
                           if ($jbIdNew != "") :
                  
                              $trSort++;
                  
                              insertStmt("tour", array("jb_id", $jbIdNew, "ad_id", $ad_id_new, "tr_sort", $trSort, "tr_comp", $f_tr_comp, "tr_comp2", "",
                                                       "tr_hsno", $f_tr_hsno, "csc_id", $cscIdPayerExtern, "tr_status", "0", 
                                                       "tr_commission_no", $f_tr_commission_no, "tr_ware_from_to", "", 
                                                       "tr_person", $f_tr_person, "tr_phone", $f_tr_phone, "tr_remark", $f_tr_remark, "tr_cs_freetext", $f_tr_cs_freetext));
                              $trIdNew = getLastInsertID();
                  
                   
                              // Insert tourservice data
   /*
                              insertStmt("tourservice", array("tr_id", $trIdNew, "jb_id", $jbIdNew, "csc_id", $cscIdPayer, "tr_sort", $trSort, 
                                                              "srv_id", "0", "trs_srv_name", "Fixpreis", "srvt_id", "0", "trs_srvt_name", "",
                                                              "trs_price", $sum_totalprice));
   */                                                           
                              insertStmt("tourservice", array("jb_id", $jbIdNew, "csc_id", $cscIdPayer, "tr_sort", $trSort, "srv_id", "0", "trs_srv_name", "Fixpreis", "srvt_id", "0", "trs_srvt_name", "", "trs_price", $sum_totalprice));

                              // Positions
                              // insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trIdNew, "gdc_gen_fieldname", "trat_sum_volume", "gdc_content", $f_palettes, "gdc_context", "TOOM"));

                              // Generate invoice text
                              // mk_jb_invtext($jbIdNew, false);
   
                  
                              // Tourname
                              // insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trIdNew, "gdc_gen_fieldname", "info_0", "gdc_content", $f_tr_commission_no . " " . $f_tr_sort . " " . $currentShortDate, "gdc_context", "TOOM"));
                              insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trIdNew, "gdc_gen_fieldname", "check_exist", "gdc_content", $f_tr_commission_no . " " . $f_tr_sort . " " . $currentShortDate, "gdc_context", "TOOM"));

                              // Services
                              $strServices = "SZ=" . $f_jb_calc_sz . "|" . "FU=" . $f_jb_calc_fu . "|" . "SDD=" . $f_jb_calc_sdd . "|" . "MH=" . $f_jb_calc_mh;
                              insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trIdNew, "gdc_gen_fieldname", "services", "gdc_content", $strServices, "gdc_context", "TOOM"));

                              // Insert tourarticle data (delivery stations)
                              /*
                              insertStmt("tourarticle", array("tr_id", $trIdNew, "jb_id", $jbIdNew, "tr_sort", $trSort, "trat_sort", "1", "at_id", "", "trat_quantity", "0", 
                                                              "trat_weight", $f_trat_weight, "trat_price", "0", "trat_packingpieces", $f_trat_packingpieces, "trat_serialno", $f_tr_commission_no, 
                                                              "trat_remark", $f_trat_remark, "trat_createtime", $currentTime));
                              */
                  
                              // Insert tourarticle data (pick up station only)
                              // ATTENTION: Execution only if pick-up station is NOT finished by default
                              /*
                              if (!$pickUpStationFinishedByDefault) :
                                 insertStmt("tourarticle", array("tr_id", $trIdPickUpNew, "jb_id", $jbIdNew, "tr_sort", "1", "trat_sort", $tratSort, "at_id", "", "trat_quantity", "0", 
                                                                 "trat_weight", $f_trat_weight, "trat_price", "0", "trat_packingpieces", $f_trat_packingpieces, "trat_serialno", $f_tr_commission_no, 
                                                                 "trat_remark", $f_trat_remark, "trat_createtime", $currentTime));
                                 $tratSort++;
                              endif;
                              */

                              // Insert jobcalculator data
                              /*
                              if ($f_jb_calculator != "") :
                                 $f_jb_calculator = str_replace("|", "-,-", $f_jb_calculator);
                                 $trCalcItemArray = spliti("§§", $f_jb_calculator);
                                 $numOfCalcItems = count($trCalcItemArray);
                                 if ($numOfCalcItems > 0) :
                                    for ($k = 0; $k < $numOfCalcItems; $k++) :
                                        $jbCalcArray = spliti("-,-", $trCalcItemArray[$k]);
                                    
                                        // Get srv_id and srvt_id, both has to exist (!!!!)
                                        $tmpSrvId = getFieldValueFromClause("service","srv_id","srv_mode = '1' AND cs_id = '" . $csId . "' AND srv_name = '" . $jbCalcArray[0] . "'");
                                        $tmpSrvtId = getFieldValueFromClause("servicetype","srvt_id","srvt_mode = '1' AND cs_id = '" . $csId . "' AND srvt_name = '" . $jbCalcArray[1] . "'");
                                        if ($tmpSrvId == "" || $tmpSrvId == "0" || $tmpSrvtId == "" || $tmpSrvtId == "0") :
                                           $tmpSrvId = getFieldValueFromClause("service","srv_id","srv_mode = '1' AND cs_id = '" . $csIdParent . "' AND srv_name = '" . $jbCalcArray[0] . "'");
                                           $tmpSrvtId = getFieldValueFromClause("servicetype","srvt_id","srvt_mode = '1' AND cs_id = '" . $csIdParent . "' AND srvt_name = '" . $jbCalcArray[1] . "'");
                                        endif;
                                        if ($tmpSrvId != "" && $tmpSrvtId != "") :
                                           // Get price from service matrix
                                           $jbCalcPrice = getServiceValues($tmpSrvId, $tmpSrvtId, $csId, $hqId, $currentTime, 1);
                                           if ($jbCalcPrice == "" || $jbCalcPrice == "0") :
                                              // Try to get price from meta customer
                                              $jbCalcPrice = getServiceValues($tmpSrvId, $tmpSrvtId, $csIdParent, $hqIdCsParent, $currentTime, 1);
                                              // If price empty or "0" then take price from request
                                              // if ($jbCalcPrice == "" || $jbCalcPrice == "0") :
                                              //    $jbCalcPrice = $trCalcItemArray[$i][$j]["price"];
                                              // endif; 
                                           endif;
                                           insertStmt("jobcalculator", array("jb_id", $jbIdNew, "tr_id", $trIdNew, "tr_sort", $trSort, "srv_id", $tmpSrvId, "srv_name", $trCalcItemArray[$i][$k]["pricetype"], 
                                                                             "srvt_id", $tmpSrvtId, "srvt_name", $trCalcItemArray[$i][$k]["servicetype"], 
                                                                             "jbc_amount", $trCalcItemArray[$i][$k]["quantity"], "jbc_price", $jbCalcPrice, 
                                                                             "jbc_totalprice", ($trCalcItemArray[$i][$k]["quantity"] * $jbCalcPrice)));
                                        endif;
                                    endfor;
                                 endif;
                              endif;
                              */
// writeToLogFile($logFilename, "0 :: CS_CSPARENT_JB_TR :: " . $csId . " " . $csIdParent . " " . $jbIdNew . " " . $trIdNew);
// writeToLogFile($logFilename, "1 :: CALC_ARRAY :: " . $f_jb_calc_arr[0] . " " . $f_jb_calc_arr[1] . " " . $f_jb_calc_arr[2] . " " . $f_jb_calc_arr[3] . " " . $f_jb_calc_arr[4]);
                              // $f_jb_calc_arr_keys = array_keys($f_jb_calc_arr);
                              // $f_jb_calc_arr_keys_len = count($f_jb_calc_arr_keys);
                              $f_jb_calc_arr_len = count($f_jb_calc_arr);
// writeToLogFile($logFilename, "2 :: CALC_ARRAY_LEN :: " . $f_jb_calc_arr_len);
// writeToLogFile($logFilename, "3 :: START ITER");
                              for ($k = 0; $k < $f_jb_calc_arr_len; $k++) :
                                  $calcKey = $f_jb_calc_arr[$k];  // "sz", "fu", "sdd", "1mh", "2mh", ....
// writeToLogFile($logFilename, "3.a :: calcKey :: " . $calcKey);
// writeToLogFile($logFilename, "3.a2 :: cs.jbCalcNameArr[vht] :: " . $jbCalcNameArr["vht"]);
// writeToLogFile($logFilename, "3.a3 :: cs.jbCalcNameArr[$calcKey] :: " . $jbCalcNameArr[$calcKey]);
                                  // Get srv_id and srvt_id, both has to exist (!!!!)
                                  $csIdForServiceNames = $csId;
                                  $tmpSrvId = getFieldValueFromClause("service","srv_id","srv_mode = '1' AND cs_id = '" . $csId . "' AND srv_name LIKE '%" . $jbCalcNameArr["vht"] . "%'");
// writeToLogFile($logFilename, "3.b :: cs.tmpSrvId :: " . $tmpSrvId);
                                  $tmpSrvtId = getFieldValueFromClause("servicetype","srvt_id","srvt_mode = '1' AND cs_id = '" . $csId . "' AND srvt_name LIKE '%" . $jbCalcNameArr[$calcKey] . "%'");
// writeToLogFile($logFilename, "3.c :: cs.tmpSrvtId :: " . $tmpSrvtId);
                                  if ($tmpSrvId == "" || $tmpSrvId == "0" || $tmpSrvtId == "" || $tmpSrvtId == "0") :
                                     $csIdForServiceNames = $csIdParent;
                                     $tmpSrvId = getFieldValueFromClause("service","srv_id","srv_mode = '1' AND cs_id = '" . $csIdParent . "' AND srv_name LIKE '%" . $jbCalcNameArr["vht"] . "%'");
// writeToLogFile($logFilename, "3.d :: cs_parent.tmpSrvId :: " . $tmpSrvId);
                                     $tmpSrvtId = getFieldValueFromClause("servicetype","srvt_id","srvt_mode = '1' AND cs_id = '" . $csIdParent . "' AND srvt_name LIKE '%" . $jbCalcNameArr[$calcKey] . "%'");
// writeToLogFile($logFilename, "3.e :: cs_parent.tmpSrvtId :: " . $tmpSrvtId);
                                  endif;
                                  if ($tmpSrvId != "" && $tmpSrvtId != "") :
// writeToLogFile($logFilename, "3.f :: IDS OK!");
                                     // Get full name of service and servicetype
                                     $tmpSrvName = getFieldValueFromClause("service","srv_name","srv_mode = '1' AND cs_id = '" . $csIdForServiceNames . "' AND srv_id = '" . $tmpSrvId . "'");
// writeToLogFile($logFilename, "3.g :: tmpSrvName :: " . $tmpSrvName);
                                     $tmpSrvtName = getFieldValueFromClause("servicetype","srvt_name","srvt_mode = '1' AND cs_id = '" . $csIdForServiceNames . "' AND srvt_id = '" . $tmpSrvtId . "'");
// writeToLogFile($logFilename, "3.h :: tmpSrvtName :: " . $tmpSrvtName);
                                     // Get price from service matrix
// writeToLogFile($logFilename, "3.i :: BEFORE PRICE REQUEST!");
                                     $jbCalcPrice = getServiceValues($tmpSrvId, $tmpSrvtId, $csId, $hqId, $currentTime, 1);
// writeToLogFile($logFilename, "3.j :: cs.jbCalcPrice :: " . $jbCalcPrice);
                                     if ($jbCalcPrice == "" || $jbCalcPrice == "0") :
                                        // Try to get price from meta customer
                                        $jbCalcPrice = getServiceValues($tmpSrvId, $tmpSrvtId, $csIdParent, $hqIdCsParent, $currentTime, 1);
// writeToLogFile($logFilename, "3.k :: cs_parent.jbCalcPrice :: " . $jbCalcPrice);
                                        // If price empty or "0" then take price from request
                                        // if ($jbCalcPrice == "" || $jbCalcPrice == "0") :
                                        //    $jbCalcPrice = $trCalcItemArray[$i][$j]["price"];
                                        // endif; 
                                     endif;
// writeToLogFile($logFilename, "3.l :: BEFORE INSERT!");
                                     insertStmt("jobcalculator", array("jb_id", $jbIdNew, "tr_id", $trIdNew, "tr_sort", $trSort, "srv_id", $tmpSrvId, "srv_name", $tmpSrvName, 
                                                                       "srvt_id", $tmpSrvtId, "srvt_name", $tmpSrvtName, "jbc_amount", "1", "jbc_price", "0", "jbc_totalprice", "0"));
// writeToLogFile($logFilename, "3.l :: AFTER INSERT!");
                                  endif;
                              endfor;
// writeToLogFile($logFilename, "3.z :: END ITER");
// writeToLogFile($logFilename, "----------------------------------------------------");
                           endif;

                           TA("C");
                           TA("E");
                        endif;
                     endif;
                  else :
                     $outText .= getLngt("Der Datensatz existiert schon! Es erfolgte kein Import!") . " [" . $f_order_id .  "]<br>";
                  endif;    
               endif;  // Check for headline
            }
            
            // If at least onne imported job does exist ($jbIdNew > 0) then finalize last imported job
            // Write "jb_tourdata" of the job currently imported
            if ($jbIdNew != "" && is_numeric($jbIdNew)) :
               $jbTourdata = $jbTourdataZipcode . "|" . $jbTourdataCity . "|" . $jbTourdataCountry;
               updateStmt("job","jb_id",$jbIdNew,array("jb_tourdata",$jbTourdata));
            endif;
   
            $outText .= getLngt("Einträge in der Importdatei: " . $dataLen . "<br>");
            $outText .= getLngt("Verarbeitete Einträge: " . $executionCount . "<br>");
         else :
            $statusMessage .= getLngt("Die angegebene Datei scheint nicht kompatibel zur angeforderten Importfunktionalität!");
         endif;
      else :
         $statusMessage .= getLngt("Das Datum für den Ausführungstag im Dateinamen scheint nicht korrekt! Bitte folgendes Format für den Dateinamen verwenden: import_TOOM_YYYYMMDD.csv");
      endif;
   else :
      $statusMessage .= getLngt("Die angegebene Datei existiert nicht!");
   endif;
else :
   $statusMessage .= getLngt("Es wurde keine Datei spezifiziert!");
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();
  };
};
-->
</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_TOOM.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; ?>">
      <input type="hidden" name="objType" value="<?php echo $objType; ?>">
      <input type="hidden" name="objId" value="<?php echo $objId; ?>">

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

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

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

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

</div>

</body>

</html>