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

include_once ("../include/mcglobal.inc.php");
include_once ("../include/auth.inc.php");
// include_once ("../include/html.inc.php");
include_once ("../include/inc_filters.inc.php");
include_once ("../include/inc_services.inc.php");


$httpVars = array("f_act", "customerId", "f_crvh_filter", "orderClause", "statusMessage", "serviceMode",
                  "f_cs_service", "f_cs_servicetype", "f_srvr_remove", "f_srvz_remove", "f_srvz_mapping_remove",
                  "f_zone_name_new", "f_zone_zipcode_new", "f_zone_zone_new", "f_radius_zipcode_new", "f_radius_zone_new", "f_radius_district_new",
                  "f_day_time_new", "f_day_time_hour_from_new", "f_day_time_minute_from_new", "f_day_time_hour_to_new", "f_day_time_minute_to_new",
                  "f_delivery_time_new", "f_delivery_time_hour_from_new", "f_delivery_time_minute_from_new", "f_delivery_time_hour_to_new", "f_delivery_time_minute_to_new",
                  "f_discount_mode_new", "f_discount_mode_type_new", "deactivateMenu",
                  "f_sms_time_hour_from_new", "f_sms_time_minute_from_new", "f_cartage_time_hour_from_new", "f_cartage_time_minute_from_new");

getSecHttpVars("1", $httpVars);

getLanguage(__FILE__);

$deactivateMenuStatic = "1";
$pageTitle = getLngt("PREIS-/LEISTUNGSTYPEN, ZONEN UND RADIEN");
include_once ("../admin/menu.php");
if ($f_act == "newRadiuses") :
   include_once("../locating/xServer.inc.php");
   include_once("../include/inc_geo.inc.php");
endif;
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, "0", "1");
authCheckEmployeeRights($emp_id, "2", "1");

// Get the emp_id of the root admin because he/she is allowed to change a password of an employee
$empIdRootAdmin = getEmpIdOfRootAdmin($userTypeName);

if ($serviceMode == "") : $serviceMode = "1"; endif;


// Check mandator state; if enabled (= 1) then differ between mandators, else set HQ_ID = 0 => same values for ALL mandators
$currentHqId = $hq_id;
if ($serviceMode >= "1") :
   $constHqId = getParameterValue("0", "MANDATOR_SERVICE2_ENABLED", $hq_id);
else : 
   $constHqId = getParameterValue("0", "MANDATOR_SERVICE_ENABLED", $hq_id);
endif;
if ($constHqId == "" || $constHqId == "0") : $currentHqId = "0"; endif;



// *****************************
// * Selection of all services *
// *****************************
$sqlquery = "SELECT srv_id, srv_name"
            . " FROM service"
            . " WHERE hq_id = '" . $currentHqId . "' AND cs_id = '0' AND srv_mode = '" . $serviceMode . "'"
            . " ORDER BY srv_sort";

$result = $db->dbQ($sqlquery);

$services = array();
$count = 0;
while ($row = $result->fetch_assoc()):
      $count++;
      $services["id"][$count] = $row["srv_id"];
      $services["name"][$count] = $row["srv_name"];
endwhile;
$result->free();


// *********************************
// * Selection of all servicetypes *
// *********************************
$sqlquery = "SELECT srvt_id, srvt_name"
            . " FROM servicetype"
            . " WHERE hq_id = '" . $currentHqId . "' AND cs_id = '0' AND srvt_mode = '" . $serviceMode . "'";

$result = $db->dbQ($sqlquery);

$serviceTypes = array();
$count = 0;
while ($row = $result->fetch_assoc()):
      $count++;
      $serviceTypes["id"][$count] = $row["srvt_id"];
      $serviceTypes["name"][$count] = $row["srvt_name"];
endwhile;
$result->free();


// Number of entries
$lenServices = count($services["id"]);
$lenServiceTypes = count($serviceTypes["id"]);


if ($customerId != "") :

   $customerHqId = getFieldValueFromId("customer", "cs_id", $customerId, "hq_id");

   // Get current address of the current customer
   $csAdId = "";
   $sqlquery = "SELECT ad.ad_id, ad.ad_street, ad.ad_zipcode, ad.ad_city, ad.ad_country, cscad.cscad_hsno"
       . " FROM customer AS cs, costcenter AS csc, costcenteraddress AS cscad, address AS ad"
       . " WHERE cs.hq_id = '" . $customerHqId . "' AND"
       . "       cs.cs_id = '" . $customerId . "' AND"
       . "       cs.csc_id = csc.csc_id           AND"
       . "       csc.csc_id =  cscad.csc_id       AND"
       . "       cscad.adt_id = '4'               AND"
       . "       cscad.ad_id = ad.ad_id";

   $result = $db->dbQ($sqlquery);
   while ($row = $result->fetch_assoc()):
         $csAdId      = $row["ad_id"];
         $csAdStreet  = $row["ad_street"];
         $csAdHsno    = $row["cscad_hsno"];
         $csAdZipcode = $row["ad_zipcode"];
         $csAdCity    = $row["ad_city"];
         $csAdCountry = $row["ad_country"];
   endwhile;
   $result->free();
   
   if ($csAdId == "") :
      // Get address of out of the customer master data
      $address = getAddress($customerId, "customer");
      $csAdId      = $address["id"];
      $csAdStreet  = $address["street"];
      $csAdHsno    = $address["hsno"];
      $csAdZipcode = $address["zipcode"];
      $csAdCity    = $address["city"];
      $csAdCountry = $address["country"];
   endif;



   // Set services of the current customer
   if ($f_act == "saveCustomerServices") :

      TA("B");

      // [1.] Set customer services
      if (!is_array($f_cs_service)) : $f_cs_service = array(); endif;
      deleteStmt("customerservice","cs_id = '" . $customerId . "'");
      $lenCsServiceStore = count($f_cs_service);      
      for ($i = 0; $i < $lenCsServiceStore; $i++) :
          insertStmt("customerservice", array("cs_id", $customerId, "srv_id", $f_cs_service[$i], "cssrv_sort", $i));
      endfor;

      // [2.] Set customer servicetypes
      if (!is_array($f_cs_servicetype)) : $f_cs_servicetype = array(); endif;
      deleteStmt("customerservicetype","cs_id = '" . $customerId . "'");
      $lenCsServiceTypeStore = count($f_cs_servicetype);
      for ($i = 0; $i < $lenCsServiceTypeStore; $i++) :
          insertStmt("customerservicetype", array("cs_id", $customerId, "srvt_id", $f_cs_servicetype[$i], "cssrvt_sort", $i));
      endfor;     

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


   // Compute new radiuses of the current customer
   if ($f_act == "newRadiuses" && $csAdId != "") :

      // if (true || existsEntry("serviceradius",array("hq_id",$customerHqId,"cs_id",$customerId))) :

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

         TA("B");

         // First remove existing entries regarding the customer in $customerId
         deleteStmt("serviceradius","hq_id = '" . $customerHqId . "' AND cs_id = '" . $customerId . "'");

         $long = "";
         $lat = "";
         // $coords[0][0] : 100 = gefunden
         // $coords[0][1] : Länge
         // $coords[0][2] : Breite
         $coords = XSfindAddress("D", $csAdZipcode, $csAdCity, $csAdStreet, $csAdHsno);
         if ($coords[0][0] == 100) :
            // Found
            $long = $coords[0][1];
            $lat  = $coords[0][2];

            $parRadiusIntervalsArray = array();
            $parRadiusIntervals = getParameterValue("0", "CUSTOMER_SERVICE_RADIUS_INTERVALS_" . $customerId, $customerHqId);
            if ($parRadiusIntervals == "") :
               $parRadiusIntervals = "1=10|2=20,10|3=30,20";
            endif;
            $parRadiusIntervalsArray = getKeyValueArrayFromString($parRadiusIntervals);
            $tmpKeys = array_keys($parRadiusIntervalsArray);
            sort($tmpKeys);
            $tmpKeysLen = count($tmpKeys);
            for ($k = 0; $k < $tmpKeysLen; $k++) :

                $tmpDistanceArray = spliti(",",$parRadiusIntervalsArray[$tmpKeys[$k]]);
                $distance = $tmpDistanceArray[0];
                $distance2 = $tmpDistanceArray[1];
                if ($distance != "" && is_numeric($distance)) :
                   if ($distance2 == "0" || !is_numeric($distance2)) : $distance2 = ""; endif;
                   $radiusAreaNo = $k + 1;
                   // Get all areas
                   $tmpArray = getDistanceData($distance, $long, $lat, $distance2);
                   $tmpArrayLen = count($tmpArray);
                   for ($j = 0; $j < $tmpArrayLen; $j++) :

                       // Insert into db
                       $tmpIncArray = array();
                       if (($j + 1) < $tmpArrayLen) :
                          $tmpIncArray = $tmpArray[($j + 1)];
                       endif;
                       $srvr_id_new = insertServiceRadius($tmpArray[$j], $customerHqId, $customerId, $radiusAreaNo, $tmpIncArray);
                   endfor;
                endif;
            endfor;
         endif;

         TA("C");
         TA("E");
      // endif;
   endif;


   // Insert new radius mapping
   // Main definition of the zones of a special customer by data import!
   if ($f_act == "insertNewRadiusMapping") :

      $f_radius_zipcode_new = trim($f_radius_zipcode_new);
      $f_radius_district_new = trim($f_radius_district_new);
      if ($f_radius_zipcode_new != "" && $f_radius_district_new != "" && $f_radius_zone_new != "") :

         // Get srvp_id from serviceplz
         $tmpSrvpId = getFieldValueFromId("serviceplz", "srvp_plz", $f_radius_zipcode_new, "srvp_id");
         if ($tmpSrvpId != "") :

            // Check for existence in "serviceradius"
            $sqlquery = "SELECT srvr.srvr_radiusarea_no FROM serviceradius AS srvr"
                      . "  WHERE srvr.hq_id = '" . $customerHqId . "' AND srvr.cs_id = '" . $customerId . "' AND srvr.srvr_zipcode = '" . $f_radius_zipcode_new . "'";
            $result = $db->dbQ($sqlquery);
            $existingSrvrNo = "";
            while ($row = $result->fetch_assoc()):
                  $existingSrvrNo = $row["srvr_radiusarea_no"];
            endwhile;
            $result->free();

            // Multiple entries are ok, because one zipcode may have more districts
            // if ($existingSrvrNo == "") :

               insertStmt("serviceradius", array("hq_id", $customerHqId, "cs_id", $customerId, "srvr_zipcode", $f_radius_zipcode_new, "srvr_city_district", $f_radius_district_new, "srvr_radiusarea_no", $f_radius_zone_new));

               $statusMessage = getLngt("Die PLZ " . $f_radius_zipcode_new . " (" . $f_radius_district_new . ") wurde dem Radiusbereich " . $f_radius_zone_new . " zugeordnet!");
               
               if ($existingSrvrNo != "") :
                  $statusMessage = getLngt("INFO: Für die PLZ " . $f_radius_zipcode_new . " existiert schon eine Zuordnung im Radiusbereich " . $existingSrvrNo . ".");
               endif;
            // else :
            //   $statusMessage = getLngt("Für die PLZ " . $f_radius_zipcode_new . " existiert schon eine Zuordnung im Radiusbereich " . $existingSrvrNo . ". Diese müsste ggfs. entfernt werden!");
            // endif;
         else :
            $statusMessage = getLngt("Die PLZ " . $f_radius_zipcode_new . " wird im Basisdatenbestand nicht geführt. Eine Zuordnung erfolgte nicht!");
         endif;
      else :
         $statusMessage = getLngt("Bitte geben Sie eine PLZ und einen Bezirk ein und wählen Sie eine Zone aus!");
      endif;
   endif;

   // Remove existing mappings between zipcode an radius zone
   if ($f_act == "removeRadiusMappings") :

      if (is_array($f_srvr_remove)) :

         $f_srvr_remove_len = count($f_srvr_remove);
         for ($i = 0; $i < $f_srvr_remove_len; $i++) :

             if ($f_srvr_remove[$i] != "") :
                deleteStmt("serviceradius","srvr_id = '" . $f_srvr_remove[$i] . "'");
             endif;
         endfor;
      endif;
   endif;


   // Insert new (service) zone
   if ($f_act == "insertNewServiceZone") :

      $f_zone_name_new = trim($f_zone_name_new);
      if ($f_zone_name_new != "" && $f_zone_name_new != "") :

         TA("B");

         // Get max value of zone number (srvz_no) for customer in servicezone
         $tmpSrvzNoMaxValue = getMaxOfField("servicezone", "srvz_no", "hq_id = '" . $customerHqId . "' AND cs_id = '" . $customerId . "'");
         if ($tmpSrvzNoMaxValue != "" && is_numeric($tmpSrvzNoMaxValue)) :
            $tmpSrvzNoMaxValue++;
         else :
            $tmpSrvzNoMaxValue = 0;
         endif;
         insertStmt("servicezone", array("hq_id", $customerHqId, "cs_id", $customerId, "srvz_no", $tmpSrvzNoMaxValue, "srvz_name", $f_zone_name_new));

         TA("C");
         TA("E");
      else :
         $statusMessage = getLngt("Bitte geben Sie eine Zonenbezeichnung ein!");
      endif;
   endif;

   // Remove existing (service) zone
   if ($f_act == "removeServiceZone") :

      if (is_array($f_srvz_remove)) :

         TA("B");

         $logArray = array();
         $f_srvz_remove_len = count($f_srvz_remove);
         for ($i = 0; $i < $f_srvz_remove_len; $i++) :

             $tmpSrvzId = $f_srvz_remove[$i];
             if ($tmpSrvzId != "" && $tmpSrvzId != "") :


                $tmpSrvzNo = getFieldValueFromId("servicezone", "srvz_id", $tmpSrvzId, "srvz_no");
                $tmpSrvzName = getFieldValueFromId("servicezone", "srvz_id", $tmpSrvzId, "srvz_name");
                $logArray[] = "[" . $tmpSrvzId . "|" . $tmpSrvzNo . "|" . $tmpSrvzName . "]";

                deleteStmt("servicezonemapping","srvz_id = '" . $tmpSrvzId . "'");
                deleteStmt("servicezone","srvz_id = '" . $tmpSrvzId . "'");
             endif;
         endfor;

         if (count($logArray) > 0) :
            // Write logdata into log database
            writeToLogDB("135",$customerHqId,"",$usr_id,"","",$customerId,"[ID,NO,NAME]=" . implode(",",$logArray));
         endif;

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


   // Insert new zone mapping
   if ($f_act == "insertNewZoneMapping") :
      
      $f_zone_zipcode_new = trim($f_zone_zipcode_new);
      if ($f_zone_zipcode_new != "" && $f_zone_zone_new != "") :
         
         // Get srvp_id from serviceplz
         $tmpSrvpId = getFieldValueFromId("serviceplz", "srvp_plz", $f_zone_zipcode_new, "srvp_id");
         if ($tmpSrvpId != "") :

            // Check for existence in "servicezonemapping"
            $existingSrvzNo = getServiceZoneByCustomerAndZipcode($customerId, $f_zone_zipcode_new);

            if ($existingSrvzNo == "") :
               insertStmt("servicezonemapping", array("srvz_id", $f_zone_zone_new, "srvp_id", $tmpSrvpId));

               $statusMessage = getLngt("Die PLZ " . $f_zone_zipcode_new . " wurde der Zone " . getFieldValueFromId("servicezone", "srvz_id", $f_zone_zone_new, "srvz_no") . " zugeordnet!");
            else :
               $statusMessage = getLngt("Für die PLZ " . $f_zone_zipcode_new . " existiert schon eine Zuordnung in der Zone " . $existingSrvzNo . ". Diese müsste ggfs. entfernt werden!");
            endif;
         else :
            $statusMessage = getLngt("Die PLZ " . $f_zone_zipcode_new . " wird im Basisdatenbestand nicht geführt. Eine Zuordnung erfolgte nicht!");
         endif;
      else :
         $statusMessage = getLngt("Bitte geben Sie eine PLZ ein und wählen Sie eine Zone aus, der die PLZ zogeordnet wird!");
      endif;
   endif;


   // Remove existing mappings between zipcode an zone
   if ($f_act == "removeZoneMappings") :

      if (is_array($f_srvz_mapping_remove)) :

         $f_srvz_mapping_remove_len = count($f_srvz_mapping_remove);
         for ($i = 0; $i < $f_srvz_mapping_remove_len; $i++) :

             $tmpItem = $f_srvz_mapping_remove[$i];
             $tmpArray = spliti(",", $tmpItem);
             $tmpSrvpId = $tmpArray[0];
             $tmpSrvzId = $tmpArray[1];

             if ($tmpSrvpId != "" && $tmpSrvzId != "") :
                deleteStmt("servicezonemapping","srvp_id = '" . $tmpSrvpId . "' AND srvz_id = '" . $tmpSrvzId . "'");
             endif;
         endfor;
      endif;
   endif;


   // Reset day times to defaults
   if ($f_act == "day_time_defaults") :
   
      TA("B");

      metatypeSetDefaultValues("day_time", "cs", $customerId);

      TA("C");
      TA("E");
   endif;
   
   // Insert new day time
   if ($f_act == "day_time_new" && $f_day_time_new != "") :
   
      TA("B");

      // Get max value for customer in metatype for mt_type = "day_time", increment this value and insert the new one
      $tmpSortValue = getMaxOfField("metatype", "mt_sort", "mt_type = 'day_time' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "'");
      if ($tmpSortValue != "" && is_numeric($tmpSortValue)) :
         $tmpSortValue++;
      else :
         $tmpSortValue = 0;
      endif;
      $tmpInterval = pad($f_day_time_hour_from_new, 2) . ":" . pad($f_day_time_minute_from_new, 2) . " - " . pad($f_day_time_hour_to_new, 2) . ":" . pad($f_day_time_minute_to_new, 2);
      insertStmt("metatype", array("mt_type", "day_time", "mt_objtype", "cs", "mt_objid", $customerId, "mt_sort", $tmpSortValue, "mt_value", $f_day_time_new, "mt_mapped_value", $tmpInterval));

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

   // Remove day time
   if ($f_act == "day_time_remove") :

      TA("B");

      // Get max value for customer in metatype for mt_type = "day_time" and remove it
      $tmpSortValue = getMaxOfField("metatype", "mt_sort", "mt_type = 'day_time' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "'");
      if ($tmpSortValue != "" && is_numeric($tmpSortValue)) :
         deleteStmt("metatype", "mt_type = 'day_time' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "' AND mt_sort = '" . $tmpSortValue . "'");
      endif;

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


   // Reset delivery times to defaults
   if ($f_act == "delivery_time_defaults") :
   
      TA("B");
   
      metatypeSetDefaultValues("delivery_time", "cs", $customerId);

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

   // Insert new delivery time
   if ($f_act == "delivery_time_new" && $f_delivery_time_new != "") :
   
      TA("B");

      // Get max value for customer in metatype for mt_type = "delivery_time", increment this value and insert the new one
      $tmpSortValue = getMaxOfField("metatype", "mt_sort", "mt_type = 'delivery_time' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "'");
      if ($tmpSortValue != "" && is_numeric($tmpSortValue)) :
         $tmpSortValue++;
      else :
         $tmpSortValue = 0;
      endif;
      // $tmpInterval = pad($f_delivery_time_hour_from_new, 2) . ":" . pad($f_delivery_time_minute_from_new, 2) . " - " . pad($f_delivery_time_hour_to_new, 2) . ":" . pad($f_delivery_time_minute_to_new, 2);
      $tmpInterval = pad($f_delivery_time_hour_to_new, 2) . ":" . pad($f_delivery_time_minute_to_new, 2);    // Presently only "to time" only !!!!
      insertStmt("metatype", array("mt_type", "delivery_time", "mt_objtype", "cs", "mt_objid", $customerId, "mt_sort", $tmpSortValue, "mt_value", $f_delivery_time_new, "mt_mapped_value", $tmpInterval));

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

   // Remove delivery time
   if ($f_act == "delivery_time_remove") :

      TA("B");

      // Get max value for customer in metatype for mt_type = "delivery_time" and remove it
      $tmpSortValue = getMaxOfField("metatype", "mt_sort", "mt_type = 'delivery_time' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "'");
      if ($tmpSortValue != "" && is_numeric($tmpSortValue)) :
         deleteStmt("metatype", "mt_type = 'delivery_time' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "' AND mt_sort = '" . $tmpSortValue . "'");
      endif;

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


   // Reset discount mode to defaults
   if ($f_act == "discount_mode_defaults") :
   
      TA("B");

      metatypeSetDefaultValues("discount_mode", "cs", $customerId);

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

   // Insert new discount mode
   if ($f_act == "discount_mode_new" && $f_discount_mode_new != "" && $f_discount_mode_type_new != "") :

      TA("B");

      // Get max value for customer in metatype for mt_type = "discount_mode", increment this value and insert the new one
      $tmpSortValue = getMaxOfField("metatype", "mt_sort", "mt_type = 'discount_mode' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "'");
      if ($tmpSortValue != "" && is_numeric($tmpSortValue)) :
         $tmpSortValue++;
      else :
         $tmpSortValue = 0;
      endif;
      insertStmt("metatype", array("mt_type", "discount_mode", "mt_objtype", "cs", "mt_objid", $customerId, "mt_sort", $tmpSortValue, "mt_value", $f_discount_mode_new, "mt_mapped_value", $f_discount_mode_type_new));

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

   // Remove discount mode
   if ($f_act == "discount_mode_remove") :

      TA("B");

      // Get max value for customer in metatype for mt_type = "discount_mode" and remove it
      $tmpSortValue = getMaxOfField("metatype", "mt_sort", "mt_type = 'discount_mode' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "'");
      if ($tmpSortValue != "" && is_numeric($tmpSortValue)) :
         deleteStmt("metatype", "mt_type = 'discount_mode' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "' AND mt_sort = '" . $tmpSortValue . "'");
      endif;

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


   // Set SMS time to default
   if ($f_act == "sms_time_default") :
   
      TA("B");

      metatypeSetDefaultValues("sms_time", "cs", $customerId);

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

   // Insert new SMS time
   if ($f_act == "sms_time_new" && $f_sms_time_hour_from_new != "" && $f_sms_time_minute_from_new != "") :
   
      TA("B");

      $tmpClockTime = pad($f_sms_time_hour_from_new, 2) . ":" . pad($f_sms_time_minute_from_new, 2);
      deleteStmt("metatype", "mt_type = 'sms_time' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "'");
      insertStmt("metatype", array("mt_type", "sms_time", "mt_objtype", "cs", "mt_objid", $customerId, "mt_sort", "0", "mt_mapped_value", $tmpClockTime));

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


   // Set time for cartage protocol to default
   if ($f_act == "cartage_time_default") :
   
      TA("B");

      metatypeSetDefaultValues("cartage_time", "cs", $customerId);

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

   // Insert new SMS time
   if ($f_act == "cartage_time_new" && $f_cartage_time_hour_from_new != "" && $f_cartage_time_minute_from_new != "") :
   
      TA("B");

      $tmpClockTime = pad($f_cartage_time_hour_from_new, 2) . ":" . pad($f_cartage_time_minute_from_new, 2);
      deleteStmt("metatype", "mt_type = 'cartage_time' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "'");
      insertStmt("metatype", array("mt_type", "cartage_time", "mt_objtype", "cs", "mt_objid", $customerId, "mt_sort", "0", "mt_mapped_value", $tmpClockTime));

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


   // Get customer services
   $sqlquery = "SELECT srv_id FROM customerservice WHERE cs_id = '" . $customerId . "' ORDER BY cssrv_sort";
   $result = $db->dbQ($sqlquery);
   $csServices = array();
   while ($row = $result->fetch_assoc()):
         $csServices[$row["srv_id"]] = "1";
   endwhile;
   $result->free();

   // Get customer servicetypes
   $sqlquery = "SELECT srvt_id FROM customerservicetype WHERE cs_id = '" . $customerId . "' ORDER BY cssrvt_sort";
   $result = $db->dbQ($sqlquery);
   $csServiceTypes = array();
   while ($row = $result->fetch_assoc()):
         $csServiceTypes[$row["srvt_id"]] = "1";
   endwhile;
   $result->free();


   // **********************************
   // * Selection of all serviceradius *
   // **********************************
   $sqlquery = "SELECT srvr_zipcode, srvr_city_district, srvr_radiusarea_no, srvr_id"
               . " FROM serviceradius"
               . " WHERE hq_id = '" . $customerHqId . "' AND cs_id = '" . $customerId . "'"
               . " ORDER BY srvr_zipcode, srvr_city_district";
   
   $result = $db->dbQ($sqlquery);
   
   $serviceRadiuses = array();
   $count = 0;
   while ($row = $result->fetch_assoc()):
         $count++;
         $serviceRadiuses[] = array($row["srvr_zipcode"], $row["srvr_city_district"], $row["srvr_radiusarea_no"], $row["srvr_id"]);
   endwhile;
   $result->free();
   
   // Number of entries
   $lenServiceRadiuses = count($serviceRadiuses);


   // *********************************
   // * Selection of all servicezones *
   // *********************************
   $sqlquery = "SELECT srvz.srvz_id, srvz.srvz_no, srvz.srvz_name, srvz.srvz_price, srvz.srvz_price_1, srvz.srvz_price_2, srvz.srvz_price_3"
               . " FROM servicezone AS srvz"
               . " WHERE srvz.hq_id = '" . $customerHqId . "' AND srvz.cs_id = '" . $customerId . "'"
               . " ORDER BY srvz_no";

   $result = $db->dbQ($sqlquery);
   
   $serviceZones = array();
   $count = 0;
   while ($row = $result->fetch_assoc()):
         $count++;
         $serviceZones[] = array($row["srvz_id"], $row["srvz_no"], $row["srvz_name"], $row["srvz_price"], $row["srvz_price_1"], $row["srvz_price_2"], $row["srvz_price_3"]);
   endwhile;
   $result->free();

   // Number of entries
   $lenServiceZones = count($serviceZones);
   

   // ****************************************
   // * Selection of all servicezonemappings *
   // ****************************************
   $sqlquery = "SELECT srvp.srvp_plz, srvz.srvz_no, srvz.srvz_id, srvp.srvp_id, srvzm.srvzm_mt_1, srvzm.srvzm_mt_2, srvzm.srvzm_mt_3"
               . " FROM servicezone AS srvz, servicezonemapping AS srvzm, serviceplz AS srvp"
               . " WHERE srvz.hq_id = '" . $customerHqId . "' AND srvz.cs_id = '" . $customerId . "' AND"
               . "       srvz.srvz_id = srvzm.srvz_id AND srvzm.srvp_id = srvp.srvp_id"
               . " ORDER BY srvp_plz, srvz_no";

   $result = $db->dbQ($sqlquery);
   
   $serviceZoneMapping = array();
   $count = 0;
   while ($row = $result->fetch_assoc()):
         $count++;
         $serviceZoneMapping[] = array($row["srvp_plz"], $row["srvz_no"], $row["srvz_id"], $row["srvp_id"], $row["srvzm_mt_1"], $row["srvzm_mt_2"], $row["srvzm_mt_3"]);
   endwhile;
   $result->free();

   // Number of entries
   $lenServiceZoneMapping = count($serviceZoneMapping);
   
   
   // **********************************
   // * Get day times for the customer *
   // **********************************   
   // if (existsEntry("metatype",array("mt_type", "day_time", "mt_objtype", "cs", "mt_objid", $customerId))) :
      $dayTimes = getColVectorFromDB2ArrayByClause("metatype", "mt_sort", "mt_type = 'day_time' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "'", "", "mt_sort", "");
      $dayTimeNames = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'day_time' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "'", "", "mt_sort", "");
      $dayTimeMappedValues  = getColVectorFromDB2ArrayByClause("metatype", "mt_mapped_value", "mt_type = 'day_time' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "'", "", "mt_sort", "");
   // else :
   //    $dayTimes = getColVectorFromDB2ArrayByClause("metatype", "mt_sort", "mt_type = 'day_time' AND mt_objtype = '' AND mt_objid = '0'", "", "mt_sort", "");
   //    $dayTimeNames = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'day_time' AND mt_objtype = '' AND mt_objid = '0'", "", "mt_sort", "");
   //    $dayTimeMappedValues = getColVectorFromDB2ArrayByClause("metatype", "mt_mapped_value", "mt_type = 'day_time' AND mt_objtype = '' AND mt_objid = '0'", "", "mt_sort", "");
   // endif;
   $dayTimesLen = count($dayTimes);
   
   // ***************************************
   // * Get discount modes for the customer *
   // ***************************************
   // if (existsEntry("metatype",array("mt_type", "discount_mode", "mt_objtype", "cs", "mt_objid", $customerId))) :
      $discountMode = getColVectorFromDB2ArrayByClause("metatype", "mt_sort", "mt_type = 'discount_mode' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "'", "", "mt_sort", "");
      $discountModeNames = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'discount_mode' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "'", "", "mt_sort", "");
      $discountModeMappedValues  = getColVectorFromDB2ArrayByClause("metatype", "mt_mapped_value", "mt_type = 'discount_mode' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "'", "", "mt_sort", "");
   // else :
   //    $discountMode = getColVectorFromDB2ArrayByClause("metatype", "mt_sort", "mt_type = 'discount_mode' AND mt_objtype = '' AND mt_objid = '0'", "", "mt_sort", "");
   //    $discountModeNames = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'discount_mode' AND mt_objtype = '' AND mt_objid = '0'", "", "mt_sort", "");
   //    $discountModeMappedValues = getColVectorFromDB2ArrayByClause("metatype", "mt_mapped_value", "mt_type = 'discount_mode' AND mt_objtype = '' AND mt_objid = '0'", "", "mt_sort", "");
   // endif;
   $discountModeLen = count($discountMode);

   // ***************************************
   // * Get delivery times for the customer *
   // ***************************************
   if (!existsEntry("metatype",array("mt_type", "delivery_time", "mt_objtype", "cs", "mt_objid", $customerId))) :
      metatypeSetDefaultValues("delivery_time", "cs", $customerId);  // Set default if no entry does exist
   endif;
   $deliveryTimes = getColVectorFromDB2ArrayByClause("metatype", "mt_sort", "mt_type = 'delivery_time' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "'", "", "mt_sort", "");
   $deliveryTimeNames = getColVectorFromDB2ArrayByClause("metatype", "mt_value", "mt_type = 'delivery_time' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "'", "", "mt_sort", "");
   $deliveryTimeMappedValues  = getColVectorFromDB2ArrayByClause("metatype", "mt_mapped_value", "mt_type = 'delivery_time' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "'", "", "mt_sort", "");
   $deliveryTimesLen = count($deliveryTimes);
endif;   


// *******************
// * Generate output *
// *******************

// * Day times *
$outputDayTimes = "<div><table style=\"padding:3px\">";
if (isset($dayTimesLen) && $dayTimesLen > 0) :   
   for ($i = 0; $i < $dayTimesLen; $i++) :
       $outputDayTimes .= "<tr><td>" . $dayTimes[$i] . "&nbsp;&nbsp;</td><td>" . $dayTimeNames[$i] . "&nbsp;&nbsp;</td><td>(" . $dayTimeMappedValues[$i] . ")</td></tr>\n";
   endfor;
endif;
// if ($i == "") : $i = 0; endif;
mcIsSet($i, "0");
$outputDayTimes .= "<tr>\n";
$outputDayTimes .= "<td>" . $i . "</td>\n";
$outputDayTimes .= "<td>" . "<input class=\"f8np1\" type=\"text\" name=\"f_day_time_new\" value=\"\" size=\"20\">" . "</td>\n";
$outputDayTimes .= "<td>&nbsp;(" . getLngt("Uhrzeit") . "&nbsp;";
$outputDayTimes .= getLngt("von") . "&nbsp;"  . "<select class=\"f8np1\" name=\"f_day_time_hour_from_new\">" . addOptionsFromRange("0", "23", "", "", "2", "0") . "</select>\n";
$outputDayTimes .= "&nbsp;"  . "<select class=\"f8np1\" name=\"f_day_time_minute_from_new\">" . addOptionsFromRange("0", "59", "", "", "2", "0") . "</select>\n";
$outputDayTimes .= getLngt("bis") . "&nbsp;"  . "<select class=\"f8np1\" name=\"f_day_time_hour_to_new\">" . addOptionsFromRange("0", "23", "", "", "2", "0") . "</select>\n";
$outputDayTimes .= "&nbsp;"  . "<select class=\"f8np1\" name=\"f_day_time_minute_to_new\">" . addOptionsFromRange("0", "59", "", "", "2", "0") . "</select>)\n";
$outputDayTimes .= "</td>\n";
$outputDayTimes .= "</tr>\n";
$outputDayTimes .= "</table></div>";

// * Discount modes *
$outputDiscountModes = "<div><table style=\"padding:3px\">";
$i = 0;
if (isset($discountModeLen) && $discountModeLen > 0) :   
   for ($i = 0; $i < $discountModeLen; $i++) :
       $outputDiscountModes .= "<tr><td>" . $discountMode[$i] . "&nbsp;&nbsp;</td><td>" . $discountModeNames[$i] . "&nbsp;&nbsp;</td><td>(" . getFieldValueFromClause("metatype","mt_value","mt_type = 'discount_mode' AND mt_sort = '" . $discountMode[$i] . "' AND mt_objtype = '' AND mt_objid = '0'") . ")</td></tr>\n";
   endfor;
endif;
if ($i == "") : $i = 0; endif;
$outputDiscountModes .= "<tr>\n";
$outputDiscountModes .= "<td>" . $i . "</td>\n";
$outputDiscountModes .= "<td>" . "<input class=\"f8np1\" type=\"text\" name=\"f_discount_mode_new\" value=\"\" size=\"20\">" . "</td>\n";
$outputDiscountModes .= "<td>&nbsp;(" . getLngt("Rabatt-Typ") . "&nbsp;";
$outputDiscountModes .= "<select class=\"f8np1\" name=\"f_discount_mode_type_new\">" . addOptionsFromTable("metatype","mt_sort","mt_value","mt_sort","mt_type = 'discount_mode' AND mt_objtype = '' AND mt_objid = '0'","") . "</select>)\n";
$outputDiscountModes .= "</td>\n";
$outputDiscountModes .= "</tr>\n";
$outputDiscountModes .= "</table></div>";

// * Delivery times *
$outputDeliveryTimes = "<div><table style=\"padding:3px\">";
if (isset($deliveryTimesLen) && $deliveryTimesLen > 0) :
   for ($i = 0; $i < $deliveryTimesLen; $i++) :
       $outputDeliveryTimes .= "<tr><td>" . $deliveryTimes[$i] . "&nbsp;&nbsp;</td><td>" . $deliveryTimeNames[$i] . "&nbsp;&nbsp;</td><td>" . ($deliveryTimeMappedValues[$i] != "" ? "(" . $deliveryTimeMappedValues[$i] . ")" : "") . "</td></tr>\n";
   endfor;
endif;
if ($i == "") : $i = 0; endif;
// Check for number of entries explicitly, because the delivery times corresponds with database fields in "servicezone" (price fields) and "servicezonemapping" (flags activated zipcodes for each delivery time (like "express", etc.))
if ($deliveryTimesLen <= 3) :
   $outputDeliveryTimes .= "<tr>\n";
   $outputDeliveryTimes .= "<td>" . $i . "</td>\n";
   $outputDeliveryTimes .= "<td>" . "<input class=\"f8np1\" type=\"text\" name=\"f_delivery_time_new\" value=\"\" size=\"20\">" . "</td>\n";
   $outputDeliveryTimes .= "<td>&nbsp;(" . getLngt("Max. Bestelluhrzeit") . "&nbsp;";
   // $outputDeliveryTimes .= getLngt("von") . "&nbsp;"  . "<select class=\"f8np1\" name=\"f_delivery_time_hour_from_new\">" . addOptionsFromRange("0", "23", "", "", "2", "0") . "</select>\n";
   // $outputDeliveryTimes .= "&nbsp;"  . "<select class=\"f8np1\" name=\"f_delivery_time_minute_from_new\">" . addOptionsFromRange("0", "59", "", "", "2", "0") . "</select>\n";
   $outputDeliveryTimes .= getLngt("bis") . "&nbsp;"  . "<select class=\"f8np1\" name=\"f_delivery_time_hour_to_new\">" . addOptionsFromRange("0", "23", "", "", "2", "0") . "</select>\n";
   $outputDeliveryTimes .= "&nbsp;"  . "<select class=\"f8np1\" name=\"f_delivery_time_minute_to_new\">" . addOptionsFromRange("0", "59", "", "", "2", "0") . "</select>)\n";
   $outputDeliveryTimes .= "</td>\n";
   $outputDeliveryTimes .= "</tr>\n";
endif;
$outputDeliveryTimes .= "</table></div>";

// * SMS times *
$mtSmsTime = getFieldValueFromClause("metatype","mt_mapped_value","mt_type = 'sms_time' AND mt_sort = '0' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "'");
if ($mtSmsTime == "") : 
   // Get default value
   $mtSmsTime = getFieldValueFromClause("metatype","mt_mapped_value","mt_type = 'sms_time' AND mt_sort = '0' AND mt_objtype = '' AND mt_objid = '0'");
endif;
$smsHourSet = "";
$smsMinuteSet = "";
if ($mtSmsTime != "") :
   $smsHourSet = substr($mtSmsTime,0,2);
   $smsMinuteSet = substr($mtSmsTime,3,2);
endif;
$outputSmsTimes = "<div><table style=\"padding:3px\">";
$outputSmsTimes .= "<tr>\n";
$outputSmsTimes .= "<td>(" . getLngt("Uhrzeit") . "&nbsp;";
$outputSmsTimes .= "<select class=\"f8np1\" name=\"f_sms_time_hour_from_new\">" . addOptionsFromRange("0", "23", $smsHourSet, "", "2", "0") . "</select>\n";
$outputSmsTimes .= "&nbsp;"  . "<select class=\"f8np1\" name=\"f_sms_time_minute_from_new\">" . addOptionsFromRange("0", "59", $smsMinuteSet, "", "2", "0") . "</select>\n";
$outputSmsTimes .= "</td>\n";
$outputSmsTimes .= "</tr>\n";
$outputSmsTimes .= "</table></div>";

// * Cartage protocol times *
$mtCartageTime = getFieldValueFromClause("metatype","mt_mapped_value","mt_type = 'cartage_time' AND mt_sort = '0' AND mt_objtype = 'cs' AND mt_objid = '" . $customerId . "'");
if ($mtCartageTime == "") : 
   // Get default value
   $mtCartageTime = getFieldValueFromClause("metatype","mt_mapped_value","mt_type = 'cartage_time' AND mt_sort = '0' AND mt_objtype = '' AND mt_objid = '0'");
endif;
$cartageHourSet = "";
$cartageMinuteSet = "";
if ($mtCartageTime != "") :
   $cartageHourSet = substr($mtCartageTime,0,2);
   $cartageMinuteSet = substr($mtCartageTime,3,2);
endif;
$outputCartageTimes = "<div><table style=\"padding:3px\">";
$outputCartageTimes .= "<tr>\n";
$outputCartageTimes .= "<td>(" . getLngt("Uhrzeit") . "&nbsp;";
$outputCartageTimes .= "<select class=\"f8np1\" name=\"f_cartage_time_hour_from_new\">" . addOptionsFromRange("0", "23", $cartageHourSet, "", "2", "0") . "</select>\n";
$outputCartageTimes .= "&nbsp;"  . "<select class=\"f8np1\" name=\"f_cartage_time_minute_from_new\">" . addOptionsFromRange("0", "59", $cartageMinuteSet, "", "2", "0") . "</select>\n";
$outputCartageTimes .= "</td>\n";
$outputCartageTimes .= "</tr>\n";
$outputCartageTimes .= "</table></div>";


$output = "<table><tr><td valign=\"top\"\n>";

// * Services *
$output .= "<table border=\"0\">\n";
$output .= "<tr><td align=\"center\" colspan=\"2\"><b>" . getLngt("Preistyp") . "</b><br></td></tr>\n";
$lineToggler = 0;
for ($i = 1; $i <= $lenServices; $i++) :
   	if ($lineToggler == 0) : $lineToggler = 1; else : $lineToggler = 0; endif;
    $cellColor = getListColor($i, $lineToggler);

    $isChecked = "";
    mcArrIsSet($csServices, $services["id"][$i]);
    if ($csServices[$services["id"][$i]] == "1") : $isChecked = " checked "; endif;

    $output .= "<tr>\n";
    $output .= "<td bgcolor=\"" . $cellColor ."\"><input type=\"checkbox\" name=\"f_cs_service[]\" value=\"" . $services["id"][$i] . "\"" . $isChecked . "></td>\n";
    $output .= "<td bgcolor=\"" . $cellColor ."\">" . $services["name"][$i] . "</td>\n";
    $output .= "</tr>";
endfor;
$output .= "</table>\n";

$output .= "</td><td>&nbsp;&nbsp;</td><td valign=\"top\"\n>\n";

$output .= "<table border=\"0\">\n";
$output .= "<tr><td align=\"center\" colspan=\"2\"><b>" . getLngt("Leistungstyp") . "</b><br></td></tr>\n";
$lineToggler = 0;
for ($i = 1; $i <= $lenServiceTypes; $i++) :
   	if ($lineToggler == 0) : $lineToggler = 1; else : $lineToggler = 0; endif;
    $cellColor = getListColor($i, $lineToggler);

    $isChecked = "";
    mcArrIsSet($csServiceTypes, $serviceTypes["id"][$i]);
    if ($csServiceTypes[$serviceTypes["id"][$i]] == "1") : $isChecked = " checked "; endif;

    $output .= "<tr>\n";
    $output .= "<td bgcolor=\"" . $cellColor ."\"><input type=\"checkbox\" name=\"f_cs_servicetype[]\" value=\"" . $serviceTypes["id"][$i] . "\"" . $isChecked . "></td>\n";
    $output .= "<td bgcolor=\"" . $cellColor ."\">" . $serviceTypes["name"][$i] . "</td>\n";
    $output .= "</tr>";
endfor;
$output .= "</table>\n";

// * Radiuses *
if ($customerId != "") :   //  && $lenServiceRadiuses > 0
   $output .= "</td><td width=\"100\">&nbsp;</td><td valign=\"top\"\n>\n";
   $output .= "<table border=\"0\">\n";
   $output .= "<tr><td align=\"center\" colspan=\"4\"><b>" . getLngt("Radiusbereichszuordnung") . "</b></td></tr>\n";
   $output .= "<tr><td align=\"center\" colspan=\"4\">" . getLngt("[Automatische Berechnung]") . "</td></tr>\n";
   $output .= "<tr><td align=\"center\"><b>" . getLngt("PLZ") . "</b></td><td align=\"center\"><b>" . getLngt("Bezirk/Stadt") . "</b></td><td align=\"center\"><b>" . getLngt("Nr.") . "</b></td></tr>\n";

   $selectRadiuses = "<select name=\"f_radius_zone_new\" id=\"f_radius_zone_new\">";
   $selectRadiuses .= addOptionsFromTable("serviceradius", "srvr_radiusarea_no", "srvr_radiusarea_no", "srvr_radiusarea_no", "hq_id = '" . $customerHqId . "' AND cs_id = '" . $customerId . "'", "" , "DISTINCT");
   $selectRadiuses .= "</select>";
   $buttonRadiusNew = defineButtonType10(getLngt("Neu"), "action_radiusmapping_new", "finishPage('insertNewRadiusMapping');", "100", "left", "0");
   $output .= "<tr><td align=\"center\"><input class=\"f8np1\" type=\"text\" name=\"f_radius_zipcode_new\" value=\"\" size=\"10\"></td>"
            . "<td align=\"center\"><input class=\"f8np1\" type=\"text\" name=\"f_radius_district_new\" value=\"\" size=\"10\"></td>"
            . "<td align=\"center\">" . $selectRadiuses . "</td><td align=\"center\">" . $buttonRadiusNew . "</td></tr>\n";

   $lineToggler = 0;
   for ($i = 0; $i < $lenServiceRadiuses; $i++) :
   	   if ($lineToggler == 0) : $lineToggler = 1; else : $lineToggler = 0; endif;
       $cellColor = getListColor($i, $lineToggler);
       
       $tmpArray = $serviceRadiuses[$i];
       $output .= "<tr>\n";
       $output .= "<td bgcolor=\"" . $cellColor ."\">" . $tmpArray[0] . "</td>";
       $output .= "<td bgcolor=\"" . $cellColor ."\">" . $tmpArray[1] . "</td>";
       $output .= "<td bgcolor=\"" . $cellColor ."\" align=\"center\">" . $tmpArray[2] . "</td>\n";
       $isChecked = "";
       $output .= "<td bgcolor=\"" . $cellColor ."\" align=\"center\"><input type=\"checkbox\" name=\"f_srvr_remove[]\" value=\"" . $tmpArray[3] . "\"" . $isChecked . "></td>\n";
       $output .= "</tr>\n";
   endfor;
   $output .= "</table>\n";
endif;

// * Zones an zone mappings *
if ($customerId != "") :

   $output .= "</td><td width=\"100\">&nbsp;</td><td valign=\"top\">\n";

   // (Service) Zones
   if ($empIdRootAdmin == $emp_id || authCheckEmployeeRights($emp_id, "29")) :
      $output .= "<table border=\"0\">\n";
      $output .= "<tr><td align=\"center\" colspan=\"3\"><b>" . getLngt("Service-Zonen") . "</b></td></tr>\n";
      // $output .= "<tr><td align=\"center\" colspan=\"3\">" . getLngt("[Manuelle Bearbeitung]") . "</td></tr>\n";
      $output .= "<tr><td align=\"center\"><b>" . getLngt("Nr.") . "</b></td><td align=\"center\"><b>" . getLngt("Zonenbezeichnung") . "</b></td><td>&nbsp;</td></tr>\n";
      
      $buttonZoneNew = defineButtonType10(getLngt("Neu"), "action_service_zone_new", "finishPage('insertNewServiceZone');", "100", "left", "0");
      $output .= "<tr><td>&nbsp;</td><td align=\"center\"><input class=\"f8np1\" type=\"text\" name=\"f_zone_name_new\" value=\"\" size=\"30\"></td><td align=\"center\">" . $buttonZoneNew . "</td></tr>\n";
      
      $lineToggler = 0;
      for ($i = 0; $i < $lenServiceZones; $i++) :
      	   if ($lineToggler == 0) : $lineToggler = 1; else : $lineToggler = 0; endif;
          $cellColor = getListColor($i, $lineToggler);
          
          $tmpArray = $serviceZones[$i];
          $output .= "<tr>\n";
          $output .= "<td bgcolor=\"" . $cellColor ."\">" . $tmpArray[1] . "</td>";
          $output .= "<td bgcolor=\"" . $cellColor ."\" align=\"center\">" . $tmpArray[2] . "</td>";
          $isChecked = "";
          $output .= "<td bgcolor=\"" . $cellColor ."\" align=\"center\"><input type=\"checkbox\" name=\"f_srvz_remove[]\" value=\"" . $tmpArray[0] . "\"" . $isChecked . "></td>\n";
          $output .= "</tr>\n";
      endfor;
      $output .= "</table>\n";
      $output .= "<br><br>\n";
   endif;

   // Zone mappings
   $output .= "<table border=\"0\">\n";
   $output .= "<tr><td align=\"center\" colspan=\"3\"><b>" . getLngt("Zonenzuordnung") . "</b></td></tr>\n";
   $output .= "<tr><td align=\"center\" colspan=\"3\">" . getLngt("[Import und manuelle Bearbeitung]") . "</td></tr>\n";
   $output .= "<tr><td align=\"center\"><b>" . getLngt("PLZ") . "</b></td><td align=\"center\"><b>" . getLngt("Nr.") . "</b></td><td>&nbsp;</td><td><b>" . getLngt("Express") . "</b></td><td><b>" . getLngt("Zonenaufschlag") . "</b></td></tr>\n";

   $selectZones = "<select name=\"f_zone_zone_new\" id=\"f_zone_zone_new\">";
   $selectZones .= addOptionsFromTable("servicezone", "srvz_id", "srvz_no", "srvz_no", "hq_id = '" . $customerHqId . "' AND cs_id = '" . $customerId . "'", "" , "");
   $selectZones .= "</select>";
   $buttonZoneMappingNew = defineButtonType10(getLngt("Neu"), "action_zonemapping_new", "finishPage('insertNewZoneMapping');", "100", "left", "0");
   $output .= "<tr><td align=\"center\"><input class=\"f8np1\" type=\"text\" name=\"f_zone_zipcode_new\" value=\"\" size=\"10\"></td><td align=\"center\">" . $selectZones . "</td><td align=\"center\">" . $buttonZoneMappingNew . "</td></tr>\n";

   $lineToggler = 0;
   for ($i = 0; $i < $lenServiceZoneMapping; $i++) :
   	   if ($lineToggler == 0) : $lineToggler = 1; else : $lineToggler = 0; endif;
       $cellColor = getListColor($i, $lineToggler);
       
       $tmpArray = $serviceZoneMapping[$i];
       $output .= "<tr>\n";
       $output .= "<td bgcolor=\"" . $cellColor ."\">" . $tmpArray[0] . "</td>";
       $output .= "<td bgcolor=\"" . $cellColor ."\" align=\"center\">" . $tmpArray[1] . "</td>";
       $isChecked = "";
       $output .= "<td bgcolor=\"" . $cellColor ."\" align=\"center\"><input type=\"checkbox\" name=\"f_srvz_mapping_remove[]\" value=\"" . $tmpArray[3] . "," . $tmpArray[2] . "\"" . $isChecked . "></td>\n";
       $output .= "<td bgcolor=\"" . $cellColor ."\" align=\"right\">" . formatOutput($tmpArray[4],"float_rounded_2") . "&nbsp;</td>";
       $output .= "<td bgcolor=\"" . $cellColor ."\" align=\"right\">" . formatOutput($tmpArray[5],"float_rounded_2") . "&nbsp;</td>";
       $output .= "</tr>\n";
   endfor;
   $output .= "</table>\n";
endif;

$output .= "</td></tr></table>\n";


// Only for output
$cmpId = getFieldValueFromId("customer", "cs_id", $customerId, "cmp_id");
$tmpFields = getFieldsValueFromId("company","cmp_id",$cmpId,array("cmp_comp","cmp_comp2"));
$title = $tmpFields[0] . " " . $tmpFields[1];
$pageHeadline = "<span class=\"f12bp1_blue\">" . $pageTitle . "</span>" . " &nbsp;&nbsp;&nbsp;&nbsp;" . $tmpFields[0] . ($tmpFields[1] != "" ? " :: " . $tmpFields[1] : "");

// Administration of "delivery reasons" enabled?
$parDeliveryReasonsEnabled = getParameterValue("0", "CUSTOMER_SERVICE_DELIVERY_REASONS", $hq_id);
if ($parDeliveryReasonsEnabled == "") :
   $parDeliveryReasonsEnabled = getParameterValue("0", "CUSTOMER_SERVICE_DELIVERY_REASONS", "0");
endif;
?>

<html>

<head>
<title><?php echo $pageTitle ?></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/searchLists.js" type="text/javascript"></script>

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

function finishPage(mode) {
  var ok = false;
  if (mode == 'saveCustomerServices') {
     if (confirm('<?php echo getLngt("Möchten Sie die Services speichern?") ?>')) {
        ok = true;
     };  
  }
  if (mode == 'newRadiuses') {
     if (confirm('<?php echo getLngt("Möchten die Radien auf Basis der aktuell eingetragenen Adresse neu berechnen?") ?>')) {
        ok = true;
     };  
  }
  if (mode == 'removeRadiusMappings') {
     if (confirm('<?php echo getLngt("Möchten die markierten Einträge für den aktuellen Kunden aus der Radiusbereichszuordnungsliste entfernen?") ?>')) {
        ok = true;
     };  
  }
  if (mode == 'insertNewServiceZone') {
     if (confirm('<?php echo getLngt("Möchten Sie die neue Zone anlegen?") ?>')) {
        ok = true;
     };  
  }
  if (mode == 'removeServiceZone') {
     if (confirm('<?php echo getLngt("Möchten Sie die selektierten Zonen mit allen Zuordnungen entfernen?") ?>')) {
     	  if (confirm('<?php echo getLngt("Wirklich sicher? Alle Zuordnungen der zu löschenden Zonen werden ebenfalls gelöscht!") ?>')) {
           ok = true;
        };
     };  
  }
  if (mode == 'removeZoneMappings') {
     if (confirm('<?php echo getLngt("Möchten die markierten Einträge für den aktuellen Kunden aus der Zonenzuordnungsliste entfernen?") ?>')) {
        ok = true;
     };  
  }
  if (mode == 'insertNewZoneMapping') {
     if (confirm('<?php echo getLngt("Möchten Sie den neuen Eintrag der Zonenzuordnungsliste zufügen?") ?>')) {
        ok = true;
     };  
  }
  if (mode == 'insertNewRadiusMapping') {
     if (confirm('<?php echo getLngt("Möchten Sie den neuen Eintrag der Radiusbereichszuordnung zufügen?") ?>')) {
        ok = true;
     };  
  }
  if (mode == 'day_time_new') {
     if (confirm('<?php echo getLngt("Möchten Sie den neuen Eintrag für den Tageszeitabschnitt an die Liste anfügen?") ?>')) {
        ok = true;
     };  
  }
  if (mode == 'day_time_remove') {
     if (confirm('<?php echo getLngt("Möchten Sie den letzten Eintrag der Tageszeitabschnittsliste entfernen?") ?>')) {
        ok = true;
     };  
  }
  if (mode == 'day_time_defaults') {
     if (confirm('<?php echo getLngt("Möchten Sie Standardwerte für die Tageszeitabschnittsliste setzen?") ?>')) {
        ok = true;
     };  
  }
  if (mode == 'delivery_time_new') {
     if (confirm('<?php echo getLngt("Möchten Sie den neuen Eintrag für die zeitabhängigen Auslieferarten an die Liste anfügen?") ?>')) {
        ok = true;
     };  
  }
  if (mode == 'delivery_time_remove') {
     if (confirm('<?php echo getLngt("Möchten Sie den letzten Eintrag der zeitabhängigen Auslieferarten entfernen?") ?>')) {
        ok = true;
     };  
  }
  if (mode == 'delivery_time_defaults') {
     if (confirm('<?php echo getLngt("Möchten Sie Standardwerte für die zeitabhängigen Auslieferarten setzen?") ?>')) {
        ok = true;
     };  
  }
  if (mode == 'sms_time_new') {
     if (confirm('<?php echo getLngt("Möchten Sie die Uhrzeit für den automatischen SMS-Versand für diesen Kunden setzen?") ?>')) {
        ok = true;
     };  
  }
  if (mode == 'sms_time_default') {
     if (confirm('<?php echo getLngt("Möchten Sie Standardzeit für den automatischen SMS-Versand für diesen Kunden setzen?") ?>')) {
        ok = true;
     };  
  }
  if (mode == 'cartage_time_new') {
     if (confirm('<?php echo getLngt("Möchten Sie die Uhrzeit für den automatischen Rollkartenversand für diesen Kunden setzen?") ?>')) {
        ok = true;
     };  
  }
  if (mode == 'cartage_time_default') {
     if (confirm('<?php echo getLngt("Möchten Sie Standardzeit für den automatischen Rollkartenversand per Mail für diesen Kunden setzen?") ?>')) {
        ok = true;
     };  
  }
  if (mode == 'discount_mode_new') {
     if (confirm('<?php echo getLngt("Möchten Sie den neuen Eintrag für eine permanente Rabattaktion an die Liste anfügen?") ?>')) {
        ok = true;
     };  
  }
  if (mode == 'discount_mode_remove') {
     if (confirm('<?php echo getLngt("Möchten Sie den letzten Eintrag der permanenten Rabattaktionsliste entfernen?") ?>')) {
        ok = true;
     };  
  }
  if (mode == 'discount_mode_defaults') {
     if (confirm('<?php echo getLngt("Möchten Sie Standardwerte für die permanente Rabattaktionliste setzen?") ?>')) {
        ok = true;
     };  
  }
  

  
  
  if (ok) {
  	 document.forms[0].f_act.value = mode;
  	 document.forms[0].submit();
  }
};

function openMetaFieldSpecial(objId, category) {
  var widthPopupWin = 900;
  var heightPopupWin = 870;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/metafield_special.php?deactivateMenu=1&category=" + category + "&objId=" + objId + "&specialPageTitle=<?php echo getLngt("PREISE") ?>" ,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function openServiceAcceptanceProtocol(csId) {
  var widthPopupWin = 900;
  var heightPopupWin = 870;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/customer_service_acceptance_protocol.php?objType=cs&objId=" + csId,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function openDeliveryReasons(csId) {
  var widthPopupWin = 900;
  var heightPopupWin = 870;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/customer_service_delivery_reasons.php?objType=cs&objId=" + csId,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};
-->
</script>

</head>

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

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

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

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

<form action="../admin/customer_service.php" method="post">
  <input type="hidden" name="f_act" value="">
  <input type="hidden" name="customerId" value="<?php echo ec($customerId) ?>">
  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">

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

  <div class="f10bp1_blue">
    <?php echo getLngt("Kundenpreise und Aktionen") ?>
  </div>
  <?php echo htmlDivLineSpacer("10px"); ?>
  <div class="f10bp1_blue">
  	<?php echo defineButtonType10(getLngt("Preis EV"), "action_cs_price_00", "openMetaFieldSpecial('" . ec($customerId) . "','20');", "150", "left", "3"); ?>
  	<?php echo defineButtonType10(getLngt("Aktionspreise 1"), "action_cs_price_01", "openMetaFieldSpecial('" . ec($customerId) . "','21');", "150", "left", "3"); ?>
  	<?php echo defineButtonType10(getLngt("Aktionspreise 2"), "action_cs_price_02", "openMetaFieldSpecial('" . ec($customerId) . "','22');", "150", "left", "3"); ?>
  	<?php echo defineButtonType10(getLngt("Aktionspreise 3"), "action_cs_price_03", "openMetaFieldSpecial('" . ec($customerId) . "','23');", "150", "left", "3"); ?>
  	<?php echo defineButtonType10(getLngt("Aktionspreise 4"), "action_cs_price_04", "openMetaFieldSpecial('" . ec($customerId) . "','24');", "150", "left", "3"); ?>
  	<?php echo defineButtonType10(getLngt("Aktionspreise 5"), "action_cs_price_05", "openMetaFieldSpecial('" . ec($customerId) . "','25');", "150", "left", "3"); ?>
  </div>
  <?php echo htmlDivLineSpacer("20px", "", "left"); ?>

  <div class="f10bp1_blue">
  	<?php echo defineButtonType10(getLngt("Frachtvergütung"), "action_cr_price_00", "openMetaFieldSpecial('" . ec($customerId) . "','30');", "150", "left", "3"); ?>
  	<?php echo defineButtonType10(getLngt("Servicepreise"), "action_cs_serviceprice_00", "openMetaFieldSpecial('" . ec($customerId) . "','40');", "150", "left", "3"); ?>
  	<?php echo defineButtonType10(getLngt("Gutschrift Extern"), "action_cs_specialprice_00", "openMetaFieldSpecial('" . ec($customerId) . "','50');", "150", "left", "3"); ?>
  	<?php echo defineButtonType10(getLngt("Forderung Extern"), "action_cs_specialprice2_00", "openMetaFieldSpecial('" . ec($customerId) . "','60');", "150", "left", "3"); ?>
  </div>
  <?php echo htmlDivLineSpacer("40px", "", "left"); ?>

  
  <div class="f10bp1_blue">
    <?php if ($empIdRootAdmin == $emp_id || authCheckEmployeeRights($emp_id, "29")) : ?>
      <div <?php echo setStyleHtmlDiv("480px","left"); ?>>
        <div class="f10bp1_blue">
          <?php echo getLngt("Tageszeiteneinteilung (Basis für Fahrzeugdisposition)") ?>
          <?php echo htmlDivLineSpacer("10px"); ?>
          <?php echo $outputDayTimes ?>
          <?php 
            echo defineButtonType10(getLngt("Eintrag einfügen"), "action_day_time_new", "finishPage('day_time_new');", "250", "", "");
            echo htmlDivLineSpacer("5px", "", "left");
            echo defineButtonType10(getLngt("Standardwerte setzen"), "action_day_time_defaults", "finishPage('day_time_defaults');", "250", "", "");
            if (isset($dayTimesLen) && $dayTimesLen > 0) :
               echo htmlDivLineSpacer("5px", "", "left");
               echo defineButtonType10(getLngt("Untersten Eintrag löschen"), "action_day_time_remove", "finishPage('day_time_remove');", "250", "", "");
            endif;
          ?>
        </div>      
      </div>
    <?php endif; ?>
    <?php if ($empIdRootAdmin == $emp_id) : ?>
      <div <?php echo setStyleHtmlDiv("480px","left"); ?>>
        <div class="f10bp1_blue">
          <?php echo getLngt("Abweichende Artikelpreise") ?><br><?php echo getLngt("(Rabattkarten, Aktionen, Gutscheine, etc.)") ?>
          <?php echo htmlDivLineSpacer("10px"); ?>
          <?php echo $outputDiscountModes ?>
          <?php 
            echo defineButtonType10(getLngt("Eintrag einfügen"), "action_discount_mode_new", "finishPage('discount_mode_new');", "250", "", "");
            echo htmlDivLineSpacer("5px", "", "left");
            echo defineButtonType10(getLngt("Standardwerte setzen"), "action_discount_mode_defaults", "finishPage('discount_mode_defaults');", "250", "", "");
            if (isset($discountModeLen) && $discountModeLen > 0) :
               echo htmlDivLineSpacer("5px", "", "left");
               echo defineButtonType10(getLngt("Untersten Eintrag löschen"), "action_discount_mode_remove", "finishPage('discount_mode_remove');", "250", "", "");
            endif;
          ?>
        </div>      
      </div>
    <?php endif; ?>

    <div <?php echo setStyleHtmlDiv("480px","left"); ?>>
      <div class="f10bp1_blue">
        <?php echo getLngt("Zeitabhängigen Auslieferarten") ?>
        <?php echo htmlDivLineSpacer("10px"); ?>
        <?php echo $outputDeliveryTimes ?>
        <?php 
          echo defineButtonType10(getLngt("Eintrag einfügen"), "action_delivery_time_new", "finishPage('delivery_time_new');", "250", "", "");
          echo htmlDivLineSpacer("5px", "", "left");
          echo defineButtonType10(getLngt("Standardwerte setzen"), "action_delivery_time_defaults", "finishPage('delivery_time_defaults');", "250", "", "");
          if (isset($deliveryTimesLen) && $deliveryTimesLen > 0) :
             echo htmlDivLineSpacer("5px", "", "left");
             echo defineButtonType10(getLngt("Untersten Eintrag löschen"), "action_delivery_time_remove", "finishPage('delivery_time_remove');", "250", "", "");
          endif;
        ?>
      </div>      
    </div>

    <div>

    </div>
  </div>
  <?php echo htmlDivLineSpacer("40px", "", "left"); ?>

  <div class="f10bp1_blue">
    <div <?php echo setStyleHtmlDiv("480px","left"); ?>>
      <div class="f10bp1_blue">
        <?php echo getLngt("Standardzeit des täglichen SMS-Versands") ?>
        <?php echo htmlDivLineSpacer("10px"); ?>
        <?php echo $outputSmsTimes ?>
        <?php 
          echo defineButtonType10(getLngt("Zeit setzen"), "action_sms_time_new", "finishPage('sms_time_new');", "250", "", "");
          echo htmlDivLineSpacer("5px", "", "left");
          echo defineButtonType10(getLngt("Standardwert setzen"), "action_sms_time_default", "finishPage('sms_time_default');", "250", "", "");
        ?>
      </div>      
    </div>

    <div <?php echo setStyleHtmlDiv("480px","left"); ?>>
      <div class="f10bp1_blue">
        <?php echo getLngt("Standardzeit des täglichen Rollkartenversands") ?>
        <?php echo htmlDivLineSpacer("10px"); ?>
        <?php echo $outputCartageTimes ?>
        <?php 
          echo defineButtonType10(getLngt("Zeit setzen"), "action_cartage_time_new", "finishPage('cartage_time_new');", "250", "", "");
          echo htmlDivLineSpacer("5px", "", "left");
          echo defineButtonType10(getLngt("Standardwert setzen"), "action_day_time_defaults", "finishPage('cartage_time_default');", "250", "", "");
        ?>
      </div>      
    </div>

    <?php if (($empIdRootAdmin == $emp_id) || ($parDeliveryReasonsEnabled == "1")) : ?>
      <div <?php echo setStyleHtmlDiv("480px","left"); ?>>
        <?php if ($empIdRootAdmin == $emp_id) : ?>
          <div class="f10bp1_blue">
            <?php echo getLngt("Abnahmeprotokolle") ?>
          </div>
          <?php echo htmlDivLineSpacer("10px"); ?>
          <div class="f10bp1_blue">
          	<?php echo defineButtonType10(getLngt("Fragen und Text"), "action_cs_service_acceptance_protocol", "openServiceAcceptanceProtocol('" . ec($customerId) . "','20');", "250", "left", "3"); ?>
          </div>
          <?php echo htmlDivLineSpacer("15px", "", "left"); ?>
        <?php endif; ?>
        
        <?php if ($parDeliveryReasonsEnabled == "1") : ?>
          <div class="f10bp1_blue">
            <?php echo getLngt("Abliefergründe auf dem Endgerät") ?>
          </div>
          <?php echo htmlDivLineSpacer("10px"); ?>
          <div class="f10bp1_blue">
          	<?php echo defineButtonType10(getLngt("Abliefergründe"), "action_cs_service_delivery_reasons", "openDeliveryReasons('" . ec($customerId) . "','20');", "250", "left", "3"); ?>
          </div>
          <?php echo htmlDivLineSpacer("15px", "", "left"); ?>
        <?php endif; ?>
      </div>
    <?php endif; ?>

    <div>

    </div>
  </div>
  <?php echo htmlDivLineSpacer("40px", "", "left"); ?>

  <div class="f10bp1_blue">
    <div <?php echo setStyleHtmlDiv("350px","left"); ?>>
      <?php echo defineButtonType10(getLngt("Auswahl speichern"), "action_save", "finishPage('saveCustomerServices');", "300", "left", "3"); ?>
    </div>
    <div>
      <?php echo defineButtonType10(getLngt("Radien neu berechnen"), "action_radius", "finishPage('newRadiuses');", "300", "left", "10"); ?>
      <?php echo defineLinkButtonType10(getLngt("Zonenzuordnungen importieren"), "action_zone_import", "../import/data_transfer.php?deactivateMenu=1&objType=cs&objId=" . ec($customerId), "300", "left", "0", "", "", "", "", "18"); ?>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px", "", "left"); ?>
  
  <div class="f10bp1_blue">
    <div <?php echo setStyleHtmlDiv("350px","left"); ?>>
    	<?php echo defineButtonType10(getLngt("Schließen"), "action_close", "window.close();", "300", "left", "3"); ?>
    </div>
    <div>
      <?php echo defineButtonType10(getLngt("Markierte Radiuszuordnungen löschen"), "action_radiusmapping_remove", "finishPage('removeRadiusMappings');", "300", "left", "10"); ?>
      <?php echo defineButtonType10(getLngt("Markierte Zonenzuordnungen löschen"), "action_zonemapping_remove", "finishPage('removeZoneMappings');", "300", "left", "0"); ?>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px", "", "left"); ?>

  <?php if ($empIdRootAdmin == $emp_id) : ?>
    <div class="f10bp1_blue">
      <div <?php echo setStyleHtmlDiv("690px","left"); ?>>
      	&nbsp;
      </div>
      <div>
        <?php echo defineButtonType10(getLngt("Markierte Zone(n) löschen"), "action_zone_remove", "finishPage('removeServiceZone');", "300", "left", "0"); ?>
      </div>
    </div>
  <?php endif; ?>
  <?php echo htmlDivLineSpacer("15px", "", "left"); ?>

  <!-- Filter -->
  <div>
    <table>   
      <tr>
        <td>          
          <?php echo $output ?>
        </td>      
      </tr>
    </table>  
  </div>  

</form>
</div>
</body>

</html>