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

include_once ("../import/import.php");

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

// Get the rights of the employee logged in and check the accessibility
authCheckEmployeeRights($emp_id, "22", "1");

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


getLanguage(__FILE__);

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

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


// Converts STR to DATE
function cStr2Date ($str, $mode = "") {
	if ($mode == "1") :
	   // Default: "d.m.Y" => "Y-m-d"
     $str = substr($str,6,4) . "-" . substr($str,3,2) . "-" . substr($str,0,2);
	elseif ($mode == "2") :
	   // "d.m.Y H:i" => "Y-m-d H:i:s"      09.08.2011 06:30
	   $str = substr($str,6,4) . "-" . substr($str,3,2) . "-" . substr($str,0,2) . " " . substr($str,11,2) . ":" . substr($str,14,2) . ":" . "00";
	else :
	   // Default: "dmY" => "Y-m-d"
     $str = substr($str,4,4) . "-" . substr($str,2,2) . "-" . substr($str,0,2);
  endif;
  return $str;
}

// Converts STR to FLOAT (with ".") [e.g.: 000011122 => 111.22 with 2 decimals]
function cStr2Float ($str, $decimals = "2") {
	if (is_numeric($str)) :
     $numberPrefix = substr($str, 0, strlen($str) - $decimals);
     $numberSuffix = substr($str, strlen($str) - $decimals, $decimals);
     while (substr($numberPrefix,0,1) == "0" && strlen($numberPrefix) > 0) {
     	     $numberPrefix = substr($numberPrefix,1);
     }
     $str = $numberPrefix . "." . $numberSuffix;
  endif;
  return $str;
}


if ($importFile != "") : 

   $importFile = urldecode($importFile);

   if (file_exists($importFile)) :

      $f_numOfRows = 0;
      $f_checksum  = 0;
      
      $currentTime = getDateTime("0");
      
      // *******************
      // * Import APO data *
      // *******************

      if ($executeImportProcess == "1") :

         $outText .= getLngt("IMPORTDATEI:") . "&nbsp;" . $importFile . "<br><br>";

// "Nr","Apotheke","Tour","Tourdatum","Tourzeit","Anrede","Vorname","Nachname","PLZ","Ort","Ortsteil","Strasse","Land","Telefon","Offene Kredite","Lieferhinweis","Bediener"
// 187,"AP90DEVVSPOS (9999010)","Morgentour Mo-Fr 06:30 – 09:00",09.08.2011,06:30,,"Urmel","Ka aus dem Eis",12345,"Titiwu",,"Im Holzhaus 1",,"012 3456789","17,27","in den Briefkasten legen","Michels, Sylvia"
// 190,"AP90DEVVSPOS (9999010)","Morgentour Mo-Fr 06:30 – 09:00",09.08.2011,06:30,"Herr","Willnix","Ka Lieferkunde",90762,"Fürth","West","Hafenstr. 87",,,"0,00",,"Kormann, Stefan"

         $rowToImport = array();
         
         $rowToImport[0]  = "f_no";
         $rowToImport[1]  = "f_apo";
         $rowToImport[2]  = "f_jb_tourname";
         $rowToImport[3]  = "f_orderdate";
         $rowToImport[4]  = "f_ordertime";
         $rowToImport[5]  = "f_title";
         $rowToImport[6]  = "f_usr_firstname";
         $rowToImport[7]  = "f_usr_name";
         $rowToImport[8]  = "f_ad_zipcode";
         $rowToImport[9]  = "f_ad_city";
         $rowToImport[10] = "f_ad_district";
         $rowToImport[11] = "f_ad_street";
         $rowToImport[12] = "f_ad_country";
         $rowToImport[13] = "f_usr_phone";
         $rowToImport[14] = "f_open_credits";
         $rowToImport[15] = "f_jb_remark";
         $rowToImport[16] = "f_driver_name";
         $rowToImport[17] = "f_dummy";

         $rowToImportLen = count($rowToImport);
         
         // read file to import
         $data = importCSV($importFile, ",");
         $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_apo = removeFieldSigns($f_apo);
            $f_jb_tourname = removeFieldSigns($f_jb_tourname);
            $f_title = removeFieldSigns($f_title);
            $f_usr_firstname = removeFieldSigns($f_usr_firstname);
            $f_usr_name = removeFieldSigns($f_usr_name);
            $f_ad_city = removeFieldSigns($f_ad_city);
            $f_ad_district = removeFieldSigns($f_ad_district);
            $f_ad_street = removeFieldSigns($f_ad_street);
            $f_ad_country = removeFieldSigns($f_ad_country);
            $f_usr_phone = removeFieldSigns($f_usr_phone);
            $f_open_credits = removeFieldSigns($f_open_credits);
            $f_jb_remark = removeFieldSigns($f_jb_remark);
            $f_driver_name = removeFieldSigns($f_driver_name);

            $f_jb_ordertime = cStr2Date ($f_orderdate . " " . $f_ordertime, "2");
            if ($f_ad_country == "") : $f_ad_country = "DE"; endif;
            $f_jb_tourdata = $f_ad_zipcode . "|" . $f_ad_city . "|" . $f_ad_country;
            $f_tr_person = $f_title . " " . $f_usr_firstname . " " . $f_usr_name;
            if ($f_open_credits != "") : 
               $f_jb_remark = $f_jb_remark . " [Außenstände: " . $f_open_credits . "]";
            endif;

            $f_ad_id = "";
            if ($f_ad_street != "" && $f_ad_zipcode != "" && $f_ad_city != "") :
            
               $sqlStmt = "SELECT ad_id FROM address WHERE ad_street = '" . $f_ad_street . "' AND ad_zipcode = '" . $f_ad_zipcode . "' AND ad_city = '" . $f_ad_city . "' AND ad_country = 'DE'";
               $f_ad_id = $db->getOne($sqlStmt);
               if (DB::isError($ad_id)) die ("$PHP_SELF: <br>$sqlStmt<br>" . $ad_id->getMessage());
               if ($f_ad_id == ""):
                  insertStmt("address", array("ad_street", $f_ad_street, "ad_zipcode", $f_ad_zipcode, "ad_city", $f_ad_city, "ad_country", "DE"));
                  $f_ad_id = getLastInsertID();
               endif;
            endif;
            
            // Get costcenter for "csc_id_payer" in "job"
            $cscId = getParameterValue("0", "CSC_ID_PAYER_EXTERN", $hq_id);
            $trCscId = getParameterValue("0", "CSC_ID_PAYER_EXTERN", $hq_id);
            $txValue = getFieldValueFromId("tax","tx_id","4","tx_value");
            $txSign = getFieldValueFromId("tax","tx_id","4","tx_sign");
            $fixprice = "0.00";
            $trCommissionNo = "";

echo "f_orderdate: " . $f_orderdate . "<br>";
echo "f_ordertime: " . $f_ordertime . "<br>";
echo "f_apo: " . $f_apo . "<br>";
echo "f_jb_tourname: " . $f_jb_tourname . "<br>";
echo "f_title: " . $f_title . "<br>";
echo "f_usr_firstname: " . $f_usr_firstname . "<br>";
echo "f_usr_name: " . $f_usr_name . "<br>";
echo "f_ad_city: " . $f_ad_city . "<br>";
echo "f_ad_district: " . $f_ad_district . "<br>";
echo "f_ad_street: " . $f_ad_street . "<br>";
echo "f_ad_country: " . $f_ad_country . "<br>";
echo "f_usr_phone: " . $f_usr_phone . "<br>";
echo "f_open_credits: " . $f_open_credits . "<br>";
echo "f_jb_remark: " . $f_jb_remark . "<br>";
echo "f_driver_name: " . $f_driver_name . "<br>";
echo "f_jb_ordertime: " . $f_jb_ordertime . "<br>";
echo "f_jb_tourdata: " . $f_jb_tourdata . "<br>";
echo "f_tr_person: " . $f_tr_person . "<br>";
echo "f_ad_id: " . $f_ad_id . "<br>";
echo "cscId: " . $cscId . "<br>";
echo "trCscId: " . $trCscId . "<br>";
echo "txValue: " . $txValue . "<br>";
echo "txSign: " . $txSign . "<br>";
echo "fixprice: " . $fixprice . "<br>";
echo "trCommissionNo: " . $trCommissionNo . "<br>";

            // Insert new job(s)
            if (true) :
            
               TA("B");                        
            
               insertStmt("job", array("hq_id", $hq_id, "csc_id", $cscId, "vht_id", "2", "csc_id_payer", $cscId, "jb_payment", "0",
                                       "jb_ordertime", $f_jb_ordertime, "cr_id", "", "cr_sid", "", "cr_id_order", "",
                                       "jb_cr_filter", "", "jb_cr_filter_opt", "", "jb_waitstorno", "0", 
                                       "jb_taketime", "", "jb_status", "9", "jb_autoranking", "0", "jb_type", "", 
                                       "jb_incomplete", "0", "jb_globaljob", "0", "jb_tourname", $f_jb_tourname,
                                       "jb_finishtime", "", "emp_id", $usr_id, "jb_fixprice", $fixprice, "jb_totalprice", $fixprice,
                                       "jb_postage", "", "jb_invmode", "", "jb_freetext_1", "",
                                       "jb_weight", "", "jb_crvh_length", "", "jb_crvh_width", "", 
                                       "jb_crvh_height", "", "jb_crvh_position", "", "jb_invtext", $f_jb_remark,
                                       "jb_tourdata", $f_jb_tourdata, "jb_lockuser", "0", "jb_id_parent", "0", "jb_dispoinfo", "",
                                       "jb_sales_tax_rate", $txValue, "jb_sales_tax_rate_sign", $txSign, "jb_booktime", ""));
               $jbIdNew = getLastInsertId();
            
               $i = 0;
               // for ($i = 0; $i < $numOfStations; $i++) :                   
            
                   $trSort = $i + 1;

                   // Insert tour data for station
                   insertStmt("tour", array("jb_id", $jbIdNew, "ad_id", $f_ad_id, "tr_sort", $trSort, "tr_comp", "", "tr_comp2", "",
                                            "tr_hsno", ".", "csc_id", $trCscId, "tr_status", "0", 
                                            "tr_commission_no", $trCommissionNo, "tr_ware_from_to", "", 
                                            "tr_person", $f_tr_person, "tr_phone", "", "tr_remark", $f_jb_remark));
            
                   // Insert tourservice data
                   insertStmt("tourservice", array("jb_id", $jbIdNew, "csc_id", $cscId, "tr_sort", "0", 
                                                   "srv_id", "0", "trs_srv_name", "Fixpreis", "srvt_id", "0", "trs_srvt_name", ""));
                                                   
                   $trCommissionNo = "";   // Reset commission number because associated to the first station only
               // endfor;
            
               TA("C");
               TA("E");
            endif;
         }
      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_APO.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; ?>">

      <?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>