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

// include_once ("../include/auth.inc.php");
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 ZIPCODE_NEIGHBOURS");
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
if ($debug) :
   echo "f_act : " . $f_act . "<br>";
   echo "objType : " . $objType . "<br>";
   echo "objId : " . $objId . "<br>";
   echo "hq_id : " . $hq_id . "<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 ($hq_id != "") :
  
      if (file_exists($importFile)) :
   
         $currentTime = getDateTime("0");
   
   
         // ********************
         // * IMPORT FILE zone *
         // ********************
         if (!(strpos($filename, "import_ZIPCODE_NEIGHBOURS_") === false)) :

            /*
            - CSV-Datei
            - die 1. Spalte enthält die PLZ, für die die folgenden Nachbar-PLZn angelegt werden sollen (Spalte 2 bin Spalte n)
            - Format-Beispiel:
              80331;80539;80469;80538;80336;80335;80333;80337;;;;
              80333;80539;80331;80335;80798;80799;80797;80336;;;;
              80335;80333;80331;80336;80339;80636;80797;;;;;
              80336;80331;80337;81373;80339;80335;80333;81371;80469;;;
              80337;80469;81371;80336;80331;81373;81543;;;;;
              80339;80336;81373;80686;80634;80636;80335;80639;80687;80337;;
              80469;81541;81543;81371;80337;80538;81667;80331;80539;80336;;
              80538;80802;81679;81675;81667;80469;80331;80539;81669;;;
              80539;80538;80469;80331;80333;80799;80802;80801;;;;
              80634;80636;80339;80639;80637;80335;80638;80687;;;;
            */

            $rowToImport = array();
   
            $rowToImport[0]  = "f_zipcode";
            $rowToImport[1]  = "f_zip_01";
            $rowToImport[2]  = "f_zip_02";
            $rowToImport[3]  = "f_zip_03";
            $rowToImport[4]  = "f_zip_04";
            $rowToImport[5]  = "f_zip_05";
            $rowToImport[6]  = "f_zip_06";
            $rowToImport[7]  = "f_zip_07";
            $rowToImport[8]  = "f_zip_08";
            $rowToImport[9]  = "f_zip_09";
            $rowToImport[10] = "f_zip_10";
            $rowToImport[11] = "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];
               }

               $zipcodeArray = array();  // Init

               $f_zipcode        = removeFieldSigns($f_zipcode);
               $zipcodeArray[0]  = $f_zipcode;
               $zipcodeArray[1]  = removeFieldSigns($f_zip_01);
               $zipcodeArray[2]  = removeFieldSigns($f_zip_02);
               $zipcodeArray[3]  = removeFieldSigns($f_zip_03);
               $zipcodeArray[4]  = removeFieldSigns($f_zip_04);
               $zipcodeArray[5]  = removeFieldSigns($f_zip_05);
               $zipcodeArray[6]  = removeFieldSigns($f_zip_06);
               $zipcodeArray[7]  = removeFieldSigns($f_zip_07);
               $zipcodeArray[8]  = removeFieldSigns($f_zip_08);
               $zipcodeArray[9]  = removeFieldSigns($f_zip_09);
               $zipcodeArray[10] = removeFieldSigns($f_zip_10);

               $zipcodeArrayLen = count($zipcodeArray);

               $outText .=  "(" . $j . ".) ";

               if ($f_zipcode != "") :  // ">1", because $zipcodeArray[1] ist first neighbour
               
                  if ($zipcodeArrayLen > 1) :  // ">1", because $zipcodeArray[1] ist first neighbour

                     // Get srvp_id from serviceplz
                     $srvpId = getFieldValueFromId("phoenix.serviceplz", "srvp_plz", $f_zipcode, "srvp_id");
                     
                     if ($srvpId != "") :
                     
                        $outText .=  $f_zipcode . " => ";
                     
                        for ($z = 1; $z < $zipcodeArrayLen; $z++) :  // ($z = 1) <=> First neighbour
                     
                            if ($zipcodeArray[$z] != "") :
                     
                               $srvpIdNeighbour = getFieldValueFromId("phoenix.serviceplz", "srvp_plz", $zipcodeArray[$z], "srvp_id");
                               
                               if ($srvpIdNeighbour != "") :
                               
                                  // Insert into serviceplzneighbour if does not exist
                                  if ($executeImportProcess == "1") :
                                     
                                     if (!existsEntry("phoenix.serviceplzneighbour",array("hq_id", $hq_id, "srvp_id", $srvpId, "srvp2_id", $srvpIdNeighbour))) :
                               
                                        if ($fire) :
                                           insertStmt("phoenix.serviceplzneighbour", array("hq_id", $hq_id, "srvp_id", $srvpId, "srvp2_id", $srvpIdNeighbour, "srvpn_sort", $z));
                                           $outText .= "[" . $zipcodeArray[$z] . " : INS_OK] ";
                                        else :
                                           $outText .= "[" . $zipcodeArray[$z] . " : INS_RDY2IMP] ";  // Ready to be imported
                                        endif;
                                     else :
                                        $outText .= "[" . $zipcodeArray[$z] . " : EXISTS] ";
                                     endif;
                                  else :
                                     $outText .= "[" . $zipcodeArray[$z] . "] ";
                                  endif;
                               else :
                                  $outText .= "<span class=\"f8np1_red\">" . "[" . getLngt("NB-PLZ " . $zipcodeArray[$z] . " NIB!") . "]</span> ";  // Nachbar-PLZ nicht im Basisdatenbestand
                               endif;
                            else :
                               $outText .= "<span class=\"f8np1_red\">" . "[" . getLngt("NB-PLZ NA!") . "]</span> ";  // Nachbar-PLZ nicht in der Importdatei angegeben
                            endif;
                        endfor;
                     else :
                        $outText .= "[" .  getLngt("Basis-PLZ " . $f_zipcode . " wird im Basisdatenbestand nicht geführt!") . "] ";
                     endif;
                  else :
                     $outText .=  getLngt("Keine Nachbar-PLZ angegeben!") . "<br>";
                  endif;
               else :
                  $outText .=  getLngt("Basis-PLZ nicht angegeben!") . "<br>";
               endif;
               
               $outText .=  "<br>";
            }
         endif;
/*
               TA("B");                        
               TA("C");
               TA("E");
*/
      else :
         $statusMessage .= getLngt("Die angegebene Datei existiert nicht!");
      endif;
   else :
      $statusMessage .= getLngt("Diese Datei muss für eine bestimmte Niederlassung 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_ZIPCODE_NEIGHBOURS.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>