<?php
/*=======================================================================
 *
 * inc_dbfields2array.inc.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/


// Converts the result of a database search to an array.
// The following fields have to be defined before calling this function.
// VARS: $fieldArray      : Fieldnames (e.g. "cmp.cmp_comp", "usr.usr_email", etc.)
//       $idArrayLen      : Number of fields to be exportable (equals to "count($fieldArray)")
// Usage e.g. in EXPORT and STATISTIC
function convertRowToArray($result,$localeFieldArray = "",$localeIdArrayLen = "") {
   global $db,$fieldArray, $idArrayLen, $f_exp_category, $f_export_mode, $specialJbPayment, $jbIdReal;

   $rowArray = array();
   $j = 0;
   // $csEidMappingArray = array();
   $currentDate = getDateTime("3");

   if ($localeFieldArray != "") : $fieldArray = $localeFieldArray; endif;
   if ($localeIdArrayLen != "") : $idArrayLen = $localeIdArrayLen; endif;

   while ($row = $result->fetch_assoc()) :    

         $doContinue = true;

         // Check conditions to avoid export of current row
         if ($f_exp_category == "2" || $f_exp_category == "3") :
            $tmpCrId = $row["cr_id"];
            if ($tmpCrId != "" && $tmpCrId > 0) :
               // [I] "cmp.cmp_contract_date"
               $tmpCmpId = getFieldValueFromId("courier","cr_id",$tmpCrId,"cmp_id");
               $contractDate = getFieldValueFromId("company","cmp_id",$tmpCmpId,"cmp_contract_date");
               if ($contractDate == "" || $contractDate == "0000-00-00") :            
                  // [II] Category 3 [2nd TP-Page], Field 1631 ["Vertragsbeginn"], [1945 <=> current mtfck association]
                  $contractDate = getMetafieldValue("3", "1631", $tmpCrId, "0");
                  if ($contractDate != "" && $contractDate != "ERR") :
                     // Convert to date
                     $contractDate = substr($contractDate,6,4) . "-" . substr($contractDate,3,2) . "-" . substr($contractDate,0,2);
                  endif;
               endif;
               if ($contractDate != "" && $contractDate != "ERR") :
                  if ($currentDate < $contractDate) :
                     $doContinue = false;
                  endif;
               endif;
            endif;
         endif;

         // Check special "no-export-date" to avoid export of current vehicle row
         if ($doContinue && $f_exp_category == "3") :            
            $tmpCrvhId = $row["crvh_id"];
            if ($tmpCrvhId != "" && $tmpCrvhId > 0) :
               // [II] Category 4 [2nd vehicle page], Field 1728 ["Enddatum SAP-Export"], [2117 <=> current mtfck association]
               $noExportDate = getMetafieldValue("4", "1728", $tmpCrvhId, "0");
               if ($noExportDate != "" && $noExportDate != "ERR" && $noExportDate != "0000-00-00") :
                  $noExportDate = substr($noExportDate, 6, 4) . "-" . substr($noExportDate, 3, 2) . "-" . substr($noExportDate, 0, 2);
                  // Increment one day
                  // $noExportDate = date('Y-m-d', strtotime($noExportDate . ' +1 day'));
                  if ($currentDate >= $noExportDate) :
                     $doContinue = false;
                  endif;
               endif;
            endif;
         endif;

         if ($doContinue) :

            $tmpJbCscIdPayer = "";
            $tmpCsCscIdRoot = "";
            
            $tmpMainadressOverrulesInvoiceaddress = FALSE;
            $tmpMainCompanynameOverrulesInvoiceCompanyname = FALSE;
            
            $jbpcId = "";
            $paymentMethod = "  ";
            if ($f_exp_category == "8") :
               // Get job payment collection ID for payment method CASH ("Barzahlung")
               // $jbpcId = getFieldValueFromClause("jobpayment","jbpc_id","jb_id = '" . $row["jb_id"] . "' AND jbp_mode = '0'");
               $jbpcId = getFieldValueFromClause("jobpayment","jbpc_id","jb_id = '" . $row["jb_id"] . "' AND jbpc_id != '0' AND jbp_price != '0'");
               $jbpCounter = getFieldValueFromClause("jobpayment","jbp_counter","jb_id = '" . $row["jb_id"] . "' AND jbp_mode = '0' AND jbp_price != '0'");
               // If $jbpCounter == "0" => $paymentMethod = JB_PAYMODE_CASH;
               // If $jbpCounter == "" =>  $paymentMethod = "  ";
               if ($jbpCounter == "0") :
                  $paymentMethod = JB_PAYMODE_CASH;
               endif;
               /*
               if ($jbpcId != "" && is_numeric($jbpcId)) :
                  $paymentMethod = JB_PAYMODE_CASH;
               else :
                  // Get job payment collection ID for payment method NOT being CASH ("Keine Barzahlung")
                  $jbpcId = getFieldValueFromClause("jobpayment","jbpc_id","jb_id = '" . $row["jb_id"] . "' AND jbp_mode != '0'");
               endif;
               */
            
                if ($f_exp_category == "8") :   // Check existing invoice vehicle. If it does exist substitute SID
                   $crIdParent = getFieldValueFromId("courier","cr_id",$row["cr_id"],"cr_id_parent");
                   if ($crIdParent == "" || $crIdParent == "0") :
                      $crIdParent = $row["cr_id"];
                   endif;
                   $crvhIdInv = getFieldValueFromClause("couriervehicle", "crvh_id_inv", "cr_id = '" . $crIdParent . "' AND RIGHT(crvh_sid,3) = '" . substr($row["cr_sid"],-3) . "'");
                   if ($crvhIdInv != "" && $crvhIdInv != "0") :
                      $crvhSidInv = getFieldValueFromId("couriervehicle","crvh_id",$crvhIdInv,"crvh_sid");
                      if ($crvhSidInv != "") :
                         $row["cr_sid"] = " " . substr($crvhSidInv,-3);
                      endif;
                   endif;
                endif;
            endif;
            
            for ($i = 0; $i < $idArrayLen; $i++) :
            
                // Extract the fieldname (right part of the ".", e.g. "cmp_comp" from "cmp.cmp_comp")
                $fieldName = substr($fieldArray[$i], strrpos($fieldArray[$i],".") + 1);
            
                // Current content of the field (e.g. $rowArray[3]["cmp_comp"] = $row["cmp_comp"])
                $rowArray[$j][$fieldName] = mcArrIsSet($row, $fieldName);
            
                // Special cases for general treatment ...
                if ($fieldName == "cmp_modify_status") :     // companies (customers, couriers, etc.)
                   if ($rowArray[$j][$fieldName] == "" || $rowArray[$j][$fieldName] == "0") :
                      $rowArray[$j][$fieldName] = " ";
                   endif;
                   if ($rowArray[$j][$fieldName] == "1") :
                      $rowArray[$j][$fieldName] = ROW_EDIT_STATUS_NEW;
                   endif;                
                   if ($rowArray[$j][$fieldName] == "2") :
                      $rowArray[$j][$fieldName] = ROW_EDIT_STATUS_MODIFY;
                   endif;                
                endif;
            
                if ($fieldName == "crvh_modify_status") :    // vehicles
                   if ($rowArray[$j][$fieldName] == "" || $rowArray[$j][$fieldName] == "0") :
                      $rowArray[$j][$fieldName] = " ";
                   endif;
                   if ($rowArray[$j][$fieldName] == "1") :
                      $rowArray[$j][$fieldName] = " ";
                   endif;                
                   if ($rowArray[$j][$fieldName] == "2") :
                      $rowArray[$j][$fieldName] = " ";
                   endif;
                   if ($rowArray[$j][$fieldName] == "3") :
                      $rowArray[$j][$fieldName] = ROW_EDIT_STATUS_DELETE;
                   endif;
                endif;
            
                if ($fieldName == "crvh_special") :            // vehicles
                   if ($rowArray[$j][$fieldName] == "1") :
                      $rowArray[$j][$fieldName] = "X";
                   else :
                      $rowArray[$j][$fieldName] = " ";
                   endif;
                endif;
            
                if ($fieldName == "crvh_corporate_identity") : // vehicles (CI)
                   $tmpCI = $rowArray[$j][$fieldName];
                   $crvhCorporateIdentity = pad("G ", 60, " ");
                   if ($tmpCI != "" && is_numeric($tmpCI)) :
                      if (((int)$tmpCI & 15) == 1 || ((int)$tmpCI & 15) == 3) :
                         $crvhCorporateIdentity = "X" . substr($crvhCorporateIdentity, 1);
                      endif;
                      if (((((int)$tmpCI) / 16) & 15) == 1 || ((((int)$tmpCI) / 16) & 15) == 3) :
                         $crvhCorporateIdentity = substr($crvhCorporateIdentity, 0, 2) . "X" . substr($crvhCorporateIdentity, 3);
                      endif;
                   endif;
                   $rowArray[$j][$fieldName] = $crvhCorporateIdentity;
                endif;

                if ($f_exp_category == "2") :
                   if ($fieldName == "cmp_type") :            // company type of the courier
                      if ($rowArray[$j][$fieldName] == "1") :
                         $rowArray[$j][$fieldName] = "X";
                      else :
                         $rowArray[$j][$fieldName] = " ";
                      endif;
                   endif;
                endif;
            
                if ($fieldName == "cmp_bankmode") :          // companies
                   if ($rowArray[$j][$fieldName] == "" || $rowArray[$j][$fieldName] == "0") :
                      $rowArray[$j][$fieldName] = CMP_BANKMODE_INVOICE;
                   endif;
                   if ($rowArray[$j][$fieldName] == "1") :
                      $rowArray[$j][$fieldName] = CMP_BANKMODE_DEBITNOTE;
                   endif;                
                endif;
                
                // Customer invoice address (if one component (street or zipcode or city) is empty take complete address of the company)
                if ($f_exp_category == "1") :
                   if ($fieldName == "adre_street" || $fieldName == "cscad_hsno" || $fieldName == "adre_zipcode" || $fieldName == "adre_city") :
                      if (trim($rowArray[$j][$fieldName]) == "") :
                         $tmpMainadressOverrulesInvoiceaddress = TRUE;
                      endif;
                   endif;
                   if ($fieldName == "cscad_comp") :
                      if (trim($rowArray[$j][$fieldName]) == "") :
                         $tmpMainCompanynameOverrulesInvoiceCompanyname = TRUE;
                      endif;
                   endif;
                endif;
            
                if ($fieldName == "cash") :                  // jobs
                   if ($f_exp_category == "8") :
                      $rowArray[$j][$fieldName] = $paymentMethod;  // Like "  " or "BZ"
                   else :
                      $tmpJbCscIdPayer = $rowArray[$j][$fieldName];
                      if ($rowArray[$j][$fieldName] == "-1" || (CSC_ID_PAYER_CASH != "" && $rowArray[$j][$fieldName] == CSC_ID_PAYER_CASH)) :
                         $rowArray[$j][$fieldName] = JB_PAYMODE_CASH;
                      else :
                         $rowArray[$j][$fieldName] = "  ";
                      endif;
                   endif;
                endif;
            
                if ($f_exp_category == "8" && $fieldName == "jbpc_id") :   // Job payment collection ID
                    $rowArray[$j][$fieldName] = $jbpcId;
                endif;
            
                if ($fieldName == "tax_rate_sign") :         // jobs
                   global $hq_id;
                   if ($hq_id >= "100" && $hq_id < "300") :
                      if ($rowArray[$j][$fieldName] == "0" || $rowArray[$j][$fieldName] == "3" || $rowArray[$j][$fieldName] == "4") :
                         $rowArray[$j][$fieldName] = JB_TAX_RATE_SIGN;                   
                      else :
                         $rowArray[$j][$fieldName] = "  ";
                      endif;                
                   else :
                      if ($rowArray[$j][$fieldName] == "0") :
                         $rowArray[$j][$fieldName] = JB_TAX_RATE_SIGN;                   
                      else :
                         $rowArray[$j][$fieldName] = "  ";
                      endif;
                   endif;
                endif;
                if ($fieldName == "tx_id") :                 // companies
                   if ($rowArray[$j][$fieldName] == "2" || $rowArray[$j][$fieldName] == "3" || $rowArray[$j][$fieldName] == "5") :
                      if ($rowArray[$j][$fieldName] == "2") :
                         $rowArray[$j][$fieldName] = "03";
                      elseif ($rowArray[$j][$fieldName] == "5") :
                         $rowArray[$j][$fieldName] = "09";
                      else :
                         $rowArray[$j][$fieldName] = "04";
                      endif;
                   else :
                      $rowArray[$j][$fieldName] = "01";
                   endif;
                endif;
                if ($fieldName == "cmp_inv2hq") :            // jobs (invoice mode customer)
                   if ($rowArray[$j][$fieldName] == "1" || $rowArray[$j][$fieldName] == "3") :
                      $rowArray[$j][$fieldName] = "RZ";
                   else :
                      $rowArray[$j][$fieldName] = "  ";
                   endif;
                endif;
                if ($fieldName == "cmp_single_invoice") :    // jobs (invoice mode customer)
                   if ($rowArray[$j][$fieldName] == "2" || $rowArray[$j][$fieldName] == "3") :
                      $rowArray[$j][$fieldName] = "ER";
                   else :
                      $rowArray[$j][$fieldName] = "  ";
                   endif;
                endif;
                if ($fieldName == "jb_cr_filter_opt") :      // jobs (invoice mode single job, overrules invoice mode customer)
                   if (!(strpos($rowArray[$j][$fieldName], "RZ") === false)) :
                      $rowArray[$j]["cmp_inv2hq"] = "RZ";
                   endif;
                   if (!(strpos($rowArray[$j][$fieldName], "EZ") === false)) :
                      $rowArray[$j]["cmp_single_invoice"] = "ER";
                   endif;
            
                   if (!(strpos($rowArray[$j][$fieldName], ",BL,") === false)) :
                      $rowArray[$j]["price_special"] = "BL";
                   endif;
                endif;
                if ($fieldName == "jb_commission_no") :      // jobs commission numbers
                   if ($rowArray[$j][$fieldName] == "") :
                      $rowArray[$j][$fieldName] = $rowArray[$j]["tr_commission_no"];
                   endif;
                endif;

                if ($f_exp_category == "1") :  
                   if ($fieldName == "cmp_dsgvo") :
                      if ($rowArray[$j][$fieldName] == "1") :
                         $rowArray[$j][$fieldName] = "JA";
                      else :
                         $rowArray[$j][$fieldName] = "NEIN";
                      endif;
                   endif;
                   if ($fieldName == "cs_jbedit") :
                      if ($rowArray[$j][$fieldName] == "1") :
                         $rowArray[$j][$fieldName] = "JA";
                      else :
                         $rowArray[$j][$fieldName] = "NEIN";
                      endif;
                   endif;
                   if ($fieldName == "cs_payment_term") :
                      $rowArray[$j][$fieldName] = getFieldValueFromClause("metatype", "mt_value", "mt_type = 'payment_term' AND mt_sort = '" . $rowArray[$j][$fieldName] . "'");
                   endif;                   
                endif;

// ATTENTION: PROPRIETARY !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                if ($fieldName == "jbpc_mode") :    // Payment mode
                   // if ($rowArray[$j][$fieldName] == "0" || $rowArray[$j][$fieldName] == "") :
                   if ($rowArray[$j][$fieldName] == "0" || $rowArray[$j][$fieldName] == "1" || $rowArray[$j][$fieldName] == "2" || $rowArray[$j][$fieldName] == "10" || $rowArray[$j][$fieldName] == "") :
                      $rowArray[$j][$fieldName] = "BZ";
                   else :
                      $rowArray[$j][$fieldName] = "  ";
                   endif;
                endif;
            
                if ($fieldName == "cr_eid_parent") :    // jobs / vehicles (if courier works for another courier, set EID of the parent)
                   if ($rowArray[$j][$fieldName] != "") :
                      if ($f_exp_category == "3") :     // vehicles
                         $rowArray[$j]["cr_eid"] = $rowArray[$j][$fieldName];
                      else :                            // jobs
                         $rowArray[$j]["cr_eid"] = $rowArray[$j][$fieldName];
                      endif;
                   endif;
                endif;
                
                if ($fieldName == "usr_name") :              // user
                   if (trim($rowArray[$j][$fieldName]) == "Name" || is_numeric(trim($rowArray[$j][$fieldName]))) :
                      $rowArray[$j][$fieldName] = "                    ";
                   endif;
                endif;
                if ($fieldName == "usr_firstname") :         // user
                   if (trim($rowArray[$j][$fieldName]) == "Vorname" || is_numeric(trim($rowArray[$j][$fieldName]))) :
                      $rowArray[$j][$fieldName] = "               ";
                   endif;
                endif;             
                
                if ($f_exp_category == "6" && $fieldName == "price") :   // jobs (only "Gutschriften")
                   $jobPrice = $rowArray[$j][$fieldName];
                   if (is_numeric(str_replace (",", ".", $jobPrice)) && $jobPrice < 0) :
                      $rowArray[$j][$fieldName] = substr($rowArray[$j][$fieldName],1);
                   endif;
                endif;
            
                if ($f_exp_category == "8" && $fieldName == "price") :
                   if ($paymentMethod != JB_PAYMODE_CASH) :
                      $rowArray[$j][$fieldName] = 0;  // Special treatment: If payment method does NOT equal CASH ("bar") then set price to 0.00
                   endif;
                endif;
            
                if ($f_exp_category == "8" && $fieldName == "gross_price") :
                   if ($paymentMethod != JB_PAYMODE_CASH) :
                      $rowArray[$j][$fieldName] = 0;  // Special treatment: If payment method does NOT equal CASH ("bar") then set price to 0.00
                   endif;
                endif;
            
                if ($f_exp_category == "6" && $fieldName == "jb_subtotalprice") :   // jobs (only "Gutschriften")
                   $jobPrice = $rowArray[$j][$fieldName];
                   if (is_numeric(str_replace (",", ".", $jobPrice)) && $jobPrice < 0) :
                      $rowArray[$j][$fieldName] = substr($rowArray[$j][$fieldName],1);
                   endif;
                endif;
                
                if ($f_exp_category == "6" && $fieldName == "jb_cr_price") :   // jobs (only "Gutschriften")
                   $jobCrPrice = $rowArray[$j][$fieldName];
                   if (is_numeric(str_replace (",", ".", $jobCrPrice)) && $jobCrPrice < 0) :
                      $rowArray[$j][$fieldName] = substr($rowArray[$j][$fieldName],1);
                   endif;
                endif;
            
                if ($f_exp_category == "6" && $fieldName == "jb_cr_subprice") :   // jobs (only "Gutschriften")
                   $jobCrSubPrice = $rowArray[$j][$fieldName];
                   if (is_numeric(str_replace (",", ".", $jobCrSubPrice)) && $jobCrSubPrice < 0) :
                      $rowArray[$j][$fieldName] = substr($rowArray[$j][$fieldName],1);
                   endif;
                endif;

                if ($f_exp_category == "6" && $fieldName == "jb_hq_id_exec_price") :   // jobs (only "Gutschriften")
                   $jobHqIdExecPrice = $rowArray[$j][$fieldName];
                   if (is_numeric(str_replace (",", ".", $jobHqIdExecPrice)) && $jobHqIdExecPrice < 0) :
                      $rowArray[$j][$fieldName] = substr($rowArray[$j][$fieldName],1);
                   endif;
                endif;

                // Get potential mapping for cs_eid by parameter to replace it with another cs_eid
                /*
                if ($f_exp_category >= "4" && $f_exp_category <= "8") :
                   if ($fieldName == "cs_eid1") :
                      // Get service of the current job
                      $tmpJbService = (int)$rowArray[$j]["jb_service"];
                      if ($tmpJbService != "") :
                         $parJbServiceArray = array();
                         $csEid = $rowArray[$j][$fieldName];
                         // Check for existence in mapping array to avoid DB request
                         if ($csEidMappingArray[$csEid] == "") :
                            // Get cs_id of the current row
                            $tmpCsId = getFieldValueFromId("customer","cs_eid",$csEid,"cs_id");
                            if ($tmpCsId != "") :
                               // Get parameter if does exist for this cutomer
                               $parCsEidMapping = getParameterValue("0", "EXPORT_CSEID_MAPPING_" . $tmpCsId, "0");
                               if ($parCsEidMapping != "") :
                                  // Add cs_eid to array
                                  $csEidMappingArray[$csEid] == $parCsEidMapping;
                               endif;
                            endif;
                         else :
                            $parCsEidMapping = $csEidMappingArray[$csEid];
                         endif;
                         if ($parCsEidMapping != "") :
                            $parJbServiceArray = getKeyValueArrayFromString($parCsEidMapping);
                            // Get keys of the array
                            $tmpKeyArray = array_keys($parJbServiceArray);
                            $tmpKeyArrayLen = count($tmpKeyArray);
                            for ($m = 0; $m < $lenTmpArray; $m++) :
                               $tmpKey = (int)$tmpKeyArray[$m];
                               if (($tmpKey & $tmpJbService) == $tmpKey || $tmpKey = "99999") :
                                  // Set new cs_eid
                                  $rowArray[$j][$fieldName] = $parJbServiceArray[$tmpKeyArray[$m]];
                               endif;
                            endfor;
                         endif;
                      endif;
                   endif;
                endif;
                */
            
                // !!! HARDCODED !!! TO BE PUT INTO THE DATABASE !!!
                if ($fieldName == "vht_id") :          // jobs
                   $vhtIdTruck = getVhtId("7", "truck_01");
                   global $hq_id;
                   if ($hq_id >= "1" && $hq_id < "100" && $rowArray[$j][$fieldName] == "999") :    // Mandator "Stadtbote" AND vehicle type "Service" only !!!!
                      $rowArray[$j][$fieldName] = "K ";
                   else :
                      if ($rowArray[$j][$fieldName] >= $vhtIdTruck) :
                         $rowArray[$j][$fieldName] = "G ";
                      else :
                         $rowArray[$j][$fieldName] = "K ";
                      endif;
                   endif;
                endif;
                // !!! HARDCODED !!! TO BE PUT INTO THE DATABASE !!!
                if ($fieldName == "jb_type") :         // jobs
                   if ($rowArray[$j][$fieldName] != "" && $rowArray[$j][$fieldName] > "0") :
                      // if value "jb_type" does exist, change value for "vht_id" !!!
                      if ($rowArray[$j][$fieldName] == "1") : $rowArray[$j]["vht_id"] = "K "; endif;
                      if ($rowArray[$j][$fieldName] == "2") : $rowArray[$j]["vht_id"] = "G "; endif;
                      if ($rowArray[$j][$fieldName] == "3") : $rowArray[$j]["vht_id"] = "M1"; endif;
                      if ($rowArray[$j][$fieldName] == "4") : $rowArray[$j]["vht_id"] = "M3"; endif;
                      if ($rowArray[$j][$fieldName] == "5") : $rowArray[$j]["vht_id"] = "M4"; endif;
                      if ($rowArray[$j][$fieldName] == "6") : $rowArray[$j]["vht_id"] = "M5"; endif;
                      if ($rowArray[$j][$fieldName] == "7") : $rowArray[$j]["vht_id"] = "M6"; endif;
                      if ($rowArray[$j][$fieldName] == "8") : $rowArray[$j]["vht_id"] = "L "; endif;
                      if ($rowArray[$j][$fieldName] == "9") : $rowArray[$j]["vht_id"] = "G3"; endif;
                   endif;
                endif;
                // !!! HARDCODED !!! TO BE PUT INTO THE DATABASE !!!
                if ($fieldName == "jb_id_parent") :         // CALCULATOR jobs !!!!!!!!!!!!
                   global $hq_id;
                   if ($hq_id >= "1" && $hq_id < "100") :    // Only Stadtbote !!!
                      $tmpJobPrice = $row["price"];
                      if ($tmpJobPrice == "") : $tmpJobPrice = 0; endif;
                      $tmpJobPrice = str_replace (",", ".", $tmpJobPrice);
                      $tmpJobCrPrice = $row["jb_cr_price"];
                      if ($tmpJobCrPrice == "") : $tmpJobCrPrice = 0; endif;
                      $tmpJobCrPrice = str_replace (",", ".", $tmpJobCrPrice);
                      if ( ($rowArray[$j][$fieldName] != "" && ($rowArray[$j][$fieldName] == "-1" || $rowArray[$j][$fieldName] > "0")) ) :
                            // || (($rowArray[$j][$fieldName] == "0") && ($tmpJobPrice != $tmpJobCrPrice) && ($tmpJobCrPrice != 0))
                         // IF job is a calculator job OR job has jb_cr_price THEN expand status with "K" !!!
                         if ($rowArray[$j]["vht_id"] == "B ") : $rowArray[$j]["vht_id"] = "BK"; endif;
                         if ($rowArray[$j]["vht_id"] == "K ") : $rowArray[$j]["vht_id"] = "KK"; endif;
                         if ($rowArray[$j]["vht_id"] == "G ") : $rowArray[$j]["vht_id"] = "GK"; endif;
                      endif;
                   endif;
                endif;             
                
                if ($fieldName == "csc_id_root") :                  // jobs
                   $tmpCsCscIdRoot = $rowArray[$j][$fieldName];
                endif;
                
                if ($fieldName == "csc_inv_interval") :          // customers
                   if ($rowArray[$j][$fieldName] != "" && $rowArray[$j][$fieldName] >= "0" && $rowArray[$j][$fieldName] <= "4") : 
                      if ($rowArray[$j][$fieldName] == "0") : $rowArray[$j][$fieldName] = "9F"; endif;
                      if ($rowArray[$j][$fieldName] == "1") : $rowArray[$j][$fieldName] = "9W"; endif;
                      if ($rowArray[$j][$fieldName] == "2") : $rowArray[$j][$fieldName] = "9U"; endif;
                      if ($rowArray[$j][$fieldName] == "3") : $rowArray[$j][$fieldName] = "9T"; endif;
                      if ($rowArray[$j][$fieldName] == "4") : $rowArray[$j][$fieldName] = "9V"; endif;
                   else :
                      $rowArray[$j][$fieldName] = "9F"; 
                   endif;
                endif;

                if ($fieldName == "cmp_no") :            // Headquarters constants
                   global $hq_id;
                   if ($f_exp_category >= "4" && $f_exp_category <= "6") :
                      $hqIdSales = $row["hq_id_sales"];
                      $rowArray[$j][$fieldName] = getParameterValue("0", "EXPORT_HQ_KEY", $hqIdSales);
                      if ($rowArray[$j][$fieldName] == "") :
                         $rowArray[$j][$fieldName] = EXPORT_HQ_KEY;
                      endif;
                   else :
                      $rowArray[$j][$fieldName] = EXPORT_HQ_KEY;
                   endif;
                endif;

                if ($specialJbPayment == "4" && $fieldName == "jb_id") :
                   $specialPaymentCollectionId = getFieldValueFromClause("genericdatacontainer", "gdc_content", "gdc_obj_type = 'jb' AND gdc_obj_id = '" . $row["jb_id"] . "' AND gdc_gen_fieldname = 'collection_number'");
                   if ($specialPaymentCollectionId != "") :
                      $jbIdReal[$specialPaymentCollectionId] = $rowArray[$j][$fieldName];  // Remember real jb_id for updating job with export time
                      $rowArray[$j][$fieldName] = $specialPaymentCollectionId;
                   endif;
                endif;
            
                if ($f_exp_category == "8" && $fieldName == "special_price_01") :   // If cr_price contains provision the change fields
                   if ($row["csc_id_related"] == "17051" && $row["jb_id"] < 343544) :
                      $rowArray[$j]["special_price_01"] = $rowArray[$j]["jb_cr_price"];
                   endif;
                endif;
            
                if ($fieldName == "jb_toll") :
                   if (trim($rowArray[$j][$fieldName]) == "") :
                      $rowArray[$j][$fieldName] = "0.00";
                   elseif (!is_numeric($rowArray[$j][$fieldName])) :
                      $rowArray[$j][$fieldName] = str_replace (",", ".", $rowArray[$j][$fieldName]);
                      if (!is_numeric($rowArray[$j][$fieldName])) :
                         $rowArray[$j][$fieldName] = "0.00";
                      endif;
                   endif;
                   // if ($f_exp_category == "6") :   // jobs (only "Gutschriften")
                      if ($rowArray[$j][$fieldName] < 0) :
                         $rowArray[$j][$fieldName] = substr($rowArray[$j][$fieldName],1);
                      endif;
                   // endif;
                endif;
            
                if ($fieldName == "jb_third_country") :
                   $jbThirdCountry = trim($rowArray[$j][$fieldName]);
                   if (is_numeric($jbThirdCountry) && $jbThirdCountry > "0") :
                      $jbThirdCountry = "X";
                   else :
                      $jbThirdCountry = " ";
                   endif;
                   $rowArray[$j][$fieldName] = $jbThirdCountry;
                endif;

                if ($fieldName == "jb_longhaul") :
                   $jbLonghaul = trim($rowArray[$j][$fieldName]);
                   if (is_numeric($jbLonghaul) && $jbLonghaul == "1") :
                      $jbLonghaul = "X";
                   else :
                      $jbLonghaul = " ";
                   endif;
                   $rowArray[$j][$fieldName] = $jbLonghaul;
                endif;
                
                if ($fieldName == "jb_longhaul_export") :
                   $jbLonghaulExport = trim($rowArray[$j][$fieldName]);
                   if (is_numeric($jbLonghaulExport) && $jbLonghaulExport == "1") :
                      $jbLonghaulExport = "X";
                   else :
                      $jbLonghaulExport = " ";
                   endif;
                   $rowArray[$j][$fieldName] = $jbLonghaulExport;
                endif;
/*          
                if ($fieldName == "const_01") :          // headquarters constants
                   global $hq_id;
                   $rowArray[$j][$fieldName] = EXPORT_CONST_01;
                endif;
            
                if ($fieldName == "const_02") :          // headquarters constants
                   global $hq_id;
                   $rowArray[$j][$fieldName] = EXPORT_CONST_02;
                endif;
            
                if ($fieldName == "const_03") :          // headquarters constants
                   global $hq_id;
                   $rowArray[$j][$fieldName] = EXPORT_CONST_03;
                endif;
*/          
            endfor;
            
            // ONLY show the name of the costcenter if is not equal to the root costcenter
            if ($tmpJbCscIdPayer != "" && $tmpCsCscIdRoot != "" && $tmpJbCscIdPayer == $tmpCsCscIdRoot) :    // jobs ("cash" = "csc_id_payer")
               $rowArray[$j]["csc_name"] = "";
            endif;
            
            // Set address, if mainaddress has to overrule the invoiceaddress
            if ($tmpMainadressOverrulesInvoiceaddress) :
               $rowArray[$j]["adre_street"] = $rowArray[$j]["ad_street"];
               $rowArray[$j]["cscad_hsno"] = $rowArray[$j]["cmp_hsno"];
               $rowArray[$j]["adre_zipcode"] = $rowArray[$j]["ad_zipcode"];
               $rowArray[$j]["adre_city"] = $rowArray[$j]["ad_city"];
               $rowArray[$j]["adre_country"] = $rowArray[$j]["ad_country"];
            endif;
            
            // Set companyname, if main companyname has to overrule the invoice companyname
            if ($tmpMainCompanynameOverrulesInvoiceCompanyname) :
               $rowArray[$j]["cscad_comp"] = $rowArray[$j]["cmp_comp"];
               $rowArray[$j]["cscad_comp2"] = $rowArray[$j]["cmp_comp2"];
            endif;
            
            $j++;
         endif;  // $doContinue
   endwhile;

   return $rowArray;
};

// Returns a new associative array with a unique(!) key field specified in $keyField 
// and a second field ($sumField) containing the numeric value to be summed up grouped by $keyField.
// The keys have to be sorted in each array!!!
// $array1,$array2 : Array to be merged
// $keyField       : Field of the key
// $sumField       : Field of the value to be summed up
function array_merge_sum ($array1, $array2, $keyField, $sumField) {
  $retArray = "";

  $lenArray1 = count($array1);
  $lenArray2 = count($array2);

  if ($array1 == "") : return $array2; endif;
  if ($array2 == "") : return $array1; endif;

  $sum = 0;  
  $ptr1 = 0;
  $ptr2 = 0;
  $count = 0;    

  // Only summation of ONE field ($sumField) because there is no $keyField
  if ($keyField == "") :
     $tmpArray = array_merge($array1, $array2);
     $lenTmpArray = count($tmpArray);

     for ($i = 0; $i < $lenTmpArray; $i++) :
         $sum += $tmpArray[$i][$sumField];
     endfor;
     $retArray[0][$sumField] = $sum;
     return $retArray;
  endif;

  // There are values to be added by a group-criteria
  while ($ptr1 < $lenArray1 || $ptr2 < $lenArray2):
      
      if ($array1[$ptr1][$keyField] == "" || $array2[$ptr2][$keyField] == "") :      
         if ($array1[$ptr1][$keyField] == "") :
            $keyFieldValue = $array2[$ptr2][$keyField];
         else :
            $keyFieldValue = $array1[$ptr1][$keyField];
         endif;
      else :      
         if ($array1[$ptr1][$keyField] <= $array2[$ptr2][$keyField]) :
            $keyFieldValue = $array1[$ptr1][$keyField];
         else :
            $keyFieldValue = $array2[$ptr2][$keyField];
         endif;
      endif;

      while ($keyFieldValue != "" && $keyFieldValue == $array1[$ptr1][$keyField]):
            if ($array1[$ptr1][$sumField] != "" && is_numeric($array1[$ptr1][$sumField])) :
               $sum += $array1[$ptr1][$sumField];
            endif;
            $ptr1++;
      endwhile;

      while ($keyFieldValue != "" && $keyFieldValue == $array2[$ptr2][$keyField]):
            if ($array2[$ptr2][$sumField] != "" && is_numeric($array2[$ptr2][$sumField])) :
               $sum += $array2[$ptr2][$sumField];
            endif;
            $ptr2++;
      endwhile;          

      if ($keyFieldValue != "") :
         $retArray[$count][$keyField] = $keyFieldValue;
         $retArray[$count][$sumField] = $sum;
      endif;

      $count++;
      $sum = 0;      
  endwhile;

  return $retArray;
};


// Returns a new associative array with a unique(!) key field specified in $keyField 
// and a second field ($sumField) containing the numeric value to be summed up grouped by $keyField.
// The keys have to be sorted in each array!!!
// $array1,$array2 : Array to be merged
// $keyFieldArray  : Array of fields grouping the key
// $sumField       : Field of the value to be summed up
function array_merge_sum2 ($array1, $array2, $keyFieldArray, $sumField) {
  $retArray = "";

  $lenArray1 = count($array1);
  $lenArray2 = count($array2);

  if ($array1 == "") : return $array2; endif;
  if ($array2 == "") : return $array1; endif;

  $lenKeyFieldArray = count($keyFieldArray);
  $sum = 0;  
  $ptr1 = 0;
  $ptr2 = 0;
  $count = 0;    

  // Only summation of ONE field ($sumField) because there is no $keyField
  if ($keyFieldArray == "") :
     $tmpArray = array_merge($array1, $array2);
     $lenTmpArray = count($tmpArray);
     for ($i = 0; $i < $lenTmpArray; $i++) :
         $sum += $tmpArray[$i][$sumField];
     endfor;
     $retArray[0][$sumField] = $sum;
     return $retArray;
  endif;

  // There are values to be added by a group-criteria
  while ($count < ($lenArray1 + $lenArray2) && ($ptr1 < $lenArray1 || $ptr2 < $lenArray2)):
      
      $groupKey1 = "";
      $groupKey2 = "";
      for ($i = 0; $i < $lenKeyFieldArray; $i++) :
          $groupKey1 .= $array1[$ptr1][$keyFieldArray[$i]];
          $groupKey2 .= $array2[$ptr2][$keyFieldArray[$i]];
      endfor;

      if ($groupKey1 == "" || $groupKey2 == "") :
         if ($groupKey1 == "") :
            $keyFieldValue = $groupKey2;
         else :
            $keyFieldValue = $groupKey1;
         endif;
      else :      
         if ($groupKey1 <= $groupKey2) :
            $keyFieldValue = $groupKey1;
         else :
            $keyFieldValue = $groupKey2;
         endif;
      endif;

      $keyFieldValue2 = "";
      for ($i = 0; $i < $lenKeyFieldArray; $i++) :
          $keyFieldValue2 .= $array1[$ptr1][$keyFieldArray[$i]];
      endfor;
      while ($keyFieldValue != "" && $keyFieldValue == $keyFieldValue2):

            if ($array1[$ptr1][$sumField] != "" && is_numeric($array1[$ptr1][$sumField])) :
               $sum += $array1[$ptr1][$sumField];
            endif;
            
            for ($i = 0; $i < $lenKeyFieldArray; $i++) :
                $retArray[$count][$keyFieldArray[$i]] = $array1[$ptr1][$keyFieldArray[$i]];
            endfor;
                        
            $ptr1++;
            
            $keyFieldValue2 = "";
            for ($i = 0; $i < $lenKeyFieldArray; $i++) :
                $keyFieldValue2 .= $array1[$ptr1][$keyFieldArray[$i]];
            endfor;
      endwhile;

      $keyFieldValue2 = "";
      for ($i = 0; $i < $lenKeyFieldArray; $i++) :
          $keyFieldValue2 .= $array2[$ptr2][$keyFieldArray[$i]];
      endfor;
      while ($keyFieldValue != "" && $keyFieldValue == $keyFieldValue2):

            if ($array2[$ptr2][$sumField] != "" && is_numeric($array2[$ptr2][$sumField])) :
               $sum += $array2[$ptr2][$sumField];
            endif;
            
            for ($i = 0; $i < $lenKeyFieldArray; $i++) :
                $retArray[$count][$keyFieldArray[$i]] = $array2[$ptr2][$keyFieldArray[$i]];
            endfor;
            
            $ptr2++;

            $keyFieldValue2 = "";
            for ($i = 0; $i < $lenKeyFieldArray; $i++) :
                $keyFieldValue2 .= $array2[$ptr2][$keyFieldArray[$i]];
            endfor;
      endwhile;          

      if ($keyFieldValue != "") :
         // $retArray[$count][$keyField] = $keyFieldValue;
         $retArray[$count][$sumField] = $sum;
      endif;

      $count++;
      $sum = 0;      
  endwhile;

  return $retArray;
};
?>