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


// $doNotIncludeGeocode = true;
include_once ("../import/import.php");
include_once ("../include/caglobal.inc.php");    // For pricing and invoice-text only
include_once ("../include/inc_vehicle.inc.php");
include_once ("../include/inc_job.inc.php");
include_once ("../include/services_func.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);
$currentYear = getDateTime("year");
$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_02"; 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_02_") === 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();
         $rowToImport = array();
         
         $parImportFieldsGroup == "";
         if ($groupId != "") :
            $parImportFieldsGroup = getParameterValue("0", "IMPORT_STANDARD_02_JOB_FIELDS", "0");
         endif;
         if ($parImportFieldsGroup != "") :
            $rowToImport = spliti(",", $parImportFieldsGroup);
         else :

            /*
            Lfd	Datum	       Auftrag / Tourenverlauf	                             Betrag	  Fahrzeug
            1;  10.03.2016;  JIS: Magna Bremen-Daimler Bremen Bordero: 6410-0001;  75,94;   HB048
            2;  11.03.2016;  JIS: Magna Bremen-Daimler Bremen Bordero: 6410-0002;  75,94;   HB048
            3;  12.03.2016;  JIS: Magna Bremen-Daimler Bremen Bordero: 6410-0003;  75,94;   HB048
            4;  13.03.2016;  JIS: Magna Bremen-Daimler Bremen Bordero: 6410-0004;  75,94;   HB048
            */

            $rowToImport[0]  = "f_lfd";                 // A : LFD
            $rowToImport[1]  = "f_tr_orderdate";        // B : Datum (Auftragszeit UND Erledigungszeit)
            $rowToImport[2]  = "f_inv_text";            // C : Rechnungstext (Auftrag/Tourenverlauf)
            $rowToImport[3]  = "f_inv_reference";       // D : Kostenstelle/Referenz
            $rowToImport[4]  = "f_jb_totalprice";       // E : Preis (Betrag)
            $rowToImport[5]  = "f_crvh_sid";            // F : Fahrzeug
            $rowToImport[6]  = "f_dummy";               // G : DUMMY

    
            // $rowToImport[6]  = "f_discount";            // F : Rabatt
            // $rowToImport[7]  = "f_markup";              // G : Zuschlag
            // $rowToImport[8]  = "f_dummy_01";            // H : DUMMY
         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 = 1; $j < $dataLen; $j++) {

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

            $f_lfd              = mcStrWrap($f_lfd);
            $f_tr_orderdate     = mcStrWrap($f_tr_orderdate);
            $f_inv_text         = mcStrWrap($f_inv_text);
            $f_inv_reference    = mcStrWrap($f_inv_reference);
            $f_jb_totalprice    = mcStrWrap($f_jb_totalprice);
            $crSid              = mcStrWrap($f_crvh_sid);
            $f_discount         = mcStrWrap($f_discount);
            $f_markup           = mcStrWrap($f_markup);

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

            // Set vehicle and courier
            $crId = "";
            $vhtId = "";
            $doContinue = false;
            if ($crSid != "") :
               $crId = getFieldValueFromId("couriervehicle","crvh_sid",$crSid,"cr_id");
               $vhtId = getFieldValueFromId("couriervehicle", "crvh_sid", $crSid, "vht_id");
               if ($crId != "" && is_numeric($crId)) :
                  $doContinue = true;
               endif;
            endif;

            if ($doContinue) :
               $jbStatus = "2";
               $jbOrdertime = substr($f_tr_orderdate,6,4) . "-" . substr($f_tr_orderdate,3,2) . "-" . substr($f_tr_orderdate,0,2) . " 08:00:00";
               $jbTaketime = "";
               if ($crId != "" && is_numeric($crId)) :
                  $jbTaketime = $jbOrdertime;
               endif;
               $f_jb_totalprice = str_replace (",", ".", $f_jb_totalprice);
               // $f_discount = str_replace (",", ".", $f_discount);
               if ($f_discount != "1") :
                  $f_discount = "0";
               endif;
               // $f_markup = str_replace (",", ".", $f_markup);
               if ($f_markup != "1") :
                  $f_markup = "0";
               endif;
               $jbType = "";
               $jbFinishtime = $jbOrdertime;
               $jbFreetext1 = $f_inv_text . " " . $f_inv_reference;
               // $jbFreetext1 = $f_inv_reference;
               $trCommissionNo = $f_inv_reference;
               $txValue = "4";
               $txSign = "V";
               $price = 0;
               $f_jb_cr_price = 0;
               $jbCrvhWeight = 0;
               $jbCrvhLength = 0;
               $jbCrvhWidth = 0;
               $jbCrvhHeight = 0;
               $jbCrvhPosition = 0;
               if (is_numeric($f_jb_totalprice)) :
                  $price = $f_jb_totalprice;
                  $f_jb_cr_price = 0;
                  $jbCrvhWeight = 0;
                  $jbCrvhLength = 0;
                  $jbCrvhWidth = 0;
                  $jbCrvhHeight = 0;
                  $jbCrvhPosition = 0;
               else :
                  $doContinue = false;
               endif;
            endif;


            echo $f_lfd . ";" . $f_tr_orderdate . ";" . $f_tr_starttime . ";" . $f_inv_text . ";" . $f_inv_reference . ";" . $f_jb_totalprice . ";" . $f_crvh_sid . ";";
            // echo $f_discount . ";" . $f_markup . ";";
            echo ";<br>";
            echo "--------------------------------------------------------------------------------------------------------------------------------------------------<br>";


            // Insert job
            if ($doContinue && $executeImportProcess == "1") :

               // Check for existence of the imported order number (for the same day ONLY)
               $gdcEntryExists = false;               
               if (existsEntry("genericdatacontainer",array("gdc_obj_type","jb","gdc_gen_fieldname","check_exist","gdc_content",$currentYear . "_" . $f_inv_reference,"gdc_context","STANDARD_02"))) :
                  $gdcEntryExists = true;
               endif;

               // Do NOT import if STANDARD_02 number does exist on the current day!!!!
               if (!$gdcEntryExists) :

                  // Check debug mode
                  if ($fire) :

                     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;

                     // Postage
                     $cmpId = getFieldValueFromId("customer", "cs_id", $csId, "cmp_id");
                     $cmpPostage = getFieldValueFromId("company", "cmp_id", $cmpId, "cmp_postage");
                     if ($cmpPostage == "" || !is_numeric($cmpPostage)) :
                        $cmpPostage = 0;
                     endif;

                     $csInvmode = getFieldValueFromId("customer", "cs_id", $csId, "cs_invmode");

                     // Check for customer provision, amount to be stored in "jb_cr_price"
                     $csProv = 0;
                     // $useCsProvEnabled = getParameterValue("0", "JB_EDITBATCH_CS_PROV_ENABLED", "0");
                     $useCsProvEnabled = "1";
                     if ($useCsProvEnabled == "1") :
                        $csProv = getFieldValueFromId("customer", "cs_id", $csId, "cs_prov");
                        if ($csProv == "" || $csProv == 0) :
                            $csProv = getParameterValue("0", "MASK_CS_PROV_DEFAULT", $hq_id);
                            $csProv = str_replace (",", ".", $csProv);
                            if ($csProv == "") :
                               $csProv = 0;
                            endif;
                        endif;
                     endif;

                     // Check for absolute customer discount (ATTENTION: Parameter means DISABLED !!!) and check for markup
                     $csDiscountAbsolute = "0";
                     $csMarkupFlag = "0";
                     if ($csId != "") :
                        // Discount
                        $csDiscountAbsolute = getFieldValueFromId("customer", "cs_id", $csId, "cs_discount");
                        // Markup
                        $csMarkupFlag = getFieldValueFromId("customer", "cs_id", $csId, "cs_markup");
                     endif;

	                   $csDiscount = "0";
	                   if ($csDiscountAbsolute != 0 && $f_discount == "1") :
	                      $csDiscount = $csDiscountAbsolute;
	                   endif;

	                   $csMarkup = "0";
	                   if ($csMarkupFlag == "1" && $f_markup == "1") :
	                      $csMarkup = "1";
	                   endif;

                     // Check prices because one of them has to be set only (!!!)
                     if ($price == "") : $price = 0; endif;
                     if ($price2 == "") : $price2 = 0; endif;             

                     // Fixprice without markup and without customer discount
                     $fixPrice = $price;

                     // Service price
                     $servicePrice = $price2;

                     // Compute markup
                     $subTotalPrice = $price;    // Price without markup

                     $tmpSrvt = $db->getOne("SELECT mt_value FROM metatype WHERE mt_sort = '" . $vhtId . "' AND mt_type= 'vehicletype'");
                     $final_markup = getFuelMarkup($tmpSrvt, $csId, $hqId, $jbFinishtime);
                     if ($f_markup == "0" && $final_markup > 0) :
                        $final_markup = 0;
                     endif;

                     // New price containing markup
                     if ($final_markup > 0) :
                        $price *= (1 + ($final_markup / 100));
                     endif;

                     // Price with markup but without customer discount
                     $trsPrice = $price;

                     // Check for absolute customer discount
                     if ($csDiscountAbsolute > 0) :
                        $price = ($price * ((100 - $csDiscount) / 100));
		                    $subTotalPrice = ($subTotalPrice * ((100 - $csDiscount) / 100));
                     endif;

                     // Courier price
                     $jbCrPrice = 0;
                     if (is_numeric($csProv) && $csProv > 0) :
                        $jbCrPrice = ($price * ((100 - $csProv) / 100));
                     endif;

                     // Total price and subtotal price containing the service price
                     $subTotalPrice = $subTotalPrice + $servicePrice;
                     $totalPrice = $price + $servicePrice;

                     insertStmt("job", array("hq_id", $hqId, "vht_id", $vhtId, "vht_id_real", $vhtId, "csc_id_payer", $cscIdPayer, "jb_payment", "0",
                                             "jb_ordertime", $jbOrdertime, "cr_id", $crId, "cr_sid", $crSid, "cr_id_order", $crId,
                                             "jb_taketime", $jbFinishtime, "jb_status", "2", "jb_autoranking", "0", "jb_type", $jbType, 
                                             "jb_finishtime", $jbFinishtime, "emp_id", $usrId, "jb_fixprice", $fixPrice, "jb_serviceprice", $servicePrice, "jb_totalprice", $totalPrice, "jb_cr_price", $jbCrPrice,
                                             "jb_subtotalprice", $subTotalPrice, "jb_markup", $final_markup, "jb_postage", $cmpPostage, "jb_invmode", $csInvmode, "jb_freetext_1", $jbFreetext1,
                                             "jb_sales_tax_rate", $txValue, "jb_sales_tax_rate_sign", $txSign,
                                             "jb_automailsent", "997", "jb_booktime", $currentTime));
                     $jbIdNew = getLastInsertId();


                     insertStmt("tour", array("jb_id", $jbIdNew, "ad_id", $adIdFrom, "tr_sort", "1", "tr_comp", my_str_check($trCompFrom), "tr_comp2", "",
                                              "tr_hsno", $trHsnoFrom, "csc_id", $cscIdPayer, "tr_status", "1", "tr_signname", "Listenbuchung",
                                              "tr_finishtime", $jbFinishtime, "tr_commission_no", $trCommissionNo));

                     if ($trsPrice != 0) :
                        insertStmt("tourservice", array("jb_id", $jbIdNew, "csc_id", $cscIdPayer, "tr_sort", "0", 
                                                        "srv_id", "0", "trs_srv_name", "Fixpreis", "srvt_id", "0", "trs_srvt_name", "", 
                                                        "trs_price", $trsPrice, "trs_discount", $csDiscount));
                     endif;
                     if ($servicePrice != 0) :
                        insertStmt("tourservice", array("jb_id", $jbIdNew, "csc_id", $cscIdPayer, "tr_sort", "0", 
                                                        "srv_id", "0", "trs_srv_name", "Servicepreis", "srvt_id", "0", "trs_srvt_name", "", 
                                                        "trs_price", $servicePrice, "trs_discount", "0"));
                     endif;

                     insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $jbIdNew, "gdc_gen_fieldname", "check_exist", "gdc_content", $currentYear . "_" . $f_inv_reference, "gdc_context", "STANDARD_02"));


                     // Write logdata into log database
                     writeToLogDB("1",$hq_id,$jbIdNew,$usrId,$crId,$crSid,"","");


                     // Generate invoice text
                     mk_jb_invtext($jbIdNew, false);

                     $executionCount++;

                     TA("C");
                     TA("E");
                  endif;
               else :
                  if ($executeImportProcess == "1") :
                     $outText .= getLngt("Der Datensatz existiert schon! Es erfolgte kein Import!") . " [" . $f_inv_reference .  "]<br>";
                  endif;
               endif;
            else :
               if ($executeImportProcess == "1") :
                  $outText .= getLngt("Der Datensatz wurde nicht importiert! Die Vorlagedaten sind nicht vollständig!") . " [" . $f_inv_reference .  "]<br>";
               endif;
            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_02.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>