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

include_once ("../include/mcglobal.inc.php");
include_once ("../include/auth.inc.php");
include_once ("../include/inc_customer.inc.php");
include_once ("../geo/geocode.inc.php");

// Check HTTP-Parameters
// Costcenters
getSecHttpVars("1",array("f_act", "customerId", "cscIdRoot", "cscIdActual", "statusMessage", "deactivateMenu",
                         "deleteCostcenter", "nameCostcenter", "cscNameActual", "cscPathActual", 
                         "cscVisibleActual", "f_show_invisible"));
// Settings
getSecHttpVars("1",array("f_csc_inv_interval", "f_csc_inv_type", "f_csc_inv_mode"));

// Addresses
getSecHttpVars("1",array("f_cscad_comp","f_cscad_comp2","f_cscad_comp3","f_cscad_comp4",
                         "v_adt_id", "f_ad_street", "f_ad_zipcode", "f_ad_city", "f_ad_country",
                         "f_cscad_hsno", "f_noaddressvalidation", "f_cscad_remark", "f_cscad_person", 
                         "f_cscad_phone", "f_cscad_email", "f_cscad_gln"));

// Id of the actual employee and the costcenter (individual root-node) logged in
if ($cscIdRoot == ""): $cscIdRoot = getFieldValueFromId("employee","emp_id",$emp_id,"csc_id"); endif;
if ($customerId == ""): $customerId = getFieldValueFromId("costcenter","csc_id",$cscIdRoot,"cs_id"); endif;

$cmpId = getFieldValueFromId("customer","cs_id",$customerId,"cmp_id");
$cmpComp = getFieldValueFromId("company","cmp_id",$cmpId,"cmp_comp");
$cmpComp2 = getFieldValueFromId("company","cmp_id",$cmpId,"cmp_comp2");

// Get the rights of the employee logged in
$empRights = getRights($emp_id);

// Initialize actual node (costcenter) if not selected by the employee
if ($cscIdActual == ""): $cscIdActual = $cscIdRoot; endif;

getLanguage(__FILE__);

// Attention: Definition AFTER definitions of $customerId, $cscIdRoot and $cscIdActual
$pageTitel = getLngt("KOSTENSTELLEN");
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");

getCurrentScript(__FILE__);

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


// Flag for "show invisible costcenters"
if ($f_show_invisible == "" || count($f_show_invisible) == 0) :
   $f_show_invisible = "0";
else: 
   $f_show_invisible = "1";
endif;

mcTrim($nameCostcenter);

// If empty then set invoicing-interval to daily per default
if ($f_csc_inv_interval == "") : $f_csc_inv_interval = "0"; endif;

// If empty then set invoicing-type of the current costcenter to root-association (not standalone)
if ($f_csc_inv_type == "") : $f_csc_inv_type = "0"; endif;

// If not numeric invoice mode then emty it
if (!isset($f_csc_inv_mode) || !is_numeric($f_csc_inv_mode)) : $f_csc_inv_mode = ""; endif;


// Insert new costcenter
if ($f_act == "newCostcenter" && $nameCostcenter != "") :

   if (!isset($cscPathActual) || $cscPathActual == ""): $cscPathActual = "//"; endif;
   
   // Check for double costcenter-names. They have to be unique for each customer
   $tmpFields = array("cs_id",$customerId,"csc_name",$nameCostcenter);
   if (!existsEntry("costcenter",$tmpFields)) :

      TA("B");

      // The new path is the concatenation of the path of the actual costcenter and id of the actual costcenter
      $defaultFields = array("cs_id",$customerId,"csc_pre_id",$cscIdActual,"csc_name",$nameCostcenter,"csc_path",$cscPathActual.$cscNameActual."//","csc_visible","1");
      insertStmt("costcenter",$defaultFields);

      // Insert default values (addresses, invoice interval, etc.) of the root costcenter
      // Get id of the new costcenter
      $cscIdNew = getFieldValueFromClause("costcenter","csc_id","cs_id = '" . $customerId . "' AND csc_name = '" . $nameCostcenter . "'");
      // Get id of the root costcenter of the current customer
      $cscIdRootAddress = getFieldValueFromId("customer","cs_id",$customerId,"csc_id");

      if ($cscIdNew != "" && $cscIdRootAddress != "") :
         // Get addresses of the root costcenter
         for ($i = 1; $i <= 4; $i++) :
             getDbFieldValues("costcenteraddress",array("ad_id","cscad_hsno","cscad_comp","cscad_comp2","cscad_comp3","cscad_comp4"),array("csc_id",$cscIdRootAddress,"adt_id",$i));
             insertStmt("costcenteraddress",array("csc_id", $cscIdNew, "cscad_comp", $cscad_comp, "cscad_comp2", $cscad_comp2, "cscad_comp3", $cscad_comp3, "cscad_comp4", $cscad_comp4, "ad_id", $ad_id, "adt_id", $i, "cscad_hsno", $cscad_hsno));
         endfor;
         
         // Get invoice values
         $cscInvIntervalRoot = getFieldValueFromId("costcenter","csc_id",$cscIdRootAddress,"csc_inv_interval");
         if ($cscInvIntervalRoot == "") : $cscInvIntervalRoot = "0"; endif;
         updateStmt("costcenter", "csc_id", $cscIdNew, array("csc_inv_interval", $cscInvIntervalRoot));
      endif;

      // Write logdata into log database
      writeToLogDB("45",$hq_id,"",$usr_id,"","",$customerId,"CSC_ID_NEW=".$cscIdNew."|CSC_ID_PARENT=".$cscIdActual."|CSC_NAME_NEW=".$nameCostcenter);

      TA("C");
      TA("E");      
   else :
     $statusMessage = getLngt("Eine Kostenstelle mit demselben Namen") . " " .$nameCostcenter . " " . getLngt("existiert schon. Bitte umbenennen!");
   endif;        
endif;


// Delete selected costcenter
if ($f_act == "deleteCostcenter" && $deleteCostcenter != "") :

   // First check for invoices or jobs! If invoices or jobs exist never remove
   if (!existsEntry("job",array("csc_id",$deleteCostcenter)) && !existsEntry("job",array("csc_id_payer",$deleteCostcenter))) :
       // !existsEntry("jobhistory",array("csc_id",$deleteCostcenter)) !existsEntry("jobhistory",array("csc_id",$deleteCostcenter))

       // $fieldsLength = count($deleteCostcenter);
       $fieldsLength = 1;  // Presently implemented is single costcenter to be deleted
       for ($i = 0; $i < $fieldsLength; $i++) :
           $tmpFields = array("cs_id",$customerId,"csc_pre_id",$deleteCostcenter);
           if (!existsEntry("costcenter",$tmpFields)) :

              // Get the name of the costcenter (ONLY for logging!)
              $cscNameToBeDeleted = getFieldValueFromId("costcenter","csc_id",$deleteCostcenter,"csc_name");

              $whereClause = "csc_id = '$deleteCostcenter'";
              deleteStmt("costcenter",$whereClause);

              // Write logdata into log database
              writeToLogDB("46",$hq_id,"",$usr_id,"","",$customerId,"CSC_ID=".$deleteCostcenter."|CSC_NAME=".$cscNameToBeDeleted);
           else: 
              $statusMessage = getLngt("Eintrag kann nicht entfernt werden, da mindestens eine Unterkostenstelle existiert!");
           endif;             
       endfor;
   else :
     $statusMessage = getLngt("Eintrag kann nicht entfernt werden, da mindestens ein Auftrag existiert!");
   endif;
endif;


// Rename actual costcenter
if ($f_act == "renameCostcenter" && $nameCostcenter != "" && $cscIdActual != "" && $cscNameActual != "") :

   // Check for double costcenter-names. They have to be unique for each customer
   $tmpFields = array("cs_id",$customerId,"csc_name",$nameCostcenter);
   if (!existsEntry("costcenter",$tmpFields)) :   

      // Select all rows where the csc_path contains the actual costcenter
      TA("B");      

      $sqlStmt = "SELECT csc_id,csc_path FROM costcenter WHERE csc_path LIKE '%//$cscNameActual//%' AND cs_id = '".$customerId."'";
      $result = $db->query($sqlStmt);     
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

      while ($row = $result->fetch_assoc()):
        $csc_id = $row["csc_id"];
        $csc_path = str_replace("//$cscNameActual//","//$nameCostcenter//",strWrapJs($row["csc_path"]));
        updateStmt("costcenter","csc_id",$csc_id,array("csc_path",$csc_path));
      endwhile;
      $result->free();
      updateStmt("costcenter","csc_id",$cscIdActual,array("csc_name",$nameCostcenter));

      // Write logdata into log database
      writeToLogDB("47",$hq_id,"",$usr_id,"","",$customerId,"CSC_ID=".$cscIdActual."|CSC_NAME=".$nameCostcenter);      

      TA("C");
      TA("E");
   else :
     $statusMessage = getLngt("Eine Kostenstelle mit demselben Namen") . " " . $nameCostcenter . " " . getLngt("existiert schon. Bitte umbenennen!");
   endif;  
endif;


// Set status of visibility of the costcenter
if ($f_act == "setVisibility") :

   // Check for existence
   $tmpFields = array("cs_id",$customerId,"csc_id",$cscIdActual);
   if (existsEntry("costcenter",$tmpFields)) :

      // Update authentication-status
      updateStmt("costcenter","csc_id",$cscIdActual,array("csc_visible",$cscVisibleActual));

      // Write logdata into log database
      writeToLogDB("51",$hq_id,"",$usr_id,"","",$customerId,"STATUS_VISIBILITY=".$cscVisibleActual);
   else :
      $statusMessage = getLngt("Die Kostenstelle wurde nicht geändert!");
   endif;
endif;


$cscNameRoot = getFieldValueFromId("costcenter","csc_id",$cscIdRoot,"csc_name");

$tmpFields = getFieldsValueFromId("costcenter","csc_id",$cscIdActual,array("csc_path","csc_name","csc_visible"));
$cscPathActual = $tmpFields[0];
$cscNameActual = $tmpFields[1];
$cscVisibleActual = $tmpFields[2];

$cscVisibleActual2 = 0;
if ($cscVisibleActual != "1") :
   $cscVisibleActual = 0; 
   $cscVisibleActual2 = 1;
endif;


// Selection of all CHILDREN of the actual costcenter

$whereClauseVisibility = " AND csc_visible = '1' ";
if ($f_show_invisible == "1") : $whereClauseVisibility = ""; endif;

$sqlquery = "SELECT csc_id, csc_name, csc_path FROM costcenter"
             . " WHERE cs_id = '" . $customerId . "' AND csc_pre_id = '" . $cscIdActual . "'" . $whereClauseVisibility
             . " ORDER BY csc_name";

$result = $db->query($sqlquery);
if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
$listOfChildren = "";
while ($row = $result->fetch_assoc()):
      $csc_id = $row["csc_id"];
      $csc_name = $row["csc_name"];
      $csc_path = $row["csc_path"];
//      $listOfChildren .= ("<input type=\"checkbox\" name=\"deleteCostcenter[]\" value=\"$csc_id\"> "
//                        . "<a href=costcenter.php?customerId=$customerId&"
//                                          . "cscIdRoot=$cscIdRoot&"
//                                          . "cscIdActual=$csc_id>"
//                             . $csc_name . "</a> | \n");
      if (strtoupper($csc_name) != "EXTERN") :
         $listOfChildren .= "<option value=\"" . ec($csc_id) . "\">" . $csc_name . "</option>\n";
      endif;
endwhile;
if ($listOfChildren != "") : $listOfChildren = "<option value=\"\">" . getLngt("Kostenstellen") . ":</option>\n" . $listOfChildren; endif;
$result->free();


// Output of the path-links for navigation in the costcenter-tree
$cscPathActualOut = "";
$fields = spliti("//",$cscPathActual);
$len = count($fields);
$pathDelimiter = "<img src=\"../images/arrow_right.jpg\" border=\"0\" height=\"10\" width=\"25\">";
$rootFlag = FALSE;
$maxPathLength = 4;
$pathPrefix = "";
$pathPrefixFlag = FALSE;
for ($i = 0; $i < $len; $i++) :
  if ($fields[$i] != "") :
     // Only show the subpath from the "actual root" of the employee     
     if ($fields[$i] == $cscNameRoot) : $rootFlag = TRUE; endif;                         
     if ($rootFlag) :
        // Only output of the last <maxPathLength> elements
        if ($i > $len - $maxPathLength) :
           $csc_id = getFieldValueFromClause("costcenter","csc_id","cs_id = '" . $customerId . "' AND csc_name = '" . strWrapJs($fields[$i]) . "'");
           $cscPathActualOut .= "<a href=costcenter.php?currentNavigationItem=kostenstellen&deactivateMenu=" . ec($deactivateMenu) . "&customerId=" . ec($customerId)
                                            . "&cscIdRoot=" . ec($cscIdRoot)
                                            . "&cscIdActual=" . ec($csc_id) . ">"
                                            . $fields[$i] . "</a>";
           $cscPathActualOut .= $pathDelimiter;
        
        else :
           if (!$pathPrefixFlag && ($i > $len - $maxPathLength - 1)) :     
              $csc_id = getFieldValueFromClause("costcenter","csc_id","cs_id = '" . $customerId . "' AND csc_name = '" . strWrapJs($fields[$i]) . "'");
              $pathPrefix = "<a href=costcenter.php?currentNavigationItem=kostenstellen&deactivateMenu=" . ec($deactivateMenu) . "&customerId=" . ec($customerId)
                                            . "&cscIdRoot=" . ec($cscIdRoot)
                                            . "&cscIdActual=" . ec($csc_id) . "><img src=\"../images/arrow_left.jpg\" border=\"0\" height=\"10\" width=\"25\"></a>"
                                            . $pathDelimiter;
              $pathPrefixFlag = TRUE;
           endif;
        endif;        
     endif;
  endif;
endfor;
$cscPathActualOut = $pathPrefix . $cscPathActualOut . $cscNameActual;


// Check for costcenter being an external costcenter, because an external one 
// has only access to addresses. Therefore the "empRights"-String has to be set 
// according to the following scheme
if (strtoupper($cscNameActual) == "EXTERN" || !(strpos(strtoupper($cscPathActual), "//EXTERN//") === FALSE)) :
   $empRights = "100100000000000";
endif;


// Check for the right to administrate the costcenters, only for output
$cscAdminDisabled = "";
$maskCostcenterCompanyFieldsEditDisabled = "";
if ($userTypeName == "cs") :
   if (substr($empRights,1,1) != "1") : $cscAdminDisabled = "disabled"; endif;
   $maskCostcenterCompanyFieldsEditDisabled = getParameterValue("0", "MASK_CSC_CMP_FIELDS_EDIT_DISABLED", "0");
   if ($maskCostcenterCompanyFieldsEditDisabled != "") :
      $maskCostcenterCompanyFieldsEditDisabled = "readonly";
   endif;
else :
   if (substr($empRights,0,1) != "1") : $cscAdminDisabled = "disabled"; endif;
endif;


// Definition of the select-fields, only for output
$selectFieldSelectCostcenter = "";
$selectFieldDeleteCostcenter = "";
if ($listOfChildren != "") :
   // Check for the right to navigate in the subtree
   if (substr($empRights,0,1) == "1") :
      $selectFieldSelectCostcenter = "<span class=\"f8np1\">\n" .
                               "<select name=\"selectCostcenter\" onChange=\"xReload();\">\n" .
                               $listOfChildren . "\n" .
                               "</select>\n" .
                               "</span>\n";
   endif;
   $selectFieldDeleteCostcenter = "<div style=\"width:100%; height:3px;\"> </div>" .
                            "<div style=\"float:left\"><span class=\"f8np1\">\n" .
                            "<select name=\"deleteCostcenter\">\n" .
                            $listOfChildren . "\n" .
                            "</select>\n" .
                            "</span>&nbsp;&nbsp;</div>\n" .
                              defineButtonType10(getLngt("Löschen"), "action_remove", "cscFinishPage('" . ec("deleteCostcenter") . "');", "120", "left", "2");
endif;

// Check the status of the visibility of the current costcenter
$buttonVisibility = "";
$displayTextVisibility = "";
$confirmTextVisibility = "";
if ($cscIdRoot != $cscIdActual) :   // NOT for the root costcenter !!!    (Check $userTypeName == "hq" ???)
   $buttonVisibility = defineButtonType10(getLngt("Ausblenden"), "action_invisible", "visibilityFinishPage();", "120", "left", "2");
   $confirmTextVisibility = getLngt("Soll die aktuelle Kostenstelle wirklich ausgeblendet werden?");
   if ($cscVisibleActual != "1") : 
      $buttonVisibility = defineButtonType10(getLngt("Einblenden"), "action_visible", "visibilityFinishPage();", "120", "left", "2");
      $displayTextVisibility = getLngt("(ausgeblendet)");
      $confirmTextVisibility = getLngt("Soll die aktuelle Kostenstelle wirklich eingeblendet werden?");
   endif;
endif;
// Checkbox for displaying all costcenters
$showInvisibles = getLngt("Alle&nbsp;anz.") . "&nbsp;<input type=\"checkbox\" name=\"f_show_invisible[]\" value=\"1\" " . ($f_show_invisible == "1" ? "checked" : "") . " onChange=\"javascript:visibilityListFinishPage();\" tabindex=\"\">";

// Check for the right to make the costcenters (in)visible, only for output
if (($userTypeName == "cs" && substr($empRights,1,1) != "1") || ($userTypeName == "hq" && substr($empRights,0,1) != "1")) :
   $buttonVisibility = "";
   $showInvisibles = "";
endif;



// ************
// * SETTINGS *
// ************

// Currently ONLY for headquarters
if ($userTypeName == "hq" && substr($empRights,0,1) == "1") :

   // Secure-check of the association between customer, costcenter and employee
   $tmpFields = array("cs_id",$customerId,"csc_id",$cscIdActual);
   if (existsEntry("costcenter",$tmpFields)) : 
        
      // Get the name of the current costcenter
      $cscNameActual = getFieldValueFromId("costcenter","csc_id",$cscIdActual,"csc_name");
         
      // *** Save the settings (Begin) ***
      // Actually one addresstype is represented only one time per costcenter in costcenteraddress
      if ($f_act == "saveSettings") :
   
         // Update costcenter
         updateStmt("costcenter", "csc_id", $cscIdActual, array("csc_inv_interval", $f_csc_inv_interval, "csc_inv_type", $f_csc_inv_type));

         // Check existence of parameter for costcenter invoice mode
         if ($f_csc_inv_mode != "" || ($f_csc_inv_mode == "" && existsEntry("parameter",array("par_key","COSTCENTER_INV_MODE_" . $cscIdActual)))) :
            setParameterValue("COSTCENTER_INV_MODE_" . $cscIdActual, $f_csc_inv_mode);
         endif;

         // Write logdata into log database
         writeToLogDB("49",$hq_id,"",$usr_id,"","",$customerId,"CSC_ID=".$cscIdActual."|CSC_NAME=".$cscNameActual."|INTERVAL=".$f_csc_inv_interval."|INVMODE=".$f_csc_inv_mode);
         
         // Set modification status of the current customer if values of the ROOT-costcenter(!) are changed
         if ($cscIdActual == $cscIdRoot) : 
            setModificationStatus($customerId);
         endif;      
      endif;   
      // *** Save the settings (End) ***
   
   
      // ******************************************************
      // * Selection of the settings of the actual costcenter *
      // ******************************************************
      $sqlquery = "SELECT csc.csc_inv_interval,csc.csc_inv_type"
                   . " FROM costcenter AS csc"
                   . " WHERE csc.csc_id = '$cscIdActual'";
      $result = $db->query($sqlquery);
   
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
      while ($row = $result->fetch_assoc()):
            $f_csc_inv_interval = $row["csc_inv_interval"];
            $f_csc_inv_type = $row["csc_inv_type"];
      endwhile;
      $result->free();

      // Get special costcenter invoice mode
      $f_csc_inv_mode = getParameterValue("0", "COSTCENTER_INV_MODE_" . $cscIdActual, "0");
   endif;   
endif;



// *************
// * ADDRESSES *
// *************

// Set the default addresstype on "Abhol-/Lieferadresse"
if ($v_adt_id == "") : $v_adt_id = "4"; endif;

// Check for validation of the address assigned to the customer
$noValidationOfAddress = FALSE;
if ($f_noaddressvalidation != "") :
   if ($f_noaddressvalidation[0] == '1') : $noValidationOfAddress = TRUE; endif;
endif;

$addressValidationErr = "";

// Secure-check of the association between customer and costcenter
$tmpFields = array("cs_id",$customerId,"csc_id",$cscIdActual);
if (existsEntry("costcenter",$tmpFields)) : 

   $cscNameActual = getFieldValueFromId("costcenter","csc_id",$cscIdActual,"csc_name");
   
   // *** Save the adress (Begin) ***
   // Actually one addresstype is represented only one time per costcenter in costcenteraddress
   if ($f_act == "saveAddress") :

      $f_cscad_comp = trim($f_cscad_comp);
      $f_cscad_comp2 = trim($f_cscad_comp2);
      $f_cscad_comp3 = trim($f_cscad_comp3);
      $f_cscad_comp4 = trim($f_cscad_comp4);
      $f_ad_street = trim($f_ad_street);
      $f_ad_zipcode = trim($f_ad_zipcode);
      $f_ad_city = trim($f_ad_city);
      $f_ad_country = trim($f_ad_country);
      $f_cscad_hsno = trim($f_cscad_hsno);

      // Check for empty entry in the company-field
      if ($f_cscad_comp != "") :

         // Check for empty entries in address-fields
         if ($f_ad_street != "" && $f_ad_zipcode != "" && $f_ad_city != "" && $f_ad_country != "") :

            // Check validity according to the address-server
            $addressValid = getGeoCoordinates($f_ad_street, $f_ad_zipcode, $f_ad_city, $f_cscad_hsno, $f_ad_country, "");
            if ($addressValid != "") :

               // Check zipcode and city
               $addressValidityArray = checkCityZipcode($f_ad_zipcode, $f_ad_city, $f_ad_street);
               if ($noValidationOfAddress || $addressValidityArray[0] >= 1) :

                  TA("B");

                  // Check for existing entry in address (because of redundance)
                  if ($f_ad_country == "") : $f_ad_country = "DE"; endif;
                  $tmpArray = insertAddress($f_ad_street, $f_ad_zipcode, $f_ad_city, "", $f_ad_country, $noValidationOfAddress);
                  $ad_id = $tmpArray[0];                     
         
                  // Check for addresstype-entry(!) in costcenteraddress
                  $cscadFields = array("csc_id",$cscIdActual,"adt_id",$v_adt_id);
                  if (existsEntry("costcenteraddress",$cscadFields)) :
   
                     // Update costcenteraddress
                     $sqlStmt = "UPDATE costcenteraddress SET ad_id = $ad_id, cscad_hsno = '$f_cscad_hsno', "
                                . "cscad_remark = '$f_cscad_remark', cscad_person = '$f_cscad_person', cscad_phone = '$f_cscad_phone', cscad_email = '$f_cscad_email', cscad_gln = '$f_cscad_gln', "
                                . "cscad_comp = '$f_cscad_comp', cscad_comp2 = '$f_cscad_comp2', cscad_comp3 = '$f_cscad_comp3', cscad_comp4 = '$f_cscad_comp4' "
                                . "WHERE csc_id = $cscIdActual AND adt_id = $v_adt_id";
//                     writeDbLog($sqlStmt);
                     $res = $db->query($sqlStmt);        
                  else :               

                     // Insert costcenteraddress
                     $sqlStmt = "INSERT INTO costcenteraddress (csc_id,adt_id,ad_id,cscad_hsno,cscad_remark,cscad_person,cscad_phone,cscad_comp,cscad_comp2,cscad_comp3,cscad_comp4,cscad_email,cscad_gln) "
                                . " VALUES ($cscIdActual,$v_adt_id,$ad_id,'$f_cscad_hsno','$f_cscad_remark','$f_cscad_person','$f_cscad_phone','$f_cscad_comp','$f_cscad_comp2','$f_cscad_comp3','$f_cscad_comp4','$f_cscad_email','$f_cscad_gln')";
//                     writeDbLog($sqlStmt);
                     $res = $db->query($sqlStmt);         
                  endif;  
                  
                  // Write logdata into log database
                  writeToLogDB("48",$hq_id,"",$usr_id,"","",$customerId,"CSC_ID=".$cscIdActual."|AD_ID=".$ad_id."|ADT_ID=".$v_adt_id."|ADDRESS=".$f_cscad_comp.";".$f_cscad_comp2.";".$f_cscad_comp3.";".$f_cscad_comp4.";".$f_ad_street.";".$f_ad_zipcode.";".$f_ad_city.";".$f_ad_country.";".$f_cscad_hsno.";".$f_cscad_remark.";".$f_cscad_person.";".$f_cscad_phone.";".$f_cscad_email.";".$f_cscad_gln);

                  // Set modification status of the current customer if values of the ROOT-costcenter(!) are changed
                  if ($cscIdActual == $cscIdRoot) : 
                     setModificationStatus($customerId);
                  endif;

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

               else :
                 $statusMessage = getLngt("Die Postleitzahl passt nicht zu dem angegebenen Ort!");
                 $addressValidationErr = "1";
               endif;               
            else :
               $statusMessage = getLngt("Der Adress-Server kennt die eingebene Adresse nicht! Bitte korrekt erfassen!");
            endif;
         else :
            $statusMessage = getLngt("Bitte geben Sie mindestens Straße, Hausnummer, Stadt und Land an!");
         endif;
      else :
         $statusMessage = getLngt("Bitte geben Sie den Firmennamen oder übernehmen Sie den aus der übergeordneten Kostenstelle!");
      endif;         
   endif;   
   // *** Save the adress (End) ***


   // ***************************************************************************************
   // * Selection of the address of the actual costcenter based on the selected addresstype *
   // ***************************************************************************************
   $sqlquery = "SELECT cscad.ad_id,cscad.cscad_comp,cscad.cscad_comp2,cscad.cscad_comp3,cscad.cscad_comp4,cscad.cscad_hsno,cscad.cscad_remark,cscad.cscad_person,cscad.cscad_phone,cscad.cscad_email,cscad.cscad_gln,ad.ad_street,ad.ad_zipcode,ad.ad_city,ad.ad_country"
                . " FROM costcenteraddress AS cscad, address AS ad"
                . " WHERE cscad.csc_id = '$cscIdActual' AND"
                . "       cscad.adt_id = '$v_adt_id'    AND"
                . "       cscad.ad_id = ad.ad_id           ";                
   $result = $db->query($sqlquery);

   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
   while ($row = $result->fetch_assoc()):
         $v_ad_id        = $row["ad_id"];         
         $v_ad_street    = $row["ad_street"];
         $v_ad_zipcode   = $row["ad_zipcode"];
         $v_ad_city      = $row["ad_city"];
         $v_ad_country   = $row["ad_country"];
         $v_cscad_comp   = $row["cscad_comp"];
         $v_cscad_comp2  = $row["cscad_comp2"];
         $v_cscad_comp3  = $row["cscad_comp3"];
         $v_cscad_comp4  = $row["cscad_comp4"];
         $v_cscad_hsno   = $row["cscad_hsno"];
         $v_cscad_remark = $row["cscad_remark"];
         $v_cscad_person = $row["cscad_person"];
         $v_cscad_phone  = $row["cscad_phone"];
         $v_cscad_email  = $row["cscad_email"];
         $v_cscad_gln    = $row["cscad_gln"];
   endwhile;
   $result->free();
endif;

// If company-name ("f_cscad_comp" and "f_cscad_comp2") in "costcenteraddress" empty,
// take the name from the parent-costcenter
if ($v_cscad_comp == "") :

   $sqlquery = "SELECT cscad.cscad_comp,cscad.cscad_comp2,cscad.cscad_comp3,cscad.cscad_comp4"
                . " FROM costcenteraddress AS cscad,costcenter AS csc, costcenter AS csc2"
                . " WHERE csc.csc_id = '$cscIdActual'   AND"
                . "       csc2.csc_id = csc.csc_pre_id  AND"
                . "       csc2.csc_id = cscad.csc_id  AND"
                . "       cscad.adt_id = '$v_adt_id'";
   $result = $db->query($sqlquery);

   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
   while ($row = $result->fetch_assoc()):
         $v_cscad_comp   = $row["cscad_comp"];
         $v_cscad_comp2  = $row["cscad_comp2"];
         $v_cscad_comp3  = $row["cscad_comp3"];
         $v_cscad_comp4  = $row["cscad_comp4"];
   endwhile;
   $result->free();   
endif;

$v_cscad_comp = strWrapHtml($v_cscad_comp);
$v_cscad_comp2 = strWrapHtml($v_cscad_comp2);
$v_cscad_comp3 = strWrapHtml($v_cscad_comp3);
$v_cscad_comp4 = strWrapHtml($v_cscad_comp4);


$pageHeadline = ($deactivateMenu == "1" ? "<span class=\"f12bp1_blue\">" . strtoupper($pageTitel) . "</span>" . " &nbsp;&nbsp;&nbsp;&nbsp;" : "" ) . $cmpComp . ($cmpComp2 != "" ? " :: " . $cmpComp2 : "");

?>

<html>

<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/searchLists.js" type="text/javascript"></script>
<script src="../include/checkFormTags.js" type="text/javascript"></script>

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


// Part for COSTCENTERS

function xReload() {  
 for(i=0;i<document.forms[0].selectCostcenter.length;++i) {
   if (document.forms[0].selectCostcenter.options[i].selected == true) {      	
      csc_id = document.forms[0].selectCostcenter.options[i].value;
      document.location.href = "costcenter.php?currentNavigationItem=kostenstellen&deactivateMenu=<?php echo $deactivateMenu ?>&customerId=<?php echo $customerId ?>&cscIdRoot=<?php echo $cscIdRoot ?>&cscIdActual=" + csc_id;
   }
 } 
};

function visibilityFinishPage() {
  if (confirm('<?php echo $confirmTextVisibility ?>')) {
     document.forms[0].cscVisibleActual.value='<?php echo ec($cscVisibleActual2) ?>';
     document.forms[0].f_act.value='setVisibility';
     document.forms[0].submit();
  }
};

function visibilityListFinishPage() {
  // document.forms[0].f_show_invisible.checked=true;
  if (document.forms[0].currentNavigationItem) {
     document.forms[0].currentNavigationItem.value='kostenstellen';
  }
  document.forms[0].submit();
};

function cscFinishPage(f_act) {
  document.forms[0].f_act.value=f_act;
  if (document.forms[0].currentNavigationItem) {
     document.forms[0].currentNavigationItem.value='kostenstellen';
  }
  document.forms[0].submit();
}


// Part for SETTINGS

function settingsFinishPage() {
  
  document.forms[0].f_act.value='saveSettings';
  if (document.forms[0].currentNavigationItem) {
     document.forms[0].currentNavigationItem.value='kostenstellen';
  }
  document.forms[0].submit();  

};


// Part for ADDRESSES

function checkFields() {
	var glnLen = 13;
  frm = document.forms[0];  
  if (!frm.f_ad_street.value){		
     alert('<?php echo getLngt("Bitte geben Sie die Straße ein!") ?>');
     frm.f_ad_street.focus();
     return;
  }
  if (!frm.f_cscad_hsno.value){		
     alert('<?php echo getLngt("Bitte geben Sie die Hausnummer ein!") ?>');
     frm.f_cscad_hsno.focus();
     return;
  }
  if (!frm.f_ad_zipcode.value){		
     alert('<?php echo getLngt("Bitte tragen Sie die Postleitzahl ein!") ?>');
     frm.f_ad_zipcode.focus();
     return;
  }
  if (!frm.f_ad_city.value){
     alert('<?php echo getLngt("Bitte geben Sie die Stadt ein!") ?>');
     frm.f_ad_city.focus();
     return;
  }
  if (frm.f_cscad_phone.value && !checkIsNaNIgnoreSpace(frm.f_cscad_phone.value, '<?php echo getLngt("Bitte tragen Sie eine Nummer bei Telefon ein!") ?>')){
     frm.f_cscad_phone.focus();
     return;
  }  
  if (frm.f_cscad_email.value.length != 0) {
     // if e-mail has content then check syntax
     if (!checkMailAddress(frm.f_cscad_email, '<?php echo getLngt("Bitte tragen Sie eine gültige Email-Adresse ein!") ?>')) {return;};
  }
  if (frm.f_cscad_gln.value.length != 0 && frm.f_cscad_gln.value.length != 13) {
     alert('<?php echo getLngt("Die geforderte Stelligkeit der GLN ist") ?>' + ' ' + glnLen);
     frm.f_cscad_gln.focus();
     return;
  }
  frm.f_act.value='saveAddress';
  if (frm.currentNavigationItem) {
     frm.currentNavigationItem.value='kostenstellen';
  }
  frm.submit();
};

-->
</script>
</head>

<body 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="../customer/costcenter.php" method="post">
  <input type="hidden" name="f_act" value="">
  <input type="hidden" name="customerId" value="<?php echo ec($customerId) ?>">
  <input type="hidden" name="cscIdRoot" value="<?php echo ec($cscIdRoot) ?>">
  <input type="hidden" name="cscIdActual" value="<?php echo ec($cscIdActual) ?>">
  <input type="hidden" name="cscNameActual" value="<?php echo $cscNameActual ?>">
  <input type="hidden" name="cscPathActual" value="<?php echo $cscPathActual ?>">
  <input type="hidden" name="cscVisibleActual" value="<?php echo ec($cscVisibleActual) ?>">
  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">
  <input type="hidden" name="ad_id" value="<?php echo ec(mcIsSet($ad_id)) ?>">

  
  <?php echo htmlDivLineSpacer("10px"); ?>
  
  <div class="f10bp1_blue">
    <div style="float:left">
       <?php echo getLngt("Aktuelle Kostenstelle:") ?>&nbsp;
       <span class="f10bp1_red"><?php echo $cscPathActualOut ?></span>
       &nbsp;&nbsp;&nbsp;
       <?php echo $selectFieldSelectCostcenter ?>
       &nbsp;&nbsp;&nbsp;
    </div>
    <?php echo $buttonVisibility ?>
    <div style="float:left">
      <?php echo $showInvisibles ?>
    </div>
  </div>

  <?php echo htmlDivLineSpacer("5px", "", "left"); ?>
  <?php echo htmlDivLineSpacer("1px","100%","","1"); ?>
  <?php echo htmlDivLineSpacer("5px"); ?>

  <div>
    <div style="float:left">
      <?php echo htmlDivLineSpacer("3px"); ?>
      <?php 
        if ($cscAdminDisabled == "disabled") :
           $selectFieldDeleteCostcenter = "";
        else :
           echo "<div style=\"float:left\">";
           echo "<input type=\"text\" name=\"nameCostcenter\" value=\"\" size=\"25\" maxlength=\"50\" class=\"input\">&nbsp;&nbsp;";
           echo "</div>";
           echo defineButtonType10(getLngt("Anlegen"), "action_new", "cscFinishPage('" . ec("newCostcenter") . "');", "120", "left", "2");
           echo defineButtonType10(getLngt("Umbenennen"), "action_rename", "cscFinishPage('" . ec("renameCostcenter") . "');", "120", "left", "2");
        endif;
      ?>    
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    </div>
    <?php echo $selectFieldDeleteCostcenter ?>
  </div>

  <?php echo htmlDivLineSpacer("10px", "", "left"); ?>
  <?php echo htmlDivLineSpacer("1px","100%","","1"); ?>
  <?php echo htmlDivLineSpacer("10px"); ?>


<!-- *** SETTINGS *********************************************************************************** -->

<?php if ($userTypeName == "hq" && substr($empRights,0,1) == "1") : ?>

  <div class="f10bp1_blue">
    Einstellungen für: <?php echo $cscNameActual ?>
  </div>
  <?php echo htmlDivLineSpacer("10px"); ?>

<!--
  <div>
    Art der Rechnungsanlagedaten: &nbsp;&nbsp;&nbsp;
    <select name="f_csc_inv_type">
      <?php echo addOptionsFromTable("metatype","mt_sort","mt_value","mt_sort","mt_type = 'invoicetype'",$f_csc_inv_type); ?>
    </select>
  </div>
-->

  <div>
    <div>
    	<?php echo getLngt("Intervall zur Erzeugung der Rechnungsanlagedaten:") ?> &nbsp;&nbsp;&nbsp;
      <select name="f_csc_inv_interval">
        <?php echo addOptionsFromTable("metatype","mt_sort","mt_value","mt_sort","mt_type = 'invoiceinterval'",$f_csc_inv_interval); ?>
      </select>
      &nbsp;&nbsp;&nbsp;
    </div>
    <?php echo htmlDivLineSpacer("10px"); ?>

    <div>
    	<?php echo getLngt("Abrechnungsmodus:") ?> &nbsp;&nbsp;&nbsp;
      <select name="f_csc_inv_mode">
        <option value="" <?php if ($f_csc_inv_mode == "") : echo "selected"; endif; ?>><?php echo getLngt("Modus wie Kundenstammblatt") ?></option>
        <option value="0" <?php if ($f_csc_inv_mode == "0") : echo "selected"; endif; ?>><?php echo getLngt("Kilometer") ?></option>
        <option value="1" <?php if ($f_csc_inv_mode == "1") : echo "selected"; endif; ?>><?php echo getLngt("PLZ") ?></option>
        <option value="2" <?php if ($f_csc_inv_mode == "2") : echo "selected"; endif; ?>><?php echo getLngt("Bereich (= zusammengefasste PLZn)") ?></option>
        <option value="3" <?php if ($f_csc_inv_mode == "3") : echo "selected"; endif; ?>><?php echo getLngt("Radius") ?></option>
      </select>
      &nbsp;&nbsp;&nbsp;
    </div>
    <?php echo htmlDivLineSpacer("10px"); ?>

    <?php echo defineButtonType10(getLngt("Speichern"), "action_save_settings", "settingsFinishPage();", "120", "left", "2") ?>
  </div>

  <?php echo htmlDivLineSpacer("10px", "", "left"); ?>
  <?php echo htmlDivLineSpacer("1px","100%","","1"); ?>
  <?php echo htmlDivLineSpacer("10px"); ?>

<?php endif; ?>


<!-- *** ADDRESSES ********************************************************************************** -->

<?php if ($userTypeName == "hq" || ($userTypeName == "cs" && substr($empRights,3,1) == "1")) : ?>

  <div class="f10bp1_blue">
    <?php echo getLngt("Adressen der Kostenstelle") ?>: <?php echo $cscNameActual ?>
  </div>
  <?php echo htmlDivLineSpacer("10px"); ?>

  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt("Typ") ?>:</div>
    <div>
      <select name="v_adt_id" onChange="submit();">
        <?php echo addOptionsFromTable("metatype","mt_sort","mt_value","mt_sort","mt_type = 'addresstype'",$v_adt_id); ?>
      </select>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px"); ?>
  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt("Firma") ?>:</div>
    <div>
      <input type="text" name="f_cscad_comp" value="<?php echo $v_cscad_comp ?>" <?php echo $maskCostcenterCompanyFieldsEditDisabled?>>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px"); ?>
  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>>&nbsp;</div>
    <div>
      <input type="text" name="f_cscad_comp2" value="<?php echo $v_cscad_comp2 ?>" <?php echo $maskCostcenterCompanyFieldsEditDisabled?>>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px"); ?>
  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>>&nbsp;</div>
    <div>
      <input type="text" name="f_cscad_comp3" value="<?php echo $v_cscad_comp3 ?>" <?php echo $maskCostcenterCompanyFieldsEditDisabled?>>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px"); ?>
  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>>&nbsp;</div>
    <div>
      <input type="text" name="f_cscad_comp4" value="<?php echo $v_cscad_comp4 ?>" <?php echo $maskCostcenterCompanyFieldsEditDisabled?>>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px"); ?>
  <?php if ($v_adt_id == "1" || $v_adt_id == "2") : ?>
    <div>
      <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt("GLN") ?>:</div>
      <div>
         <input type="text" name="f_cscad_gln" value="<?php echo $v_cscad_gln ?>">
      </div>
    </div>
    <?php echo htmlDivLineSpacer("15px"); ?>
  <?php else : ?>
         <input type="hidden" name="f_cscad_gln" value="">
  <?php endif; ?>  
  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt("Strasse & Hsnr.") ?>:</div>
    <div>
      <input type="text" name="f_ad_street" value="<?php echo $v_ad_street ?>">&nbsp;
      <input type="text" name="f_cscad_hsno" size="5" value="<?php echo $v_cscad_hsno ?>">
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px"); ?>
  
  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt("PLZ") ?>:</div>
    <div style="float:left">
       <input type="text" name="f_ad_zipcode" value="<?php echo $v_ad_zipcode ?>">&nbsp;&nbsp;
    </div>
    <?php echo defineButtonType10("...", "action_ad_search", "searchAddress('cs');", "23", "left"); ?>
  </div>
  <?php echo htmlDivLineSpacer("5px", "", "left"); ?>
  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt("Ort") ?>:</div>
    <div>
       <input type="text" name="f_ad_city" value="<?php echo $v_ad_city ?>">
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px"); ?>
  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt("Land") ?>:</div>
    <div>
      <select class="f8np1" name="f_ad_country">
        <?php echo getCountryCodesAsOptions($v_ad_country); ?>
      </select>
      <input type="checkbox" name="f_noaddressvalidation[]" value="1"><?php echo getLngt("Keine Prüfung") ?>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px"); ?>

  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt("Bemerkung") ?>:</div>
    <div>
       <input type="text" name="f_cscad_remark" value="<?php echo $v_cscad_remark ?>">
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px"); ?>
  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt("Person") ?>:</div>
    <div>
       <input type="text" name="f_cscad_person" value="<?php echo $v_cscad_person ?>">
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px"); ?>
  <div>
    <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt("Telefon") ?>:</div>
    <div>
       <input type="text" name="f_cscad_phone" value="<?php echo $v_cscad_phone ?>">
    </div>
  </div>
  <?php echo htmlDivLineSpacer("5px"); ?>
  <?php if ($v_adt_id == "2") : ?>
    <div>
      <div <?php echo setStyleHtmlDiv("110px","left"); ?>><?php echo getLngt("Email") ?>:</div>
      <div>
         <input type="text" name="f_cscad_email" value="<?php echo $v_cscad_email ?>">
      </div>
    </div>
    <?php echo htmlDivLineSpacer("15px"); ?>
  <?php else : ?>
         <input type="hidden" name="f_cscad_email" value="">
  <?php endif; ?>
  
  <?php echo defineButtonType10(getLngt("Speichern"), "action_ad_save", "checkFields();", "120", "left", "2") ?>

  
<?php endif; ?>

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

</html>
