<?php
/*=======================================================================
 *
 * contractor_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_wording_wrapper.inc.php");
include_once ("../include/inc_file.inc.php");
include_once ("../include/inc_courier.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();

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

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

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

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

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

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


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

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

contractorRequestLogFile($currentTime . " - " . $currentClientIP);
contractorRequestLogFile($contractorReq);


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 Auftragnehmers ist nicht gesetzt.");
   $errCode[103] = getLngt("Der Auftragnehmer wurde nicht im Datenbestand gefunden.");
   $errCode[104] = getLngt("Der Auftragnehmer hat den Status eines Metakunden für einen anderen Auftragnehmer.");
   $errCode[105] = getLngt("Der Auftragnehmer 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 Auftragnehmer-ID (EID) ist bereits vergeben.");
   $errCode[117] = getLngt("Es wurde bei dem Fahrzeug keine Operation übergeben.");
   $errCode[118] = getLngt("Zum Löschen eines Fahrzeugs muss die ID übergeben werden.");
   $errCode[119] = getLngt("Das Fahrzeug ist nicht dem Auftragnehmer zugeordnet und kann nicht gelöscht werden.");
   $errCode[120] = getLngt("");
   $errCode[121] = getLngt("Beim Einfügen eines neuen Fahrzeugs darf keine Fahrzeug-ID übergeben werden.");
   $errCode[122] = getLngt("Beim Einfügen eines neuen Fahrzeugs darf die SID nicht leer sein und sie darf nicht schon existieren.");
   $errCode[123] = getLngt("");
   $errCode[124] = getLngt("");
   $errCode[125] = getLngt("Zur Aktualisierung einer Kostenstelle muss die ID übergeben werden.");
   $errCode[126] = getLngt("Die eindeutige Fahrzeug SID existiert schon systemweit 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("Die übergebene ID des übergeordneten Auftragnehmers muss numerisch sein.");
   $errCode[133] = getLngt("Die übergebene ID des übergeordneten Auftragnehmers existiert nicht.");
   $errCode[134] = getLngt("Der übergeordnete Auftragnehmer hat seinerseits schon einen übergeordneten Auftragnemer. Eine Subunternehmerkaskade ist nicht möglich.");
   $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 contractor defined for operation.");
   $errCode[103] = getLngt("Contractor not found in database.");
   $errCode[104] = getLngt("Contractor is meta contractor of another contractor. Delete operation not executed.");
   $errCode[105] = getLngt("At least one job does exist for contractor. Delete operation not executed.");
   $errCode[106] = getLngt("Contractor 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 contractor ID (EID) does exist at another contractor.");
   $errCode[117] = getLngt("The couriervehicle operation tag has to be set but does not exist.");
   $errCode[118] = getLngt("To delete a couriervehicle the id has to be set.");
   $errCode[119] = getLngt("The couriervehicle is not associated to the contractor and may not be deleted.");
   $errCode[120] = getLngt("");
   $errCode[121] = getLngt("The couriervehicle ID has to be empty because of requested insert operation a new one will be generated.");
   $errCode[122] = getLngt("The couriervehicle SID may not be empty and may not exist by insert operation.");
   $errCode[123] = getLngt("");
   $errCode[124] = getLngt("");
   $errCode[125] = getLngt("To update a couriervehicle the id has to be set.");
   $errCode[126] = getLngt("No update of the couriervehicle possible because the couriervehicle SID does exist for another couriervehicle.");
   $errCode[127] = getLngt("The operation to modify the couriervehicle address is not correct.");
   $errCode[128] = getLngt("All operations on couriervehicle addresses require the addres type ID.");
   $errCode[129] = getLngt("The couriervehicleaddress cannot be inserted because an address with the specified address type does exist.");
   $errCode[130] = getLngt("The update of the specified couriervehicleaddress failed, because a couriervehicle address with the specified address type does not exist.");
   $errCode[131] = getLngt("The parent vehicle ID has to be empty for couriervehicle update operation.");
   $errCode[132] = getLngt("The parent contractor ID is not a number.");
   $errCode[133] = getLngt("The parent contractor ID does not exist.");
   $errCode[134] = getLngt("Insert operation with this parent ID not possible, because this parent has a parent by himself. A cascade is not desired.");
   $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($contractorReq);


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

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

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

   $crArray = array();
   $eidPrefix = "AN";
   $debugOut[] = "Authentication okay!";

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

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

   $crId  = convertSpecial($dataArray["xml"]["contractor"]["cr_id"]);
   $crEid = convertSpecial($dataArray["xml"]["contractor"]["cr_eid"]);  // NOT for INSERT (!!!!)
   if ($crId != "" && $crEid == "") :
      $crEid = getFieldValueFromId("courier","cr_id",$crId,"cr_eid");
   elseif ($crEid != "" && $crId == "") :
      $crId = getFieldValueFromId("courier","cr_eid",$crEid,"cr_id");
   endif;
   $crArray["cr_eid"]              = $crEid;

   $crArray["cr_sid"]              = convertSpecial($dataArray["xml"]["contractor"]["cr_sid"]);
   $crArray["cr_id_parent"]        = convertSpecial($dataArray["xml"]["contractor"]["cr_id_parent"]);

   $crArray["vht_id"]              = convertSpecial($dataArray["xml"]["contractor"]["vht_id"]);
   $crArray["vht_id_inv"]          = convertSpecial($dataArray["xml"]["contractor"]["vht_id_inv"]);
   $crArray["cr_vh_sign"]          = convertSpecial($dataArray["xml"]["contractor"]["cr_vh_sign"]);
   $crArray["cr_imei"]             = convertSpecial($dataArray["xml"]["contractor"]["cr_imei"]);
   $crArray["cr_mobile_pda"]       = convertSpecial($dataArray["xml"]["contractor"]["cr_mobile_pda"]);
   $crArray["cr_maxweight"]        = convertSpecial($dataArray["xml"]["contractor"]["cr_maxweight"]);
   $crArray["cr_outlay"]           = convertSpecial($dataArray["xml"]["contractor"]["cr_outlay"]);
   $crArray["cr_locationzipcode"]  = convertSpecial($dataArray["xml"]["contractor"]["cr_locationzipcode"]);
   $crArray["cr_available"]        = convertSpecial($dataArray["xml"]["contractor"]["cr_available"]);
   $crArray["cr_availabletime"]    = convertSpecial($dataArray["xml"]["contractor"]["cr_availabletime"]);
   $crArray["cr_occupied"]         = convertSpecial($dataArray["xml"]["contractor"]["cr_occupied"]);
   $crArray["cr_logintime"]        = convertSpecial($dataArray["xml"]["contractor"]["cr_logintime"]);
   
   $crArray["cr_gps_lat"]          = convertSpecial($dataArray["xml"]["contractor"]["cr_gps_lat"]);
     $crArray["cr_gps_lat"] = str_replace(",", ".", $crArray["cr_gps_lat"]);
   $crArray["cr_gps_long"]         = convertSpecial($dataArray["xml"]["contractor"]["cr_gps_long"]);
     $crArray["cr_gps_long"] = str_replace(",", ".", $crArray["cr_gps_long"]);
   if (!is_numeric($crArray["cr_gps_lat"]) || !is_numeric($crArray["cr_gps_long"])) :
      $crArray["cr_gps_lat"] = "";
      $crArray["cr_gps_long"] = "";
   endif;
   $crArray["cr_gps_time"]         = convertSpecial($dataArray["xml"]["contractor"]["cr_gps_time"]);
   $crArray["cr_gps_type"]         = convertSpecial($dataArray["xml"]["contractor"]["cr_gps_type"]);
   $crArray["cr_mobile_cell"]      = convertSpecial($dataArray["xml"]["contractor"]["cr_mobile_cell"]);

   $crArray["cr_weekdays"]         = convertSpecial($dataArray["xml"]["contractor"]["cr_weekdays"]);

   $crArray["cmp_type"]            = convertSpecial($dataArray["xml"]["contractor"]["company"]["cmp_type"]);
   $crArray["cmp_comp"]            = convertSpecial($dataArray["xml"]["contractor"]["company"]["cmp_comp"]);
   $crArray["cmp_comp2"]           = convertSpecial($dataArray["xml"]["contractor"]["company"]["cmp_comp2"]);
   $crArray["cmp_comp3"]           = convertSpecial($dataArray["xml"]["contractor"]["company"]["cmp_comp3"]);
   $crArray["cmp_comp4"]           = convertSpecial($dataArray["xml"]["contractor"]["company"]["cmp_comp4"]);

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

   $crArray["cmp_iln"]             = convertSpecial($dataArray["xml"]["contractor"]["company"]["cmp_iln"]);
   $crArray["cmp_tax_idno"]        = convertSpecial($dataArray["xml"]["contractor"]["company"]["cmp_tax_idno"]);
   $crArray["cmp_stax_idno"]       = convertSpecial($dataArray["xml"]["contractor"]["company"]["cmp_stax_idno"]);

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

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

   $crArray["cmp_newsletter"]      = convertSpecial($dataArray["xml"]["contractor"]["company"]["cmp_newsletter"]);
   $crArray["cmp_pda_usage"]       = convertSpecial($dataArray["xml"]["contractor"]["company"]["cmp_pda_usage"]);
                                   
   $crArray["usr_name"]            = convertSpecial($dataArray["xml"]["contractor"]["user"]["usr_name"]);
   $crArray["usr_firstname"]       = convertSpecial($dataArray["xml"]["contractor"]["user"]["usr_firstname"]);
   $crArray["usr_birthdate"]       = convertSpecial($dataArray["xml"]["contractor"]["user"]["usr_birthdate"]);
                                   
   $crArray["usr_email"]           = convertSpecial($dataArray["xml"]["contractor"]["user"]["usr_email"]);
   $crArray["usr_inv_email"]       = convertSpecial($dataArray["xml"]["contractor"]["user"]["usr_inv_email"]);
   $crArray["usr_phone"]           = convertSpecial($dataArray["xml"]["contractor"]["user"]["usr_phone"]);
   $crArray["usr_phone2"]          = convertSpecial($dataArray["xml"]["contractor"]["user"]["usr_phone2"]);
   $crArray["usr_fax"]             = convertSpecial($dataArray["xml"]["contractor"]["user"]["usr_fax"]);
                                   
   $crArray["usr_account"]         = convertSpecial($dataArray["xml"]["contractor"]["user"]["usr_account"]);
   $crArray["usr_password"]        = convertSpecial($dataArray["xml"]["contractor"]["user"]["usr_password"]);
   $crArray["usr_password2"]       = $crArray["usr_password"];  // Equality has to be checked by frontend !!!!

   $crArray["sys_inc_geocode_disabled"] = "1";  // No geo-check of the address
   $crArray["noValidationOfAddress"] = true;    // No call of "checkCityZipcode()" [AND insertAddress()]


   // Init special values e.g. if does not exist
   if ($crArray["cr_locationzipcode"] == "" && $crArray["ad_zipcode"] != "") :
      $crArray["cr_locationzipcode"] = $crArray["ad_zipcode"];
   endif;
   if ($crArray["cr_available"] == "") :
      $crArray["cr_available"] = "1";
   endif;
   if ($crArray["cr_availabletime"] == "") :
      $crArray["cr_availabletime"] = $currentTime;
   endif;


   $crArray["crvh"] = array();
   $numOfCouriervehicles = 0;
   if ($dataArray["xml"]["contractor"]["couriervehicles"]["couriervehicle"]["crvh_operation"] != "" || $dataArray["xml"]["contractor"]["couriervehicles"]["couriervehicle"]["crvh_id"] != "") :
      $numOfCouriervehicles = 1;
   else :
      $numOfCouriervehicles = count($dataArray["xml"]["contractor"]["couriervehicles"]["couriervehicle"]);
   endif;
   if ($debug) : echo "numOfCouriervehicles = " . $numOfCouriervehicles . "<br>\n"; endif;

   if ($numOfCouriervehicles > 0) :

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

          if ($numOfCouriervehicles == 1) : 
             $dataCrvhArr[$i] = $dataArray["xml"]["contractor"]["couriervehicles"]["couriervehicle"];
          else :
             $dataCrvhArr[$i] = $dataArray["xml"]["contractor"]["couriervehicles"]["couriervehicle"][$i];
          endif;

          $crArray["crvh"][$i]["crvh_operation"]                 = convertSpecial($dataCrvhArr[$i]["crvh_operation"]);
            $crArray["crvh"][$i]["crvh_operation"]               = strtoupper($crArray["crvh"][$i]["crvh_operation"]);
          $crArray["crvh"][$i]["crvh_id"]                        = convertSpecial($dataCrvhArr[$i]["crvh_id"]);
          $crArray["crvh"][$i]["crvh_sort"]                      = convertSpecial($dataCrvhArr[$i]["crvh_sort"]);
          $crArray["crvh"][$i]["crvh_sid"]                       = convertSpecial($dataCrvhArr[$i]["crvh_sid"]);
          $crArray["crvh"][$i]["crvh_comm_no"]                   = convertSpecial($dataCrvhArr[$i]["crvh_comm_no"]);
          $crArray["crvh"][$i]["crvh_vh_sign"]                   = convertSpecial($dataCrvhArr[$i]["crvh_vh_sign"]);
          $crArray["crvh"][$i]["crvh_vh_name"]                   = convertSpecial($dataCrvhArr[$i]["crvh_vh_name"]);
          $crArray["crvh"][$i]["crvh_licence_date"]              = convertSpecial($dataCrvhArr[$i]["crvh_licence_date"]);
          $crArray["crvh"][$i]["crvh_env_badge_level"]           = convertSpecial($dataCrvhArr[$i]["crvh_env_badge_level"]);
          $crArray["crvh"][$i]["crvh_prov"]                      = convertSpecial($dataCrvhArr[$i]["crvh_prov"]);
          $crArray["crvh"][$i]["crvh_payload"]                   = convertSpecial($dataCrvhArr[$i]["crvh_payload"]);
          $crArray["crvh"][$i]["crvh_totalweight"]               = convertSpecial($dataCrvhArr[$i]["crvh_totalweight"]);
          $crArray["crvh"][$i]["crvh_length"]                    = convertSpecial($dataCrvhArr[$i]["crvh_length"]);
          $crArray["crvh"][$i]["crvh_width"]                     = convertSpecial($dataCrvhArr[$i]["crvh_width"]);
          $crArray["crvh"][$i]["crvh_height"]                    = convertSpecial($dataCrvhArr[$i]["crvh_height"]);
          $crArray["crvh"][$i]["crvh_position"]                  = convertSpecial($dataCrvhArr[$i]["crvh_position"]);
          $crArray["crvh"][$i]["crvh_aperture_height_side"]      = convertSpecial($dataCrvhArr[$i]["crvh_aperture_height_side"]);
          $crArray["crvh"][$i]["crvh_aperture_height_rear"]      = convertSpecial($dataCrvhArr[$i]["crvh_aperture_height_rear"]);
          $crArray["crvh"][$i]["crvh_insurance_name"]            = convertSpecial($dataCrvhArr[$i]["crvh_insurance_name"]);
          $crArray["crvh"][$i]["crvh_insurance_no"]              = convertSpecial($dataCrvhArr[$i]["crvh_insurance_no"]);
          $crArray["crvh"][$i]["crvh_remark"]                    = convertSpecial($dataCrvhArr[$i]["crvh_remark"]);
          $crArray["crvh"][$i]["crvh_filter"]                    = convertSpecial($dataCrvhArr[$i]["crvh_filter"]);
          $crArray["crvh"][$i]["crvh_service"]                   = convertSpecial($dataCrvhArr[$i]["crvh_service"]);
          $crArray["crvh"][$i]["crvh_group"]                     = convertSpecial($dataCrvhArr[$i]["crvh_group"]);
          $crArray["crvh"][$i]["crvh_special"]                   = convertSpecial($dataCrvhArr[$i]["crvh_special"]);
          $crArray["crvh"][$i]["crvh_corporate_identity"]        = convertSpecial($dataCrvhArr[$i]["crvh_corporate_identity"]);
          $crArray["crvh"][$i]["crvh_funding_state"]             = convertSpecial($dataCrvhArr[$i]["crvh_funding_state"]);
          $crArray["crvh"][$i]["crvh_funding_final_installment"] = convertSpecial($dataCrvhArr[$i]["crvh_funding_final_installment"]);
          $crArray["crvh"][$i]["crvh_funding_residual_value"]    = convertSpecial($dataCrvhArr[$i]["crvh_funding_residual_value"]);
          $crArray["crvh"][$i]["crvh_pda_usage"]                 = convertSpecial($dataCrvhArr[$i]["crvh_pda_usage"]);
          $crArray["crvh"][$i]["crvh_system_fee"]                = convertSpecial($dataCrvhArr[$i]["crvh_system_fee"]);
          $crArray["crvh"][$i]["crvh_freetext_1"]                = convertSpecial($dataCrvhArr[$i]["crvh_freetext_1"]);
          
          $crArray["crvh"][$i]["crvh_weekdays"]                  = convertSpecial($dataCrvhArr[$i]["crvh_weekdays"]);
      endfor;
   endif;

   if ($debug) :
      echo "operationMode = " . $operationMode . "<br>\n";
      echo "crId = " . $crId . "<br>\n";
      print_r($crArray); echo "<br><br><br>";
      print_r($dataArray); echo "<br><br><br>";
   endif;


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

   if ($operationMode == "GET") :

      // Check existence of the contractor
      if ($crId != "" && is_numeric($crId)) :

         $crId = getFieldValueFromId("courier","cr_id",$crId,"cr_id");
         if ($crId != "") :

            $contractorArray = array();
            $cmpId = getFieldValueFromId("courier","cr_id",$crId,"cmp_id");
            $hq_id = getFieldValueFromId("courier","cr_id",$crId,"hq_id");
            $f_hq_id = array();
            $emp_id = "";
            $contractorArray["contractor"] = getCourier($cmpId, "2");
            $contractorArray["contractor"]["company"]["cmp_id"] = $cmpId;  // Add company ID

            // (Fix) GPS coordinates from "geocode"
            $contractorArray["cr_gps_fix_lat"] = getFieldValueFromClause("geocode","gc_lat","gc_obj_type = 'cr' AND gc_obj_id = '" . $crId . "'");
            $contractorArray["cr_gps_fix_long"] = getFieldValueFromClause("geocode","gc_long","gc_obj_type = 'cr' AND gc_obj_id = '" . $crId . "'");

            // Vehicles
            $tmpCrvhIds = getColVectorFromDB2ArrayByClause("couriervehicle", "crvh_id", "cr_id = '" . $crId . "'", "", "", "");
   if ($debug) :
      echo "<br><br>FAHRZEUG_ID (crvh_id) VON: " . $crId . ": <br>\n";
      print_r($tmpCrvhIds); echo "<br><br><br>";
   endif;
            $tmpCrvhIdsLen = count($tmpCrvhIds);
            if ($tmpCrvhIdsLen > 0) :
               $contractorArray["contractor"]["vehicles"]["vehicle"] = array();
               for ($c = 0; $c < $tmpCrvhIdsLen; $c++) :
                   getDBData("couriervehicle", $tmpCrvhIds[$c]);
                   $contractorArray["contractor"]["vehicles"]["vehicle"][$c] = $dbData["couriervehicle"];
               endfor;
            endif;
   if ($debug) :
      echo "<br><br>FAHRZEUGDATEN VON: " . $crId . ": <br>\n";
      print_r($contractorArray["contractor"]["vehicles"]); echo "<br><br><br>";
   endif;
            // Favoured customers
            $tmpCsIds = getColVectorFromDB2ArrayByClause("customercourier", "cs_id", "cr_id = '" . $crId . "' AND cscr_relation = '1'", "", "", "");
            $tmpCsIdsLen = count($tmpCsIds);
            if ($tmpCsIdsLen > 0) :
               $contractorArray["contractor"]["customercouriers"]["customercourier"] = array();
               for ($c = 0; $c < $tmpCsIdsLen; $c++) :
                   $csId = $tmpCsIds[$c];
                   $contractorArray["contractor"]["customercouriers"]["customercourier"][$c]["cs_id"] = $csId;
                   $contractorArray["contractor"]["customercouriers"]["customercourier"][$c]["cs_eid"] = getFieldValueFromId("customer","cs_id",$csId,"cs_eid");
               endfor;
            endif;

            // Check asset tables
            $parAddCrToAsset = getParameterValue("0", "CR_ADD_TO_ASSET_ENABLED", "0");
            if ($parAddCrToAsset == "1") :
               $asId = getAsset("", "cr", $crId, array("asset","assetrelation","asd_as"));
               if ($asId != "" && is_numeric($asId) && $asId > "0") :
                  $contractorArray["contractor"]["asset"] = $dbData["asset"];
                  if (is_array($dbData["asr_owner"]) && count($dbData["asr_owner"]) > 0) :
                     $contractorArray["contractor"]["asset"]["assetrelations"]["asr_owner"] = $dbData["asr_owner"];
                  endif;
                  if (is_array($dbData["assetrelation"]) && count($dbData["assetrelation"]) > 0) :
                     $contractorArray["contractor"]["asset"]["assetrelations"]["assetrelation"] = $dbData["assetrelation"];
                  endif;
                  if (is_array($dbData["assetdisposition"]) && count($dbData["assetdisposition"]) > 0) :
                     $contractorArray["contractor"]["asset"]["assetdisposition"] = $dbData["assetdisposition"];
                  endif;
               endif;
            endif;

            $contractorXML = mcArray2Xml($contractorArray, "", $lineFeed);
         else :
            // ERR: "Contractor not found in database."
            $err[] = array("103", $errCode[103]);
         endif;
      else :
         // ERR: "No contractor defined for operation."
         $err[] = array("102", $errCode[102]);
      endif;
   endif;


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

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

      // Check existence of the contractor
      if ($crId != "" && is_numeric($crId)) :

         $crId = getFieldValueFromId("courier","cr_id",$crId,"cr_id");
         if ($crId != "") :

            // Check for being meta contractor (parent for another contractor)
            if (!existsEntry("courier",array("cr_id_parent",$crId))) :

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

                  TA("B");

                  $hq_id = getFieldValueFromId("courier","cr_id",$crId,"hq_id");
                  $tmpCmpId = getFieldValueFromId("courier","cr_id",$crId,"cmp_id");

                  $tmpCsAdmin = getFieldValueFromId("courier","cr_id",$crId,"cr_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", "cr_id = '" . $crId . "'", "", "", "");
                  $tmpCscIdsLen = count($tmpCscIds);
                  if ($tmpCscIdsLen > 0) :
                     deleteStmt("costcenteraddress", "csc_id IN (" . implode(",", $tmpCscIds) . ")");
                     deleteStmt("costcenter", "cr_id = '" . $crId . "'");
                  endif;

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

                  // Check asset tables
                  $parAddCrToAsset = getParameterValue("0", "CR_ADD_TO_ASSET_ENABLED", "0");
                  if ($parAddCrToAsset == "1") :
                     
                  endif;

                  deleteStmt("courier", "cr_id = '" . $crId . "'");

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

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


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

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

      if ($crId == "") :

         $crEid = $eidPrefix . getDateTime(6);  // "YmdHis"
         $crArray["cr_eid"] = $crEid;
         if ($debug) : echo "crArray[cr_eid] = " . $crArray["cr_eid"] . "<br>"; endif;

         // Check existence of usr_account
         $doInsert = true;

         // Check user
         $defaultFieldArray = array();
         $sqlPhraseArr = array();
         $checkFieldArray = getFieldsAndTypes("user");
         $errKey = checkTypesForDbImportFieldValues($crArray, $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($crArray, $defaultFieldArray, $checkFieldArray, $sqlPhraseArr);
            if ($errKey != "") :
               $doInsert = false;
               $err[] = array("100", $errCode[100] . " [" . $errKey . "]");
            endif;
         endif;

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

         if ($doInsert) :
            // Check existence of usr_account
            if ($crArray["usr_account"] != ""):
               $doInsert = false;
               if (!existsEntry("user",array("usr_account",$crArray["usr_account"]))) :
            
                  if ($crArray["usr_password"] != "" && checkPasswordValidation($crArray["usr_password"],$crArray["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 :
               $crArray["usr_password"] = "";  // Remove password if "usr_account" is empty
            endif;

            // Check existence of parent ID if not empty
            if ($crArray["cr_id_parent"] != ""):
               $doInsert = false;
               // Check parent ID is numeric
               // if (is_numeric($crArray["cr_id_parent"])) :
                  // Check existence of the parent ID
                  if (existsEntry("courier",array("cr_id",$crArray["cr_id_parent"]))) :
                     // If parent does exist then check this parent does NOT have a parent ID (!!!!)
                     $crParentIdOfParent = getFieldValueFromId("courier","cr_id",$crArray["cr_id_parent"],"cr_id_parent");
                     if ($crParentIdOfParent == "" || $crParentIdOfParent == "0") :
                        $doInsert = true;
                     else :
                        $err[] = array("134", $errCode[134]);
                     endif;
                  else :
                     $err[] = array("133", $errCode[133]);
                  endif;
               // else :
               //    $err[] = array("132", $errCode[132]);
               // endif;
            endif;

            if ($doInsert) :
               $retArr = insertCourier($crArray, "1");
               if ($debug) : print_r($retArr); endif;
               if (is_array($retArr) && $retArr[0] != "") :

                  // Because of multi user access the last two digits of the "cr_id" will be added to the "cr_eid"
                  updateStmt("courier","cr_id",$retArr[0], array("cr_eid", $crArray["cr_eid"] . substr($retArr[0],-2)));

                  // Insert (fix) GPS coordinates into geocode
                  if ($crArray["cr_gps_lat"] != "" && $crArray["cr_gps_long"] != "") :
                     $gc_id_new = dbInsert("geocode", array("gc_obj_type", "cs", "gc_obj_id", $retArr[0], "gc_lat", $crArray["cr_gps_lat"], "gc_long", $crArray["cr_gps_long"]));
                  endif;

                  $retDbIds = getDbIdTree("cr", $retArr[0], "1", "db_id_struct", "\n");
               else :
                  // ERR: "Insert operation failed."
                  $err[] = array("107", $errCode[107]);
               endif;
            endif;
         endif;
/*
         if ($doInsert) :
            // TA("B");
            $ok = insertCourier($crArray);
            if ($ok) :
               // TA("C");
            else:             
               // TA("R");
               // ERR: "Insert operation failed."
               $err[] = array("107", $errCode[107]);
            endif;
            // TA("E");
         endif;
*/
      else :
         // ERR: "Contractor ID may not exist for insert operation."
         $err[] = array("106", $errCode[106]);
      endif;
   endif;


   // ****************
   // **** UPDATE ****
   // ****************

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

      // Check existence of the contractor
      if ($crId != "" && is_numeric($crId)) :

         $crId = getFieldValueFromId("courier","cr_id",$crId,"cr_id");
         if ($crId != "") :

            TA("B");

            // Get current primary IDs
            $crCmpId = getFieldValueFromId("courier","cr_id",$crId,"cmp_id");
            $crUsrId = getFieldValueFromId("courier","cr_id",$crId,"usr_id");

            $doCrUpdate = true;

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

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

            if ($doCrUpdate):
               // Take current data to log for history
               // .............. !!!! ..............

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

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

                  if ($crArray["ad_country"] == "") : $crArray["ad_country"] = "DE"; endif;
                  $sqlStmt = "SELECT ad_id FROM address WHERE ad_street = '" . $crArray["ad_street"] . "' AND ad_zipcode = '" . $crArray["ad_zipcode"] . "' AND ad_city = '" . $crArray["ad_city"] . "' AND ad_country = '" . $crArray["ad_country"] . "'";
                  $crCmpAdId = $db->getOne($sqlStmt);
                  if (DB::isError($crCmpAdId)) die ("$PHP_SELF: <br>$sqlStmt<br>" . $crCmpAdId->getMessage());
                  if ($crCmpAdId == ""):
                     insertStmt("address", array("ad_street", $crArray["ad_street"], "ad_zipcode", $crArray["ad_zipcode"], "ad_city", $crArray["ad_city"], "ad_country", $crArray["ad_country"]));
                     $crCmpAdId = getLastInsertID();
                  endif;
                  array_push($defaultFieldArray, "ad_id", $crCmpAdId);
               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", $crCmpId, "cmp_modify_status");
                  if ($modifyStatus != "1") : $modifyStatus = "2"; endif;
                  array_push($defaultFieldArray, "cmp_modify_status", $modifyStatus);

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


            // **** Contractor data ****

            // Check unique contractor ID
            if ($crArray["cr_eid"] != "" && $db->getOne("SELECT cr_eid FROM courier WHERE cr_eid = '" . $crArray["cr_eid"] . "' AND NOT (cr_id = '" . $crId . "')")) :
               $err[] = array("116", $errCode[116]);
               $doCrUpdate = false;
               $crArray["cr_eid"] = "";
            endif;

            // Check existence of parent ID if not empty
            if ($doCrUpdate):
               if ($crArray["cr_id_parent"] != ""):
                  $doCrUpdate = false;
                  // Check parent ID is numeric
                  // if (is_numeric($crArray["cr_id_parent"])) :
                     // Check existence of the parent ID
                     if (existsEntry("courier",array("cr_id",$crArray["cr_id_parent"]))) :
                        // If parent does exist then check this parent does NOT have a parent ID (!!!!)
                        $crParentIdOfParent = getFieldValueFromId("courier","cr_id",$crArray["cr_id_parent"],"cr_id_parent");
                        if ($crParentIdOfParent == "" || $crParentIdOfParent == "0") :
                           $doCrUpdate = true;
                        else :
                           $err[] = array("134", $errCode[134]);
                        endif;
                     else :
                        $err[] = array("133", $errCode[133]);
                     endif;
                  // else :
                  //    $err[] = array("132", $errCode[132]);
                  // endif;
               endif;
            endif;

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

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

               if ($crArray["cr_gps_lat"] != "" && $crArray["cr_gps_long"] != "") :
                  array_push($defaultFieldArray, "cr_gps_lat", $crArray["cr_gps_lat"]);
                  array_push($defaultFieldArray, "cr_gps_long", $crArray["cr_gps_long"]);
                  
                  // Take these coordinates for fix GPS coordinate in "geocode"
                  updateStmt("geocode", "gc_obj_id", $crId, array("gc_lat", $crArray["cr_gps_lat"], "gc_long", $crArray["cr_gps_long"]), "gc_obj_type = 'cr'");
               endif;
               if ($crArray["cr_gps_time"] != "") :    array_push($defaultFieldArray, "cr_gps_time", $crArray["cr_gps_time"]); endif;
               if ($crArray["cr_gps_type"] != "") :    array_push($defaultFieldArray, "cr_gps_type", $crArray["cr_gps_type"]); endif;
               if ($crArray["cr_mobile_cell"] != "") : array_push($defaultFieldArray, "cr_mobile_cell", $crArray["cr_mobile_cell"]); endif;

               if (count($defaultFieldArray) > 0) :
                  updateStmt("courier","cr_id",$crId,$defaultFieldArray);
               endif;
            endif;


            // **** Couriervehicle data ****

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

               $numOfCouriervehicles = count($crArray["crvh"]);
               if ($debug) : echo "numOfCouriervehicles = " . $numOfCouriervehicles . "<br>\n"; endif;

               if ($numOfCouriervehicles > 0) :
            
                  for ($i = 0; $i < $numOfCouriervehicles; $i++) :

                      $crvhOperation = $crArray["crvh"][$i]["crvh_operation"];
                      $crvhId = $crArray["crvh"][$i]["crvh_id"];                      

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

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

                               // Check contractor is owner of the couriervehicle
                               if (existsEntry("couriervehicle", array("crvh_id",$crvhId,"cr_id",$crId))) :

                                  // Check couriervehicle to be deleted ....
                                  // if (!existsEntry("couriervehicle", array("cr_id",$crId,"xxxx",$xxxx))) :

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

                                       deleteStmt("couriervehicle", "crvh_id = '" . $crvhId . "'");
                                    // else :
                                    //    $err[] = array("124", $errCode[124] . " [crvh:" . $i . "]");
                                    //    $doCrUpdate = false;
                                    // endif;
                                  // else :
                                  //   $err[] = array("120", $errCode[120] . " [crvh:" . $i . "]");
                                  //   $doCrUpdate = false;
                                  // endif;
                               else :
                                  $err[] = array("119", $errCode[119] . " [crvh:" . $i . "]");
                                  $doCrUpdate = false;
                               endif;
                            else :
                              $err[] = array("118", $errCode[118] . " [crvh:" . $i . "]");
                               $doCrUpdate = false;
                            endif;

                         elseif ($crvhOperation == "INS") :

                            if ($crvhId == "") :

                               $doInsert = false;
                               // Check existence of crvh_sid
                               if ($crArray["crvh"][$i]["crvh_sid"] != "" && !existsEntry("couriervehicle", array("cr_id",$crId,"crvh_sid",$crArray["crvh"][$i]["crvh_sid"]))):

                                  // if (true) :
                                     $defaultFields = array("cr_id", $crId);
                                     $sqlPhraseArr = array();
                                     $checkFieldArray = getFieldsAndTypes("couriervehicle");
                                     $errKey = checkTypesForDbImportFieldValues($crArray["crvh"][$i], $defaultFields, $checkFieldArray, $sqlPhraseArr);
                                     if ($errKey == "") :
                                        insertStmt("couriervehicle",$defaultFields);
                                     else :
                                        $doCrUpdate = false;
                                        $err[] = array("100", $errCode[100] . " [" . $errKey . "]");
                                     endif;

                                  // else :
                                  //    $err[] = array("123", $errCode[123] . " [crvh:" . $i . "]");
                                  //    $doCrUpdate = false;
                                  // endif;
                               else :
                                  $err[] = array("122", $errCode[122] . " [crvh:" . $i . "]");
                                  $doCrUpdate = false;
                               endif;
                            else :
                               $err[] = array("121", $errCode[121] . " [crvh:" . $i . "]");
                               $doCrUpdate = false;
                            endif;

                         elseif ($crvhOperation == "UPD") :

                            if ($crvhId != "") :

                               $defaultFields = array();

                               // Update couriervehicle data because couriervehicle SID is set and should rename the current one
                               if ($crArray["crvh"][$i]["crvh_sid"] != ""):

                                  if (!$db->getOne("SELECT crvh.crvh_id FROM couriervehicle AS crvh WHERE crvh.crvh_sid = '" . $crArray["crvh"][$i]["crvh_sid"] . "' AND crvh.crvh_id != '" . $crvhId . "'")):

                                     $defaultFields = array("crvh_sid", $crArray["crvh"][$i]["crvh_sid"]);
                                     $sqlPhraseArr = array();
                                     $checkFieldArray = getFieldsAndTypes("couriervehicle");
                                     $errKey = checkTypesForDbImportFieldValues($crArray["crvh"][$i], $defaultFields, $checkFieldArray, $sqlPhraseArr);
                                     if ($errKey == "") :
                                        insertStmt("couriervehicle",$defaultFields);
                                     else :
                                        $doCrUpdate = false;
                                        $err[] = array("100", $errCode[100] . " [" . $errKey . "]");
                                     endif;
                                  else :
                                     $err[] = array("126", $errCode[126] . " [crvh:" . $i . "]");
                                     $doCrUpdate = false;
                                  endif;
                               endif;

                               // if ($doCrUpdate) :

                                  // Update requested couriervehicle item
                                  if (count($defaultFields) > 0 && $doCrUpdate) :
                                     updateStmt("couriervehicle","crvh_id",$crvhId, $defaultFields);
                                  endif;

                               // endif;  // $doCrUpdate
                            else :
                               $err[] = array("125", $errCode[125] . " [crvh:" . $i . "]");
                               $doCrUpdate = false;
                            endif;
                         endif;
                      else :
                         $err[] = array("117", $errCode[117] . " [crvh:" . $i . "]");
                         $doCrUpdate = false;
                      endif;
                  endfor;
               endif;
            endif;

            // Commit or rollback of all transactions on "costcenter" and "costcenteraddress".
            // "contractor", "company", "user", etc. are executed and made persistent if operations are ok. (!!!!)
            if ($doCrUpdate) :

               // Insert into or update in table "asset" if enabled
               $parAddCrToAsset = getParameterValue("0", "CR_ADD_TO_ASSET_ENABLED", "0");
               if ($parAddCrToAsset == "1") :

                  $tmpParentId = $crId;
                  if ($crArray["cr_id_parent"] != "" && is_numeric($crArray["cr_id_parent"]) && $crArray["cr_id_parent"] > "0") :
                     $tmpParentId = $crArray["cr_id_parent"];
                  endif;

                  if (existsEntry("asset", array("as_ref_obj_type","cr","as_ref_obj_id",$crId,"as_context","parent"))) :
                     updateStmt("asset","as_ref_obj_id",$crId, array("as_obj_type","cr","as_obj_id",$tmpParentId,"as_weekdays",$crArray["cr_weekdays"]),"as_ref_obj_type = 'cr' AND as_context = 'parent'");
                  else :
                     insertStmt("asset", array("as_obj_type", "cr", "as_obj_id", $tmpParentId, "as_ref_obj_type", "cr", "as_ref_obj_id", $crId, 
                                               "as_key", "", "as_value", "", "as_context", "parent", "as_weekdays", $crArray["cr_weekdays"]));
                  endif;
               endif;

               $retDbIds = getDbIdTree("cr", $crId, "1", "db_id_struct", "\n");
               TA("C");
            else :
               TA("R");
            endif;
            TA("E");
         else :
            // ERR: "Contractor not found in database."
            $err[] = array("103", $errCode[103]);
         endif;
      else :
         // ERR: "No contractor defined for operation."
         $err[] = array("102", $errCode[102]);
      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
// $crvLogLine = $crEid . ";" . $currentTime . ";" . $commissionNo . ";" . $commNoRelated . ";" . $commNoService . ";" . $operationMode . ";";

// Output
$outResponse .= "<xml>" . $lineFeed;
if ($errLen > 0) :
   $errCsv = "";
   contractorRequestLogFile("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;
       contractorRequestLogFile($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
   $crvLogLine .= $errCsv;
   CSVRequestLogFile ($crvLogLine, 2);
else :
   $outResponse .= "<state>OK</state>" . $lineFeed;
   if ($debug) :
      $outResponse .= "<debug>" . implode("<br>", $debugOut) . "</debug>" . $lineFeed;
   endif;
   $outResponse .= $retDbIds;
   $outResponse .= $contractorXML;

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

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

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

// Return output
echo $outResponse;




/*
// FELDER UND IHRE BEDEUTUNG
// Pefices: [cr = contractor] [cmp = company] [ad = address] [usr = user] [crvh = couriervehicle]
//          => cr has one cmp
//          => cr has one usr
//          => cr has none, one or more vehicles
// Usage:   [mdtr = mandatory] [opt = optional] [doop = depends on operation] [fut = future]
<xml>
  <contractor>                                                // Auftragnehmer
    <auth>                                                    // Abschnitt für Authentifikation des Requests
      <session_id>[mdtr]</session_id>                         // Zusätzliche Session-ID, die mit dem Auftragnehmer 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 contractor dataset (INS, INSERT, UPD, UPDATE, DEL, DELETE) [default = empty = INS(ERT)]
    <debug_on>[opt]</debug_on>                                // Activates debug output ("ON" or "YES")

    <cr_id>[doop]</cr_id>                                     // ID of the contractor, needed for DEL or UPD
    <cr_eid>[opt]</cr_eid>                                    // EID of the contractor, needed for INS (use explicitly if does not exist) or UPD (overwrite if does not exist)
    <cr_sid>[doop]</cr_sid>                                   // Commission no of the contractor 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"
    <cr_id_parent>[opt]</cr_id_parent>                        // Unternehmer, dem die Person zugeordnet wird bzw. ist
    <vht_id>[opt]</vht_id>                                    // Fahrzeug zur Verfügung
    <vht_id_inv>[fut]</vht_id_inv>                            // Rechnungsfahrzeug
    <cr_vh_sign>[opt]</cr_vh_sign>                            // KFZ-Kennzeichen
    <cr_imei>[opt]</cr_imei>                                  // IMEI eines vorhandenen Endgerätes
    <cr_mobile_pda>[opt]</cr_mobile_pda>                      // Mobilnummer / Kartennummer
    <cr_maxweight>[opt]</cr_maxweight>                        // Maximales Tragegewicht für Person
    <cr_outlay>[opt]</cr_outlay>                              // Maximale Auslage an Geld
    <cr_locationzipcode>[opt]</cr_locationzipcode>            // Aktuelle Position (PLZ)
    <cr_available>[opt]</cr_available>                        // Person steht aktuell zur Verfügung
    <cr_availabletime>[opt]</cr_availabletime>                // Zeitpunkt der Verfügbarkeit
    <cr_occupied>[opt]</cr_occupied>                          // Person absolviert aktuell einen Auftrag
    <cr_logintime>[opt]</cr_logintime>                        // Letzer Anmeldezeitpunkt wenn Endgerät verfügbar
    <cr_gps_long>[opt]</cr_gps_long>                          // Aktuelle Position (Länge)
    <cr_gps_lat>[opt]</cr_gps_lat>                            // Aktuelle Position (Breite)
    <cr_gps_time>[opt]</cr_gps_time>                          // Jüngster Ortungszeitpunkt
    <cr_gps_type>[opt]</cr_gps_type>                          // Ortungstyp (1 = LBS [depricated], 2 = GPS, 3 = Network)
    <cr_mobile_cell>[opt]</cr_mobile_cell>                    // Aktuelle Zellinformationen wenn Endgerät aktiv

    <cr_weekdays>                                             // Wochentage, an denen die Person grundsätzlich zur Verfügung steht (Integer value for bitstring [2^0 = Montag, 2^1 = Dienstag, ....])

    <company>                                                 // COMPANY [1:1 CUSTOMER]
      <cmp_type>[fut]</cmp_type>                              // Type of the contractor (default = 0 <=> active contractor)
                                                              
      <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 cr_id or cr_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 contractor
      <cmp_remark2>[opt]</cmp_remark2>                        // Private (internal) remark for the contractor
      <cmp_match>[opt]</cmp_match>                            // Freetext (200 chars) with space separated buzzword for search requests in contractor 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 Auftragnehmers, der sich (in votian und/oder im (Börsen-)Portal) einloggen kann
      <usr_name>[opt]</usr_name>                              // Lastname
      <usr_firstname>[opt]</usr_firstname>                    // Fistname
      <usr_birthdate>[opt]</usr_birthdate>                    // Birthdate ["Y-m-d" <=> "JJJJ-MM-TT"]

      <usr_email>[doop]</usr_email>                           // Mail-Address (primäre Mailadresse)
      <usr_inv_email>[opt]</usr_inv_email>                    // Invoice Mmail-Address
      <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>                     // Password (mind. 8-stellig, mind. eine Zahl, mind. ein Buchstabe)
    </user>

    <couriervehicles>                                         // FAHRZEUGE
      <couriervehicle>                                        
        <crvh_operation>[mdtr]</crvh_operation>               // Has to be set (INS, INSERT, UPD, UPDATE, DEL, DELETE)]
        <crvh_id>[doop]</crvh_id>                             // Ignored if tag <operation> != "UPD" or <csc_operation> == "INS", otherwise delete or update costcenter
        
        <vht_id>[mdtr]</vht_id>                               // Vehicle type
        <crvh_sort>[fut]</crvh_sort>                          // Number for sort sequence
        <crvh_sid>[opt]</crvh_sid>                            // Short name (e.g. "HH1001") of the vehicle
        <crvh_comm_no>[opt]</crvh_comm_no>                    // Commission number
        <crvh_vh_sign>[opt]</crvh_vh_sign>                    // Vehicle sign
        <crvh_vh_name>[opt]</crvh_vh_name>                    // Auto brand
        <crvh_licence_date>[opt]</crvh_licence_date>          // Erstzulassung (Y-m-d)
        <crvh_env_badge_level>[opt]</crvh_env_badge_level>    // Umweltstufe (1..6)
        <crvh_prov>[opt]</crvh_prov>                          // Provision
        <crvh_payload>[opt]</crvh_payload>                    // Nutzlast
        <crvh_totalweight>[opt]</crvh_totalweight>            // Gesamtgewicht
        <crvh_length>[opt]</crvh_length>                      // Länge
        <crvh_width>[opt]</crvh_width>                        // Breite
        <crvh_height>[opt]</crvh_height>                      // Höhe
        <crvh_position>[opt]</crvh_position>                  // Stellplätze
        <crvh_aperture_height_side>[opt]</crvh_aperture_height_side>  // Seitendurchladehöhe
        <crvh_aperture_height_rear>[opt]</crvh_aperture_height_rear>  // Heckdurchladehöhe
        <crvh_insurance_name>[opt]</crvh_insurance_name>      // Versicherung
        <crvh_insurance_no>[opt]</crvh_insurance_no>          // Versicherungsnummer
        <crvh_remark>[opt]</crvh_remark>                      // Bemerkung
        <crvh_filter>[opt]</crvh_filter>                      // Fahrzeug-Filter / vehicle skills
        <crvh_service>[opt]</crvh_service>                    // Services (Lieferung und/oder Montage und/oder ....)
        <crvh_group>[opt]</crvh_group>                        // Gruppenzugehörigkeitenß
        <crvh_special>[opt]</crvh_special>                    // Eigenfahrzeug
        <crvh_corporate_identity>[opt]</crvh_corporate_identity>                // Fahrzeug-CI (Fahrzeug UND Fahrer zusammen)
        <crvh_funding_state>[opt]</crvh_funding_state>                          // Finanzierung
        <crvh_funding_final_installment>[opt]</crvh_funding_final_installment>  // 
        <crvh_funding_residual_value>[opt]</crvh_funding_residual_value>        // 
        <crvh_pda_usage>[opt]</crvh_pda_usage>                // Endgerätenutzung (ja/nein)
        <crvh_system_fee>[opt]</crvh_system_fee>              // Systemgebühr
        <crvh_freetext_1>[opt]</crvh_freetext_1>              // Freitext

        <crvh_weekdays>                                       // Wochentage, an denen das Fahrzeug grundsätzlich zur Verfügung steht (Integer value for bitstring [2^0 = Montag, 2^1 = Dienstag, ....])
      </couriervehicle>

      <couriervehicle>                                        // Next vehicle ....
        ....
      </couriervehicle>
      ....
    </couriervehicles>

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

  </contractor>
</xml>
*/
?>

