<?php
/*=======================================================================
 *
 * import_ZONE.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 ZONEN");
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");
   $csId = $objId;
endif;
if ($csId != "") :
   $hqId = getFieldValueFromId("phoenix.customer", "cs_id", $csId, "hq_id");
   $csEid = getFieldValueFromId("phoenix.customer", "cs_id", $csId, "cs_eid");
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 "<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 != "") :

      // Create internal representation
      $srvpArray = array();
      $zoneArray = array();
   
      if (file_exists($importFile)) :
   
         $currentTime = getDateTime("0");
   
   
         // ********************
         // * IMPORT FILE zone *
         // ********************
         if (!(strpos($filename, "import_ZONE_") === false)) :
   
            // Gebietstyptyp; Land; PLZ; Preis
            // Bsp.-Gebietstyptypen IKEA: 0=Kerngebiet, 1=Sekundärgebiet Nord, 2=Sekundärgebiet Süd, 3=Restgebiet Nord, 4=Restgebiet Süd, ...
            // 0;DE;22844;
            // 0;DE;22850;
            // ...
            // 1;DE;22xxx;
            // ...
   
            $rowToImport = array();
   
            $rowToImport[0] = "f_zone_no";
            $rowToImport[1] = "f_country";
            $rowToImport[2] = "f_zipcode";
            $rowToImport[3] = "f_price";
            $rowToImport[4] = "f_price2";
            $rowToImport[5] = "f_price3";
            $rowToImport[6] = "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_zone_no = removeFieldSigns($f_zone_no);
               $f_country = removeFieldSigns($f_country);
               $f_zipcode = removeFieldSigns($f_zipcode);
               $f_price   = removeFieldSigns($f_price);
               $f_price2  = removeFieldSigns($f_price2);
               $f_price3  = removeFieldSigns($f_price3);

               if ($f_zipcode != "") :

                  if ($f_country == "" || !existsEntry("phoenix_special.country",array("cou_iso_2",$f_country))) :
                     $f_country = "DE";
                  endif;

                  // Convert price(s)
                  $f_price  = str_replace (",", ".", $f_price);
                  $f_price2 = str_replace (",", ".", $f_price2);
                  $f_price3 = str_replace (",", ".", $f_price3);

                  // 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($srvpId, $f_zipcode, $f_zone_no, $f_country, $f_price, $f_price2, $f_price3);
                     $x = array_search($f_zone_no, $zoneArray);
                     if ($x === FALSE) :
                        $zoneArray[] = $f_zone_no;
                     endif;
   
                  else :
                     $outText .= getLngt("PLZ " . $f_zipcode . " wird im Basisdatenbestand nicht geführt!") . "<br>";
                  endif;
               else :
                  $outText .= getLngt("Keine PLZ im Datensatz!") . "<br>";
               endif;
            }

if ($debug) :
//   print_r($zoneArray); echo "<br><br>";
//   print_r($srvpArray); echo "<br><br>";
endif;

            // Insert new zone zipcodes into the database from internal structure
            if ($fire && $executeImportProcess == "1") :

               $zoneArrayLen = count($zoneArray);
               $srvpArrayLen = count($srvpArray);

               TA("B");                        

               // Delete all mapped entries of a zone for a special headquarters and customer to be reimported
               // Check for zones existing for the headquarters and the customer.
               $csZonesToBeImported = array();
               for ($k = 0; $k < $zoneArrayLen; $k++) :

                   // Get zone id (primary key) of the current zone number regarding hqId, csId
                   $srvz_id = getFieldValueFromClause("phoenix.servicezone","srvz_id","hq_id = '" . $hqId . "' AND cs_id = '" . $csId . "' AND srvz_no = '" . $zoneArray[$k] . "'");

                   // Delete mapped zipcodes
                   if ($srvz_id != "") :
                      $csZonesToBeImported[$zoneArray[$k]] = $srvz_id;  // Define zones for zone mapppings to be deleted and reimported only
                      deleteStmt("phoenix.servicezonemapping","srvz_id = '" . $srvz_id . "'");
                      $outText .= getLngt("Zone " . $zoneArray[$k] . " für den Kunden " . $csEid . " wurde im Basisdatenbestand entfernt!") . "<br>";
                   else :
                      $outText .= getLngt("Die Zone " . $zoneArray[$k] . " für den Kunden " . $csEid . " wurde nicht gefunden! Wurden die Zonendaten eingerichtet?") . "<br>";
                   endif;
               endfor;

               // Get zones to be imported
               $csZonesKeys = array_keys($csZonesToBeImported);
               // $csZonesKeysLen = count($csZonesKeys);

               // Import new zipcodes
               $executionCount = 0;
               $existingCount = 0;
               for ($k = 0; $k < $srvpArrayLen; $k++) :

                   $x = array_search($srvpArray[$k][2], $csZonesKeys);
                   if (!($x === FALSE)) :

                      // Check for existence of mapping entry
                      if (!existsEntry("phoenix.servicezonemapping",array("srvz_id", $csZonesToBeImported[$srvpArray[$k][2]], "srvp_id", $srvpArray[$k][0]))) :

                         insertStmt("phoenix.servicezonemapping", array("srvz_id", $csZonesToBeImported[$srvpArray[$k][2]], "srvp_id", $srvpArray[$k][0], "srvzm_mt_1", $srvpArray[$k][4], "srvzm_mt_2", $srvpArray[$k][5], "srvzm_mt_3", $srvpArray[$k][6]));
                         $executionCount++;
                      else :
                         $existingCount++;
                      endif;
                   endif;
               endfor;

               TA("C");
               TA("E");

               $outText .= getLngt("Einträge in der Importdatei: " . $dataLen . "<br>");
               $outText .= getLngt("Eingefügte Einträge: " . $executionCount . "<br>");
               $outText .= getLngt("Existierende Einträge: " . $existingCount . "<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;


/*
CREATE TABLE servicezone (
  srvz_id int(10) NOT NULL auto_increment,
  hq_id int(10) NOT NULL default '0',
  cs_id int(10) NOT NULL default '0',
  srvz_no tinyint(3) default '0',
  srvz_name varchar(50) NOT NULL default '',
  srvz_price float(10,4) NOT NULL default '0.0000',
  srvz_price2 float(10,4) NOT NULL default '0.0000',
  PRIMARY KEY (srvz_id)
) ENGINE=InnoDB;

CREATE TABLE servicezonemapping (
  srvz_id int(10) NOT NULL default '0',
  srvp_id int(10) NOT NULL default '0'
) ENGINE=InnoDB;
*/
?>

<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_ZONE.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>