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

include_once ("../include/global.inc.php");
include_once ("../include/auth.inc.php");


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act","mode","csId","vhtId","opener","orderByServices","statusMessage","zipcodeRow","zipcodeCol",
                         "f_zipcode2", "f_del_neighbour_id", "f_newneighbourforzipcode", "deactivateMenu", "f_vehicletype",
                         "pageFirstCall", "f_chkbx_toggle", "f_chkbx_toggle_cr"));

getLanguage(__FILE__);

$pageTitel = getLngt("PLZ-PREISE");
if ($mode == "discount") : $pageTitel = getLngt("PLZ-RABATTE"); endif;
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");

getCurrentScript(__FILE__);

// Check for authentication access and granted rights
$usrAccessArray["hq"] = "1";
authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
authCheckEmployeeRights($emp_id, "2", "1");

// Get usr_id of the current employee (session)
$currentSessionUsrId = getFieldValueFromId("employee", "emp_id", $emp_id, "usr_id");


if ($pageFirstCall == "" || ($f_chkbx_toggle == "" && $f_chkbx_toggle_cr == "")) :
   $pageFirstCall = 1;
   $f_chkbx_toggle = "service";
   $f_chkbx_toggle_cr = "";
endif;
$f_chkbx_toggle_checked = "";
$f_chkbx_toggle_cr_checked = "";
if ($f_chkbx_toggle == "service") : $f_chkbx_toggle_checked = "checked"; endif;
if ($f_chkbx_toggle_cr == "service_cr") : $f_chkbx_toggle_cr_checked = "checked"; endif;

// Price-mode or discount-mode
if ($mode == "") : $mode = "price"; endif;

// General price/discount for all customers
if ($csId == "") : $csId = "0"; endif;

// General price/discount for all vehicle types
if ($vhtId == "") : $vhtId = "0"; endif;
if ($f_vehicletype != "" && is_numeric($f_vehicletype)) : $vhtId = $f_vehicletype; endif;
if (!existsEntry("metatype",array("mt_type","vehicletype","mt_sort",$vhtId))) : $vhtId = "0"; endif;  // Check for existence in "metatype"

// Check opener ONLY for output in target
$htmlFormTarget = "target=\"\"";
if ($opener == "1") : $htmlFormTarget = ""; endif;

// Get parameters
$parServiceVehicleTypeEnabled = getParameterValue("0", "SERVICE_VEHICLE_TYPE_ENABLED", $hq_id);

// Get mapped vehicle type id if a mapping does exist
$vhtId = getServiceVehicleTypeMappingId($vhtId);

// Init
$areaneighbours = array();
$areaneighbours["id"] = array();
$areaneighbours["name"] = array();
$areaneighbours["sort"] = array();


$cmpComp = "";
$cmpComp2 = "";
if ($csId != "0") :    
   $cmpId = getFieldValueFromId("customer","cs_id",$csId,"cmp_id");
   $tmpFields = getFieldsValueFromId("company","cmp_id",$cmpId,array("cmp_comp","cmp_comp2"));
   $cmpComp = $tmpFields[0];
   $cmpComp2 = $tmpFields[1];
endif;

$vhtName = "";
if ($vhtId != "0") :
   $vhtName = getFieldValueFromClause("metatype","mt_value","mt_type = 'vehicletype' AND mt_sort = '" . $vhtId . "'");
endif;

// Sorting of the services to be displayed
if ($orderByServices == "") : $orderByServices = "srvp.srvp_plz" ; endif;

// Offset for output
$offset = NUM_ROWS_ZIPCODE_MATRIX;

// Selection and display from the starting zipcodes (row and column)
if ($zipcodeRow == "" || $zipcodeCol == "") : 
   $sqlquery = "SELECT MIN(srvp.srvp_plz) AS plz"
             . " FROM serviceplz AS srvp";
             
   $result = $db->query($sqlquery);
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());   
   while ($row = $result->fetch_assoc()):
      if ($zipcodeRow == "") : $zipcodeRow = $row["plz"]; endif;
      if ($zipcodeCol == "") : $zipcodeCol = $row["plz"]; endif;
   endwhile;
   $result->free();   
endif;


// *******************************************************
// * Selection of all plz of the specified submatrix-row *
// *******************************************************           
$sqlquery = "SELECT srvp.srvp_id, srvp.srvp_plz"
            . " FROM serviceplz AS srvp"
            . " WHERE srvp.srvp_plz >= '" . $zipcodeRow . "' AND "
            . "       srvp.srvp_valid = '1' "
            . " ORDER BY " . $orderByServices 
            . " LIMIT " . $offset;

$result = $db->query($sqlquery);
if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

$services = array();
$count = 0;
while ($row = $result->fetch_assoc()):
      $count++;
      $services["id"][$count] = $row["srvp_id"];
      $services["plz"][$count] = $row["srvp_plz"];
endwhile;
$result->free();


// **********************************************************
// * Selection of all plz of the specified submatrix-column *
// **********************************************************
$sqlquery = "SELECT srvp.srvp_id, srvp.srvp_plz"
            . " FROM serviceplz AS srvp"
            . " WHERE srvp.srvp_plz >= '" . $zipcodeCol . "' AND "
            . "       srvp.srvp_valid = '1' "            
            . " ORDER BY " . $orderByServices 
            . " LIMIT " . $offset;

$result = $db->query($sqlquery);
if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

$services2 = array();
$count = 0;
while ($row = $result->fetch_assoc()):
      $count++;
      $services2["id"][$count] = $row["srvp_id"];
      $services2["plz"][$count] = $row["srvp_plz"];
endwhile;
$result->free();


// ******************************************
// * Selection of serviceplzcustomer-values *
// ******************************************
$sqlquery = "SELECT srvpc.srvp_id, srvpc.srvp2_id, srvpc.cs_id, srvpc.srvpc_price, srvpc.srvpc_discount, srvpc.srvpc_cr_price, srvpc.srvpc_cr_discount"
            . " FROM serviceplz AS srvp, serviceplz AS srvp2, serviceplzcustomer AS srvpc"
            . " WHERE srvpc.srvp_id = srvp.srvp_id"
            . "   AND srvpc.srvp2_id = srvp2.srvp_id"
            . "   AND srvpc.cs_id = " . $csId
            . "   AND srvpc.vht_id = " . $vhtId
            . "   AND srvpc.hq_id = " . $hq_id
            . " ORDER BY " . $orderByServices;

$result = $db->query($sqlquery);
if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

$servicePrices = array();
$serviceDiscounts = array();
while ($row = $result->fetch_assoc()):
      $servicePrices[$row["srvp_id"]][$row["srvp2_id"]] = $row["srvpc_price"];
      $serviceDiscounts[$row["srvp_id"]][$row["srvp2_id"]] = $row["srvpc_discount"];
      $serviceCrPrices[$row["srvp_id"]][$row["srvp2_id"]] = $row["srvpc_cr_price"];
      $serviceCrDiscounts[$row["srvp_id"]][$row["srvp2_id"]] = $row["srvpc_cr_discount"];
endwhile;
$result->free();


// Number of entries
$lenServices = count($services["id"]);
$lenServices2 = count($services2["id"]);
if ($services["id"][1] == "" || $services2["id"][1] == ""): 
   $lenServices = 0;
   $lenServices2 = 0;
endif;


// If matrix (generated above) is from a special customer ($csId != "0"), the default prices ($csId == "0") have to be shown to compare the prices
// Setup a second request according to the one before with ($csId == "0")
if ($csId != "0") :
   $sqlquery = "SELECT srvpc.srvp_id, srvpc.srvp2_id, srvpc.cs_id, srvpc.srvpc_price, srvpc.srvpc_discount, srvpc.srvpc_cr_price, srvpc.srvpc_cr_discount"
               . " FROM serviceplz AS srvp, serviceplz AS srvp2, serviceplzcustomer AS srvpc"
               . " WHERE srvpc.srvp_id = srvp.srvp_id"
               . "   AND srvpc.srvp2_id = srvp2.srvp_id"
               . "   AND srvpc.cs_id = '0'"
               . "   AND srvpc.vht_id = " . $vhtId
               . "   AND srvpc.hq_id = " . $hq_id
               . " ORDER BY " . $orderByServices;
   
   $result = $db->query($sqlquery);
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
   
   $servicePricesDefault = array();
   $serviceDiscountsDefault = array();
   while ($row = $result->fetch_assoc()):
         $servicePricesDefault[$row["srvp_id"]][$row["srvp2_id"]] = $row["srvpc_price"];
         $serviceDiscountsDefault[$row["srvp_id"]][$row["srvp2_id"]] = $row["srvpc_discount"];
         $serviceCrPricesDefault[$row["srvp_id"]][$row["srvp2_id"]] = $row["srvpc_cr_price"];
         $serviceCrDiscountsDefault[$row["srvp_id"]][$row["srvp2_id"]] = $row["srvpc_cr_discount"];
   endwhile;
   $result->free();   
endif;


// *** Storing-processes ***
// *** BEGIN ***************

// Storing prices and discounts if requested
// Using the results of the statements before!!!
if ($f_act != "" && $f_act == "save") :

   // Set the current timestamp to store the data
   $currentTime = getDateTime("0");

   TA("B");

   for ($i = 1; $i <= $lenServices2; $i++) :

       for ($j = 1; $j <= $lenServices; $j++) :    

           // Define current service-plz-ids
           $srvPlzCur = $services["id"][$j];
           $srvp2PlzCur = $services2["id"][$i];

           // Get current input-type-text-field with price-/dicount-value
           list ($newValueToBeStored) = getHttpVars(array("service_". $srvPlzCur ."_" . $srvp2PlzCur));
           if ($newValueToBeStored == "") : $newValueToBeStored = "0"; endif;
           list ($newCrValueToBeStored) = getHttpVars(array("service_cr_". $srvPlzCur ."_" . $srvp2PlzCur));
           if ($newCrValueToBeStored == "") : $newCrValueToBeStored = "0"; endif;
           
           // Allow float data with "." and ","
           $newValueToBeStored = str_replace (",", ".", $newValueToBeStored);
           $newCrValueToBeStored = str_replace (",", ".", $newCrValueToBeStored);
           
           $servicePrices[$srvPlzCur][$srvp2PlzCur] = mcArrMultiDimIsSet($servicePrices[$srvPlzCur], $srvp2PlzCur);
           $serviceDiscounts[$srvPlzCur][$srvp2PlzCur] = mcArrMultiDimIsSet($serviceDiscounts[$srvPlzCur], $srvp2PlzCur);
           $serviceCrPrices[$srvPlzCur][$srvp2PlzCur] = mcArrMultiDimIsSet($serviceCrPrices[$srvPlzCur], $srvp2PlzCur);
           $serviceCrDiscounts[$srvPlzCur][$srvp2PlzCur] = mcArrMultiDimIsSet($serviceCrDiscounts[$srvPlzCur], $srvp2PlzCur);
           
           if ($servicePrices[$srvPlzCur][$srvp2PlzCur] == "") : $servicePrices[$srvPlzCur][$srvp2PlzCur] = "0"; endif;
           if ($serviceDiscounts[$srvPlzCur][$srvp2PlzCur] == "") : $serviceDiscounts[$srvPlzCur][$srvp2PlzCur] = "0"; endif;
           if ($serviceCrPrices[$srvPlzCur][$srvp2PlzCur] == "") : $serviceCrPrices[$srvPlzCur][$srvp2PlzCur] = "0"; endif;
           if ($serviceCrDiscounts[$srvPlzCur][$srvp2PlzCur] == "") : $serviceCrDiscounts[$srvPlzCur][$srvp2PlzCur] = "0"; endif;

           if ($mode == "price") :

              // Check for necessity to update or insert
              if ($servicePrices[$srvPlzCur][$srvp2PlzCur] != $newValueToBeStored || $serviceCrPrices[$srvPlzCur][$srvp2PlzCur] != $newCrValueToBeStored) :

                 if (existsEntry("serviceplzcustomer",array("srvp_id",$srvPlzCur,"srvp2_id",$srvp2PlzCur,"hq_id",$hq_id,"cs_id",$csId,"vht_id",$vhtId))) :
                    // Update the new price              
                    $sqlStmt = "UPDATE serviceplzcustomer SET srvpc_price = $newValueToBeStored, srvpc_cr_price = $newCrValueToBeStored"
                               . " WHERE srvp_id = $srvPlzCur AND srvp2_id = $srvp2PlzCur AND hq_id = $hq_id AND cs_id = $csId AND vht_id = $vhtId";
                    $res = $db->query($sqlStmt);
                    if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;
                 else :                
                    if ($newValueToBeStored != "0" || $newCrValueToBeStored != "0") :
                       // Insert the new price
                       $tmpFields = array("srvp_id",$srvPlzCur,"srvp2_id",$srvp2PlzCur,"hq_id",$hq_id,"cs_id",$csId,"vht_id",$vhtId,"srvpc_price",$newValueToBeStored,"srvpc_discount",$serviceDiscounts[$srvPlzCur][$srvp2PlzCur],"srvpc_cr_price",$newCrValueToBeStored,"srvpc_cr_discount",$serviceCrDiscounts[$srvPlzCur][$srvp2PlzCur]);
                       insertStmt("serviceplzcustomer",$tmpFields);
                    endif;
                 endif;
                 
                 // Insert current prices AND (!) discounts into the servicehistory
                 $tmpFields = array("srvp_id",$srvPlzCur,"srvp2_id",$srvp2PlzCur,"hq_id",$hq_id,"cs_id",$csId,"vht_id",$vhtId,"usr_id",$currentSessionUsrId,"srvph_validfrom",$currentTime,"srvph_price",$newValueToBeStored,"srvph_discount",$serviceDiscounts[$srvPlzCur][$srvp2PlzCur],"srvph_cr_price",$newCrValueToBeStored,"srvph_cr_discount",$serviceCrDiscounts[$srvPlzCur][$srvp2PlzCur]);
                 insertStmt("serviceplzhistory",$tmpFields);
                 
                 $servicePrices[$srvPlzCur][$srvp2PlzCur] = $newValueToBeStored;
                 $serviceCrPrices[$srvPlzCur][$srvp2PlzCur] = $newCrValueToBeStored;
              endif;
                 
           else :

              // Check for necessity to update or insert
              if ($serviceDiscounts[$srvPlzCur][$srvp2PlzCur] != $newValueToBeStored || $serviceCrDiscounts[$srvPlzCur][$srvp2PlzCur] != $newCrValueToBeStored) :
           
                 if (existsEntry("serviceplzcustomer",array("srvp_id",$srvPlzCur,"srvp2_id",$srvp2PlzCur,"hq_id",$hq_id,"cs_id",$csId,"vht_id",$vhtId))) :
                    // Update the new discount              
                    $sqlStmt = "UPDATE serviceplzcustomer SET srvpc_discount = $newValueToBeStored, srvpc_cr_discount = $newCrValueToBeStored"
                               . " WHERE srvp_id = $srvPlzCur AND srvp2_id = $srvp2PlzCur AND hq_id = $hq_id AND cs_id = $csId AND vht_id = $vhtId";
                    $res = $db->query($sqlStmt);
                    if (DB::isError($res)) : die ("$PHP_SELF: " . $res->getMessage()); endif;
                 else :                
                    if ($newValueToBeStored != "0" || $newCrValueToBeStored != "0") :
                       // Insert the new discount
                       $tmpFields = array("srvp_id",$srvPlzCur,"srvp2_id",$srvp2PlzCur,"hq_id",$hq_id,"cs_id",$csId,"vht_id",$vhtId,"srvpc_price",$servicePrices[$srvPlzCur][$srvp2PlzCur],"srvpc_discount",$newValueToBeStored,"srvpc_cr_price",$serviceCrPrices[$srvPlzCur][$srvp2PlzCur],"srvpc_cr_discount",$newCrValueToBeStored);
                       insertStmt("serviceplzcustomer",$tmpFields);
                    endif;
                 endif;
                 
                 // Insert current prices AND (!) discounts into the servicehistory
                 $tmpFields = array("srvp_id",$srvPlzCur,"srvp2_id",$srvp2PlzCur,"hq_id",$hq_id,"cs_id",$csId,"vht_id",$vhtId,"usr_id",$currentSessionUsrId,"srvph_validfrom",$currentTime,"srvph_price",$servicePrices[$srvPlzCur][$srvp2PlzCur],"srvph_discount",$newValueToBeStored,"srvph_cr_price",$serviceCrPrices[$srvPlzCur][$srvp2PlzCur],"srvph_cr_discount",$newCrValueToBeStored);
                 insertStmt("serviceplzhistory",$tmpFields);
                 
                 $serviceDiscounts[$srvPlzCur][$srvp2PlzCur] = $newValueToBeStored;
                 $serviceCrDiscounts[$srvPlzCur][$srvp2PlzCur] = $newCrValueToBeStored;
              endif;           
           endif;
                      
       endfor;
   endfor;
   
   TA("C");
   TA("E");   
endif;


// Store new association between current area and entered neighbour
if ($f_act != "" && $f_act == "save_newneighbourassociation" && $f_zipcode2 != "") :

   // Syntax of the zipcode is correct?
   if ($f_newneighbourforzipcode != "") :

      // Get the internal id of the current zipcode
      $srvp_id = getFieldValueFromId("serviceplz","srvp_plz",$f_zipcode2,"srvp_id");
      // First make a lookup if neighbour exists and get the internal id of the new neighbour
      $srvp2_id = getFieldValueFromId("serviceplz","srvp_plz",$f_newneighbourforzipcode,"srvp_id");
      
      if ($srvp_id != "" && $srvp2_id != "") :

         if ($srvp_id != $srvp2_id) :

            // The relation of the neighbourhood is symmetric but NOT transitive!
            // Therefore ONLY both relations (aRb AND bRa) have to be inserted into the database
            
            TA("B");
            
            $relationOne = existsEntry("serviceplzneighbour",array("hq_id",$hq_id,"srvp_id",$srvp_id,"srvp2_id",$srvp2_id));
            $relationTwo = existsEntry("serviceplzneighbour",array("hq_id",$hq_id,"srvp_id",$srvp2_id,"srvp2_id",$srvp_id));

            // If neighbour exists then lookup for an existing association between the neighbour and another zipcode
            if (!$relationOne) :
               // Insert the new association
               $tmpFields = array("hq_id",$hq_id,"srvp_id",$srvp_id,"srvp2_id",$srvp2_id);
               insertStmt("serviceplzneighbour",$tmpFields);
            endif;
         
            if (!$relationTwo) :
              // Insert the new reverse association
              $tmpFields = array("hq_id",$hq_id,"srvp_id",$srvp2_id,"srvp2_id",$srvp_id);
              insertStmt("serviceplzneighbour",$tmpFields);
            endif;         
           
            if ($relationOne && $relationTwo) :           
               $statusMessage = "Diese Nachbarschaft besteht bereits!";
            endif;

            TA("C");
            TA("E");
         else :
            $statusMessage = getLngt("Eine Nachbarschaft identischer PLZn liegt implizit schon vor!");
         endif;

      else :
         $statusMessage = getLngt("Die PLZ ist nicht in der Datenbank verzeichnet!");
      endif;
   else :
      $statusMessage = getLngt("Die PLZ wurde falsch eingegeben!");
   endif;      
endif;

// Store new association between current area and entered zipcode
if ($f_act != "" && $f_act == "save_removeneighbourassociation") :

   // Entries to be deleted?
   $fieldsLength = count($f_del_neighbour_id);

   if ($fieldsLength > 0 && $f_del_neighbour_id[0] != "") :

      TA("B");
      
      // Remove all associations according to the zipcode nested in array $f_del_zipcode_id
      for ($i = 0; $i < $fieldsLength; $i++) :
         
          // Get the internal id of the current area
          $srvp_id = getFieldValueFromId("serviceplz","srvp_plz",$f_zipcode2,"srvp_id");
      
          deleteStmt("serviceplzneighbour","hq_id = '" . $hq_id . "' AND srvp_id = " . $srvp_id . " AND srvp2_id = " . $f_del_neighbour_id[$i]);
          deleteStmt("serviceplzneighbour","hq_id = '" . $hq_id . "' AND srvp_id = " . $f_del_neighbour_id[$i] . " AND srvp2_id = " . $srvp_id);
      endfor;
      
      TA("C");
      TA("E");
   else :
      $statusMessage = getLngt("Bitte markieren Sie zu löschenden Nachbar-PLZn durch anklicken der jeweiligen Checkbox hinter der PLZ!");
   endif;      
endif;

// *** END ***************


// *****************************************************
// * Generation of the price-matrix or discount-matrix *
// *****************************************************

// Table-header
$serviceOutput = "<tr>\n";
$serviceOutput .= "<td>&nbsp;</td>\n";   // because of the following row-names
for ($j = 1; $j <= $lenServices2; $j++) :
    $serviceOutput .= "<td>" . $services2["plz"][$j] . "</td>\n";
endfor;
$serviceOutput .= "</tr>\n";

// Table-data
for ($j = 1; $j <= $lenServices; $j++) :
    $serviceOutput .= "<tr>\n";
    $serviceOutput .= "<td style=\"vertical-align: middle;\">" . $services["plz"][$j] . "</td>\n";
    for ($i = 1; $i <= $lenServices2; $i++) :    
    
        // Define current plz-ids
        $srvPlzCur = $services["id"][$j];
        $srvp2PlzCur = $services2["id"][$i];    

        if ($mode == "price") :
           $servicePrices[$srvPlzCur][$srvp2PlzCur] = mcArrMultiDimIsSet($servicePrices[$srvPlzCur], $srvp2PlzCur);
           if ($servicePrices[$srvPlzCur][$srvp2PlzCur] == "") : $servicePrices[$srvPlzCur][$srvp2PlzCur] = "0.00"; endif;
           $serviceCrPrices[$srvPlzCur][$srvp2PlzCur] = mcArrMultiDimIsSet($serviceCrPrices[$srvPlzCur], $srvp2PlzCur);
           if ($serviceCrPrices[$srvPlzCur][$srvp2PlzCur] == "") : $serviceCrPrices[$srvPlzCur][$srvp2PlzCur] = "0.00"; endif;
           $serviceOutput .= "<td>";
           $serviceOutput .= "<div class=\"service\">";
           $serviceOutput .= "<input type=\"text\" class=\"cell_attr\" name=\"service_" . $srvPlzCur . "_" . $srvp2PlzCur . "\" value=\"" . $servicePrices[$srvPlzCur][$srvp2PlzCur] . "\" size=\"7\" align=\"right\">";
           if ($csId != "0") :
              $servicePricesDefault[$srvPlzCur][$srvp2PlzCur] = mcArrMultiDimIsSet($servicePricesDefault[$srvPlzCur], $srvp2PlzCur);
              if ($servicePricesDefault[$srvPlzCur][$srvp2PlzCur] == "") : $servicePricesDefault[$srvPlzCur][$srvp2PlzCur] = "0.00"; endif;
              $serviceOutput .= "(" . $servicePricesDefault[$srvPlzCur][$srvp2PlzCur] . ")&nbsp;&nbsp;";
           endif;
           $serviceOutput .= "</div>\n";
           $serviceOutput .= "<div class=\"service_cr\">";
           $serviceOutput .= "<input type=\"text\" class=\"cell_attr_cr\" name=\"service_cr_" . $srvPlzCur . "_" . $srvp2PlzCur . "\" value=\"" . $serviceCrPrices[$srvPlzCur][$srvp2PlzCur] . "\" size=\"7\" align=\"right\">";
           if ($csId != "0") :
              $serviceCrPricesDefault[$srvPlzCur][$srvp2PlzCur] = mcArrMultiDimIsSet($serviceCrPricesDefault[$srvPlzCur], $srvp2PlzCur);
              if ($serviceCrPricesDefault[$srvPlzCur][$srvp2PlzCur] == "") : $serviceCrPricesDefault[$srvPlzCur][$srvp2PlzCur] = "0.00"; endif;
              $serviceOutput .= "(" . $serviceCrPricesDefault[$srvPlzCur][$srvp2PlzCur] . ")&nbsp;&nbsp;";
           endif;
           $serviceOutput .= "</div></br>\n";
           $serviceOutput .= "</td>\n";
        else :
           $serviceDiscounts[$srvPlzCur][$srvp2PlzCur] = mcArrMultiDimIsSet($serviceDiscounts[$srvPlzCur], $srvp2PlzCur);
           if ($serviceDiscounts[$srvPlzCur][$srvp2PlzCur] == "") : $serviceDiscounts[$srvPlzCur][$srvp2PlzCur] = "0.00"; endif;
           $serviceCrDiscounts[$srvPlzCur][$srvp2PlzCur] = mcArrMultiDimIsSet($serviceCrDiscounts[$srvPlzCur], $srvp2PlzCur);
           if ($serviceCrDiscounts[$srvPlzCur][$srvp2PlzCur] == "") : $serviceCrDiscounts[$srvPlzCur][$srvp2PlzCur] = "0.00"; endif;
           $serviceOutput .= "<td>";
           $serviceOutput .= "<div class=\"service\">";
           $serviceOutput .= "<input type=\"text\" class=\"cell_attr\" name=\"service_" . $srvPlzCur . "_" . $srvp2PlzCur . "\" value=\"" . $serviceDiscounts[$srvPlzCur][$srvp2PlzCur] . "\" size=\"7\" align=\"right\">";
           if ($csId != "0") :
              $serviceDiscountsDefault[$srvPlzCur][$srvp2PlzCur] = mcArrMultiDimIsSet($serviceDiscountsDefault[$srvPlzCur], $srvp2PlzCur);
              if ($serviceDiscountsDefault[$srvPlzCur][$srvp2PlzCur] == "") : $serviceDiscountsDefault[$srvPlzCur][$srvp2PlzCur] = "0.00"; endif;
              $serviceOutput .= "(" . $serviceDiscountsDefault[$srvPlzCur][$srvp2PlzCur] . ")&nbsp;&nbsp;";
           endif;
           $serviceOutput .= "</div>\n";
           $serviceOutput .= "<div class=\"service_cr\">";
           $serviceOutput .= "<input type=\"text\" class=\"cell_attr_cr\" name=\"service_cr_" . $srvPlzCur . "_" . $srvp2PlzCur . "\" value=\"" . $serviceCrDiscounts[$srvPlzCur][$srvp2PlzCur] . "\" size=\"7\" align=\"right\">";
           if ($csId != "0") :
              $serviceCrDiscountsDefault[$srvPlzCur][$srvp2PlzCur] = mcArrMultiDimIsSet($serviceCrDiscountsDefault[$srvPlzCur], $srvp2PlzCur);
              if ($serviceCrDiscountsDefault[$srvPlzCur][$srvp2PlzCur] == "") : $serviceCrDiscountsDefault[$srvPlzCur][$srvp2PlzCur] = "0.00"; endif;
              $serviceOutput .= "(" . $serviceCrDiscountsDefault[$srvPlzCur][$srvp2PlzCur] . ")&nbsp;&nbsp;";
           endif;
           $serviceOutput .= "</div></br>\n";
           $serviceOutput .= "</td>\n";
        endif;
    endfor;
    $serviceOutput .= "</tr>\n";
endfor;


// Output
if ($mode == "price") : 
   $title = getLngt("Allgemeine Preise und Frachtvergütungen für PLZ-Bereiche");
else :    
   $title = getLngt("Allgemeine Rabatte und Frachtvergütungsrabatte für PLZ-Bereiche [in %]");
endif;   
if ($csId != "0") :   
   if ($mode == "price") : 
      $title = getLngt("PLZ-Bereichspreise/-frachtvergütungen speziell für den Kunden") . " " . $cmpComp . " " . $cmpComp2;
   else :    
      $title = getLngt("PLZ-Bereichsrabatte speziell für den Kunden") . " " . $cmpComp . " " . $cmpComp2;
   endif;   
endif;
$title2 = getLngt("Verwaltung der Bereichsnachbarschaft");
$title4 = getLngt("Verwaltung der Bereichsaddressen");



// BEGINNING OF ADMINISTRATION OF NEIGHBOURS

if ($f_zipcode2 == "") : $f_zipcode2 = $zipcodeRow; endif;

// **************************************************
// * Get all neighbours for the current zipcodearea *
// **************************************************
$sqlquery = "SELECT srvp2.srvp_id, srvp2.srvp_plz, srvpn.srvpn_sort"
            . " FROM serviceplzneighbour AS srvpn, serviceplz AS srvp, serviceplz AS srvp2"
            . " WHERE srvp.srvp_plz = '" . $f_zipcode2 . "' AND"
            . "       srvp.srvp_id = srvpn.srvp_id AND"
            . "       srvpn.hq_id = '" . $hq_id . "' AND"            
            . "       srvpn.srvp2_id = srvp2.srvp_id"            
            . " ORDER BY srvpn.srvpn_sort";

$result = $db->query($sqlquery);
if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

$services2 = "";
$count = 0;
while ($row = $result->fetch_assoc()):
      $count++;
      $areaneighbours["id"][$count] = $row["srvp_id"];
      $areaneighbours["name"][$count] = $row["srvp_plz"];
      $areaneighbours["sort"][$count] = $row["srvpn_sort"];
endwhile;
$result->free();

// Length of the array containing the zipcodes according to the current selected area
$lenAreaNeighbours = count($areaneighbours["id"]);


// ***************************************************************
// * Display all neighbours based on the filter set in $areaRow. *
// * It is the same filter like for the matrix above!            *
// ***************************************************************
// Select-Box
$serviceOutput3 = "<div><select name=\"f_zipcode2\" onChange=\"document.forms[0].submit();\">\n";
for ($j = 1; $j <= $lenServices; $j++) :
    $is_selected = "";
    if ($f_zipcode2 == $services["plz"][$j]) : $is_selected = " selected"; endif;
    $serviceOutput3 .= "<option value=\"" . $services["plz"][$j] . "\" " . $is_selected . ">" . $services["plz"][$j] . "</option>\n";
endfor;
$serviceOutput3 .= "</select><br><br></div>\n";

// Output of the existing neighbours of the current selected area
for ($j = 1; $j <= $lenAreaNeighbours; $j++) :
    $serviceOutput3 .= "<div>\n";
    $serviceOutput3 .= $areaneighbours["name"][$j];
    $serviceOutput3 .= "<input type=\"checkbox\" name=\"f_del_neighbour_id[]\" value=\"" . $areaneighbours["id"][$j] . "\">";
    $serviceOutput3 .= "</div>\n";
endfor;
$serviceOutput3 .= "<br>";

// Button to remove associations between area and zipcode(s). Only show if at least one zipcode is associated to the current area.
if ($lenAreaNeighbours > 0) :
   $serviceOutput3 .= defineButtonType10(getLngt("Markierte&nbsp;Nachbar-PLZn&nbsp;entfernen"), "action_remove", "finishPage('save_removeneighbourassociation');", "250");
endif;
?>


<html lang="de">
<head>
<title><?php echo $pageTitel; ?></title>

<style type="text/css">
  <?php include_once ("../css/phoenix.css.php"); ?>
  <?php include_once ("../css/navigation.css.php"); ?>
  <?php include_once ("../css/mc.css.php"); ?>
</style>

<?php include_once ("../include/js_framework.inc.php"); ?>

<script src="../include/checkFormTags.js" type="text/javascript"></script>
<script src="../include/lib_global.js" type="text/javascript"></script>

<script type="text/javascript">
<!--
// NAVIGATION
<?php echo $jsMenuOut; ?>

function searchCustomerPopup() {
  var widthPopupWin = 800;
  var heightPopupWin = 600;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin=window.open("../admin/impressum.html", "","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin);  	
};	

function finishPage(f_act) { 
 // for(i=0;i<document.forms[0].jb_costcenter_select.length;++i) {
 //   if (document.forms[0].jb_costcenter_select.options[i].selected == true) {   
 //      document.forms[0].jb_costcenter.value=document.forms[0].jb_costcenter_select.options[i].value;
 //   }
 // };
 if (f_act == 'save') {
    if (!confirm('<?php echo getLngt("Preisbereichsmatrix speichern?") ?>')) {
       return false;
    }
 }
 document.forms[0].f_act.value = f_act;
 document.forms[0].submit();
};

function initCells() {
	// Show or hide cells
  if ('<?php echo $f_chkbx_toggle_checked ?>' == 'checked') { $(".service").show(); } else { $(".service").hide(); };
  if ('<?php echo $f_chkbx_toggle_cr_checked ?>' == 'checked') { $(".service_cr").show(); } else { $(".service_cr").hide(); };
  // Common checkbox attributes
  $(".chkbox_attr").css("display", "inline-block");
  $(".chkbox_attr").css("height", "20px");
  <?php if ($mode == "discount") : ?>
    $(".chkbox_attr").css("width", "200px");
  <?php else : ?>
  	$(".chkbox_attr").css("width", "160px");
  <?php endif; ?>
  // Special checkbox attributes
  $(".chkbox_attr_special").css("background-color", "#FFFFFF");
  $(".chkbox_attr_special_cr").css("background-color", "#F7F8E0");
  // Special cell attributes
  $(".cell_attr").css("background-color", "#FFFFFF");
  $(".cell_attr_cr").css("background-color", "#F7F8E0");
}

function toggleCells() {
	// Check at least one checkbox has to be set
	if (!$('#f_chkbx_toggle').prop('checked') && !$('#f_chkbx_toggle_cr').prop('checked')) {
		 $('#f_chkbx_toggle').val('service');
		 $('#f_chkbx_toggle').prop('checked',true);
		 alert('<?php echo getLngt("Mindestens eine der Checkboxen muss gesetzt sein!") ?>');
	}
  if ($('#f_chkbx_toggle').prop('checked')) { $(".service").show(); } else { $(".service").hide(); };
  if ($('#f_chkbx_toggle_cr').prop('checked')) { $(".service_cr").show(); } else { $(".service_cr").hide(); };
}

-->
</script>
<noscript>
  <center>
  <b><br>JavaScript ist nicht verf&uuml;gbar. Bitte aktivieren Sie JavaScript<br><br>
        in Ihrem Browser, damit diese Seite ordnungsgem&auml;&szlig; funktioniert!</b><br><br>
  </center>
</noscript>
</head>

<body onLoad="<?php echo $phpCurrentNavigationOnLoad ?>initCells();displayStatusMessage();">

<?php echo $phpMenuOut ?>
<?php echo $phpReducedMenuOut ?>
<?php echo $phpPageTitelOut ?>

<div class="mc_page-header">
  <?php echo $title ?>
</div>

<div class="maincontent mc_elem" name="maincontent" id="maincontent">

<form name="services" action="../admin/services_plz.php" method="post" <?php echo $htmlFormTarget ?>>

  <input type="hidden" name="f_act" value="">
  <input type="hidden" name="mode" value="<?php echo ec($mode) ?>">
  <input type="hidden" name="orderByServices" value="<?php echo $orderByServices ?>">
  <input type="hidden" name="csId" value="<?php echo ec($csId) ?>">
  <input type="hidden" name="opener" value="<?php echo $opener ?>">
  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">
  <input type="hidden" name="pageFirstCall" value="<?php echo $pageFirstCall ?>">


  <?php echo htmlDivLineSpacer("30px"); ?>

  <div>
    <div <?php echo setStyleHtmlDiv("100px","left"); ?>><?php echo getLngt("Zeile") ?>:</div>
    <div>
      <input type="text" name="zipcodeRow" value="<?php echo $zipcodeRow ?>" size="6"> <?php echo getLngt("(VON)") ?>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px"); ?>
  <div>
    <div <?php echo setStyleHtmlDiv("100px","left"); ?>><?php echo getLngt("Spalte") ?>:</div>
    <div>
      <input type="text" name="zipcodeCol" value="<?php echo $zipcodeCol ?>" size="6"> <?php echo getLngt("(NACH)") ?>
    </div>
  </div>
  <?php if ($parServiceVehicleTypeEnabled == "1") : ?>
    <?php echo htmlDivLineSpacer("10px"); ?>
    <div>
      <div <?php echo setStyleHtmlDiv("100px","left"); ?>><?php echo getLngt("Fahrzeugtyp") ?>:</div>
      <div>
        <select name="f_vehicletype" class="f8np1" onChange="finishPage('');">
          <?php
            // Check excludes vehicle type IDs
            $mask_exclude_vht_ids = getParameterValue("0", "MASK_EXCLUDE_VHT_IDS", $hq_id);      
            if ($mask_exclude_vht_ids != "") $mask_exclude_vht_ids = " AND NOT mt_sort IN (" . $mask_exclude_vht_ids . ")";
            echo addOptionsFromTable("metatype","mt_sort","mt_value","mt_sort","mt_type = 'vehicletype'" . $mask_exclude_vht_ids, $vhtId);
          ?>
        </select>
      </div>
    </div>
  <?php endif; ?>
  <?php echo htmlDivLineSpacer("10px", "", "left"); ?>

  <?php echo defineButtonType10(getLngt("Tabelle&nbsp;anzeigen"), "action_display", "document.forms[0].submit();", "150","left","3"); ?>
    &nbsp;&nbsp;
    <span class="chkbox_attr chkbox_attr_special"><input type="checkbox"  id="f_chkbx_toggle" name="f_chkbx_toggle" value="service" onChange="toggleCells();" <?php echo $f_chkbx_toggle_checked ?>> <?php echo ($mode == "price" ? getLngt("Preise") : getLngt("Rabatte")); ?></span>
    &nbsp;&nbsp;
    <span class="chkbox_attr chkbox_attr_special_cr"><input type="checkbox" id="f_chkbx_toggle_cr" name="f_chkbx_toggle_cr" value="service_cr" onChange="toggleCells();" <?php echo $f_chkbx_toggle_cr_checked ?>> <?php echo ($mode == "price" ? getLngt("Frachtvergütungen") : getLngt("Frachtvergütungsrabatte")); ?></span>
  <?php echo htmlDivLineSpacer("30px"); ?>

  <div>
    <table width="100%" align="left" cellspacing="0" cellpadding="0" vspace="0" hspace="0">
      <?php echo $serviceOutput ?>
    </table>
  </div>
  <?php echo htmlDivLineSpacer("20px", "", "left"); ?>

  <?php echo defineButtonType10(getLngt("Speichern"), "action_save", "finishPage('save');", "100"); ?>
  <?php echo htmlDivLineSpacer("50px"); ?>


  <!-- Verwaltung der Bereichsadressen -->
  <!--
  <div class="f10bp1_blue">
    <?php echo $title4 ?>:&nbsp;&nbsp;&nbsp;<span class="f10bp1"><a href="../admin/srvpa_list.php" target="_blank"><?php echo getLngt("Zuordnungen bearbeiten") ?></a></span>
  </div>
  <?php echo htmlDivLineSpacer("40px"); ?>
  -->


  <!-- Verwaltung der PLZ-Nachbarschaft -->
  <div class="f12bp1_blue">
    <?php echo $title2 ?>
  </div>
  <?php echo htmlDivLineSpacer("20px"); ?>

  <div>
    <?php echo $serviceOutput3 ?>
  </div>
  <?php echo htmlDivLineSpacer("20px", "", "left"); ?>

  <div class="f10bp1_blue">
    <div style="float:left">
	    <?php echo getLngt("PLZ für Nachbarschaftsverknüpfung eingeben") ?>:&nbsp;&nbsp;
	    <input type="text" name="f_newneighbourforzipcode" value="">&nbsp;&nbsp;&nbsp;
	  </div>
	  <?php echo defineButtonType10(getLngt("Nachbar&nbsp;anlegen"), "action_new", "finishPage('save_newneighbourassociation');", "180"); ?>
  </div>
  <?php echo htmlDivLineSpacer("20px", "", "left"); ?>
    
</form>
</div>
</body>
</html>
