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


// $doNotIncludeGeocode = true;
include_once ("../import/import.php");
include_once ("../include/inc_vehicle.inc.php");
include_once ("../include/inc_job.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__);

// Get special user types from parameter
$specialUserTypeIsLoggedIn = false;
$specialUserType = "";
$specialUserHqId = "";
$specialUserFTPServerList = "";
$specialUserDirSpecialForObjType = "";
$userTypesSpecialArray = getDatatransferSpecialUserData($userType);
if (count($userTypesSpecialArray) > 0) :
   $specialUserTypeIsLoggedIn = true;
   list($specialUserType, $specialUserHqId, $specialUserFTPServerList, $specialUserObjType, $specialUserObjId, $specialUserDirSpecialForObjType) = $userTypesSpecialArray;
   if ($objType == $specialUserObjType && $objId == $specialUserObjType) :
      $hqId = $specialUserHqId;
   endif;
endif;

// Check for authentication access
$empHasAdminRights = false;
if (!$specialUserTypeIsLoggedIn) :
   $usrAccessArray["hq"] = "1";
   authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
   if (!(authCheckEmployeeRights($emp_id, "22"))) : gotoReferer("1"); endif;
   
   $empIdRootAdmin = getEmpIdOfRootAdmin($userTypeName);
   if ($empIdRootAdmin != "" && $emp_id == $empIdRootAdmin) : 
      $empHasAdminRights = true;
   endif;
endif;

$debug = false;
if ($empIdRootAdmin == $emp_id) :
   $debug = false;
endif;

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

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


// Import for special customer ONLY !!!!
$csId = "";
$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;
$csAddress = array();
$adIdFrom = 0;
if ($csId != "") : 
   $hqId = getFieldValueFromClause("customer", "hq_id", "cs_id = '" . $csId . "'");
   $csEid = getFieldValueFromClause("customer", "cs_eid", "cs_id = '" . $csId . "'");
   // $csAddress = getAddress($csId, "customer");
   $csAddress = getAddress($csId, "costcenteraddress");
   $adIdFrom = $csAddress["id"];
   $trHsnoFrom = $csAddress["hsno"];
   if ($trHsnoFrom == "") : $trHsnoFrom = "."; endif;
   
   $trCompFrom = $csAddress["comp"];
   if ($trCompFrom == "") : $trCompFrom = "STANDARD_01"; endif;

   $trFloorFrom = "";
   // USE FOLLOWING FIX ADDRESS
   // $adIdFrom = "220594";  // Invoice address
   // $adIdFrom = "125964";  // Pick-up address
   // $trHsnoFrom = "4";
endif;
if ($hqId == "") : 
   $hqId = $hq_id;
endif;
$cscIdPayerExtern = getParameterValue("0", "CSC_ID_PAYER_EXTERN", $hqId);

$pickUpStationFinishedByDefault = true;

// Tourdata array
$jbTourdata = "";
$jbTourdataZipcodeArray = array();
$jbTourdataCityArray = array();
$jbTourdataCountryArray = array();


// Current file to be imported
$importFile = urldecode($importFile);
$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>";


// Mapping "tour id" to "vehicle SID"
$tourVehicleArray = array();
/*
if ($hqId == "nnn") :
   // NL X
   $tourVehicleArray["294501"] = "E501";
   $tourVehicleArray["294502"] = "E502";
   $tourVehicleArray["294503"] = "E503";
   $tourVehicleArray["294504"] = "E504";
   ....
elseif ($hqId == "mmm") :
   // NL Y
endif;
*/

/*
BSP.:
TOUR_NO SID    EID       NAME        FIRSTNAME
294501	E501	 e8020201	 Schmidt	   Alexander	 0176 62283533
294502	E502	 e8020202	 Brazinskas	 Zilvinas	 0152 55904274
294503	E503	 e8020203	 Orakov	     Anton	 0152 01985959
294504	E504	 e8020204	 Isaak	     Alexander	 0152 53172115
....

$tourCourierArray = array();
$tourCourierArray["294501"] = "e8020201";
$tourCourierArray["294502"] = "e8020202";
$tourCourierArray["294503"] = "e8020203";
$tourCourierArray["294504"] = "e8020204";
....
*/

$tourCourierArray = array();
/*
if ($hqId == "nnn") :
   // NL X
   $tourCourierArray["294590"] = "e8020401";  // stepenka 01
   $tourCourierArray["294501"] = "e8020402";  // stepenka 02
   $tourCourierArray["294502"] = "e8020403";  // stepenka 03
   $tourCourierArray["294503"] = "e8020404";  // stepneka 04
   ....
elseif ($hqId == "mmm") :
   // NL Y
endif;

// SID array (fix!)
$tourSIDArray = array();
if ($hqId == "107") :
   // NL X
   $tourSIDArray["294590"] = "E355";
   $tourSIDArray["294501"] = "E356";
   $tourSIDArray["294502"] = "E357";
   $tourSIDArray["294503"] = "E358";
   ....
elseif ($hqId == "110") :
   // NL Y
endif;
*/


function mcStrWrap($aStr)
{
	$aStr = str_replace("'", "", $aStr);
	$aStr = removeFieldSigns($aStr);
  // $aStr = str_replace("'", "\'", $aStr);
  $aStr = str_replace("\"", '', $aStr);
  return $aStr;
}


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

   if (file_exists($importFile)) :

      $currentTime = getDateTime("0");


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

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

         $remTourNo = "";
         $jbIdNew = 0;
         $trSort = 2;    // Init for 2nd station equals first delivery !!!!
         $tratSort = 1;  // Init all serial numbers !!!!

         $jobNewArray = array();
         $useJbNewArray = false;
         $rowToImport = array();
         
         $parImportFieldsGroup == "";
         if ($groupId != "") :
            $parImportFieldsGroup = getParameterValue("0", "IMPORT_STANDARD_01_JOB_FIELDS", "0");
         endif;
         if ($parImportFieldsGroup != "") :
            $rowToImport = spliti(",", $parImportFieldsGroup);
         else :

            $rowToImport[0]  = "f_tour_no";             // A : Tournr. / Tourbezeichnung
            $rowToImport[1]  = "f_shipment_mode";       // B : Lieferung/Abholung
            $rowToImport[2]  = "f_tr_orderdate";        // C : Ausführungsdatum / Ausführungszeitstempel
            $rowToImport[3]  = "f_tr_warningdate";      // D : Zustellungsdatum
            $rowToImport[4]  = "f_tr_starttime";        // E : Zustellung von
            $rowToImport[5]  = "f_tr_endtime";          // F : Zustellung bis
            $rowToImport[6]  = "f_tr_commission_no";    // G : Lieferscheinnummer
            $rowToImport[7]  = "f_order_id";            // H : Kundenauftragsnummer
            $rowToImport[8]  = "f_cs_id_external";      // I : Kundennummer extern / Lieferantennummer
            $rowToImport[9]  = "f_cs_eid";              // J : Kundenummer (EID,intern)
            $rowToImport[10] = "f_tr_comp";             // K : Firma
            $rowToImport[11] = "f_tr_comp2";            // L : Firma Zusatz
            $rowToImport[12] = "f_special_01";          // M : Besteller
            $rowToImport[13] = "f_ad_street";           // N : Straße
            $rowToImport[14] = "f_tr_hsno";             // O : Hausnummer
            $rowToImport[15] = "f_tr_floor";            // P : Etage
            $rowToImport[16] = "f_ad_zipcode";          // Q : PLZ
            $rowToImport[17] = "f_ad_city";             // R : Ort
            $rowToImport[18] = "f_ad_country";          // S : Land
            $rowToImport[19] = "f_ad_supplement_1";     // T : Adresszusatz I
            $rowToImport[20] = "f_ad_supplement_2";     // U : Adresszusatz II
            $rowToImport[21] = "f_tr_person";           // V : Ansprechpartner
            $rowToImport[22] = "f_tr_phone";            // W : Telefon
            $rowToImport[23] = "f_special_02";          // X : Mobiltelefonnummer
            $rowToImport[24] = "f_special_03";          // Y : Emailadresse
            $rowToImport[25] = "f_tr_remark";           // Z : Bemerkung / Zustellinfo
            $rowToImport[26] = "f_id";                  // AA: Sendungsidentifikationsnummer
            $rowToImport[27] = "f_trat_packingpieces";  // AB: Packstücke
            $rowToImport[28] = "f_trat_palets";         // AC: Paletten
            $rowToImport[29] = "f_trat_weight";         // AD: Gewicht
            $rowToImport[30] = "f_special_04";          // AE: Stellplätze
            $rowToImport[31] = "f_special_05";          // AF: Warenart
            $rowToImport[32] = "f_zone_no";             // AG: Zone
            $rowToImport[33] = "f_special_06";          // AH: Inkasso/Rückführung
            $rowToImport[34] = "f_price_type";          // AI: Preistyp
            $rowToImport[35] = "f_service_type";        // AJ: Leistungstyp
            $rowToImport[36] = "f_dummy_01";            // AK: DUMMY_01
         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_tour_no            = mcStrWrap($f_tour_no);            // Tournr. / Tourbezeichnung
            $f_shipment_mode      = mcStrWrap($f_shipment_mode);      // Lieferung/Abholung
            $f_tr_ware_from_to = 0;
            if ($f_shipment_mode == "R") :
               $f_tr_ware_from_to = 1;
            elseif ($f_shipment_mode == "L") :
               $f_tr_ware_from_to = 2;
            endif;
            $f_tr_orderdate       = mcStrWrap($f_tr_orderdate);       // Ausführungsdatum / Ausführungszeitstempel
            $f_tr_warningdate     = mcStrWrap($f_tr_warningdate);     // Zustellungsdatum
            $f_tr_starttime       = mcStrWrap($f_tr_starttime);       // Zustellung von
            $f_tr_endtime         = mcStrWrap($f_tr_endtime);         // Zustellung bis
            $f_tr_commission_no   = mcStrWrap($f_tr_commission_no);   // Lieferscheinnummer
            $f_order_id           = mcStrWrap($f_order_id);           // Kundenauftragsnummer
            $f_cs_id_external     = mcStrWrap($f_cs_id_external);     // Kundennummer extern / Lieferantennummer
            $f_cs_eid             = mcStrWrap($f_cs_eid);             // Kundenummer (votian)
            $f_tr_comp            = mcStrWrap($f_tr_comp);            // Firma
            $f_tr_comp2           = mcStrWrap($f_tr_comp2);           // Firma Zusatz
            $f_special_01         = mcStrWrap($f_special_01);         // Besteller
            $f_ad_street          = mcStrWrap($f_ad_street);          // Straße
            $f_tr_hsno            = mcStrWrap($f_tr_hsno);            // Hausnummer
            if ($f_tr_hsno == "") : $f_tr_hsno = "."; endif;
            $f_tr_floor           = mcStrWrap($f_tr_floor);           // Etage
            $f_ad_zipcode         = mcStrWrap($f_ad_zipcode);         // PLZ
            $f_ad_city            = mcStrWrap($f_ad_city);            // Ort
            $f_ad_country         = mcStrWrap($f_ad_country);         // Land
              if ($f_ad_country == "" || $f_ad_country == "D") : $f_ad_country = "DE"; endif;
            $f_ad_supplement_1    = mcStrWrap($f_ad_supplement_1);    // Adresszusatz I
            $f_ad_supplement_2    = mcStrWrap($f_ad_supplement_2);    // Adresszusatz II
            $f_tr_person          = mcStrWrap($f_tr_person);          // Ansprechpartner
            $f_tr_phone           = mcStrWrap($f_tr_phone);           // Telefon
            $f_special_02         = mcStrWrap($f_special_02);         // Mobiltelefonnummer
            $f_special_03         = mcStrWrap($f_special_03);         // Emailadresse
            $f_tr_remark          = mcStrWrap($f_tr_remark);          // Bemerkung / Zustellinfo
            $f_id                 = mcStrWrap($f_id);                 // Sendungsidentifikationsnummer
            $f_trat_packingpieces = mcStrWrap($f_trat_packingpieces); // Packstücke
            $f_trat_palets        = mcStrWrap($f_trat_palets);        // Paletten
            $f_trat_weight        = mcStrWrap($f_trat_weight);        // Gewicht
              $f_trat_weight = str_replace (",", ".", $f_trat_weight);
            $f_special_04         = mcStrWrap($f_special_04);         // Stellplätze
            $f_special_05         = mcStrWrap($f_special_05);         // Warenart
            $f_zone_no            = mcStrWrap($f_zone_no);            // Zone
            $f_special_06         = mcStrWrap($f_special_06);         // Inkasso/Rückführung
            $f_price_type         = mcStrWrap($f_price_type);         // Preistyp
            $f_service_type       = mcStrWrap($f_service_type);       // Leistungstyp
            $f_dummy_01           = mcStrWrap($f_dummy_01);

            if ($f_special_01 != "") : $f_tr_remark .= "\n<br>" . getLngt("Besteller") . ": " .  $f_special_01; endif;
            if ($f_special_02 != "") : $f_tr_remark .= "\n<br>" . getLngt("Mobiltelefonnummer") . ": " .  $f_special_02; endif;
            if ($f_special_03 != "") : $f_tr_remark .= "\n<br>" . getLngt("Emailadresse") . ": " .  $f_special_03; endif;
            if ($f_id != "") : $f_tr_remark .= "\n<br>" . getLngt("Sendungs-ID") . ": " .  $f_id; endif;
            if ($f_trat_packingpieces != "") : $f_tr_remark .= "\n<br>" . getLngt("Packstücke") . ": " .  $f_trat_packingpieces; endif;
            if ($f_trat_palets != "") : $f_tr_remark .= "\n<br>" . getLngt("Paletten") . ": " .  $f_trat_palets; endif;
            if ($f_trat_weight != "") : $f_tr_remark .= "\n<br>" . getLngt("Gewicht") . ": " .  $f_trat_weight; endif;
            if ($f_special_04 != "") : $f_tr_remark .= "\n<br>" . getLngt("Stellplätze") . ": " .  $f_special_04; endif;
            if ($f_special_05 != "") : $f_tr_remark .= "\n<br>" . getLngt("Warenart") . ": " .  $f_special_05; endif;
            if ($f_zone_no != "") : $f_tr_remark .= "\n<br>" . getLngt("Zone") . ": " .  $f_zone_no; endif;
            if ($f_special_06 != "") : $f_tr_remark .= "\n<br>" . getLngt("Inkasso/Rückführung") . ": " .  $f_special_06; endif;
            if ($f_price_type != "") : $f_tr_remark .= "\n<br>" . getLngt("Preistyp") . ": " .  $f_price_type; endif;
            if ($f_service_type != "") : $f_tr_remark .= "\n<br>" . getLngt("Leistungstyp") . ": " .  $f_service_type; endif;


            // Set vehicle and courier
            $crId = "";
            /*
            $crSid = $tourVehicleArray[$f_tour_no];
            if ($crSid != "") :
               $crId = getFieldValueFromId("courier","cr_sid",$crSid,"cr_id");
            endif;
            */
            $crEid = $tourCourierArray[$f_tour_no];
            if ($crEid != "") :
               $crId = getFieldValueFromId("courier","cr_eid",$crEid,"cr_id");
               $crSid = $tourSIDArray[$f_tour_no];
            endif;
            
            $jbStatus = "9";
            $jbTaketime = "";            
            if ($crId != "" && is_numeric($crId)) :
               // $jbStatus = "1";  // jb_status will be set after the whole job is generated
               $jbTaketime = $currentTime;
               $useJbNewArray = true;
            endif;
            $jbType = "";
            $jbFinishtime = "";
            $jbRemark = "";
            $vhtId = "";
            $jbCrFilter = "";
            $sum_totalprice = 0;
            $f_jb_cr_price = 0;
            $jbCrvhWeight = 0;
            $jbCrvhLength = 0;
            $jbCrvhWidth = 0;
            $jbCrvhHeight = 0;
            $jbCrvhPosition = 0;


            echo $f_id . ";" . $f_tour_no . ";" . $f_shipment_mode . ";" . $f_jb_orderdate . ";" . $f_jb_warningdate . ";" . $f_jb_starttime . ";" . $f_jb_endtime . ";";
            echo $f_tr_commission_no . ";" . $f_order_id . ";" . $f_cs_id_external . ";" . $f_cs_eid . ";" . $f_tr_comp . ";" . $f_tr_comp2 . ";" . $f_special_01 . ";";
            echo $f_tr_remark . ";" . $f_ad_street . ";" . $f_tr_hsno . ";" . $f_tr_floor . ";" . $f_ad_zipcode . ";" . $f_ad_city . ";" . ";" . $f_ad_country;
            echo $f_ad_supplement_1 . ";" . $f_ad_supplement_2 . ";" . $f_tr_person . ";" . $f_tr_phone . ";" . $f_special_02 . ";" . $f_special_03 . ";" . ";" . $f_tr_remark;
            echo $f_trat_packingpieces . ";" . $f_trat_palets . ";" . $f_trat_weight . ";" . $f_special_04 . ";" . $f_special_05 . ";";
            echo $f_zone_no . ";" . $f_special_06 . ";" . $f_price_type . ";" . $f_service_type . ";";
            echo "<br>";
            echo "----------------------------------------------------------------------------------------------------------------------------------------------<br>";

            // Check for existence of the imported order number (for the same day ONLY)
            $gdcEntryExists = false;
            // if (existsEntry("genericdatacontainer",array("gdc_obj_type","tr","gdc_gen_fieldname","info_2","gdc_content",$f_tr_commission_no,"gdc_context","STANDARD_01"))) :
            if (existsEntry("genericdatacontainer",array("gdc_obj_type","tr","gdc_gen_fieldname","check_exist","gdc_content",$f_tr_commission_no . "_" . $currentDate,"gdc_context","STANDARD_01"))) :
               $gdcEntryExists = true;
            endif;

            // Do NOT import if STANDARD_01 number does exist on the current day!!!!
            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";
                  
                  $callInsertAddress = true;
                  if ($f_cs_eid != "") :
                     $csEndId = getFieldValueFromId("customer","cs_eid",$f_cs_eid,"cs_id");
                     if ($csEndId != "") :
                        $csEndAddress = getAddress($csEndId, "costcenteraddress");
                        
                        $adIdCsEnd = $csEndAddress["id"];
                        if ($adIdCsEnd != "") :
                           $callInsertAddress = false;
                        endif;
                        $f_ad_street  = $csEndAddress["street"];
                        $f_tr_hsno    = $csEndAddress["hsno"];
                        $f_ad_zipcode = $csEndAddress["zipcode"];
                        $f_ad_city    = $csEndAddress["city"];
                        $f_ad_country = $csEndAddress["country"];
                        if ($f_ad_country == "") : 
                           $f_ad_country = "DE";
                        endif;
                     endif;
                  endif;

                  $noValidationOfAddress = true;

                  // Insert address
                  if ($callInsertAddress) :
                     $tmpArray = insertAddress($f_ad_street, $f_ad_zipcode, $f_ad_city, "", $f_ad_country, $noValidationOfAddress);
                     $ad_id_new = $tmpArray[0];
                  endif;

                  $outText .= "AD_ID : " . $ad_id_new . " | ";


                  if ($fire) :

                     // Insert new job because new cartage note does begin
                     if ($remTourNo == "" || $remTourNo != $f_tour_no) :

                        $jbIdNew = "";

                        // Start datetime
                        if ($f_tr_starttime == "") : $f_tr_starttime = "08:00"; endif;
                        $f_jb_ordertime = substr($f_tr_orderdate, 0,4) . "-" . substr($f_tr_orderdate, 4,2) . "-" . substr($f_tr_orderdate, 6,2) . " " . $f_tr_starttime . ":00";

                        // End datetime
                        $f_jb_warningtime = "";
                        if ($f_tr_endtime == "") : $f_tr_endtime = "18:00"; endif;
                        /*
                        if ($f_jb_warningdate != "") :
                           $f_jb_warningtime = substr($f_tr_warningdate, 0,4) . "-" . substr($f_tr_warningdate, 4,2) . "-" . substr($f_tr_warningdate, 6,2);
                           if ($f_tr_warningdate != "") :
                              $f_jb_warningtime .= " " . $f_tr_endtime . ":00";
                           endif;
                        endif;
                        */

                        // Remove existing tourname
                        updateStmt("job","jb_tourname",$f_tour_no,array("jb_tourname",""), "jb_tourname = '" . $f_tour_no . "'");


                        // 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", $f_jb_ordertime, "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_tour_no,
                                                "jb_finishtime", $jbFinishtime, "jb_warningtime", $f_jb_warningtime, "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_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();
                        $jobNewArray[] = $jbIdNew;

                        // Tour-Nr. "$f_tour_no"
                        insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbIdNew, "gdc_gen_fieldname", "tourname", "gdc_content", $f_tour_no, "gdc_context", "STANDARD_01"));

                        $trSort = 2;    // Init for 2nd station equals first delivery !!!!
                        $tratSort = 1;  // Init all serial numbers !!!!
                        $remTourNo = $f_tour_no;
                     endif;


                     // Check for inserted job
                     if ($jbIdNew != "") :

                        // Insert stations
                        if ($trSort == 2) :

                           $trStatus = "0";
                           $trFinishtime = "";
                           if ($pickUpStationFinishedByDefault) :
                              $trStatus = "1";
                              $trFinishtime = $currentTime;
                           endif;

                           // Insert pick up station during first iteration
                           insertStmt("tour", array("jb_id", $jbIdNew, "ad_id", $adIdFrom, "tr_sort", "1", "tr_comp", $trCompFrom, "tr_comp2", "",
                                                    "tr_hsno", $trHsnoFrom, "tr_floor", $trFloorFrom, "csc_id", $cscIdPayer, "tr_status", $trStatus, "tr_finishtime", $trFinishtime,
                                                    "tr_commission_no", "", "tr_ware_from_to", $f_tr_ware_from_to,
                                                    "tr_person", "", "tr_phone", "", "tr_remark", ""));
                           $trIdPickUpNew = getLastInsertID();
                           
                           // Init array für jb_tourdata
                           $jbTourdataZipcodeArray[$jbIdNew][] = $csAddress["zipcode"];
                           $jbTourdataCityArray[$jbIdNew][] = $csAddress["city"];
                           $jbTourdataCountryArray[$jbIdNew][] = $csAddress["country"];

                        endif;

                        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, "tr_floor", $f_tr_floor, "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();

                        $jbTourdataZipcodeArray[$jbIdNew][] = $f_ad_zipcode;
                        $jbTourdataCityArray[$jbIdNew][] = $f_ad_city;
                        $jbTourdataCountryArray[$jbIdNew][] = $f_ad_country;


                        // Insert tourservice data
// !!!! MIT tr_id !!!!  insertStmt("tourservice", array("tr_id", $trIdNew, "jb_id", $jbIdNew, "csc_id", $cscIdPayer, "tr_sort", $trSort,
                        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));

                        // Generate invoice text
                        // mk_jb_invtext($jbIdNew, false);
                        
                        // ****
                        // Special patch because of "bug" in function "mk_jb_invtext()"
                        if ($jbIdNew != "" && is_numeric($jbIdNew)) :
                        //    updateStmt("job","jb_id",$jbIdNew,array("jb_tourdata",$jbTourdata));
                        endif;
                        // ****

                        // Fremdauftragsnummer "$f_order_id"
                        insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trIdNew, "gdc_gen_fieldname", "info_0", "gdc_content", $f_order_id, "gdc_context", "STANDARD_01"));

                        // Kundennummer "$f_cs_id_external"
                        insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trIdNew, "gdc_gen_fieldname", "info_1", "gdc_content", $f_cs_id_external, "gdc_context", "STANDARD_01"));
                        insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trIdNew, "gdc_gen_fieldname", "info_cust_no", "gdc_content", $f_cs_id_external, "gdc_context", "STANDARD_01"));

                        // Lieferscheinnummer "$f_tr_commission_no"
                        insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trIdNew, "gdc_gen_fieldname", "info_2", "gdc_content", $f_tr_commission_no, "gdc_context", "STANDARD_01"));
                        insertStmt("genericdatacontainer", array("gdc_obj_type", "tr", "gdc_obj_id", $trIdNew, "gdc_gen_fieldname", "check_exist", "gdc_content", $f_tr_commission_no . "_" . $currentDate, "gdc_context", "STANDARD_01"));


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

                        $trSort++;
                        $executionCount++;
                     endif;

                     TA("C");
                     TA("E");
                  endif;
               endif;
            else :
               $outText .= getLngt("Der Datensatz existiert schon! Es erfolgte kein Import!") . " [" . $f_order_id .  "]<br>";
            endif;
         }

         // Set generated jobs to status "taken"
         $jobNewArrayLen = count($jobNewArray);
         if ($jobNewArrayLen > 0) :
            for ($i = 0; $i < $jobNewArrayLen; $i++) :
                // jb_status
                // updateStmt("job", "jb_id", $jobNewArray[$i], array("jb_status", "1"));

                // jb_tourdata
                $jbTourdata = implode(";", $jbTourdataZipcodeArray[$jobNewArray[$i]]) . "|" . implode(";", $jbTourdataCityArray[$jobNewArray[$i]]) . "|" . implode(";", $jbTourdataCountryArray[$jobNewArray[$i]]);
                updateStmt("job", "jb_id", $jobNewArray[$i], array("jb_tourdata", $jbTourdata));
            endfor;
         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("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_STANDARD_01.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>