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


include_once ("../include/mcglobal.inc.php");
// include_once ('../include/email/htmlMimeMail.php');
// include_once ("../include/services_func.inc.php");
include_once ("../include/inc_parseXML.inc.php");
include_once ("../include/inc_mtf_func.inc.php");
include_once ("../include/inc_job.inc.php");
include_once ("../include/inc_customer.inc.php");
include_once ("../include/inc_vehicle.inc.php");
// include_once ("../include/inc_disposition.inc.php");
// include_once ("../include/inc_tracking.inc.php");
// include_once ("../include/inc_disposition_DEV.inc.php");
// include_once ("../geo/geocode.inc.php");


// Write logdata into log file
$currentTime = getDateTime("0");
$currentDate = getDateTime("3");

// Get global constants
defineGlobalParameters("1");

$debug = false;
$debugOut = array();

$customerXML = "";
$retDbIds = "";
$lineFeed = "\n";

// $customerReq = file_get_contents('php://input');

// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "customerReq", "selectedLanguage"));

if ($customerReq == "") :
   if (isset($argv[1])) : 
      $customerReq = $argv[1];
   endif;
endif;

function customerRequestLogFile ($msg, $logLevel = 0) {
  XMLRequestLogFile($msg, $logLevel, $logFile = "customerReq.log");
}

function authCheckEmployeeRights ($empId, $right) {
  return false;
}


// Calling client IP
$currentClientIP = trim($_SERVER['REMOTE_ADDR']);

$customerReq = urldecode($customerReq);
$customerReq = str_replace("'", "", $customerReq);
$customerReq = mcEncode($customerReq);
$customerReq = str_replace("'", "", $customerReq);
// echo $customerReq . "<br><br>";

customerRequestLogFile($currentTime . " - " . $currentClientIP);
customerRequestLogFile($customerReq);


if ($selectedLanguage == "" || !is_numeric($selectedLanguage)) : $selectedLanguage = "1"; endif;  // Default in English
$languageSelected = $selectedLanguage;

getLanguage(__FILE__);
getCurrentScript(__FILE__);

$err = array();
$outResponse = "";
$acceptOrder = true;

// ---------------------------------------------------------------------------

// ERROR CODES
$errCode = array();
$modeErrCode = "DE";

if ($modeErrCode == "DE") :
   $errCode[100] = getLngt("Der Wert entspricht nicht dem geforderten Typ bzw. den Validitätsbedungungen.");
   $errCode[101] = getLngt("Die Authentifizierungsdaten sind nicht in Ordnung.");
   $errCode[102] = getLngt("Die notwendige ID des Auftraggebers ist nicht gesetzt.");
   $errCode[103] = getLngt("Der Auftraggeber wurde nicht im Datenbestand gefunden.");
   $errCode[104] = getLngt("Der Auftraggeber hat den Status eines Metakunden für einen anderen Auftraggeber.");
   $errCode[105] = getLngt("Der Auftraggeber hat mindestens einen Auftrag und kann daher nicht entfernt werden.");
   $errCode[106] = getLngt("Eine ID darf bei einer Neuanlage nicht existieren.");
   $errCode[107] = getLngt("Eine Neuanlage erfolgte nicht.");
   $errCode[108] = getLngt("Der Benutzername existiert schon. Eine Neuanlage fand nicht statt.");
   $errCode[109] = getLngt("Die Validierung des Passwortes schlug fehl. Eine Neuanlage fand nicht statt.");
   $errCode[110] = getLngt("Der Benutzername existiert schon bei einem anderen Benutzer");
   $errCode[111] = getLngt("Das Passwort genügt nicht den Sicherheitsanforderungen.");
   $errCode[112] = getLngt("Das Geburtsdatum ist nicht korrekt.");
   $errCode[113] = getLngt("Die Syntax der Email-Adresse ist nicht korrekt.");
   $errCode[114] = getLngt("Die Syntax der Rechnungs-Email-Adresse ist nicht korrekt.");
   $errCode[115] = getLngt("Die Adressdaten ist nicht vollständig.");
   $errCode[116] = getLngt("Die eindeutige Kundennummer (EID) ist bereits vergeben.");
   $errCode[117] = getLngt("Es wurde bei der Kostenstelle keine Operation übergeben.");
   $errCode[118] = getLngt("Zum Löschen einer Kostenstelle muss die ID übergeben werden.");
   $errCode[119] = getLngt("Die Hauptkostenstelle kann nicht gelöscht werden.");
   $errCode[120] = getLngt("Die Kostenstelle wird durch andere Kostenstellen referenziert (parent) und kann nicht entfernt werden.");
   $errCode[121] = getLngt("Beim Einfügen einer neuen Kostenstelle darf keine Kostenstellen-ID übergeben werden.");
   $errCode[122] = getLngt("Beim Einfügen einer neuen Kostenstelle darf die Kostenstellenbezeichnung nicht leer sein und sie darf nicht schon existieren.");
   $errCode[123] = getLngt("Eine Kostenstellenreferenz wurde übergeben, die jedoch nicht zu existieren scheint.");
   $errCode[124] = getLngt("Die Kostenstelle kann nicht gelöscht werden, weil mindestens ein Auftrag existiert.");
   $errCode[125] = getLngt("Zur Aktualisierung einer Kostenstelle muss die ID übergeben werden.");
   $errCode[126] = getLngt("Der Kostenstellenname existiert bei dem Kunden schon und kann nicht zur Aktualisierung herangezogen werden.");
   $errCode[127] = getLngt("Zur Änderung einer Kostenstellenadresse ist die beabsichtigte Operation anzugeben.");
   $errCode[128] = getLngt("Für alle Operationen auf Kostenstellenadressen ist die jeweilige Adresstypnummer anzugeben.");
   $errCode[129] = getLngt("Die Kostenstellenadresse kann nicht eingefügt werden, weil der Adresstyp schon existiert für die spezifizierte Kostenstelle.");
   $errCode[130] = getLngt("Eine Aktualisierung der Kostenstelle konnte nicht erfolgen, da ein Eintrag mit dem spezifizierten Adresstyp nicht existiert.");
   $errCode[131] = getLngt("Die Zuordnung zur übergeordneten Kostenstelle kann bei einer Aktualisierung einer Kostenstelle nicht geändert werden.");
   $errCode[132] = getLngt("Wird ein Auftraggeber neu angelegt (Operation INS), müssen alle Sub-Operationen ebenfalls INS sein.");
   $errCode[133] = getLngt("");
   $errCode[134] = getLngt("");
   $errCode[135] = getLngt("");
   $errCode[136] = getLngt("");
   $errCode[137] = getLngt("");
   $errCode[138] = getLngt("");
   $errCode[139] = getLngt("");
else :
   $errCode[100] = getLngt("The value does not match the requested type or is not valid.");
   $errCode[101] = getLngt("Authentication Data not correct.");
   $errCode[102] = getLngt("No customer defined for operation.");
   $errCode[103] = getLngt("Customer not found in database.");
   $errCode[104] = getLngt("Customer is meta customer of another customer. Delete operation not executed.");
   $errCode[105] = getLngt("At least one job does exist for customer. Delete operation not executed.");
   $errCode[106] = getLngt("Customer ID may not exist for insert operation.");
   $errCode[107] = getLngt("Insert operation failed.");
   $errCode[108] = getLngt("User account does exist. Insert operation not executed.");
   $errCode[109] = getLngt("Password validation failed. Insert operation not executed.");
   $errCode[110] = getLngt("The user account does exist for another user.");
   $errCode[111] = getLngt("Passwort is not strong enough.");
   $errCode[112] = getLngt("The birthdate is not valid.");
   $errCode[113] = getLngt("Syntax of the mail address is not correct.");
   $errCode[114] = getLngt("Syntax of the invoice mail address is not correct.");
   $errCode[115] = getLngt("The address is not complete.");
   $errCode[116] = getLngt("The unique customer ID (EID) does exist at another customer.");
   $errCode[117] = getLngt("The costcenter operation tag has to be set but does not exist.");
   $errCode[118] = getLngt("To delete a costcenter the id has to be set.");
   $errCode[119] = getLngt("The root costcenter cannont be deleted.");
   $errCode[120] = getLngt("The costcenter may not be deleted because there are children costcenters.");
   $errCode[121] = getLngt("The costcenter ID has to be empty because of requested insert operation a new one will be generated.");
   $errCode[122] = getLngt("The costcenter name may not be empty and may not exist for the current customer by insert operation.");
   $errCode[123] = getLngt("The requested reference of the parent costcenter ID does not exist regarding the customer.");
   $errCode[124] = getLngt("The costcenter may not be deleted because there is at least one job.");
   $errCode[125] = getLngt("To update a costcenter the id has to be set.");
   $errCode[126] = getLngt("No update of the costcenter possible because the costcenter name does exist for another costcenter for the current customer.");
   $errCode[127] = getLngt("The operation to modify the costcenter address is not correct.");
   $errCode[128] = getLngt("All operations on costcenter addresses require the addres type ID.");
   $errCode[129] = getLngt("The costcenteraddress cannot be inserted because an address with the specified address type does exist.");
   $errCode[130] = getLngt("The update of the specified costcenteraddress failed, because a costcenter address with the specified address type does not exist.");
   $errCode[131] = getLngt("The parent costcenter ID has to be empty for costcenter update operation.");
   $errCode[132] = getLngt("Customer insertion requires INS in all sub operations.");
   $errCode[133] = getLngt("");
   $errCode[134] = getLngt("");
   $errCode[135] = getLngt("");
   $errCode[136] = getLngt("");
   $errCode[137] = getLngt("");
   $errCode[138] = getLngt("");
   $errCode[139] = getLngt("");
endif;
$statusMessage = getLngt("");
// ---------------------------------------------------------------------------

// GLOBAL MODE OF USAGE
$globalParUseRelatedCustomer = getParameterValue("0", "GLOBAL_USE_RELATED_CUSTOMER", "0");

// *** Init ***
// $maxNumOfOrdersPerDay = 300;
// $maxNumOfRunningOrders = 1000;
$hqId = "";
$usr_id = "";
$txId = "4";
$txValue = getFieldValueFromId("tax","tx_id",$txId,"tx_value");
$txSign = getFieldValueFromId("tax","tx_id",$txId,"tx_sign");
if ($globalParUseRelatedCustomer == "1") :
   $txValue = $txId;
   $txSign = "";
endif;


// *** Parse request ***
$dataArray = xml2array($customerReq);


// *** Convert result array to usable parameters ***
// Authentication data
$sessionId      = convertSpecial($dataArray["xml"]["customer"]["auth"]["session_id"]);
$passPhrase     = convertSpecial($dataArray["xml"]["customer"]["auth"]["passphrase"]);

if (checkRequestAuthenticationData2($sessionId, $passPhrase)) :

   // **************************
   // **** Get request data ****
   // **************************

   $csArray = array();
   $eidPrefix = "AG";
   $debugOut[] = "Authentication okay!";

   $operationMode      = convertSpecial($dataArray["xml"]["customer"]["operation"]);
   if ($operationMode == "") : 
      $operationMode = "GET";
   else :
      $operationMode = strtoupper($operationMode);
   endif;

   $debugOn            = convertSpecial($dataArray["xml"]["customer"]["debug_on"]);
   if (strtoupper($debugOn) == "YES" || strtoupper($debugOn) == "ON") :
      $debug = true;
   endif;

   $csId               = convertSpecial($dataArray["xml"]["customer"]["cs_id"]);
   $csEid              = convertSpecial($dataArray["xml"]["customer"]["cs_eid"]);  // NOT for INSERT (!!!!)
   if ($csId != "" && $csEid == "") :
      $csEid = getFieldValueFromId("customer","cs_id",$csId,"cs_eid");
   elseif ($csEid != "" && $csId == "") :
      $csId = getFieldValueFromId("customer","cs_eid",$csEid,"cs_id");
   endif;
   $csArray["cs_eid"]              = $csEid;

   $csSid                          = convertSpecial($dataArray["xml"]["customer"]["cs_sid"]);
   $csArray["cs_sid"]              = $csSid;
   
   $csArray["hq_id"]               = convertSpecial($dataArray["xml"]["customer"]["hq_id"]);
   
   $csArray["cs_prov"]             = convertSpecial($dataArray["xml"]["customer"]["cs_prov"]);
   $csArray["cs_discount"]         = convertSpecial($dataArray["xml"]["customer"]["cs_discount"]);
   $csArray["cs_invmode"]          = convertSpecial($dataArray["xml"]["customer"]["cs_invmode"]);
   $csArray["cs_cr_fav_only"]      = convertSpecial($dataArray["xml"]["customer"]["cs_cr_fav_only"]);
                       
   $csArray["cs_jbstatusmail"]     = convertSpecial($dataArray["xml"]["customer"]["cs_jbstatusmail"]);
   $csArray["cs_jbstatusmail2"]    = convertSpecial($dataArray["xml"]["customer"]["cs_jbstatusmail2"]);
   $csArray["cs_jbstatusmail3"]    = convertSpecial($dataArray["xml"]["customer"]["cs_jbstatusmail3"]);
   $csArray["cs_jbstatusmail_pdf"] = convertSpecial($dataArray["xml"]["customer"]["cs_jbstatusmail_pdf"]);

   $csArray["cs_filter"]           = convertSpecial($dataArray["xml"]["customer"]["cs_filter"]);
   $csArray["cs_group"]            = convertSpecial($dataArray["xml"]["customer"]["cs_group"]);
   $csArray["cs_tracking"]         = convertSpecial($dataArray["xml"]["customer"]["cs_tracking"]);
   
   $csArray["cmp_type"]            = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_type"]);
   $csArray["cmp_comp"]            = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_comp"]);
   $csArray["cmp_comp2"]           = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_comp2"]);
   $csArray["cmp_comp3"]           = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_comp3"]);
   $csArray["cmp_comp4"]           = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_comp4"]);

   $csArray["ad_street"]           = convertSpecial($dataArray["xml"]["customer"]["company"]["ad_street"]);
   $csArray["cmp_hsno"]            = convertSpecial($dataArray["xml"]["customer"]["company"]["ad_hsno"]);
   $csArray["ad_zipcode"]          = convertSpecial($dataArray["xml"]["customer"]["company"]["ad_zipcode"]);
   $csArray["ad_city"]             = convertSpecial($dataArray["xml"]["customer"]["company"]["ad_city"]);
   $csArray["ad_country"]          = convertSpecial($dataArray["xml"]["customer"]["company"]["ad_country"]);

   $csArray["cmp_iln"]             = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_iln"]);
   $csArray["cmp_tax_idno"]        = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_tax_idno"]);
   $csArray["cmp_stax_idno"]       = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_stax_idno"]);

   $csArray["cmp_bank"]            = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_bank"]);
   $csArray["cmp_bankno"]          = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_bankno"]);
   $csArray["cmp_bankacc"]         = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_bankacc"]);
   $csArray["cmp_iban"]            = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_iban"]);
   $csArray["cmp_swift"]           = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_swift"]);
   
   $csArray["cmp_logo"]            = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_logo"]);
   $csArray["cmp_logo_width"]      = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_logo_width"]);
   $csArray["cmp_logo_height"]     = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_logo_height"]);

   $csArray["cmp_remark"]          = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_remark"]);
   $csArray["cmp_remark2"]         = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_remark2"]);
   $csArray["cmp_match"]           = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_match"]);
   $csArray["cmp_match2"]          = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_match2"]);

   $csArray["cmp_newsletter"]      = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_newsletter"]);
   $csArray["cmp_pda_usage"]       = convertSpecial($dataArray["xml"]["customer"]["company"]["cmp_pda_usage"]);
                                   
   $csArray["usr_name"]            = convertSpecial($dataArray["xml"]["customer"]["user"]["usr_name"]);
   $csArray["usr_firstname"]       = convertSpecial($dataArray["xml"]["customer"]["user"]["usr_firstname"]);
   $csArray["usr_birthdate"]       = convertSpecial($dataArray["xml"]["customer"]["user"]["usr_birthdate"]);
                                   
   $csArray["usr_email"]           = convertSpecial($dataArray["xml"]["customer"]["user"]["usr_email"]);
   $csArray["usr_inv_email"]       = convertSpecial($dataArray["xml"]["customer"]["user"]["usr_inv_email"]);
   $csArray["usr_phone"]           = convertSpecial($dataArray["xml"]["customer"]["user"]["usr_phone"]);
   $csArray["usr_phone2"]          = convertSpecial($dataArray["xml"]["customer"]["user"]["usr_phone2"]);
   $csArray["usr_fax"]             = convertSpecial($dataArray["xml"]["customer"]["user"]["usr_fax"]);
                                   
   $csArray["usr_account"]         = convertSpecial($dataArray["xml"]["customer"]["user"]["usr_account"]);
   $csArray["usr_password"]        = convertSpecial($dataArray["xml"]["customer"]["user"]["usr_password"]);

   $csArray["csc"] = array();

   $numOfCostcenters = 0;
   if ($dataArray["xml"]["customer"]["costcenters"]["costcenter"]["csc_operation"] != "" || $dataArray["xml"]["customer"]["costcenters"]["costcenter"]["csc_id"] != "") :
      $numOfCostcenters = 1;
   else :
      $numOfCostcenters = count($dataArray["xml"]["customer"]["costcenters"]["costcenter"]);
   endif;
   if ($debug) : echo "numOfCostcenters = " . $numOfCostcenters . "<br>\n"; endif;

   if ($numOfCostcenters > 0) :

      for ($i = 0; $i < $numOfCostcenters; $i++) :

          if ($numOfCostcenters == 1) : 
             $dataCscArr[$i] = $dataArray["xml"]["customer"]["costcenters"]["costcenter"];
          else :
             $dataCscArr[$i] = $dataArray["xml"]["customer"]["costcenters"]["costcenter"][$i];
          endif;

          $csArray["csc"][$i]["csc_operation"] = convertSpecial($dataCscArr[$i]["csc_operation"]);
            $csArray["csc"][$i]["csc_operation"] = strtoupper($csArray["csc"][$i]["csc_operation"]);
          $csArray["csc"][$i]["csc_id"]        = convertSpecial($dataCscArr[$i]["csc_id"]);
          $csArray["csc"][$i]["csc_name"]      = convertSpecial($dataCscArr[$i]["csc_name"]);
          $csArray["csc"][$i]["csc_pre_id"]    = convertSpecial($dataCscArr[$i]["csc_pre_id"]);

          $numOfCostcenterAddresses = 0;
          if ($dataCscArr[$i]["costcenteraddresses"]["costcenteraddress"]["cscad_operation"] != "" || $dataCscArr[$i]["costcenteraddresses"]["costcenteraddress"]["adt_id"] != "") :
             $numOfCostcenterAddresses = 1;
          else :
             $numOfCostcenterAddresses = count($dataCscArr[$i]["costcenteraddresses"]["costcenteraddress"]);
          endif;
          if ($debug) : echo "numOfCostcenterAddresses = " . $numOfCostcenterAddresses . "<br>\n"; endif;

          $csArray["csc"][$i]["cscad"] = array();

          if ($numOfCostcenterAddresses > 0) :

              for ($j = 0; $j < $numOfCostcenterAddresses; $j++) :

                  if ($numOfCostcenterAddresses == 1) : 
                     $dataCscArr[$i][$j] = $dataCscArr[$i]["costcenteraddresses"]["costcenteraddress"];
                  else :
                     $dataCscArr[$i][$j] = $dataCscArr[$i]["costcenteraddresses"]["costcenteraddress"][$j];
                  endif;

                  $csArray["csc"][$i]["cscad"][$j]["cscad_operation"] = convertSpecial($dataCscArr[$i][$j]["cscad_operation"]);
                    $csArray["csc"][$i]["cscad"][$j]["cscad_operation"] = strtoupper($csArray["csc"][$i]["cscad"][$j]["cscad_operation"]);
                  $csArray["csc"][$i]["cscad"][$j]["adt_id"]          = convertSpecial($dataCscArr[$i][$j]["adt_id"]);

                  $csArray["csc"][$i]["cscad"][$j]["cscad_comp"]      = convertSpecial($dataCscArr[$i][$j]["cscad_comp"]);
                  $csArray["csc"][$i]["cscad"][$j]["cscad_comp2"]     = convertSpecial($dataCscArr[$i][$j]["cscad_comp2"]);
                  $csArray["csc"][$i]["cscad"][$j]["cscad_comp3"]     = convertSpecial($dataCscArr[$i][$j]["cscad_comp3"]);
                  $csArray["csc"][$i]["cscad"][$j]["cscad_comp4"]     = convertSpecial($dataCscArr[$i][$j]["cscad_comp4"]);

                  $csArray["csc"][$i]["cscad"][$j]["ad_street"]       = convertSpecial($dataCscArr[$i][$j]["ad_street"]);
                  $csArray["csc"][$i]["cscad"][$j]["ad_hsno"]         = convertSpecial($dataCscArr[$i][$j]["ad_hsno"]);
                  $csArray["csc"][$i]["cscad"][$j]["ad_floor"]        = convertSpecial($dataCscArr[$i][$j]["ad_floor"]);
                  $csArray["csc"][$i]["cscad"][$j]["ad_zipcode"]      = convertSpecial($dataCscArr[$i][$j]["ad_zipcode"]);
                  $csArray["csc"][$i]["cscad"][$j]["ad_city"]         = convertSpecial($dataCscArr[$i][$j]["ad_city"]);
                  $csArray["csc"][$i]["cscad"][$j]["ad_country"]      = convertSpecial($dataCscArr[$i][$j]["ad_country"]);

                  $csArray["csc"][$i]["cscad"][$j]["cscad_person"]    = convertSpecial($dataCscArr[$i][$j]["cscad_person"]);
                  $csArray["csc"][$i]["cscad"][$j]["cscad_phone"]     = convertSpecial($dataCscArr[$i][$j]["cscad_phone"]);
                  $csArray["csc"][$i]["cscad"][$j]["cscad_email"]     = convertSpecial($dataCscArr[$i][$j]["cscad_email"]);
                  $csArray["csc"][$i]["cscad"][$j]["cscad_remark"]    = convertSpecial($dataCscArr[$i][$j]["cscad_remark"]);
              endfor;
          endif;
      endfor;
   endif;
   
   if ($debug) :       
      echo "operationMode = " . $operationMode . "<br>\n";
      echo "csId = " . $csId . "<br>\n";
      print_r($csArray); echo "<br><br><br>";
      print_r($dataArray); echo "<br><br><br>";
   endif;   

   // *************
   // **** GET ****
   // *************

   if ($operationMode == "GET") :

      // Check existence of the customer
      if ($csId != "" && is_numeric($csId)) :

         $csId = getFieldValueFromId("customer","cs_id",$csId,"cs_id");
         if ($csId != "") :

            $customerArray = array();
            $cmpId = getFieldValueFromId("customer","cs_id",$csId,"cmp_id");
/*
            $dbData = array();
            getDBData("customer", $csId);
            getDBData("company", $cmpId);
            $tmpCscIds = getColVectorFromDB2ArrayByClause("costcenter", "csc_id", "cs_id = '" . $csId . "'", "", "", "");
            $tmpCscIdsLen = count($tmpCscIds);
            if ($tmpCscIdsLen > 0) :
               for ($c = 0; $c < $tmpCscIdsLen; $c++) :
                   getDBData("costcenter", $tmpCscIds[$c]);
                   getDBData("costcenteraddress", $tmpCscIds[$c]);
               endfor;
            endif;
            $customerArray = $dbData;
*/

            $hq_id = getFieldValueFromId("customer","cs_id",$csId,"hq_id");
            $f_hq_id = array();
            $emp_id = "";
            $customerArray["customer"] = getCustomer($cmpId, "2");
            $customerArray["customer"]["company"]["cmp_id"] = $cmpId;  // Add company ID

            $tmpCscIds = getColVectorFromDB2ArrayByClause("costcenter", "csc_id", "cs_id = '" . $csId . "'", "", "", "");
            $tmpCscIdsLen = count($tmpCscIds);
            if ($tmpCscIdsLen > 0) :
               $customerArray["customer"]["costcenters"]["costcenter"] = array();
               for ($c = 0; $c < $tmpCscIdsLen; $c++) :

                   getDBData("costcenter", $tmpCscIds[$c]);
                   $customerArray["customer"]["costcenters"]["costcenter"][$c] = $dbData["costcenter"];

                   getDBData("costcenteraddress", $tmpCscIds[$c]);
                   $customerArray["customer"]["costcenters"]["costcenter"][$c]["costcenteraddresses"]["costcenteraddress"] = $dbData["costcenteraddress"];
               endfor;
            endif;

            $customerXML = mcArray2Xml($customerArray, "", $lineFeed);
         else :
            // ERR: "Customer not found in database."
            $err[] = array("103", $errCode[103]);
         endif;
      else :
         // ERR: "No customer defined for operation."
         $err[] = array("102", $errCode[102]);
      endif;
   endif;


   // ****************
   // **** DELETE ****
   // ****************

   if ($operationMode == "DELETE" || $operationMode == "DEL") :

      // Check existence of the customer
      if ($csId != "" && is_numeric($csId)) :

         $csId = getFieldValueFromId("customer","cs_id",$csId,"cs_id");
         if ($csId != "") :

            // Check for being meta customer (parent for another customer)
            if (!existsEntry("customer",array("cs_id_parent",$csId))) :

               // Check at least one job
               $jbId = getLastJob($csId, "cs");
               if ($jbId == "") :

                  TA("B");

                  $hq_id = getFieldValueFromId("customer","cs_id",$csId,"hq_id");
                  $tmpCmpId = getFieldValueFromId("customer","cs_id",$csId,"cmp_id");

                  $tmpCsAdmin = getFieldValueFromId("customer","cs_id",$csId,"cs_admin");  // Equals "emp_id"
                  if ($tmpCsAdmin != "") :
                      $tmpUsrId = getFieldValueFromId("employee","emp_id",$tmpCsAdmin,"usr_id");
                      if ($tmpUsrId != "") :
                         deleteStmt("user", "usr_id = '" . $tmpUsrId . "'");
                      endif;
                      deleteStmt("employee", "emp_id = '" . $tmpCsAdmin . "'");
                  endif;

                  $tmpCscIds = getColVectorFromDB2ArrayByClause("costcenter", "csc_id", "cs_id = '" . $csId . "'", "", "", "");
                  $tmpCscIdsLen = count($tmpCscIds);
                  if ($tmpCscIdsLen > 0) :
                     deleteStmt("costcenteraddress", "csc_id IN (" . implode(",", $tmpCscIds) . ")");
                     deleteStmt("costcenter", "cs_id = '" . $csId . "'");
                  endif;

                  if ($tmpCmpId != "") :
                     deleteStmt("company", "cmp_id = '" . $tmpCmpId . "'");
                  endif;

                  deleteStmt("customer", "cs_id = '" . $csId . "'");

                  // Write logdata into log database
                  writeToLogDB("42",$hq_id,"","0","","",$csId,"STATUS_DELETED");

                  TA("C");
                  TA("E");
               else :
                  // ERR: "At least one job does exist for customer. Delete operation not executed."
                  $err[] = array("105", $errCode[105]);
               endif;
            else :
               // ERR: "Customer is meta customer of another customer. Delete operation not executed."
               $err[] = array("104", $errCode[104]);
            endif;
         else :
            // ERR: "Customer not found in database."
            $err[] = array("103", $errCode[103]);
         endif;
      else :
         // ERR: "No customer defined for operation."
         $err[] = array("102", $errCode[102]);
      endif;
   endif;


   // ****************
   // **** INSERT ****
   // ****************

   if ($operationMode == "INS" || $operationMode == "INSERT") :

      if ($csId == "") :

         $csEid = $eidPrefix . getDateTime(6);  // "YmdHis"
         $csArray["cs_eid"] = $csEid;
         $doInsert = true;

         // Check user
         $defaultFieldArray = array();
         $sqlPhraseArr = array();
         $checkFieldArray = getFieldsAndTypes("user");
         $errKey = checkTypesForDbImportFieldValues($csArray, $defaultFieldArray, $checkFieldArray, $sqlPhraseArr);
         if ($errKey != "") :
            $doInsert = false;
            $err[] = array("100", $errCode[100] . " [" . $errKey . "]");
         endif;

         // Check company
         if ($doInsert) :
            $defaultFieldArray = array();
            $sqlPhraseArr = array();
            $checkFieldArray = getFieldsAndTypes("company");
            $errKey = checkTypesForDbImportFieldValues($csArray, $defaultFieldArray, $checkFieldArray, $sqlPhraseArr);
            if ($errKey != "") :
               $doInsert = false;
               $err[] = array("100", $errCode[100] . " [" . $errKey . "]");
            endif;
         endif;

         // Check customer
         if ($doInsert) :
            $defaultFieldArray = array();
            $sqlPhraseArr = array();
            $checkFieldArray = getFieldsAndTypes("customer");
            $errKey = checkTypesForDbImportFieldValues($csArray, $defaultFieldArray, $checkFieldArray, $sqlPhraseArr);
            if ($errKey != "") :
               $doInsert = false;
               $err[] = array("100", $errCode[100] . " [" . $errKey . "]");
            endif;
         endif;

         // Presently disabled because costcenters an their costcenter addresses will be inserted automatically. They can be modified by updating the customer only
         /*
         // Check costcenters and costcenter addresses
         if ($doInsert) :
            $numOfCostcenters = count($csArray["csc"]);           
            if ($numOfCostcenters > 0) :
               for ($i = 0; $i < $numOfCostcenters; $i++) :
                   $cscOperation = $csArray["csc"][$i]["csc_operation"];
                   $cscId = $csArray["csc"][$i]["csc_id"];
                   $cscPreId = $csArray["csc"][$i]["csc_pre_id"];
                   if ($cscOperation == "INS") :

                      // Check for costcenter addresses
                      $numOfCostcenterAddresses = count($csArray["csc"][$i]["cscad"]);
                      if ($numOfCostcenterAddresses > 0) :

                         for ($j = 0; $j < $numOfCostcenterAddresses; $j++) :
                             $cscadOperation = $csArray["csc"][$i]["cscad"][$j]["cscad_operation"];
                             if ($cscadOperation == "INS") :

                                $defaultCscadFieldArray = array("csc_id", $cscId, "adt_id", $cscadAdt);
                                $sqlPhraseArr = array();
                                $checkFieldArray = getFieldsAndTypes("costcenteraddress");
                                $errKey = checkTypesForDbImportFieldValues($csArray["csc"][$i]["cscad"][$j], $defaultCscadFieldArray, $checkFieldArray, $sqlPhraseArr);
                                if ($errKey != "") :
                                   $doCsUpdate = false;
                                   $err[] = array("100", $errCode[100] . " [" . $errKey . "]");
                                endif;

                             else :  
                                $doInsert = false;
                                $err[] = array("132", $errCode[132]);
                             endif;
                         endfor;
                      endif;
                   else :
                      $doInsert = false;
                      $err[] = array("132", $errCode[132]);
                   endif;
               endfor;
            endif;
         endif;
         */

         if ($doInsert) :
            // Check existence of usr_account
            if ($csArray["usr_account"] != ""):
               $doInsert = false;
               if (!existsEntry("user",array("usr_account",$csArray["usr_account"]))) :
            
                  if ($csArray["usr_password"] != "" && checkPasswordValidation($csArray["usr_password"],$csArray["usr_password"])) :
                     $doInsert = true;
                  else:
                     // ERR: "Password validation failed. Insert operation not executed."
                    $err[] = array("109", $errCode[109]);
                  endif;
               else :
                  // ERR: "User account does exist. Insert operation not executed."
                  $err[] = array("108", $errCode[108]);
               endif;
            else :
               $csArray["usr_password"] = "";  // Remove password if "usr_account" is empty
            endif;

            if ($doInsert) :
               $retArr = insertCustomer($csArray, "1");
               if (is_array($retArr) && $retArr[0] != "") :
                  $retDbIds = getDbIdTree("cs", $retArr[0], "1", "db_id_struct", "\n");
               else :
                  // ERR: "Insert operation failed."
                  $err[] = array("107", $errCode[107]);
               endif;
            endif;
         endif;
      else :
         // ERR: "Customer ID may not exist for insert operation."
         $err[] = array("106", $errCode[106]);
      endif;
   endif;


   // ****************
   // **** UPDATE ****
   // ****************
 
   if ($operationMode == "UPD" || $operationMode == "UPDATE") :

      // Check existence of the customer
      if ($csId != "" && is_numeric($csId)) :

         $csId = getFieldValueFromId("customer","cs_id",$csId,"cs_id");
         if ($csId != "") :

            TA("B");

            // Get current primary IDs
            $csCmpId = getFieldValueFromId("customer","cs_id",$csId,"cmp_id");
            $csCscRootId = getFieldValueFromId("customer","cs_id",$csId,"csc_id");
            $csEmpId = getFieldValueFromId("customer","cs_id",$csId,"cs_admin");
            $csUsrId = getFieldValueFromId("employee","emp_id",$csEmpId,"usr_id");

            $doCsUpdate = true;

            // **** User data ****
            if ($doCsUpdate):
               $defaultFieldArray = array();
               $sqlPhraseArr = array("db.account.1" => $csUsrId);
               $checkFieldArray = getFieldsAndTypes("user");
               $errKey = checkTypesForDbImportFieldValues($csArray, $defaultFieldArray, $checkFieldArray, $sqlPhraseArr);
               if ($errKey == "") :
                  if (count($defaultFieldArray) > 0) :
                     updateStmt("user","usr_id",$csUsrId,$defaultFieldArray);
                  endif;
               else :
                  $doCsUpdate = false;
                  $err[] = array("100", $errCode[100] . " [" . $errKey . "]");
               endif;
            endif;

            // **** Company data ****
            if ($doCsUpdate):
               // Check address data being not empty
               if ($csArray["ad_street"] == "" || $csArray["ad_zipcode"] == "" || $csArray["ad_city"] == "" || $csArray["cmp_hsno"] == "") :
                  if ($csArray["ad_street"] . $csArray["ad_zipcode"] . $csArray["ad_city"] . $csArray["cmp_hsno"] != "") :
                     $err[] = array("115", $errCode[115]);
                     $doCsUpdate = false;
                     $csArray["ad_street"] = "";
                     $csArray["ad_zipcode"] = "";
                     $csArray["ad_city"] = "";
                     $csArray["cmp_hsno"] = "";
                  endif;
               endif;
            endif;

            // Update company data
            if ($doCsUpdate):
               // Take current data to log for history
               // .............. !!!! ..............

               $defaultFieldArray = array();
               $sqlPhraseArr = array();
               $checkFieldArray = getFieldsAndTypes("company");
               $errKey = checkTypesForDbImportFieldValues($csArray, $defaultFieldArray, $checkFieldArray, $sqlPhraseArr);
               if ($errKey != "") :
                  $doCsUpdate = false;
                  $err[] = array("100", $errCode[100] . " [" . $errKey . "]");
               endif;

               if ($csArray["ad_street"] != "" && $csArray["ad_zipcode"] != "" && $csArray["ad_city"] != "") :

                  if ($csArray["ad_country"] == "") : $csArray["ad_country"] = "DE"; endif;
                  $sqlStmt = "SELECT ad_id FROM address WHERE ad_street = '" . $csArray["ad_street"] . "' AND ad_zipcode = '" . $csArray["ad_zipcode"] . "' AND ad_city = '" . $csArray["ad_city"] . "' AND ad_country = '" . $csArray["ad_country"] . "'";
                  $csCmpAdId = $db->getOne($sqlStmt);
                  if (DB::isError($csCmpAdId)) die ("$PHP_SELF: <br>$sqlStmt<br>" . $csCmpAdId->getMessage());
                  if ($csCmpAdId == ""):
                     insertStmt("address", array("ad_street", $csArray["ad_street"], "ad_zipcode", $csArray["ad_zipcode"], "ad_city", $csArray["ad_city"], "ad_country", $csArray["ad_country"]));
                     $csCmpAdId = getLastInsertID();
                  endif;
                  array_push($defaultFieldArray, "ad_id", $csCmpAdId);
               endif;

               if (count($defaultFieldArray) > 0) :
                  // Get current state in cmp_modify_status because it is equal to "1" then do NOT change                        
                  $modifyStatus = getFieldValueFromId("company", "cmp_id", $csCmpId, "cmp_modify_status");
                  if ($modifyStatus != "1") : $modifyStatus = "2"; endif;
                  array_push($defaultFieldArray, "cmp_modify_status", $modifyStatus);

                  updateStmt("company","cmp_id",$csCmpId,$defaultFieldArray);
               endif;
            endif;


            // **** Customer data ****

            // Check unique customer ID
            if ($csArray["cs_eid"] != "" && $db->getOne("SELECT cs_eid FROM customer WHERE cs_eid = '" . $csArray["cs_eid"] . "' AND NOT (cs_id = '" . $csId . "')")) :
               $err[] = array("116", $errCode[116]);
               $doCsUpdate = false;
               $csArray["cs_eid"] = "";
            endif;

            // Update customer data
            if ($doCsUpdate):
               // Take current data to log for history
               // .............. !!!! ..............

               $defaultFieldArray = array();
               $sqlPhraseArr = array();
               $checkFieldArray = getFieldsAndTypes("customer");
               $errKey = checkTypesForDbImportFieldValues($csArray, $defaultFieldArray, $checkFieldArray, $sqlPhraseArr);
               if ($errKey != "") :
                  $doCsUpdate = false;
                  $err[] = array("100", $errCode[100] . " [" . $errKey . "]");
               endif;

               if ($doCsUpdate):
                  if ($csArray["cs_prov"] != "") :
                     $csArray["cs_prov"] = str_replace (",", ".", $csArray["cs_prov"]);
                     array_push($defaultFieldArray, "cs_prov", $csArray["cs_prov"]);
                  endif;
                  if ($csArray["cs_discount"] != "") :
                     $csArray["cs_discount"] = str_replace (",", ".", $csArray["cs_discount"]);
                     array_push($defaultFieldArray, "cs_discount", $csArray["cs_discount"]);
                  endif;

                  if (count($defaultFieldArray) > 0) :
                     updateStmt("customer","cs_id",$csId,$defaultFieldArray);
                  endif;
               endif;
            endif;


            // **** Costcenter data ****

            // Update customer data
            if ($doCsUpdate):
               // Take current data to log for history
               // .............. !!!! ..............

               $numOfCostcenters = count($csArray["csc"]);
               if ($debug) : echo "numOfCostcenters = " . $numOfCostcenters . "<br>\n"; endif;
            
               if ($numOfCostcenters > 0) :
            
                  for ($i = 0; $i < $numOfCostcenters; $i++) :

                      $cscOperation = $csArray["csc"][$i]["csc_operation"];
                      $cscId = $csArray["csc"][$i]["csc_id"];
                      $cscPreId = $csArray["csc"][$i]["csc_pre_id"];

                      if ($cscOperation == "INS" || $cscOperation == "UPD" || $cscOperation == "DEL") :
                         
                         if ($cscOperation == "DEL") :

                            if ($cscId != "" && is_numeric($cscId)) :

                               // Check costcenter not to be root costcenter
                               $csCscIdRoot = getFieldValueFromId("customer", "cs_id", $csId, "csc_id");
                               if ($csCscIdRoot != $cscId) :

                                  // Check costcenter to be deleted is not a parent costcenter for another costcenter
                                 if (!existsEntry("costcenter", array("cs_id",$csId,"csc_pre_id",$cscId))) :

                                    // Check costcenter to be deleted does not have any job
                                    if (!existsEntry("job", array("csc_id",$cscId)) && !existsEntry("job", array("csc_id_payer",$cscId)) && !existsEntry("job", array("csc_id_payer_cash",$cscId))) :

                                       deleteStmt("costcenteraddress", "csc_id = '" . $cscId . "'");
                                       deleteStmt("costcenter", "csc_id = '" . $cscId . "'");
                                    else :
                                       $err[] = array("124", $errCode[124] . " [csc:" . $i . "]");
                                       $doCsUpdate = false;
                                    endif;
                                 else :
                                    $err[] = array("120", $errCode[120] . " [csc:" . $i . "]");
                                    $doCsUpdate = false;
                                 endif;
                               else :
                                  $err[] = array("119", $errCode[119] . " [csc:" . $i . "]");
                                  $doCsUpdate = false;
                               endif;
                            else :
                               $err[] = array("118", $errCode[118] . " [csc:" . $i . "]");
                               $doCsUpdate = false;
                            endif;

                         elseif ($cscOperation == "INS") :

                            if ($cscId == "") :

                               $doInsert = false;
                               // Check existence of csc_name for the current customer
                               if ($csArray["csc"][$i]["csc_name"] != "" && !existsEntry("costcenter", array("cs_id",$csId,"csc_name",$csArray["csc"][$i]["csc_name"]))):

                                  // If parent ID is set for this (new) costcenter to be inserted then get current path of the future parent costcenter
                                  $cscNameParent = "";
                                  $cscPathParent = "";
                                  if ($cscPreId != "" && is_numeric($cscPreId) && $cscPreId > 0 && existsEntry("costcenter",array("cs_id",$csId,"csc_id",$cscPreId))) :
                                     $cscNameParent = getFieldValueFromId("costcenter", "csc_id", $cscPreId, "csc_name");
                                     $cscPathParent = getFieldValueFromId("costcenter", "csc_id", $cscPreId, "csc_path");
                                     if ($cscPathParent == ""): $cscPathParent = "//"; endif;
                                  endif;

                                  // The new path is the concatenation of the path of the current costcenter and id of the current costcenter
                                  if ($cscNameParent != "") :
                                     $defaultFields = array("cs_id",$csId,"csc_pre_id",$cscPreId,"csc_name",$csArray["csc"][$i]["csc_name"],"csc_path",$cscPathParent . $cscNameParent . "//","csc_visible","1");
                                     insertStmt("costcenter",$defaultFields);

                                     // Per default costcenteraddresses (one of each address type) of the root costcenter will be inserted
                                     $csCscIdRoot = getFieldValueFromId("customer", "cs_id", $csId, "csc_id");
                                     if ($csCscIdRoot != "" && is_numeric($csCscIdRoot) && $csCscIdRoot > 0) :
                                        for ($c = 1; $c <= 4; $c++) :
                                            getDbFieldValues("costcenteraddress",array("ad_id","cscad_hsno","cscad_comp","cscad_comp2","cscad_comp3","cscad_comp4"),array("csc_id",$csCscIdRoot,"adt_id",$c));
                                            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", $c, "cscad_hsno", $cscad_hsno));
                                        endfor;
                                     endif;
                                  else :
                                     $err[] = array("123", $errCode[123] . " [csc:" . $i . "]");
                                     $doCsUpdate = false;
                                  endif;
                               else :
                                  $err[] = array("122", $errCode[122] . " [csc:" . $i . "]");
                                  $doCsUpdate = false;
                               endif;
                            else :
                               $err[] = array("121", $errCode[121] . " [csc:" . $i . "]");
                               $doCsUpdate = false;
                            endif;

                         elseif ($cscOperation == "UPD") :

                            if ($cscId != "") :
                              
                               $defaultCscFieldArray = array();

                               // Update costcenter data because costcenter name is set and should rename the current one
                               if ($csArray["csc"][$i]["csc_name"] != ""):
                                                              
                                  if (!$db->getOne("SELECT csc.csc_id FROM costcenter AS csc WHERE csc.csc_name = '" . $csArray["csc"][$i]["csc_name"] . "' AND csc.csc_id != '" . $cscId . "' AND csc.cs_id = '" . $csId . "'")):
   
                                     $defaultCscFieldArray = array("csc_name", $csArray["csc"][$i]["csc_name"]);

                                     // All path field values of potential sub-costcenters have to be updated
                                     $cscNameCurrent = getFieldValueFromId("costcenter","csc_id",$cscId,"csc_name");
                                     $sqlStmt = "SELECT csc_id,csc_path FROM costcenter WHERE csc_path LIKE '%//" . $cscNameCurrent . "//%' AND cs_id = '" . $csId . "'";
                                     $result = $db->query($sqlStmt);     
                                     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
                                     
                                     while ($row = $result->fetch_assoc()):
                                       $tmpCscId = $row["csc_id"];
                                       $tmpCscPath = str_replace("//" . $cscNameCurrent . "//","//" . $csArray["csc"][$i]["csc_name"] . "//",strWrapJs($row["csc_path"]));
                                       updateStmt("costcenter","csc_id",$tmpCscId,array("csc_path",$tmpCscPath));
                                     endwhile;
                                     $result->free();
                                  else :
                                     $err[] = array("126", $errCode[126] . " [csc:" . $i . "]");
                                     $doCsUpdate = false;
                                  endif;
                               endif;

                               // Check parent costcenter ID to reassign sub-tree to another costcenter.
                               // Currently the tag <csc_pre_id> is of type "doop" and is used by INS only
                               if ($cscPreId != "") : 
                                   $err[] = array("131", $errCode[131] . " [csc:" . $i . "]");
                                   $doCsUpdate = false;
                                   // array_push($defaultCscFieldArray, "csc_pre_id", $cscPreId);
                               endif;

                               if ($doCsUpdate) :

                                  // Update requested costcenter item
                                  if (count($defaultCscFieldArray) > 0) :
                                     updateStmt("costcenter","csc_id",$cscId, $defaultCscFieldArray);
                                  endif;

                                  // Check for costcenter addresses
                                  $numOfCostcenterAddresses = count($csArray["csc"][$i]["cscad"]);   
                                  if ($debug) : echo "numOfCostcenterAddresses = " . $numOfCostcenterAddresses . " [csc:" . $i . "]" . "<br>\n"; endif;

                                  if ($numOfCostcenterAddresses > 0) :

                                     for ($j = 0; $j < $numOfCostcenterAddresses; $j++) :

                                         $cscadOperation = $csArray["csc"][$i]["cscad"][$j]["cscad_operation"];

                                         if ($cscadOperation == "INS" || $cscadOperation == "UPD" || $cscadOperation == "DEL") :

                                            // For all operations the address type is required
                                            $cscadAdt = $csArray["csc"][$i]["cscad"][$j]["adt_id"];

                                            if ($cscadAdt != "" && is_numeric($cscadAdt) && $cscadAdt >= 0 && $cscadAdt <= 4) :

                                               if ($cscadOperation == "DEL") :

                                                  deleteStmt("costcenteraddress", "csc_id = '" . $cscId . "' AND adt_id = '" . $cscadAdt . "'");

                                               elseif ($cscadOperation == "INS") :

                                                  // Check existence of an address with the specified address type. It does NOT have to exist!
                                                  if (!existsEntry("costcenteraddress",array("csc_id",$cscId,"adt_id",$cscadAdt))) :

                                                     $defaultCscadFieldArray = array("csc_id", $cscId, "adt_id", $cscadAdt);
                                                     $sqlPhraseArr = array();
                                                     $checkFieldArray = getFieldsAndTypes("costcenteraddress");
                                                     $errKey = checkTypesForDbImportFieldValues($csArray["csc"][$i]["cscad"][$j], $defaultCscadFieldArray, $checkFieldArray, $sqlPhraseArr);
                                                     if ($errKey != "") :
                                                        $doCsUpdate = false;
                                                        $err[] = array("100", $errCode[100] . " [" . $errKey . "]");
                                                     endif;

                                                     if ($doCsUpdate) :
                                                        // Check address to be complete
                                                        $cscadAdId = "0";
                                                        if ($csArray["csc"][$i]["cscad"][$j]["ad_street"] != "" && $csArray["csc"][$i]["cscad"][$j]["ad_zipcode"] != "" && $csArray["csc"][$i]["cscad"][$j]["ad_city"] != "") :
                                                           if ($csArray["csc"][$i]["cscad"][$j]["ad_country"] == "") : $csArray["csc"][$i]["cscad"][$j]["ad_country"] = "DE"; endif;
                                                           $sqlStmt = "SELECT ad_id FROM address WHERE ad_street = '" . $csArray["csc"][$i]["cscad"][$j]["ad_street"] . "' AND ad_zipcode = '" . $csArray["csc"][$i]["cscad"][$j]["ad_zipcode"] . "' AND ad_city = '" . $csArray["csc"][$i]["cscad"][$j]["ad_city"] . "' AND ad_country = '" . $csArray["csc"][$i]["cscad"][$j]["ad_country"] . "'";
                                                           $cscadAdId = $db->getOne($sqlStmt);
                                                           if (DB::isError($cscadAdId)) die ("$PHP_SELF: <br>$sqlStmt<br>" . $cscadAdId->getMessage());
                                                           if ($cscadAdId == ""):
                                                              insertStmt("address", array("ad_street", $csArray["csc"][$i]["cscad"][$j]["ad_street"], "ad_zipcode", $csArray["csc"][$i]["cscad"][$j]["ad_zipcode"], "ad_city", $csArray["csc"][$i]["cscad"][$j]["ad_city"], "ad_country", $csArray["csc"][$i]["cscad"][$j]["ad_country"]));
                                                              $cscadAdId = getLastInsertID();
                                                           endif;
                                                           array_push($defaultCscadFieldArray, "ad_id", $cscadAdId);
                                                        endif;

                                                        if (count($defaultCscadFieldArray) > 0 && $cscadAdId > 0) :
                                                           insertStmt("costcenteraddress", $defaultCscadFieldArray);
                                                        endif;
                                                     endif;
                                                  else :
                                                     $err[] = array("129", $errCode[129] . " [csc:" . $i . "][cscad:" . $j . "]");
                                                     $doCsUpdate = false;
                                                  endif;

                                               elseif ($cscadOperation == "UPD") :

                                                  // Check existence of an address with the specified address type. It has to exist!
                                                  if (existsEntry("costcenteraddress",array("csc_id",$cscId,"adt_id",$cscadAdt))) :

                                                     $defaultCscadFieldArray = array("csc_id", $cscId, "adt_id", $cscadAdt);
                                                     $sqlPhraseArr = array();
                                                     $checkFieldArray = getFieldsAndTypes("costcenteraddress");
                                                     $errKey = checkTypesForDbImportFieldValues($csArray["csc"][$i]["cscad"][$j], $defaultCscadFieldArray, $checkFieldArray, $sqlPhraseArr);
                                                     if ($errKey != "") :
                                                        $doCsUpdate = false;
                                                        $err[] = array("100", $errCode[100] . " [" . $errKey . "]");
                                                     endif;

                                                     if ($csArray["csc"][$i]["cscad"][$j]["ad_hsno"] != "") : array_push($defaultCscadFieldArray, "cscad_hsno", $csArray["csc"][$i]["cscad"][$j]["ad_hsno"]); endif;
                                                     if ($csArray["csc"][$i]["cscad"][$j]["ad_floor"] != "" && checkValueByType($csArray["csc"][$i]["cscad"][$j]["ad_floor"], "integer")) : 
                                                        array_push($defaultCscadFieldArray, "cscad_floor", $csArray["csc"][$i]["cscad"][$j]["ad_floor"]);
                                                     else :
                                                        $doCsUpdate = false;
                                                        $err[] = array("100", $errCode[100] . " [" . "ad_floor" . "]");
                                                     endif;

                                                     if ($doCsUpdate) :
                                                        // Check address to be complete
                                                        $cscadAdId = "0";
                                                        if ($csArray["csc"][$i]["cscad"][$j]["ad_street"] != "" && $csArray["csc"][$i]["cscad"][$j]["ad_zipcode"] != "" && $csArray["csc"][$i]["cscad"][$j]["ad_city"] != "") :
                                                           if ($csArray["csc"][$i]["cscad"][$j]["ad_country"] == "") : $csArray["csc"][$i]["cscad"][$j]["ad_country"] = "DE"; endif;
                                                           $sqlStmt = "SELECT ad_id FROM address WHERE ad_street = '" . $csArray["csc"][$i]["cscad"][$j]["ad_street"] . "' AND ad_zipcode = '" . $csArray["csc"][$i]["cscad"][$j]["ad_zipcode"] . "' AND ad_city = '" . $csArray["csc"][$i]["cscad"][$j]["ad_city"] . "' AND ad_country = '" . $csArray["csc"][$i]["cscad"][$j]["ad_country"] . "'";
                                                           $cscadAdId = $db->getOne($sqlStmt);
                                                           if (DB::isError($cscadAdId)) die ("$PHP_SELF: <br>$sqlStmt<br>" . $cscadAdId->getMessage());
                                                           if ($cscadAdId == ""):
                                                              insertStmt("address", array("ad_street", $csArray["csc"][$i]["cscad"][$j]["ad_street"], "ad_zipcode", $csArray["csc"][$i]["cscad"][$j]["ad_zipcode"], "ad_city", $csArray["csc"][$i]["cscad"][$j]["ad_city"], "ad_country", $csArray["csc"][$i]["cscad"][$j]["ad_country"]));
                                                              $cscadAdId = getLastInsertID();
                                                           endif;
                                                           array_push($defaultCscadFieldArray, "ad_id", $cscadAdId);
                                                        endif;
                                                        
                                                        if ($doCsUpdate) :
                                                           if (count($defaultCscadFieldArray) > 0 && $cscadAdId > 0) :
                                                              updateStmt("costcenteraddress","csc_id",$cscId, $defaultCscadFieldArray, "adt_id = '" . $cscadAdt . "'");
                                                           endif;
                                                        endif;
                                                     endif;
                                                  else :
                                                     $err[] = array("130", $errCode[130] . " [csc:" . $i . "][cscad:" . $j . "]");
                                                     $doCsUpdate = false;
                                                  endif;
                                               endif;
                                            else :
                                               $err[] = array("128", $errCode[128] . " [csc:" . $i . "][cscad:" . $j . "]");
                                               $doCsUpdate = false;
                                            endif;
                                         else :
                                            $err[] = array("127", $errCode[127] . " [csc:" . $i . "][cscad:" . $j . "]");
                                            $doCsUpdate = false;
                                         endif;
                                     endfor;
                                  endif;
                               endif;  // $doCsUpdate
                            else :
                               $err[] = array("125", $errCode[125] . " [csc:" . $i . "]");
                               $doCsUpdate = false;
                            endif;
                         endif;
                      else :
                         $err[] = array("117", $errCode[117] . " [csc:" . $i . "]");
                         $doCsUpdate = false;
                      endif;
                  endfor;
               endif;
            endif;

            // Commit or rollback of all transactions on "costcenter" and "costcenteraddress".
            // "customer", "company", "user", etc. are executed and made persistent if operations are ok. (!!!!)
            if ($doCsUpdate) :
               $retDbIds = getDbIdTree("cs", $csId, "1", "db_id_struct", "\n");
               TA("C");
            else :
               TA("R");
            endif;
            TA("E");
         else :
            // ERR: "Customer not found in database."
            $err[] = array("103", $errCode[103]);
         endif;
      else :
         // ERR: "No customer defined for operation."
         $err[] = array("102", $errCode[102]);
      endif;
   endif;
   
/*
   if (!$errHandlerDisabled) :
      $cscIdList = array();
      if ($csId != "" && $csId > "0") :
         $sqlquery = "SELECT csc.csc_id FROM costcenter AS csc WHERE csc.cs_id = '" . $csId . "'";
         $result = $db->query($sqlquery);
         if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
         while ($row = $result->fetch_assoc()):
               $cscIdList[] = $row["csc_id"];
         endwhile;
         $result->free();
      endif;
      if (count($cscIdList) > 0) :
         // Check for maximum number of jobs per day
         $numOfOrdersOfTheCurrentDay = getCountOfTable("job", "jb_modify >= '" . $currentDate . " 00:00:00' AND csc_id_payer IN (" . implode(",", $cscIdList) . ")");
         if ($numOfOrdersOfTheCurrentDay == "" || (is_numeric($numOfOrdersOfTheCurrentDay) && $numOfOrdersOfTheCurrentDay > $maxNumOfOrdersPerDay)) :
            $acceptOrder = false;
            $err[] = array("102", getLngt("Das Limit der Aufträge pro Tag wurde überschritten. Derzeit sind dies") . " " . $maxNumOfOrdersPerDay . " " . getLngt("Aufträge"));
         endif;
         // Check for maximum number of running jobs
         $numOfRunningOrders = getCountOfTable("job", "jb_status != '2' AND csc_id_payer IN (" . implode(",", $cscIdList) . ")");
         if ($numOfRunningOrders > $maxNumOfRunningOrders) :
            $acceptOrder = false;
            $err[] = array("103", getLngt("Das Limit insgesamt laufender Aufträge wurde überschritten. Derzeit sind dies") . " " . $maxNumOfRunningOrders . " " . getLngt("Aufträge"));
         endif;
      endif;
   endif;
*/

   // Check existence of at least one error
   $errLen = count($err);

else :
  // Authentication data not ok
  $err[] = array("101", getLngt("Die Authentifizierungsdaten sind nicht in Ordnung."));
endif;
// print_r($err);

// Check existence of at least one error
$errLen = count($err);

// Log execution data in CSV format if activated
// $csvLogLine = $csEid . ";" . $currentTime . ";" . $commissionNo . ";" . $commNoRelated . ";" . $commNoService . ";" . $operationMode . ";";

// Output
$outResponse .= "<xml>" . $lineFeed;
if ($errLen > 0) :
   $errCsv = "";
   customerRequestLogFile("ERRORS", 1);
   $outResponse .= "<state>NOT OK</state>" . $lineFeed;
   $outResponse .= "<errors>" . $lineFeed;
   for ($i = 0; $i < $errLen; $i++) :
       $outResponse .= "<error>" . $lineFeed;
       $outResponse .= "<err_no>" . $err[$i][0] . "</err_no>" . $lineFeed;
       $outResponse .= "<err_desc><![CDATA[" . mcEncode($err[$i][1]) . "]]></err_desc>" . $lineFeed;
       $outResponse .= "</error>" . $lineFeed;
       if ($debug) :
          $outResponse .= "<debug>" . implode("<br>", $debugOut) . "</debug>" . $lineFeed;
       endif;
       customerRequestLogFile($err[$i][0] . " : " . mcEncode($err[$i][1]), 1);
       $errCsv .= "[[" . $err[$i][0] . "][" . mcEncode($err[$i][1]) . "]]";
   endfor;
   $outResponse .= "</errors>" . $lineFeed;

   // Log failed request in CSV format if activated
   $csvLogLine .= $errCsv;
   CSVRequestLogFile ($csvLogLine, 2);
else :
   $outResponse .= "<state>OK</state>" . $lineFeed;
   if ($debug) :
      $outResponse .= "<debug>" . implode("<br>", $debugOut) . "</debug>" . $lineFeed;
   endif;
   $outResponse .= $retDbIds;
   $outResponse .= $customerXML;

   // Log requests being OK in CSV format if activated
   $csvLogLine .= "OK";
   CSVRequestLogFile ($csvLogLine, 1);
endif;
$outResponse .= "</xml>" . $lineFeed;

// Log entries
customerRequestLogFile(getDateTime("0") . " - " . $outResponse);    // Write response into log
customerRequestLogFile("___________________________________________________________________________________");

// Call autoresponder for the new job if enabled for the customer
$parAutoresponseEnabled = getParameterValue("0", "ORDER_REQUEST_AUTORESPONSE_ENABLED_CS_" . $csId, "0");
if ($parAutoresponseEnabled == "1" || $parAutoresponseEnabled == "on" || $parAutoresponseEnabled == "yes") :
   $path = getAbsoluteSystemPath();
   $cmd = "php " . $path . "/tools/auto_response_job_new.php acapella7890 " . $csId . " " . $jbIdNew . " &";
   system($cmd);
endif;

// Return output
echo $outResponse;




/*
// FELDER UND IHRE BEDEUTUNG
// Pefices: [cs = customer] [cmp = company] [csc = costcenter] [ad = address] [usr = user]
//          => cs has one cmp
//          => cs has one or more costcenters, but if no costcenter defined in request then the "root costcenter" would be created by tag data of user segment like user address
// Usage:   [mdtr = mandatory] [opt = optional] [doop = depends on operation] [fut = future]
<xml>
  <customer>                                                  // Auftraggeber
    <auth>                                                    // Abschnitt für Authentifikation des Requests
      <session_id>[mdtr]</session_id>                         // Zusätzliche Session-ID, die mit dem Kunden ausgehandelt wurde   [mandatory]
      <passphrase>[mdtr]</passphrase>                         // Per Algorithmus generierte Phrase, die per one-way-encryption ermittelt wird sowohl für den Versand als auch zum Abgleich bei Eingang
    </auth>                                                   
    <operation>[opt]</operation>                              // Operation on customer dataset (INS, INSERT, UPD, UPDATE, DEL, DELETE) [default = empty = INS(ERT)]
    <debug_on>[opt]</debug_on>                                // Activates debug output ("ON" or "YES")

    <cs_id>[doop]</cs_id>                                     // ID of the customer, needed for DEL or UPD
    <cs_eid>[opt]</cs_eid>                                    // EID of the customer, needed for INS (use explicitly if does not exist) or UPD (overwrite if does not exist)
    <cs_sid>[doop]</cs_sid>                                   // Commission no of the customer of remote system
    <hq_id>[fut]</hq_id>                                      // Headquarters {1, 2, ....} or {HB, HH, ....}. If numeric value then checked by database field "hq_id", otherwise by "hq_mnemonic"
    <cs_prov>[fut]</cs_prov>                                  // Provision [%]
    <cs_discount>[fut]</cs_discount>                          // Discount  [%]
    <cs_invmode>[opt]</cs_invmode>                            // Invoice mode
    <cs_cr_fav_only>[fut]</cs_cr_fav_only>                    // Favoured couriers only
                                                              
 	  <cs_jbstatusmail>[opt]</cs_jbstatusmail>                  // Mail per order being finished
 	  <cs_jbstatusmail2>[opt]</cs_jbstatusmail2>                // Mail per order being picked up
 	  <cs_jbstatusmail3>[opt]</cs_jbstatusmail3>                // Mail per order being created
 	  <cs_jbstatusmail_pdf>[opt]</cs_jbstatusmail_pdf>          // Generate PDF attachement for mail "finished order"
 	 	                                                          
 	 	<cs_filter>[opt]</cs_filter>                              // Classic filter regarding every order
 	 	<cs_group>[opt]</cs_group>                                // Customer can belong to a special group
 	 	<cs_tracking>[opt]</cs_tracking>                          // System is allowed to track the customer
                                                              
    <company>                                                 // COMPANY [1:1 CUSTOMER]
      <cmp_type>[fut]</cmp_type>                              // Type of the customer (default = 0 <=> active customer)
                                                              
      <cmp_comp>[doop]</cmp_comp>                             // Name field 1 [mandatory for insert]
      <cmp_comp2>[opt]</cmp_comp2>                            // Name field 2
      <cmp_comp3>[opt]</cmp_comp3>                            // Name field 3
      <cmp_comp4>[opt]</cmp_comp4>                            // Name field 4
                                                              
      <ad_street>[mdtr]</ad_street>                           // Street
      <ad_hsno>[mdtr]</ad_hsno>                               // House number
      <ad_zipcode>[mdtr]</ad_zipcode>                         // Zipcode
      <ad_city>[mdtr]</ad_city>                               // City
      <ad_country>[mdtr]</ad_country>                         // Country
                                                              
      <cmp_iln>[opt]</cmp_iln>                                // ILN (= GLN = Global Location Number)
      <cmp_tax_idno>[opt]</cmp_tax_idno>                      // Tax no
      <cmp_stax_idno>[mdtr]</cmp_stax_idno>                   // Sales tax no (Umsatzsteueridentifikationsnummer)
                                                              
      <cmp_bank>[opt]</cmp_bank>                              // Bank name
      <cmp_bankno>[opt]</cmp_bankno>                          // Bank no (BLZ)
      <cmp_bankacc>[opt]</cmp_bankacc>                        // bank account (in connection with the bank no)
      <cmp_iban>[mdtr]</cmp_iban>                             // IBAN  (either IBAN is mandatory or fields <cmp_bankno> and <cmp_bankacc> have to be set)
      <cmp_swift>[opt]</cmp_swift>                            // SWIFT
                                                              
      <cmp_logo>[opt]</cmp_logo>                              // Filename of the logo (The generated cs_id or cs_eid will be the prefix of the filename)
      <cmp_logo_width>[opt]</cmp_logo_width>                  // Width of the logo
      <cmp_logo_height>[opt]</cmp_logo_height>                // Height of the logo
                                                              
      <cmp_remark>[opt]</cmp_remark>                          // Public remark for the customer
      <cmp_remark2>[opt]</cmp_remark2>                        // Private (internal) remark for the customer
      <cmp_match>[opt]</cmp_match>                            // Freetext (200 chars) with space separated buzzword for search requests in customer master data
      <cmp_match2>[opt]</cmp_match2>                          // Freetext (50 chars) for internal categorization
                                                              
      <cmp_newsletter>[fut]</cmp_newsletter>                  // Flag for getting newsletter (default = 0)
      <cmp_pda_usage>[fut]</cmp_pda_usage>                    // Flag for using pda with app (default = 0)
    </company>                                                 

    <user>                                                    // USER [1:1 CUSTOMER] ("Root"-)User des Kunden bzw. Auftraggebers, der sich (in votian und/oder im (Börsen-)Portal) einloggen kann
      <usr_name>[opt]</usr_name>                              // Nachname
      <usr_firstname>[opt]</usr_firstname>                    // Vorname
      <usr_birthdate>[opt]</usr_birthdate>                    // Geburtsdatum ["Y-m-d" <=> "JJJJ-MM-TT"]

      <usr_email>[opt]</usr_email>                            // Email-Adresse (primäre Mailadresse)
      <usr_inv_email>[fut]</usr_inv_email>                    // Rechnungs-Email-Adresse [NICHT IN VERWENDUNG BEI CUSTOMER]
      <usr_phone>[opt]</usr_phone>                            // Telefon
      <usr_phone2>[opt]</usr_phone2>                          // Mobil
      <usr_fax>[opt]</usr_fax>                                // Fax
      
      <usr_account>[doop]</usr_account>                       // Account
      <usr_password>[doop]</usr_password>                     // Passwort (mind. 8-stellig, mind. eine Zahl, mind. ein Buchstabe)
    </user>

    <costcenters>                                             // COSTCENTERS
      <costcenter>
        <csc_operation>[opt]</csc_operation>                  // Ignored if tag <operation> != "UPD", otherwise <csc_operation> IN (INS, INSERT, UPD, UPDATE, DEL, DELETE) [default = empty = INS(ERT)]
        <csc_id>[doop]</csc_id>                               // Ignored if tag <operation> != "UPD" or <csc_operation> == "INS", otherwise delete or update costcenter

        <csc_pre_id>[doop]</csc_pre_id>                       // Parent ID for hierarchy (default = empty for root costcenter). Mandatory for operation INS.
        <csc_name>[opt]</csc_name>                            // Name of the costcenter. If empty for root costcenter then company name will be used
    
        <costcenteraddresses>                                 // Attention: If <csc_operation> is "INS" then segment <costcenteraddresses> will be ignored. Default addresses will be added identically to root costcenter addresses. A second update request is (presently) necessary! (!!!!)
         <costcenteraddress>
           <cscad_operation>[mdtr]</cscad_operation>          // Ignored if tag <operation> != "UPD" and <csc_operation> != "UPD" and <csc_id> == "" and <adt_id> == "", otherwise INS, INSERT, UPD, UPDATE, DEL, DELETE [default = empty = INS(ERT)]
           <adt_id>[mdtr]</adt_id>                            // Mandatory for all operations ("csc_id" and "adt_id" <=> combined index)

           <cscad_comp>[doop]</cscad_comp>                    // Name field 1 [mandatory for insert]
           <cscad_comp2>[opt]</cscad_comp2>                   // Name field 2
           <cscad_comp3>[opt]</cscad_comp3>                   // Name field 3
           <cscad_comp4>[opt]</cscad_comp4>                   // Name field 4

           <ad_street>[opt]</ad_street>                       // Street (<adt_id> has to be set for update)
           <ad_hsno>[opt]</ad_hsno>                           // House number (<adt_id> has to be set for update)
           <ad_floor>[opt]</ad_floor>                         // Floor (für address) (<adt_id> has to be set for update)
           <ad_zipcode>[opt]</ad_zipcode>                     // Zipcode (<adt_id> has to be set for update)
           <ad_city>[opt]</ad_city>                           // City (<adt_id> has to be set for update)
           <ad_country>[opt]</ad_country>                     // Country (<adt_id> has to be set for update)

           <cscad_person>[opt]</cscad_person>                 // Person for costcenter address
           <cscad_phone>[opt]</cscad_phone>                   // Phone for costcenter address
           <cscad_email>[opt]</cscad_email>                   // Email for costcenter address
           <cscad_remark>[opt]</cscad_remark>                 // Remark for costcenter address
         </costcenteraddress>

         <costcenteraddress>
           ....
         </costcenteraddress>         
         ....
        </costcenteraddresses>
      </costcenter>

      <costcenter>                                            // Next costcenter ....
        ....
      </costcenter>
      ....
    </costcenters>

    <skills>                                                   // Manuelle EVENTS
      <val>[fut]</val>
      <val>[fut]</val>
      <val>[fut]</val>
      ...
    </skills>

  </customer>
</xml>
*/
?>

