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

include_once ("../import/import.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 EXPRESS");
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 = true;
endif;

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

// Customer and headquarters references have to exist
$hqId = "";
$csEid = "";
$objType = trim($objType);
$objId = trim($objId);
if ($objType == "CS" && is_numeric($objId)) :
   $csId = getFieldValueFromId("phoenix.customer", "cs_id", $objId, "cs_id");
endif;
if ($csId != "") :
   $hqId = getFieldValueFromId("phoenix.customer", "cs_id", $csId, "hq_id");
   $csEid = getFieldValueFromId("phoenix.customer", "cs_id", $csId, "cs_eid");
   
   // Get zone IDs because an update of zipcodes has to be filtered by the zones of the current customer
   $srvzIdArray = getColVectorFromDB2ArrayByClause("servicezone", "srvz_id", "cs_id = '" . $csId . "'", "", "", "");
   $srvzIdArrayLen = count($srvzIdArray);
endif;
if ($debug) :
   echo "f_act : " . $f_act . "<br>";
   echo "objType : " . $objType . "<br>";
   echo "objId : " . $objId . "<br>";
   echo "hqId : " . $hqId . "<br>";
   echo "csId : " . $csId . "<br>";
   echo "srvzIdArray : " . implode(",", $srvzIdArray) . "<br>";
   echo "<br>";   
endif;


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


if ($importFile != "") :

   if ($hqId != "" && $csId != "" && $srvzIdArrayLen > 0) :
   
      // Create internal representation
      $srvpArray = array();
      $srvzIdsOfCurrentCustomer = implode(",", $srvzIdArray);  // Zone IDs of the current customer
   
      if (file_exists($importFile)) :
   
         $currentTime = getDateTime("0");
         $executionCount = 0;
         $failedCount = 0;
   
         // ********************
         // * IMPORT FILE zone *
         // ********************
         if (!(strpos($filename, "import_EXPRESS_") === false)) :
   
            // PLZ
            // 22844
            // 22850
            // ...
            // 22xxx
            // ...
   
            $rowToImport = array();
   
            $rowToImport[0] = "f_zipcode";
            $rowToImport[1] = "f_price";
            $rowToImport[2] = "f_dummy";
   
            $rowToImportLen = count($rowToImport);
   
            // read file to import
            $data = importCSV($importFile, $delimiter);
            $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_zipcode = removeFieldSigns($f_zipcode);
               $f_price = str_replace(",", ".", $f_price);
               if ($f_price == "" || !is_numeric($f_price)) :
                  $f_price = "0.00";
               endif;
               $f_country = "";
   
               if ($f_zipcode != "") :
   
                  if ($f_country == "" || !existsEntry("phoenix_special.country",array("cou_iso_2",$f_country))) :
                     $f_country = "DE";
                  endif;
   
                  // Get srvp_id from serviceplz
                  $srvpId = getFieldValueFromId("phoenix.serviceplz", "srvp_plz", $f_zipcode, "srvp_id");
   
                  if ($srvpId != "") :
   
                     // If country "Germany" then fill zipcode with "0" up to 5 chars
                     if ($f_country == "DE") :
                        $f_zipcode = pad($f_zipcode, 5);
                     endif;
   
                     // Set arrays
                     $srvpArray[] = array($f_zipcode, $srvpId, $f_country, $f_price);
   
                  else :
                     $outText .= getLngt("PLZ " . $f_zipcode . " wird im Basisdatenbestand nicht geführt!") . "<br>";
                  endif;
               else :
                  $outText .= getLngt("Keine PLZ im Datensatz!") . "<br>";
               endif;
            }
   
   
            // Insert new zone zipcodes into the database from internal structure
            if ($fire && $executeImportProcess == "1") :
   
               $srvpArrayLen = count($srvpArray);
   
               TA("B");                        
   
               // Remove ALL EXPRESS associations for the CURRENT CUSTOMER
               updateStmt("phoenix.servicezonemapping", "", "", array("srvzm_mt_1", "0.00"), "srvz_id IN (" . $srvzIdsOfCurrentCustomer . ")");
   
               // Associate zipcodes to be enabled for EXPRESS for the current customer
               for ($k = 0; $k < $srvpArrayLen; $k++) :
   
                   $res = updateStmt("phoenix.servicezonemapping", "srvp_id", $srvpArray[$k][1], array("srvzm_mt_1", $srvpArray[$k][3]), "srvz_id IN (" . $srvzIdsOfCurrentCustomer . ")");
                   
                   // Check update for success
                   if ($db->affected_rows > 0) :
                      $executionCount++;
                      $outText .= getLngt("Update PLZ:") . " " . $srvpArray[$k][0] . " " . getLngt("mit Preis") . " " . $srvpArray[$k][3] . "<br>";
                   else :
                      $failedCount++;
                   endif;
               endfor;
   
               TA("C");
               TA("E");
   
               $outText .= getLngt("Einträge in der Importdatei: " . $dataLen . "<br>");
               $outText .= getLngt("Verarbeitete Einträge: " . $executionCount . "<br>");
               $outText .= getLngt("Nicht verarbeitete Einträge: " . $failedCount . "<br>");
               // $closeWindow = "1";
            endif;
         endif;
   
         
         // ********************
         // * IMPORT FILE xxxx *
         // ********************
         // if (!(strpos($filename, "import_xxxx") === false)) :
   
   
   
         // endif;
         
      else :
         $statusMessage .= getLngt("Die angegebene Datei existiert nicht!");
      endif;
   else :
      $statusMessage .= getLngt("Diese Datei muss für einen bestimmten Kunden verarbeitet werden!");
   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_EXPRESS.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>