<?php
/*=======================================================================
 *
 * import_tourbo.php
 *
 * Autor: Marc Vollmann
 *
 * 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
 *
 =======================================================================*/

include_once ("import.php");

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


// 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 = "";
$fJbTourname = "";
$fTrSort = "";

// 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) :

      $importFileStatusMsg .= "<br><br><br><br><span class=\"f12bp1_red\" colspan=\"2\">Verarbeitungsprotokoll:</span><br><br>";
      $importFileStatusMsg .= "Import-Datei: " . $f_importFile . "<br><br>";

      $rowToImport = array();
/*      
      $rowToImport[0]  = "f_position";            // position
      $rowToImport[1]  = "f_tr_person";           // externalOrderID
      $rowToImport[2]  = "f_dummy_01";            // dummy
      $rowToImport[3]  = "f_tr_ware_from_to";     // type
      $rowToImport[4]  = "f_tr_comp_01";          // name 1
      $rowToImport[5]  = "f_tr_comp2_01";         // name 2
      $rowToImport[6]  = "f_ad_street_01";        // pickup/street
      $rowToImport[7]  = "f_ad_zipcode_01";       // pickup/zipCode
      $rowToImport[8]  = "f_ad_city_01";          // pickup/city
      $rowToImport[9]  = "f_tr_remark_1";         // goodsdescription
      $rowToImport[10] = "f_tr_commission_no";    // loadingUnitType
      $rowToImport[11] = "f_jb_ordertime_01";     // pickup/plannedPickup
      $rowToImport[12] = "f_jb_tourname";         // tourID
*/
      $rowToImport[0]  = "f_cs_eid";              // customer EID
      $rowToImport[1]  = "f_jb_tourname";         // tourID
      $rowToImport[2]  = "f_cr_sid";              // courier SID
      $rowToImport[3]  = "f_jb_ordertime_01";     // pickup time
      $rowToImport[4]  = "f_position";            // position
      $rowToImport[5]  = "f_ad_zipcode_01";       // zipcode
      $rowToImport[6]  = "f_ad_city_01";          // city
      $rowToImport[7]  = "f_ad_street_01";        // street
      $rowToImport[8]  = "f_tr_hsno_01";          // house number
      $rowToImport[9]  = "f_time_arrival";        // extra
      $rowToImport[10] = "f_km";                  // extra
      $rowToImport[11] = "f_ls";                  // extra
      $rowToImport[12] = "f_tr_remark_1";         // remark
      $rowToImport[13] = "f_kg";                  // weight


      $rowToImportLen = count($rowToImport);
      
      // read file to import
      $data = importCSV($importPath . $f_importFile);
      $dataLen = count($data);
         
      // loop all rows
      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];
         }         

         // Next job begins
         if ($fJbTourname == "" || $fJbTourname != $f_jb_tourname) :

            $jbIdNew = "";
            $fTrSort = "";
            $fJbTourname = $f_jb_tourname;
         endif;

         // Check import log table in db according to the unique key "tourID + position" (<=> $f_jb_tourname + $f_position)
         $logJbId = getFieldValueFromClause("phoenix_log.import","jb_id","imp_id = '" . $f_jb_tourname . "' AND imp_pos = '" . $f_position . "'");

         if ($logJbId == "") :
         
            TA("B");

            $f_position = trim($f_position);            
            $f_position++;      // Increment because votian starts with "1" instead of "0"
            $f_jb_tourname = trim($f_jb_tourname);
            $f_jb_ordertime_01 = trim($f_jb_ordertime_01);
            $f_ad_street_01 = trim($f_ad_street_01);
            $f_tr_hsno_01 = trim($f_tr_hsno_01);
            $f_ad_zipcode_01 = trim($f_ad_zipcode_01);
            $f_ad_city_01 = trim($f_ad_city_01);
            $f_tr_remark_1 = trim($f_tr_remark_1);
            $f_cs_eid = trim($f_cs_eid);
            $f_cr_sid = trim($f_cr_sid);

            $f_time_arrival = trim($f_time_arrival);
            $f_km = trim($f_km);
            $f_ls = trim($f_ls);
            $f_kg = trim($f_kg);

            $f_tr_person = trim($f_tr_person);
            $f_tr_ware_from_to = trim($f_tr_ware_from_to);
            $f_tr_comp_01 = trim($f_tr_comp_01);
            $f_tr_comp2_01 = trim($f_tr_comp2_01);
            $f_tr_commission_no = trim($f_tr_commission_no);

            if ($f_ad_street_01 == "") : $f_ad_street_01 = "."; endif;
            if ($f_tr_hsno_01 == "") : $f_tr_hsno_01 = "."; endif;
            if ($f_ad_zipcode_01 == "") : $f_ad_zipcode_01 = "."; endif;
            if ($f_ad_city_01 == "") : $f_ad_city_01 = "."; endif;

            // Constants
            // $cscIdCashPayer = getParameterValue("0", "CSC_ID_PAYER_CASH", $f_hq_id);

            // Concatenation of external cs_eid and name
            $f_cs_id = getFieldValueFromId("customer","cs_eid",$f_cs_eid,"cs_id");
            $f_cmp_id = getFieldValueFromId("company","cs_id",$f_cs_id,"cmp_id");
            $f_tr_comp_01 = getFieldValueFromId("company","cmp_id",$f_cmp_id,"cmp_comp");
            $f_tr_comp2_01 = getFieldValueFromId("company","cmp_id",$f_cmp_id,"cmp_comp2");
            
            // $f_tr_comp_01 = $f_tr_comp_01 . " " . $f_tr_comp2_01;
            // $f_tr_comp2_01 = "";

            if ($f_tr_ware_from_to == "Rücknahme") :
               $f_tr_ware_from_to = "1";
            elseif ($f_tr_ware_from_to == "Installation") :
               $f_tr_ware_from_to = "2";
            else :
               $f_tr_ware_from_to = "0";
            endif;

            // $f_tr_remark = $f_tr_remark_1;    // . " " . $f_tr_remark_2 . " " . $f_tr_remark_3 . " " . $f_jb_ordertime_02;
            $f_tr_remark = $f_tr_remark_1 . " | Ankunft: " . $f_time_arrival . " | KM: " . $f_km . " | LS: " . $f_ls . " | KG: " . $f_kg;
            
            // Extra field "internal remark of the customer" for customer export
            $f_tr_cs_freetext = $f_tr_remark;

            // Format date field
            $dVal = $f_jb_ordertime_01;
            // $f_jb_ordertime_01 = substr($dVal,6,4) . "-" . substr($dVal,3,2) . "-" . substr($dVal,0,2) . " 00:00";

            // Split street to street and houseno.
            // $f_tr_hsno_01 = ".";
            // $f_tr_hsno_02 = ".";
            
            // Get 1. address id
            $tmpArray = insertAddress($f_ad_street_01, $f_ad_zipcode_01, $f_ad_city_01, "", "", true);
            $ad_id_new_01 = $tmpArray[0];

            // Get the current time
            $currentTime = getDateTime("0");
      

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

               $jbStatus = "1";
               $jbType = "0";    // "---"
               $crSid = $f_cr_sid;
               $crId = getFieldValueFromId("couriervehicle","crvh_sid",$crSid,"cr_id");
               $jbTaketime = $f_jb_ordertime_01;
               $jbFinishtime = "";
               $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";
 
               // Mapping of the headquarters
               $tmpZipcode = substr($f_ad_zipcode_01 ,0 ,1);   // Get the first character
               if (true) :
                  $f_hq_id = "1";   // SB HB (Default !!!)
                  $f_cs_eid_payer = $f_cs_eid;
                  $trCscIdRoot_01 = "141012";   // Hauptkostenstelle Kunde "Extern"
               endif;

               $csId = getFieldValueFromId("customer","cs_eid",$f_cs_eid_payer,"cs_id");
               $cscIdRoot = 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");
               $useDicountDisabled = getParameterValue("0", "JB_EDITBATCH_DISCOUNT_DISABLED");
               if ($useDicountDisabled == "1") :
                  $csDiscountAbsolute = 0;
               endif;

               // Mapping of the vehicle type
               $f_vht_id = getFieldValueFromId("couriervehicle","crvh_sid",$crSid,"vht_id");
               /*
               if ($f_vht_id == "1") :
                  $f_vht_id = "8";    // 3-To.
               elseif ($f_vht_id == "2") :
                  $f_vht_id = "9";    // 5-To.
               elseif ($f_vht_id == "3") :
                  $f_vht_id = "7";    // 1-To.
               else :
                  $f_vht_id = "8";    // 3-To.
               endif;
               */

               insertStmt("job", array("hq_id", $f_hq_id, "vht_id", $f_vht_id, "csc_id_payer", $cscIdRoot, "jb_payment", "0",
                                       "jb_ordertime", $f_jb_ordertime_01, "cr_id", $crId, "cr_sid", $crSid, "cr_id_order", $crId,
                                       "jb_taketime", $jbTaketime, "jb_status", $jbStatus, "jb_autoranking", "0", "jb_type", $jbType, "jb_tourname", $f_jb_tourname,
                                       "jb_finishtime", $jbFinishtime, "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, "jb_booktime", ""));
               $jbIdNew = getLastInsertId();
               
               // Insert tour data for station
               insertStmt("tour", array("jb_id", $jbIdNew, "ad_id", $ad_id_new_01, "tr_sort", "1", "tr_comp", $f_tr_comp_01, "tr_comp2", $f_tr_comp2_01,
                                        "tr_hsno", $f_tr_hsno_01, "csc_id", $trCscIdRoot_01, "tr_status", "0", 
                                        "tr_commission_no", $f_tr_commission_no, "tr_ware_from_to", $f_tr_ware_from_to, 
                                        "tr_person", $f_tr_person, "tr_remark", $f_tr_remark, "tr_cs_freetext", $f_tr_cs_freetext));
         
               // Insert tourservice data
               insertStmt("tourservice", array("jb_id", $jbIdNew, "csc_id", $cscIdRoot, "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,"","","",$csId);
               
               $importFileStatusMsg .= "Station 1 des Auftrags " . $jbIdNew . " wurde importiert.<br>";

            else :
               if ($fTrSort == "") :
                  $fTrSort = "2";
               else :
                  $fTrSort++;
               endif;
            
               // Update job data
               // updateStmt("job","jb_id",$jbIdNew,array("usr_name",$f_usr_name,"usr_firstname",$f_usr_firstname));
               
               // Insert tour data
               insertStmt("tour", array("jb_id", $jbIdNew, "ad_id", $ad_id_new_01, "tr_sort", $fTrSort, "tr_comp", $f_tr_comp_01, "tr_comp2", $f_tr_comp2_01,
                                        "tr_hsno", $f_tr_hsno_01, "csc_id", $trCscIdRoot_01, "tr_status", "0", 
                                        "tr_commission_no", $f_tr_commission_no, "tr_ware_from_to", $f_tr_ware_from_to, 
                                        "tr_person", $f_tr_person, "tr_remark", $f_tr_remark, "tr_cs_freetext", $f_tr_cs_freetext));

               $importFileStatusMsg .= "Station " . $fTrSort . " des Auftrags " . $jbIdNew . " wurde importiert.<br>";
            endif;
            
            // Insert into import log table
            insertStmt("phoenix_log.import", array("imp_id", $f_jb_tourname, "imp_pos", $f_position, "imp_createtime", $currentTime, "jb_id", $jbIdNew));
   
            TA("C");
            TA("E");
         else :
            $importFileStatusMsg .= "Datensatz " . $j . " wurde NICHT importiert, weil sie schon importiert wurde! (Auftrag " . $logJbId . ")<br>";
         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;
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_job.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_job.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>