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

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


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

getSecHttpVars("1",array("f_act", "dbhistory", "day_from", "month_from", "year_from", "day_to", "month_to", "year_to",
                         "hour_from", "minute_from", "hour_to", "minute_to",
                         "f_category", "f_statistic", "f_sort", "f_direction_sort", "g_cs_eid", "g_cr_eid", "g_crvh_filter",
                         "f_statusMode", "f_editCsMode", "f_priceMode", "f_dateMode", "f_showDateAndTime", "f_hq_id", "f_numOfIntervals", "f_price_formular",
                         "f_filter", "f_filter2", "f_filter3", "f_filter4", "f_filter5", "f_filter6", "f_filter7", "f_filter8", 
                         "f_filter9", "f_filter10", "f_filter11", "f_filter12", "f_filter13", "f_filter14", "f_filter_calc", "f_filter_a", "f_filter_interval", 
                         "f_show_invoice_address", "f_show_delivery_address", "f_show_master_data", "f_bookedJobsOnly", "f_permanentJobsOnly",
                         "f_cs_meta", "f_cr_meta", "f_cr_parent", "f_cr_pda_actions", "f_crvh_sid", "f_jb_service", 
                         "f_split_jb_services", "f_jb_specifics", "f_cmp_new_date_month", "f_cmp_new_date_year", 
                         "f_cs_become_cs_date_month", "f_cs_become_cs_date_year", "f_service", "f_servicetype", 
                         "f_filter_jb_weight_from", "f_filter_jb_length_from", "f_filter_jb_width_from", "f_filter_jb_height_from", "f_filter_jb_position_from", 
                         "f_filter_jb_weight_to", "f_filter_jb_length_to", "f_filter_jb_width_to", "f_filter_jb_height_to", "f_filter_jb_position_to", 
                         "cscIdRoot", "customerId", "cscIdActual", "f_net_gross", "outputTitle", "outputColumnMode", 
                         "noStatisticMenu", "specialAligns", "fileOutput", "f_group", "f_staticGroup", "f_type_chart"));


$usrAccessArray["hq"] = "1"; $usrAccessArray["cs"] = "1";
authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
authCheckEmployeeRights($emp_id, "8", "1");


// *******************
// * Initialisations *
// *******************

// Include the modules for 
// - generating the category-dbfields
// - converting result of database search to array
// - defining the SQL-SELECT-statements
include_once ("../include/inc_category_dbfields.inc.php");
include_once ("../include/inc_dbfields2array.inc.php");
include_once ("../include/inc_group.inc.php");
include_once ("../statistic/statistic_sql.inc.php");
$pageTitel = "STATISTIK";
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");


// Special initialization for CUSTOMERS ACCESS
if ($userTypeName == "cs") :
   $f_category = "3";
   $g_cs_eid = getFieldValueFromId("customer","cs_id",$customerId,"cs_eid");
   $f_dateMode = "2";
   $f_statusMode = "1";
   $f_editCsMode = "0";
   $f_priceMode = "0";
   
   // Get status of the customer according to being meta customer
   $isMeta = "0";
   if (existsEntry("customer",array("cs_id_parent",$customerId))) : $isMeta = "1"; endif;
endif;

// Get parameter for global usage of the "related customer"
$parGlobalUseRelatedCustomer = getParameterValue("0", "GLOBAL_USE_RELATED_CUSTOMER", "0");

// Check for displaying ALL VALUES
$statisticAllValues = false;
if ($f_priceMode == "19") : $statisticAllValues = true; endif;
if ($statisticAllValues) :
   // Init some filter regarding this mode
   if ($f_numOfIntervals != "" && $f_numOfIntervals > "0") :
      $f_numOfIntervals = "0";  // No comparison regarding all fields
      $statusMessage = "Ein Vergleich steht bei der Aufstellung aller Werte nicht zur Verfügung!";
   endif;
endif;

// Initialize the http-values
if ($f_category == "") : $f_category = "0"; endif;               // statistic-category (courier, job, ...)
if ($f_statistic == "") : $f_statistic = "0"; endif;             // statistic-mode (all jobs, jobs monthly, jobs monthly per courier, ...)
if ($f_filter_calc == "" || count($f_filter_calc) == 0) : $f_filter_calc = "0"; else: $f_filter_calc = "1"; endif;  // Filter (Split for job calculator)
$f_mode_statistic = "0";
if ($f_filter_calc == "1" ||
    ($f_statistic >= "101" && $f_statistic <= "104") ||
    ($f_statistic >= "201" && $f_statistic <= "204") ||
    ($f_statistic >= "301" && $f_statistic <= "309")) :          // Statistic based on "Preis-/Leistungstypen"
   if (!$statisticAllValues) :
      $f_mode_statistic = "1";
   else :
      $statusMessage = "Diese Statistik steht nicht für die Darstellung aller Werte zur Verfügung!";
   endif;
endif;   
if ($f_service == "") : $f_service = "0"; endif;                 // Service for "service statistic"
if ($f_servicetype == "") : $f_servicetype = "0"; endif;         // Servicetype for "service statistic"
if ($f_sort == "") : $f_sort = "0"; endif;      		             // ORDER BY column "$fieldSortArray[$f_sort]"
if ($f_direction_sort == "") : $f_direction_sort = "0"; endif;   // ORDER BY ASC or DESC"
if ($g_cs_eid == "") : $g_cs_eid = ""; endif;                    // statistic only for a special customer
if ($g_cr_eid == "") : $g_cr_eid = ""; endif;                    // statistic only for a special courier
if ($f_showDateAndTime == "") : $f_showDateAndTime = "0"; endif; // Show the clock time fields [default "NO"]
if ($f_price_formular == "") : $f_price_formular = "0"; endif;   // Computation of the price
$filterAlignOffset = 0;                                          // Activating more filters will change the column
if ($f_filter == "") : $f_filter = "0"; endif;                   // Filter (Split for vehicletype, start zipcode, etc.)
if ($f_filter_a == "") : $f_filter_a = "0"; endif;               // Subfilter to $f_filter (Kind of vehicletype [Requested or real])
if ($f_filter2 == "") : $f_filter2 = "0"; endif;                 // Filter (Split for "Aufträge und Gutschriften")
if ($f_filter3 == "") : $f_filter3 = "0"; endif;                 // Filter (Split for "Fahrzeugkategorie" ["jb_type"])
if ($f_filter4 == "" || count($f_filter4) == 0) : $f_filter4 = "0"; else: $f_filter4 = "1"; endif;  // Filter (Split for headquarters)
if ($f_filter5 == "" || count($f_filter5) == 0) : $f_filter5 = "0"; else: $f_filter5 = "1"; endif;  // Filter (Split for branches)
if ($f_filter6 == "" || count($f_filter6) == 0) : $f_filter6 = "0"; else: $f_filter6 = "1"; endif;  // Filter (Split for carriers [ONLY customer statistics])
if ($f_filter7 == "" || count($f_filter7) == 0) : $f_filter7 = "0"; else: $f_filter7 = "1"; endif;  // Filter (Split for vehicles)
if ($f_filter8 == "" || count($f_filter8) == 0) : $f_filter8 = "0"; else: $f_filter8 = "1"; endif;  // Filter (Split for employees)
if ($f_filter9 == "" || count($f_filter9) == 0) : $f_filter9 = "0"; else: $f_filter9 = "1"; endif;  // Filter (Split for job types ["jb_type"])
if ($f_filter10 == "") : $f_filter10 = "0"; endif;               // Filter (Split for costcenter ["csc_id_payer" / "csc_id_related"])
if ($f_filter11 == "" || count($f_filter11) == 0) : $f_filter11 = "0"; else: $f_filter11 = "1"; endif;  // Filter (Split for customers [ONLY carrier statistics])
if ($f_filter12 == "" || count($f_filter12) == 0) : $f_filter12 = "0"; else: $f_filter12 = "1"; endif;  // Filter (Split for partner provision)
if ($f_filter13 == "" || count($f_filter13) == 0) : $f_filter13 = "0"; else: $f_filter13 = "1"; endif;  // Filter (Split for system fee) [Presently no split, only joined !!!!]
if ($f_filter14 == "" || count($f_filter14) == 0) : $f_filter14 = "0"; else: $f_filter14 = "1"; endif;  // Filter (Split for advertising allowance) [Presently no split, only joined !!!!]

// Measures
if ($f_filter_jb_weight_from == "" || !is_numeric($f_filter_jb_weight_from) || $f_filter_jb_weight_from < 0) : $f_filter_jb_weight_from = ""; endif;  // Filter job weight lower range
if ($f_filter_jb_length_from == "" || !is_numeric($f_filter_jb_length_from) || $f_filter_jb_length_from < 0) : $f_filter_jb_length_from = ""; endif;  // Filter job length lower range
if ($f_filter_jb_width_from == "" || !is_numeric($f_filter_jb_width_from) || $f_filter_jb_width_from < 0) : $f_filter_jb_width_from = ""; endif;  // Filter job width lower range
if ($f_filter_jb_height_from == "" || !is_numeric($f_filter_jb_height_from) || $f_filter_jb_height_from < 0) : $f_filter_jb_height_from = ""; endif;  // Filter job height lower range
if ($f_filter_jb_position_from == "" || !is_numeric($f_filter_jb_position_from) || $f_filter_jb_position_from < 0) : $f_filter_jb_position_from = ""; endif;  // Filter job position lower range
if ($f_filter_jb_weight_to == "" || !is_numeric($f_filter_jb_weight_to) || $f_filter_jb_weight_to < 0) : $f_filter_jb_weight_to = ""; endif;  // Filter job weight upper range
if ($f_filter_jb_length_to == "" || !is_numeric($f_filter_jb_length_to) || $f_filter_jb_length_to < 0) : $f_filter_jb_length_to = ""; endif;  // Filter job length upper range
if ($f_filter_jb_width_to == "" || !is_numeric($f_filter_jb_width_to) || $f_filter_jb_width_to < 0) : $f_filter_jb_width_to = ""; endif;  // Filter job width upper range
if ($f_filter_jb_height_to == "" || !is_numeric($f_filter_jb_height_to) || $f_filter_jb_height_to < 0) : $f_filter_jb_height_to = ""; endif;  // Filter job height upper range
if ($f_filter_jb_position_to == "" || !is_numeric($f_filter_jb_position_to) || $f_filter_jb_position_to < 0) : $f_filter_jb_position_to = ""; endif;  // Filter job position upper range

if ($f_bookedJobsOnly == "") : $f_bookedJobsOnly = "0"; endif;   // Filter (With or without booked jobs)
if ($f_permanentJobsOnly == "") : $f_permanentJobsOnly = "0"; endif;   // Filter (With or without permanent jobs)
if ($f_cs_meta == "") : $f_cs_meta = "0"; endif;                 // Filter (Split for sub customers ["meta-customer"])
if ($f_cr_meta == "") : $f_cr_meta = "0"; endif;                 // Filter (Split for driver)
if ($f_cr_parent == "") :                                        // Every courier or driver OR cumulation by parent
   $f_cr_parent = "0";
   if ($parGlobalUseRelatedCustomer == "1") :
      $f_cr_parent = "2";
   endif;
endif;
if ($f_cr_pda_actions == "") : $f_cr_pda_actions = "0"; endif;   // Filter for courier action statistics (absolute/relative per job)
if ($f_crvh_sid == "") : $f_crvh_sid = ""; endif;                // Filter for vehicles (special SID)
if ($f_numOfIntervals == "") : $f_numOfIntervals = "0"; endif;   // Filter (Number of intervals to be compared)
if ($f_filter_interval == "") : $f_filter_interval = "0"; endif; // Filter (Split for time intervals)
if ($f_show_invoice_address == "" || count($f_show_invoice_address) == 0) : $f_show_invoice_address = "0"; else: $f_show_invoice_address = "1"; endif;      // Switch to show invoice address data (from root costcenter) for displayed customers or couriers
if ($f_show_delivery_address == "" || count($f_show_delivery_address) == 0) : $f_show_delivery_address = "0"; else: $f_show_delivery_address = "1"; endif;  // Switch to show delivery address data (from root costcenter) for displayed customers or couriers
if ($f_show_master_data == "" || count($f_show_master_data) == 0) : $f_show_master_data = "0"; else: $f_show_master_data = "1"; endif;  // Switch to show master data for displayed customers or couriers

if ($f_split_jb_services == "" || count($f_split_jb_services) == 0) : $f_split_jb_services = "0"; else: $f_split_jb_services = "1"; endif;  // Filter (Split for job services)
if ($f_net_gross == "") :                                        // Business volume output in net or gross
   $f_net_gross = "0";
   if ($parGlobalUseRelatedCustomer == "1") :
      // $f_net_gross = "1";
   endif;
endif;
if ($f_type_chart == "") : $f_type_chart = "0"; endif;           // Chart output ("0" = no output)

if (!isset($station_based_group_field)) : $station_based_group_field = ""; endif;  // Special group statistic, e.g. station mode, overwriting job based statements
if ($f_filter == "7") :
   $station_based_group_field = "ad.ad_zipcode";
endif;


$f_cmp_new_date = "";                                            // Filter (Only new data set since date)
if ($f_cmp_new_date_month != "" && $f_cmp_new_date_year != "") :
   $f_cmp_new_date = $f_cmp_new_date_year . "-" . pad($f_cmp_new_date_month,2) . "-01 00:00:00";
endif;

$f_cs_become_cs_date = "";                                            // Filter (Only new customers since date)
if ($f_cs_become_cs_date_month != "" && $f_cs_become_cs_date_year != "") :
   $f_cs_become_cs_date = $f_cs_become_cs_date_year . "-" . pad($f_cs_become_cs_date_month,2) . "-01 00:00:00";
endif;


if ($fileOutput == "1") : 
   $fileOutput = true; 
else : 
   $fileOutput = false;
endif;

// Groups used as filter
if ($f_group == "") : $f_group = array(); endif;
$f_groupLen = count($f_group);

// Static groups used as filter
if ($f_staticGroup == "") : $f_staticGroup = array(); endif;
$f_staticGroupLen = count($f_staticGroup);

// Job services used as filter
if ($f_jb_service == "") : $f_jb_service = array(); endif;
$f_jb_serviceLen = count($f_jb_service);

// Job specifics used as filter
if ($f_jb_specifics == "") : $f_jb_specifics = array(); endif;
$f_jb_specificsLen = count($f_jb_specifics);

// State of the jobs
if ($f_statusMode == "") :
   $f_statusMode = "1";   // Init to "finished jobs" by default
endif;

// Jobs created by customer or headquarters
if ($f_editCsMode == "") :
   $f_editCsMode = "0";   // Init to "all jobs" by default
endif;


// Hide selection for creation date a customer row had been inserted independend from state (customer, prospect, etc.)
$constDisplayCreationDateDisabled = getParameterValue("0", "MASK_STATISTIC_CS_CREATE_DATE_DISABLED", $hq_id);
if ($constDisplayCreationDateDisabled == "") : $constDisplayCreationDateDisabled = getParameterValue("0", "MASK_STATISTIC_CS_CREATE_DATE_DISABLED", "0"); endif;

// Switch to display options to select the date mode
$constDisplayPriceMode = getParameterValue("0", "MASK_STATISTIC_PRICE_MODE", $hq_id);
if ($constDisplayPriceMode == "") : $constDisplayPriceMode = getParameterValue("0", "MASK_STATISTIC_PRICE_MODE", "0"); endif;

// Parameter for displaying survey
$constMaskStationsSurvey = getParameterValue("0", "MASK_STATISTIC_STATIONS_SURVEY", $hq_id);
if ($constMaskStationsSurvey == "") : $constMaskStationsSurvey = getParameterValue("0", "MASK_STATISTIC_STATIONS_SURVEY", "0"); endif;

// Price type
if ($f_priceMode == "") :
   $f_priceMode = "0";   // Init to business volume
endif;
// Array for output only, e.g. the options of the select box
// $priceModeOutArr = array(getLngt("Auftragswert"),getLngt("Frachtvergütung"),getLngt("EAU"),getLngt("BSG [%]"),getLngt("Servicepreis"),getLngt("Manuelle Servicevergütung"),getLngt("Automatische Servicevergütung"),getLngt("Manuelle Frachtvergütung"),"","","",getLngt("KM"),getLngt("CO2äq/kg"));
// $priceModeOutArr = array(getLngt("Auftragswert"),getLngt("Frachtvergütung"),getLngt("EAU"),getLngt("BSG [%]"),getLngt("Servicepreis"),getLngt("Manuelle Servicevergütung"),"","","","","",getLngt("KM"),getLngt("CO2äq/kg"));
$priceModeOutArr = array(getLngt("Auftragswert"),getLngt("Frachtvergütung"),getLngt("EAU"),getLngt("BSG [%]"),getLngt("Servicepreis"),getLngt("Manuelle Servicevergütung"),"","","","","",getLngt("KM"),getLngt("CO2äq/kg"),"","","","","","","ALLE WERTE");

// Statistic base (criteria for grouping)
if ($f_dateMode == "") :                                         // "creating date", "booking date", "finish date" [default], "export date", "order_date"
   $f_dateMode = getParameterValue("0", "STATISTIC_DATE_MODE", $hq_id);
   if ($f_dateMode == "") :
      $f_dateMode = "3";    // Export date
      // $f_statusMode = "1";  // For exported jobs the filter has to be set to done jobs
      // $f_editCsMode = "0";
   endif;
endif;

// Switch to display options to select the date mode
$constDisplayDateMode = getParameterValue("0", "MASK_STATISTIC_DATE_MODE", $hq_id);

// Switch to activate functionality according to intervals to be compared
// and number of intervals to be displayed
$constIntervalsEnabled = getParameterValue("0", "STATISTIC_INTERVALS_ENABLED", "0");
$constIntervalsNumOf = getParameterValue("0", "STATISTIC_INTERVALS_NUMBER_OF", "0");
$numOfIntervalIters = $f_numOfIntervals + 1;
$numOfSummationCols = 2;         // Default = 2 because of "number of jobs" and "netto business volume"
$showColMarkup = false;
if ($f_price_formular == "3") :  // With markup
   $numOfSummationCols++;
   $showColMarkup = true;
endif;
if ($station_based_group_field != "") :
   $numOfSummationCols = 1;  // Column "business volume" will not be computed and summated
endif;

// Mandator filter
if ($f_hq_id == "") : $f_hq_id = array(); endif;
if (count($f_hq_id) == 0) : array_push($f_hq_id, $hq_id); endif;

// Filter
/*
$f_split_vehicletype = "";
if ($f_filter != "") :
   if (!(array_search("split_vehicletype",$f_filter) === FALSE)) : $f_split_vehicletype = "1"; endif;
   // if (!(array_search("job_future",$f_filter) === FALSE)) : $filter_job_future = "checked"; endif;
endif;
*/

// Initialize other values
$idArray = array();
$fieldArray = array();
$titleArray = array();
$fieldSqlArray = array();
$fieldSortArray = array();
$supersetFieldString = "";
$aligns = "";
$output = "";
$summationField  = "";  $summationField2 = "";  $summationField3 = "";
$summationField4 = "";  $summationField5 = "";  $summationField6 = "";
$summationField7 = "";  $summationField8 = "";  $summationField9 = "";
$summationFieldArray = array();
$summationFieldArray2 = array();
$summationFieldArray3 = array();
$uniqueSearchFields = array();
$uniqueSearchFieldsPRE = array();   // Attention "...PRE" means pre-definitions added to $uniqueSearchFields !!!
mcIsSet($mode, "2");  // Output from MATRIX as table per default
$tableHeader = "";
$tableBody = "";
$posOfLastSummationField = 0;

// Check ranges of time. All fields have to be set
if ($f_showDateAndTime == "0" || $hour_from == "" || $minute_from == "" || $hour_to == "" || $minute_to == "") :
    $hour_from = "00";
    $minute_from = "00";
    $hour_to = "23";
    $minute_to = "59";
    $f_showDateAndTime == "0";
endif;
$hour_from = pad($hour_from,2);
$minute_from = pad($minute_from,2);
$hour_to = pad($hour_to,2);
$minute_to = pad($minute_to,2);

// Time range
$fromTimeRange = " " . $hour_from . ":" . $minute_from . ":00";
$toTimeRange = " " . $hour_to . ":" . $minute_to . ":59";

// Check ranges of date. All fields have to be set
if ($day_from == "" || $month_from == "" || $year_from == "" || 
    $day_to == "" || $month_to == "" || $year_to == "") :

    // Initialize date-ranges to the current date
    $fromDateRange = getDateTime("3") . $fromTimeRange;
    $toDateRange = getDateTime("3") . $toTimeRange;
    
    $day_from = getDateTime("day");
    $month_from = getDateTime("month");
    $year_from = getDateTime("year");
    $day_to = getDateTime("day");
    $month_to = getDateTime("month");
    $year_to = getDateTime("year");
else :
    $fromDateRange = $year_from . "-" . pad($month_from,2) . "-" . pad($day_from,2) . $fromTimeRange;
    $toDateRange = $year_to . "-" . pad($month_to,2) . "-" . pad($day_to,2) . $toTimeRange;
endif;

/*
echo "year_from: " . $year_from . "<br>";
// Get the year of the begin of history data
$dbhistory = getDBNames($dbhistory, $year_from);
echo "dbhistory: " . $dbhistory . "<br>";
$remDbHistory = $dbhistory;
$constYearOfBeginHistory = getParameterValue("0", "STATISTIC_YEAR_OF_BEGIN_HISTORY", "0");
if ($dbhistory == "1" || !is_numeric($constYearOfBeginHistory) || $constYearOfBeginHistory >= getDateTime("year")) :
   $constYearOfBeginHistory = "";
endif;
echo "constYearOfBeginHistory: " . $constYearOfBeginHistory . "<br>";
echo "dbh_jb: " . $dbh_jb . "<br>";
*/

// Get the year of the begin of history data
$dbhistory = "0";
// echo "dbhistory: " . $dbhistory . "<br>";
$dbhistory = getDBNames($dbhistory, $year_from);
// echo "dbhistory: " . $dbhistory . "<br>";
$constYearOfBeginHistory = getParameterValue("0", "STATISTIC_YEAR_OF_BEGIN_HISTORY", "0");
if ($dbhistory == "0" && is_numeric($constYearOfBeginHistory) && $year_from <= $constYearOfBeginHistory) :
   $dbhistory = "1";
   $dbhistory = getDBNames($dbhistory, $year_from);
endif;
$remDbHistory = $dbhistory;
// echo "year_from: " . $year_from . "<br>";
// echo "dbhistory: " . $dbhistory . "<br>";
// echo "constYearOfBeginHistory: " . $constYearOfBeginHistory . "<br>";
// echo "dbh_jb: " . $dbh_jb . "<br>";

// Wording for title amount field
$titleFieldToBeChanged = "Nettobetrag";
$titleFieldNewValue = "Nettobetrag" . "&nbsp;[&euro;]";
if ($f_priceMode == "3") : 
   $titleFieldNewValue = "BSG" . "&nbsp;[%]";
elseif ($f_priceMode == "11") : 
   $titleFieldNewValue = "KM";
elseif ($f_priceMode == "12") : 
   $titleFieldNewValue = "CO2äq/kg";
elseif ($f_priceMode == "19") : 
   $titleFieldNewValue = "Alle Werte";
endif;

function postParseStatisticDetails ($textToParse) {
	global $f_category;
  $textToParse = trim($textToParse);
  if ($textToParse != "") :  
     // Iterate ALL occurrences of "<postparser>...</postparser>"          
     while (!(strpos($textToParse, "<postparser>") === FALSE)) {
        $beginTagPosBegin = strpos($textToParse, "<postparser>");
        $beginTagPosEnd = $beginTagPosBegin + 12;
        $endTagPosBegin = strpos($textToParse, "</postparser>");
        $endTagPosEnd = $endTagPosBegin + 13;
        if ($beginTagPosEnd < $endTagPosBegin) :
           $tagContent = substr($textToParse, $beginTagPosEnd, $endTagPosBegin - $beginTagPosEnd);
           if ($tagContent != "") :
              // Special treatment
              if ($f_category == "3") :
                 $tmpCmpId = getFieldValueFromId("customer","cs_eid",$tagContent,"cmp_id");
                 if ($tmpCmpId != "" && is_numeric($tmpCmpId)) :
                    $tagContent = "<a href=\"../admin/customer_special.php?companyId=" . ec($tmpCmpId) . "\" target=\"_blank\">" . $tagContent . "</a>";
                 endif;
              elseif ($f_category == "2") :
                 $tmpCmpId = getFieldValueFromId("courier","cr_eid",$tagContent,"cmp_id");
                 if ($tmpCmpId != "" && is_numeric($tmpCmpId)) :
                    $tagContent = "<a href=\"../admin/courier_special.php?companyId=" . ec($tmpCmpId) . "\" target=\"_blank\">" . $tagContent . "</a>";
                 endif;
              endif;
           endif;
           // Substitute text fragment
           $textToParse = substr_replace($textToParse, $tagContent, $beginTagPosBegin, $endTagPosEnd - $beginTagPosBegin);
        endif;
      }
  endif;
  return $textToParse;  
}



// ***************************
// * Calculate the statistic *
// ***************************
if ($f_act == "calculate") :

   if ($f_category != "" && $f_category > "0" && $f_statistic != "" && $f_statistic > "0") :

      // Get the array for formatting the database-values for the output according to the defined type
      $outputFormatField = defineOutputFormats($outputColumnMode);

      // Get category field data and set global fields: $idArray, $fieldArray, $titleArray, $fieldSortArray
      // Map some statistics to existing category fields
      // Further check combinations of categories and filter being consistent (!!!)
      // ***
      $f_statistic_tmp = $f_statistic;
      if ($f_statistic >= "1000" && $f_statistic <= "1099") : 
         $f_statistic_tmp = "1000";
         $numOfSummationCols = 2;
      else :
         if ($f_cr_pda_actions != "0") :
            $f_cr_pda_actions = "0";
            $statusMessage = "Diese Statistik ist nicht zu kombinieren mit dem Filter für Mehrfachaktionen!";
         endif;
      endif;
      // Mapping exportcategoryfields from "normal statistic" to "service statistic"
      // , 3020 => 60, 3021 => 61, 3010 => 10, 3011 => 11, 3012 => 12, 3000 => 30, 3001 => 31, 3002 => 32
      $stmNumberArrayTmp = array(101 => 30, 102 => 31, 103 => 32, 104 => 33, 105 => 34, 201 => 10, 202 => 11, 203 => 12, 204 => 13, 205 => 14, 301 => 60, 302 => 61, 303 => 62, 304 => 63, 305 => 64);
      if (($f_statistic >= 101 && $f_statistic <= 109) || 
          ($f_statistic >= 201 && $f_statistic <= 209) || 
          ($f_statistic >= 301 && $f_statistic <= 309)) : 
         $f_statistic_tmp = $stmNumberArrayTmp[$f_statistic];
      endif;
      $idArrayLen = getCategoryDBFields($f_statistic_tmp);

      $aligns = getFieldValueFromId("exportcategory","expc_id",$f_statistic,"expc_aligns");
      $alignArray = spliti(",",$aligns);

      if ($f_statistic == "15" || $f_statistic == "16" || $f_statistic == "17" || $f_statistic == "18") : 
         $numOfSummationCols = 1;
      endif;

      if ($f_statistic == "15" || $f_statistic == "16" || $f_statistic == "17" || $f_statistic == "18" || $f_statistic == "2000" || $f_statistic == "2010") :

         if ($f_filter != "0" || $f_filter4 != "0" || $f_filter5 != "0" || $f_filter6 != "0" || $f_filter7 != "0" || 
             $f_filter8 != "0" || $f_filter9 != "0" || $f_filter10 != "0" || $f_filter11 != "0" || $f_filter12 != "0" || $f_filter13 != "0" || $f_filter14 != "0" || $f_filter_calc != "0" || $f_filter_interval != "0") :
            $f_filter = "0";
            $f_filter4 = "0";
            $f_filter5 = "0";
            $f_filter6 = "0";
            $f_filter7 = "0";
            $f_filter8 = "0";
            $f_filter9 = "0";
            $f_filter10 = "0";
            $f_filter11 = "0";
            $f_filter12 = "0";
            $f_filter13 = "0";
            $f_filter14 = "0";
            $f_filter_calc = "0";
            $f_filter_interval = "0";
            $statusMessage = "Diese Statistik ist nicht zu kombinieren mit den spezifizierten Aufteilungsfilterbedingungen!";
         endif;
      endif;
      // ***

      // *** Special extensions according to category fields ***

      if ($statisticAllValues) :
         // Remove last element "business_volume" (default)
         $idArrayLen = changeCategoryDBFields(array(),"1");
         // Insert new elements at the last position
         $idArrayLen = changeCategoryDBFields(array("0","stat.turnover","stat.turnover",getLngt("Auftragswert"),"turnover","r") ,"0");
         $idArrayLen = changeCategoryDBFields(array("0","stat.remuneration","stat.remuneration",getLngt("Frachtvergütung"),"remuneration","r") ,"0");
         $idArrayLen = changeCategoryDBFields(array("0","stat.eau","stat.eau",getLngt("EAU"),"eau","r") ,"0");
         $idArrayLen = changeCategoryDBFields(array("0","stat.bsg","stat.bsg",getLngt("BSG [%]"),"bsg","r") ,"0");
         $idArrayLen = changeCategoryDBFields(array("0","stat.service_price","stat.service_price",getLngt("Servicepreis"),"service_price","r") ,"0");
         $idArrayLen = changeCategoryDBFields(array("0","stat.service_remuneration_man","stat.service_remuneration_man",getLngt("Manuelle Servicevergütung"),"service_remuneration_man","r") ,"0");
         $idArrayLen = changeCategoryDBFields(array("0","stat.km","stat.km",getLngt("KM"),"km","r") ,"0");
         $idArrayLen = changeCategoryDBFields(array("0","stat.co2e","stat.co2e",getLngt("CO2äq/kg"),"co2e","r") ,"0");
         // $uniqueSearchFieldsPRE[] = "ad_zipcode";
      else :
if (false) :
         // Set the current headline column for the "business volume" field
         if ($f_category == "2") :
            $titleArray[5] = $priceModeOutArr[$f_priceMode];
         elseif ($f_category == "3") :
            $titleArray[4] = $priceModeOutArr[$f_priceMode];
         else :
            $titleArray[1] = $priceModeOutArr[$f_priceMode];
         endif;
endif;
      endif;

      // Split per vehicletypes
      if ($f_filter == "1") :
         $tmpArray = array("0","stat.vehicletype","stat.vehicletype","Fahrzeugtyp","vehicletype");
         $uniqueSearchFieldsPRE[] = "vehicletype";
      endif;
      if ($f_filter == "2") :
         $tmpArray = array("0","stat.ad_zipcode","stat.ad_zipcode","Start-PLZ","ad_zipcode");
         $uniqueSearchFieldsPRE[] = "ad_zipcode";
      endif;
      if ($f_filter == "3") :
         $tmpArray = array("0","stat.jb_lastzipcode","stat.jb_lastzipcode","Ziel-PLZ","jb_lastzipcode");
         $uniqueSearchFieldsPRE[] = "jb_lastzipcode";
      endif;
      if ($f_filter == "4") :
         $tmpArray = array("0","stat.vehicletype","stat.vehicletype","Fahrzeugtyp","vehicletype");
         $uniqueSearchFieldsPRE[] = "vehicletype";
         $tmp2Array = array("0","stat.ad_zipcode","stat.ad_zipcode","Start-PLZ","ad_zipcode");
         $uniqueSearchFieldsPRE[] = "ad_zipcode";
      endif;
      if ($f_filter == "5") :
         $tmpArray = array("0","stat.vehicletype","stat.vehicletype","Fahrzeugtyp","vehicletype");
         $uniqueSearchFieldsPRE[] = "vehicletype";
         $tmp2Array = array("0","stat.jb_lastzipcode","stat.jb_lastzipcode","Ziel-PLZ","jb_lastzipcode");
         $uniqueSearchFieldsPRE[] = "jb_lastzipcode";
      endif;
      if ($f_filter == "6") :
         $tmpArray = array("0","stat.target_address","stat.target_address","Adresse 2. Station","target_address");
         $uniqueSearchFieldsPRE[] = "target_address";
         $tmp2Array = array("0","stat.start_address","stat.start_address","Startadresse","start_address");
         $uniqueSearchFieldsPRE[] = "start_address";
      endif;
      if ($f_filter == "7") :
         // First remove last two elements (count_jobs, business volume)
         $idArrayLen = changeCategoryDBFields(array(),"1");
         $idArrayLen = changeCategoryDBFields(array(),"1");
         $tmpArray = array("0","stat.count_jobs","stat.count_jobs","Anzahl","count_jobs","r");
         $tmp2Array = array("0","stat.ad_zipcode","stat.ad_zipcode","Ziel-PLZ","ad_zipcode","l");
         $uniqueSearchFieldsPRE[] = "ad_zipcode";
      endif;
      if ($f_filter == "1" || $f_filter == "2" || $f_filter == "3" || $f_filter == "4" || $f_filter == "5" || $f_filter == "6" || $f_filter == "7") :
         $tmpPosition = "0";    // Position in table (col.)
         if ($f_statistic == "21" || $f_statistic == "22" || $f_statistic == "26" || $f_statistic == "27" || 
             $f_statistic == "31" || $f_statistic == "32" || $f_statistic == "33" || $f_statistic == "34" || $f_statistic == "40" || $f_statistic == "45") :
            $tmpPosition = "1";
         endif;
         if ($f_statistic == "41" || $f_statistic == "42" || $f_statistic == "46" || $f_statistic == "47") :
            $tmpPosition = "2";
         endif;
         if ($f_statistic == "10" || $f_statistic == "50" || $f_statistic == "60" ||
             ($f_statistic >= "1000" && $f_statistic <= "1099") || $f_statistic == "2010") :
            $tmpPosition = "3";
         endif;
         if ($f_statistic == "11" || $f_statistic == "12" || $f_statistic == "13" || $f_statistic == "14" || $f_statistic == "15" || 
             $f_statistic == "51" || $f_statistic == "61" || $f_statistic == "62" || $f_statistic == "64" || $f_statistic == "1100") :
            $tmpPosition = "4";
         endif;
         if ($f_statistic == "2000") :
            $tmpPosition = "5";
         endif;
         $idArrayLen = changeCategoryDBFields($tmpArray,"0",$tmpPosition);
	       if (count($tmp2Array) > 0) :
	          $idArrayLen = changeCategoryDBFields($tmp2Array,"0",$tmpPosition);
	       endif;
      endif;
if (false) :
   echo "tmpPosition: " . $tmpPosition . "<br><br>\n\n";
   print_r($idArray); echo "<br><br>\n\n";
   print_r($fieldArray); echo "<br><br>\n\n";
   print_r($fieldSqlArray); echo "<br><br>\n\n";
   print_r($titleArray); echo "<br><br>\n\n";
   print_r($fieldSortArray); echo "<br><br>\n\n";
   print_r($alignArray); echo "<br><br>\n\n";
endif;
      // Split per headquarters
      if ($f_filter4 == "1") :
         $posOffset = 0 + $filterAlignOffset;
         $tmpArray = array("0","stat.headquarters","stat.headquarters","Niederlassung","headquarters","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","$posOffset");
         $uniqueSearchFieldsPRE[] = "headquarters";
         $filterAlignOffset++;
      endif;

      // Split per branches
      if ($f_filter5 == "1") :
         $posOffset = 0 + $filterAlignOffset;
         $tmpArray = array("0","stat.branch","stat.branch","Branche","branch","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","$posOffset");
         $uniqueSearchFieldsPRE[] = "branch";
         $filterAlignOffset++;
      endif;
      
      // Split per couriers
      if ($f_filter6 == "1") :
         $posOffset = 3 + $filterAlignOffset;
         $tmpArray = array("0","stat.usr_name","stat.usr_name","Name","usr_name","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","$posOffset");
         $tmpArray = array("0","stat.usr_firstname","stat.usr_firstname","Vorname","usr_firstname","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","$posOffset");
         $tmpArray = array("0","stat.cr_eid","stat.cr_eid","Unternehmer-Nr.","cr_eid","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","$posOffset");
         $uniqueSearchFieldsPRE[] = "cr_eid";
         $filterAlignOffset = $filterAlignOffset + 3;
      endif;

      // Split per vehicles
      if ($f_filter7 == "1") :
         $posOffset = 0 + $filterAlignOffset;
         $tmpArray = array("0","stat.cr_sid","stat.cr_sid","Fahrzeug-Nr.","cr_sid","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","$posOffset");
         $uniqueSearchFieldsPRE[] = "cr_sid";
         $filterAlignOffset++;
      endif;

      // Split per partner provision
      if ($f_filter12 == "1") :
         $posOffset = 0 + $filterAlignOffset;
         $tmpArray = array("0","stat.jb_crvh_partner_commission","stat.jb_crvh_partner_commission","Partnerprovision","jb_crvh_partner_commission","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","$posOffset");
         $uniqueSearchFieldsPRE[] = "jb_crvh_partner_commission";
         $filterAlignOffset++;
      endif;
      
      // Split per system fee
      $f_filter13 = "0";  // !!!!!!!!!!!!!!!!!!!!!!!!!!!! To be removed !!!!
      if ($f_category == "2" && $f_priceMode == "19") : $f_filter13 = "1"; endif;  // !!!!!!!!!!!!!!!!!!!!!!!!!!!! To be removed !!!!
      if ($f_filter13 == "1") :
         $posOffset = 0 + $filterAlignOffset;
         $tmpArray = array("0","stat.jb_crvh_system_fee_amount","stat.jb_crvh_system_fee_amount","Systemgebühr","jb_crvh_system_fee_amount","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","$posOffset");
         $uniqueSearchFieldsPRE[] = "jb_crvh_system_fee_amount";
         $filterAlignOffset++;
      endif;
      // Split per advertising allowance
      $f_filter14 = "0";  // !!!!!!!!!!!!!!!!!!!!!!!!!!!! To be removed !!!!
      if ($f_category == "2" && $f_priceMode == "19") : $f_filter14 = "1"; endif;  // !!!!!!!!!!!!!!!!!!!!!!!!!!!! To be removed !!!!
      if ($f_filter14 == "1") :
         $posOffset = 0 + $filterAlignOffset;
         $tmpArray = array("0","stat.jb_crvh_advertising_allowance","stat.crvh_advertising_allowance","Werbevergütung","jb_crvh_advertising_allowance","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","$posOffset");
         $uniqueSearchFieldsPRE[] = "jb_crvh_advertising_allowance";
         $filterAlignOffset++;
      endif;

      // Split per employees
      if ($f_filter8 == "1") :
         $posOffset = 0 + $filterAlignOffset;
         $tmpArray = array("0","stat.emp_id","stat.emp_id","Mitarbeiter","emp_id","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","$posOffset");
         $uniqueSearchFieldsPRE[] = "emp_id";
         $filterAlignOffset++;
      endif;
      
      // Split per job types
      if ($f_filter9 == "1") :
         $posOffset = 0 + $filterAlignOffset;
         $tmpArray = array("0","stat.jb_type","stat.jb_type","Typ","jb_type","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","$posOffset");
         $uniqueSearchFieldsPRE[] = "jb_type";
         $filterAlignOffset++;
      endif;
      
      // Split per paying costcenter
      if ($f_filter10 == "1") :
         $posOffset = 0 + $filterAlignOffset;
         $tmpArray = array("0","stat.csc_id_payer","stat.csc_id_payer","Kostenstelle","csc_name","r");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","$posOffset");
         $uniqueSearchFieldsPRE[] = "csc_id_payer";
         $filterAlignOffset++;
      elseif ($f_filter10 == "2") :
         $posOffset = 0 + $filterAlignOffset;
         $tmpArray = array("0","stat.csc_id_related","stat.csc_id_related","Kostenstelle","csc_name","r");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","$posOffset");
         $uniqueSearchFieldsPRE[] = "csc_id_related";
         $filterAlignOffset++;
      endif;

      // Split per customers
      if ($f_filter11 == "1") :
         $posOffset = 4 + $filterAlignOffset;
         $tmpArray = array("0","stat.cr_cs_cmp_comp2","stat.cr_cs_cmp_comp2","Firma2","cr_cs_cmp_comp2","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","$posOffset");
         $tmpArray = array("0","stat.cr_cs_cmp_comp","stat.cr_cs_cmp_comp","Firma","cr_cs_cmp_comp","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","$posOffset");
         $tmpArray = array("0","stat.cs_eid","stat.cs_eid","Kunden-Nr.","cs_eid","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","$posOffset");
         $uniqueSearchFieldsPRE[] = "cr_eid";
         $filterAlignOffset = $filterAlignOffset + 3;
      endif;

      // Split per job types
      if ($f_filter_calc == "1") :
         $tmpArray = array("0","stat.count_amount","stat.count_amount","Leistung Menge","count_amount","r");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","3");
         $uniqueSearchFieldsPRE[] = "count_amount";
         $tmpArray = array("0","stat.jbc_price","stat.jbc_price","Grundpreis","jbc_price","r");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","3");
         $uniqueSearchFieldsPRE[] = "jbc_price";
         $tmpArray = array("0","stat.srv_name","stat.srv_name","Leistung","srv_name","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","3");
         $uniqueSearchFieldsPRE[] = "srv_name";
      endif;

      // Split per time intervals
      if ($f_filter_interval != "0") :
         $tmpArray = array("0","stat.time_interval","stat.time_interval","Zeitintervall","time_interval","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","0");
         $uniqueSearchFieldsPRE[] = "time_interval";
      endif;

      // Add column meta customer 
      if ($f_cs_meta == "1") :
         $tmpArray = array("0","stat.cs_id_parent","stat.cs_id_parent","Metakundennr.","cs_id_parent","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","0");
         $uniqueSearchFieldsPRE[] = "cs_id_parent";
      endif;

      // Add columns invoice address data
      if ($f_show_invoice_address == "1") :
         $tmpArray = array("3","stat.ad_inv_city","stat.ad_inv_city","Ort","ad_inv_city","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","3");
         $tmpArray = array("3","stat.ad_inv_zipcode","stat.ad_inv_zipcode","PLZ","ad_inv_zipcode","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","3");
         $tmpArray = array("3","stat.ad_inv_hsno","stat.ad_inv_hsno","Hausnr.","ad_inv_hsno","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","3");
         $tmpArray = array("3","stat.ad_inv_street","stat.ad_inv_street","Strasse","ad_inv_street","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","3");
         // $uniqueSearchFieldsPRE[] = "cr_eid";
      endif;

      // Add columns delivery address data
      if ($f_show_delivery_address == "1") :
         $tmpArray = array("3","stat.ad_city","stat.ad_city","Ort","ad_city","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","3");
         $tmpArray = array("3","stat.ad_zipcode","stat.ad_zipcode","PLZ","ad_zipcode","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","3");
         $tmpArray = array("3","stat.ad_hsno","stat.ad_hsno","Hausnr.","ad_hsno","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","3");
         $tmpArray = array("3","stat.ad_street","stat.ad_street","Strasse","ad_street","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","3");
         // $uniqueSearchFieldsPRE[] = "cr_eid";
      endif;

      // Add columns master data
      if ($f_show_master_data == "1") :
         $tmpArray = array("3","stat.usr_email","stat.usr_email","Email","usr_email","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","3");
         $tmpArray = array("3","stat.usr_phone","stat.usr_phone","Telefon","usr_phone","l");
         $idArrayLen = changeCategoryDBFields($tmpArray,"0","3");
         // $uniqueSearchFieldsPRE[] = "cr_eid";
      endif;

      // Extra column 
      if ($showColMarkup) :
          $tmpArray = array("0","stat.markup_volume","stat.markup_volume","Zuschläge","markup_volume","r");
          $idArrayLen = changeCategoryDBFields($tmpArray,"0");
          // $uniqueSearchFieldsPRE[] = "markup_volume";
      endif;

      // Restore align string from array (!!!!)
      $aligns = implode(",", $alignArray);

      // Remember positions of the last (summation) field (necessary for comparisons)
      $posOfLastSummationField = $idArrayLen - 1;
      if ($numOfSummationCols > 1) :
         if ($statisticAllValues) :
            $posOfLastSummationField = $posOfLastSummationField - 8;
         else :
            // $posOfLastSummationField = $idArrayLen - 1;
            $posOfLastSummationField--;
            if ($showColMarkup) :
               $posOfLastSummationField--;
            endif;
         endif;
      endif;                           

      // Get the SQL-SELECT-values as result array containing the individual statistic data
      if ($idArrayLen > 0) :

         // Iterations according to the number of compared time intervals
         $remFromDateRange = $fromDateRange;
         $remToDateRange = $toDateRange;
         $remYearFrom = $year_from;
         $remYearTo = $year_to;
         $currentYearIsLeapYearTo = date("L", mktime(0, 0, 0, $month_to, $day_to, $year_to));
         for ($iter = 0; $iter < $numOfIntervalIters; $iter++) :

             // **** Call statistic function [BEGIN] ****

             $globalParArray = array($aligns, $f_statusMode, $f_dateMode, $f_showDateAndTime, $f_crvh_sid, $f_direction_sort, 
                                     $f_filter, $f_filter2, $f_filter3, $f_filter4, $f_filter5, $f_filter6, $f_filter7, $f_filter8, $f_filter9, $f_filter10,
                                     $f_price_formular, $f_filter_a, $f_filter_interval, $g_crvh_filter, $f_mode_statistic, $f_filter_calc, $f_service, $f_servicetype, $f_jb_service, $f_split_jb_services, $f_jb_specifics,
                                     $f_cs_meta, $f_cr_meta, $f_cr_parent, $f_cr_pda_actions, $f_show_invoice_address, $f_show_delivery_address, $summationField, $summationField2, $uniqueSearchFields,
                                     $hour_from, $minute_from, $hour_to, $minute_to, $fromTimeRange, $toTimeRange, $f_cmp_new_date, $f_cs_become_cs_date, $f_net_gross,
                                     $f_group, $f_groupLen, $f_staticGroup, $f_staticGroupLen, $f_priceMode, $f_editCsMode, $station_based_group_field, $f_bookedJobsOnly, $f_permanentJobsOnly,
                                     $f_filter_jb_weight_from, $f_filter_jb_length_from, $f_filter_jb_width_from, $f_filter_jb_height_from, $f_filter_jb_position_from,
                                     $f_filter_jb_weight_to, $f_filter_jb_length_to, $f_filter_jb_width_to, $f_filter_jb_height_to, $f_filter_jb_position_to, $f_show_master_data, $summationField3, $f_filter11, $f_filter12, $f_filter13, $f_filter14,
                                     $summationField4, $summationField5, $summationField6, $summationField7, $summationField8, $summationField9);

             $retArray = getStatistic($globalParArray, $f_statistic, $fromDateRange, $toDateRange, $g_cs_eid, $g_cr_eid, $fieldSortArray[$f_sort]);

             $rowArray = $retArray[0];        // Statistic data
             $globalParArray = $retArray[1];  // Global parameters

             list($aligns, $f_statusMode, $f_dateMode, $f_showDateAndTime, $f_crvh_sid, $f_direction_sort, 
                  $f_filter, $f_filter2, $f_filter3, $f_filter4, $f_filter5, $f_filter6, $f_filter7, $f_filter8, $f_filter9, $f_filter10,
                  $f_price_formular, $f_filter_a, $f_filter_interval, $g_crvh_filter, $f_mode_statistic, $f_filter_calc, $f_service, $f_servicetype, $f_jb_service, $f_split_jb_services, $f_jb_specifics,
                  $f_cs_meta, $f_cr_meta, $f_cr_parent, $f_cr_pda_actions, $f_show_invoice_address, $f_show_delivery_address, $summationField, $summationField2, $uniqueSearchFields,
                  $hour_from, $minute_from, $hour_to, $minute_to, $fromTimeRange, $toTimeRange, $f_cmp_new_date, $f_cs_become_cs_date, $f_net_gross,
                  $f_group, $f_groupLen, $f_staticGroup, $f_staticGroupLen, $f_priceMode, $f_editCsMode, $station_based_group_field, $f_bookedJobsOnly, $f_permanentJobsOnly,
                  $f_filter_jb_weight_from, $f_filter_jb_length_from, $f_filter_jb_width_from, $f_filter_jb_height_from, $f_filter_jb_position_from,
                  $f_filter_jb_weight_to, $f_filter_jb_length_to, $f_filter_jb_width_to, $f_filter_jb_height_to, $f_filter_jb_position_to, $f_show_master_data, $summationField3, $f_filter11, $f_filter12, $f_filter13, $f_filter14,
                  $summationField4, $summationField5, $summationField6, $summationField7, $summationField8, $summationField9) = $globalParArray;

             // **** Call statistic function [END] ****

             $uniqueSearchFields = array_merge($uniqueSearchFields, $uniqueSearchFieldsPRE);
// TO BE DONE
              // Change title of cols to be displayed (only first iteration)
              if ($iter == 0) :
                 if ($f_mode_statistic == "1") :
                    for ($t = 0; $t < $idArrayLen; $t++) :
                        // if ($fieldArray[$t] == "stat.count_jobs") :
                        //    $titleArray[$t] = getLngt("Anzahl Aufträge");
                        // endif;
                        if ($fieldArray[$t] == "stat.business_volume") :
                           $titleArray[$t] = getLngt("Umsatz Leistung");
                        endif;
                        if ($fieldArray[$t] == "stat.count_amount") :
                           $titleArray[$t] = getLngt("Menge Leistung");
                        endif;
                        // Check for split by calculator service
                        if ($f_filter_calc == "1") :
                           if ($fieldArray[$t] == "stat.srv_name") :
                              $titleArray[$t] = "Leistung";
                           endif;
                        endif;
                    endfor;
                 endif;
              endif;

             // *******************************************
             // * Special treatments of the result arrays *
             // * BEGIN                                   *
             // *******************************************
             $lenRowArray = count($rowArray);                  
    
             if ($f_statistic == "15") :
                $rowArray2 = "";
                $count = 0;
                $remCount[0] = 0; $minuteText[0] = "              <=  5 Min.";
                $remCount[1] = 0; $minuteText[1] = ">  5 Min. und <= 10 Min.";
                $remCount[2] = 0; $minuteText[2] = "> 10 Min. und <= 15 Min.";
                $remCount[3] = 0; $minuteText[3] = "> 15 Min. und <= 20 Min.";
                $remCount[4] = 0; $minuteText[4] = "> 20 Min.              ";
                $remCrEid = "";
                for ($i = 0; $i < $lenRowArray; $i++) :
                    
                    // If new courier then insert next rows in target array
                    if ($remCrEid == "" || $remCrEid != $rowArray[$i]["cr_eid"]) :
                       for ($j = 0; $j < count($remCount); $j++) :
                           $rowArray2[$count]["cr_eid"] = $rowArray[$i]["cr_eid"];
                           $rowArray2[$count]["usr_firstname"] = $rowArray[$i]["usr_firstname"];
                           $rowArray2[$count]["usr_name"] = $rowArray[$i]["usr_name"];
                           // $rowArray2[$count]["jb_taketime"] = "";
                           // $rowArray2[$count]["tr_finishtime"] = $minuteText[$j];
                           $rowArray2[$count]["minutetext"] = $minuteText[$j];
                           $rowArray2[$count]["time"] = 0;
                           $remCount[$j] = $count;
                           $count++;                       
                       endfor;
                       $remCrEid = $rowArray[$i]["cr_eid"];
                    endif;
                    
                    // Compute minutes and write into target array
                    $timeDiff = ($rowArray[$i]["time"]/60);
                    if ($timeDiff <= 5) :
                       $rowArray2[$remCount[0]]["time"] += 1;
                    elseif ($timeDiff > 5 && $timeDiff <= 10) :
                            $rowArray2[$remCount[1]]["time"] += 1;
                    elseif ($timeDiff > 10 && $timeDiff <= 15) :
                            $rowArray2[$remCount[2]]["time"] += 1;
                    elseif ($timeDiff > 15 && $timeDiff <= 20) :
                            $rowArray2[$remCount[3]]["time"] += 1;
                    else :
                       $rowArray2[$remCount[4]]["time"] += 1;
                    endif;
                endfor;
                $rowArray = $rowArray2;
             endif;

             // Change filled "emp_id" in firstname and lastname of the employee
             if ($f_filter8 == "1") :
                $remEmpId = "";
                $nameStr = "";
                for ($i = 0; $i < $lenRowArray; $i++) :
                    $empId = $rowArray[$i]["emp_id"];
                    if ($remEmpId == "" || $empId != $remEmpId) :
                       
                       // Get the name of the current employee
                       // $usrId = getFieldValueFromId("employee","emp_id",$empId,"usr_id");
                       $usrId = $empId;
                       
                       $tmpFields = getFieldsValueFromId("user","usr_id",$usrId,array("usr_firstname","usr_name"));
                       $nameStr = trim($tmpFields[0] . " ". $tmpFields[1]);
                       $remEmpId = $empId;
                    endif;
                    if ($empId == "0") :
                       $rowArray[$i]["emp_id"] = "Dauerauftrag";
                    else :
                       $rowArray[$i]["emp_id"] = $nameStr;
                       if ($rowArray[$i]["emp_id"] == "") :
                          $rowArray[$i]["emp_id"] = "- gelöscht -";
                       endif;
                    endif;
                endfor;
             endif;
             
             // Change "vehicletype" from ID to name of the vehicle
             if ($f_filter == "1" || $f_filter == "4" || $f_filter == "5") :
                for ($i = 0; $i < $lenRowArray; $i++) :
                    $rowArray[$i]["vehicletype"] = getFieldValueFromClause("metatype","mt_value","mt_type = 'vehicletype' AND mt_sort = '" . $rowArray[$i]["vehicletype"] . "'");
                endfor;            
             endif;

             // Change "headquarters" from ID to name of the vehicle
             if ($f_filter4 == "1") :
                for ($i = 0; $i < $lenRowArray; $i++) :
                    $rowArray[$i]["headquarters"] = getFieldValueFromClause("headquarters","hq_mnemonic","hq_id = '" . $rowArray[$i]["headquarters"] . "'");
                endfor;            
             endif;
             
             // Change "job type" from ID to name of the job type
             if ($f_filter9 == "1") :
                for ($i = 0; $i < $lenRowArray; $i++) :
                    $rowArray[$i]["jb_type"] = getFieldValueFromClause("metatype","mt_value","mt_type = 'vht_product' AND mt_sort = '" . $rowArray[$i]["jb_type"] . "'");
                endfor;
             endif;
             
             // Change "csc_id_payer" (or "csc_id_related") from ID to name of the costcenter
             if ($f_filter10 == "1") :
                for ($i = 0; $i < $lenRowArray; $i++) :
                    $rowArray[$i]["csc_id_payer"] = getFieldValueFromClause("costcenter","csc_name","csc_id = '" . $rowArray[$i]["csc_id_payer"] . "'");
                endfor;
             elseif ($f_filter10 == "2") :
                for ($i = 0; $i < $lenRowArray; $i++) :
                    $rowArray[$i]["csc_id_related"] = getFieldValueFromClause("costcenter","csc_name","csc_id = '" . $rowArray[$i]["csc_id_related"] . "'");
                endfor;
             endif;

             // Change system fee value of the vehicle
             $f_filter13 = "0";  // !!!!!!!!!!!!!!!!!!!!!!!!!!!! To be removed !!!!
             if ($f_category == "2" && $f_priceMode == "19") : $f_filter13 = "1"; endif;  // !!!!!!!!!!!!!!!!!!!!!!!!!!!! To be removed !!!!
             if ($f_filter13 == "1") :
                for ($i = 0; $i < $lenRowArray; $i++) :
                    if ($rowArray[$i]["jb_crvh_system_fee_amount"] == "") :
                       $tmpCrId = getFieldValueFromId("courier","cr_eid",$rowArray[$i]["cr_eid"],"cr_id");
                       $rowArray[$i]["jb_crvh_system_fee_amount"] = getFieldValueFromClause("couriervehicle","crvh_system_fee_amount","cr_id = '" . $tmpCrId . "'");
                    endif;
                endfor;
             endif;
             // Change advertising allowance value of the vehicle
             $f_filter14 = "0";  // !!!!!!!!!!!!!!!!!!!!!!!!!!!! To be removed !!!!
             if ($f_category == "2" && $f_priceMode == "19") : $f_filter14 = "1"; endif;  // !!!!!!!!!!!!!!!!!!!!!!!!!!!! To be removed !!!!
             if ($f_filter14 == "1") :
                for ($i = 0; $i < $lenRowArray; $i++) :
                    if ($rowArray[$i]["jb_crvh_advertising_allowance"] == "") :
                       $tmpCrId = getFieldValueFromId("courier","cr_eid",$rowArray[$i]["cr_eid"],"cr_id");
                       $rowArray[$i]["jb_crvh_advertising_allowance"] = getFieldValueFromClause("couriervehicle","crvh_advertising_allowance","cr_id = '" . $tmpCrId . "'");
                    endif;
                endfor;
             endif;

             // Change "meta customer" from ID to EID
             if ($f_cs_meta == "1") :
                for ($i = 0; $i < $lenRowArray; $i++) :
                    $rowArray[$i]["cs_id_parent"] = getFieldValueFromClause("customer","cs_eid","cs_id = '" . $rowArray[$i]["cs_id_parent"] . "'");
                endfor;
             endif;
             
             // Change "time intervals" from a number to datetime (e.g. "0" = 1st hour, "1" = 2nd hour, "2" = 3rd hour, ...)
             if ($f_filter_interval != "0") :
                // Per half an hour
                if ($f_filter_interval == "1") :
                   for ($i = 0; $i < $lenRowArray; $i++) :
                       $tmpTimeInterval = floor($rowArray[$i]["time_interval"] / 2);
                       if (($rowArray[$i]["time_interval"] % 2) == 0) :
                          $rowArray[$i]["time_interval"] = pad($tmpTimeInterval, 2, "0") . ":00:00 - " . pad($tmpTimeInterval, 2, "0") . ":29:59";
                       else :
                          $rowArray[$i]["time_interval"] = pad($tmpTimeInterval, 2, "0") . ":30:00 - " . pad($tmpTimeInterval, 2, "0") . ":59:59";
                       endif;
                   endfor;
                endif;
                // Per hour
                if ($f_filter_interval == "2") :
                   for ($i = 0; $i < $lenRowArray; $i++) :
                       $rowArray[$i]["time_interval"] = pad($rowArray[$i]["time_interval"], 2, "0") . ":00:00 - " . pad($rowArray[$i]["time_interval"], 2, "0") . ":59:59";
                   endfor;
                endif;
                // Per two hours
                if ($f_filter_interval == "3") :
                   for ($i = 0; $i < $lenRowArray; $i++) :
                       $tmpTimeIntervalFrom = ($rowArray[$i]["time_interval"] * 2);
                       $tmpTimeIntervalTo = (($rowArray[$i]["time_interval"] * 2) + 1);
                       $rowArray[$i]["time_interval"] = pad($tmpTimeIntervalFrom, 2, "0") . ":00:00 - " . pad($tmpTimeIntervalTo, 2, "0") . ":59:59";
                   endfor;
                endif;
             endif;
             
             
             // Change "branch" from key to "key and name"
             /*
             if ($f_filter5 == "1") :
                for ($i = 0; $i < $lenRowArray; $i++) :
                    $rowArray[$i]["branch"] = getFieldValueFromClause("branch","CONCAT(br_key,' ',br_name)","br_id = '" . $rowArray[$i]["branch"] . "'");
                endfor;            
             endif;
             */
             // *******
             // * END *          
             // *******


             // Store into a temporary array
             if ($numOfIntervalIters >= "2") :

                // Check current year for leap year
                // IMPORTANT: If current year selected is a leap year only!!!
                $tmpDayTo = $day_to;
                if ($currentYearIsLeapYearTo == "1") :
                   if ($month_to == "2" && $day_to == "29") :
                      // Case 1: $fromDateRange == $toDateRange == "29.02.YYYY"
                      if ($month_from == "2" && $day_from == "29" && $year_from == $year_to) :
                         // Reset values before break
                         $numOfIntervalIters = 1;
                         $dbhistory = $remDbHistory;
                         $fromDateRange = $remFromDateRange;
                         $toDateRange = $remToDateRange;
                         $year_from = $remYearFrom;
                         $year_to = $remYearTo;
                         $dbhistory = getDBNames($dbhistory, $year_from);
                         break;
                      else :
                         $tmpDayTo = "28";
                      endif;
                   endif;
                endif;

                if ($iter > 0) :
                   if ($statisticAllValues) : 
// xxxxxxxxxxxxxx
                   else :
                      $tmpArray = array("0","stat.#".$year_from,"stat.#".$year_from,"#".$year_from,"stat.#".$year_from);
                      $idArrayLen = changeCategoryDBFields($tmpArray,"0",$idArrayLen);
                      
                      $summationFieldArray[($iter - 1)] = "stat.#" . $year_from;
                      
                      if ($numOfSummationCols > 1) :
                         $tmpArray = array("0","stat.".$year_from,"stat.".$year_from,$year_from,"stat.".$year_from);
                         $idArrayLen = changeCategoryDBFields($tmpArray,"0",$idArrayLen);
                      
                         $summationFieldArray2[($iter - 1)] = "stat." . $year_from;
                         
                         if ($numOfSummationCols == 3) :
                            $tmpArray = array("0","stat.Z".$year_from,"stat.Z".$year_from,"Z".$year_from,"stat.Z".$year_from);
                            $idArrayLen = changeCategoryDBFields($tmpArray,"0",$idArrayLen);
                      
                            $summationFieldArray3[($iter - 1)] = "stat.Z" . $year_from;
                         endif;
                      endif;
                   endif;
                endif;

                $remRowArray[$iter] = $rowArray;

                // Set time range exacly to one year before
                $year_from = $year_from - 1;
                $year_to = $year_to - 1;
                
                $fromDateRange = date("Y-m-d H:i:s",mktime(0,0,0,$month_from,$day_from,$year_from));
                $toDateRange = date("Y-m-d H:i:s",mktime(23,59,59,$month_to,$tmpDayTo,$year_to));
                
                // $fromDateRange = date("Y-m-d H:i:s",mktime(0,0,0,$month_from,$day_from,$year_from));
                // $toDateRange = date("Y-m-d H:i:s",mktime(23,59,59,$month_to,$day_to,$year_to));
                
                // Prepare statistic computations according to history tables if necessary
                if ($constYearOfBeginHistory != "" && $year_from <= $constYearOfBeginHistory) :
                   $dbhistory = "1";
                   $dbhistory = getDBNames($dbhistory, $year_from);
                endif;
             endif;
         endfor;  // Iterations intervals
         
         // Restore value for history access
         $dbhistory = $remDbHistory;


         // ****************************************************************
         // * Begin of preparation of output with intervals for comparison *
         // ****************************************************************
         $fromDateRange = $remFromDateRange;
         $toDateRange = $remToDateRange;
         $year_from = $remYearFrom;
         $year_to = $remYearTo;
         $uniqueSearchFieldsLen = count($uniqueSearchFields);

         // Make a new array with the new interval column
         if ($numOfIntervalIters >= "2") :

            // Reset "$rowArray" to the result of the initial (first) request without comparison with the intervals before
            $rowArray = $remRowArray[0];

            for ($iter = 1; $iter < $numOfIntervalIters; $iter++) :
                
                $rowArray2 = $remRowArray[$iter];
                $lenRowArray2 = count($rowArray2);

                // Iterate all rows
                for ($j = 0; $j < $lenRowArray2; $j++) :

                    $lenRowArray = count($rowArray);  // Could be changed if rows would be inserted

                    // Check unique existence for the current row in "$rowArray2" being in "$rowArray"                    
                    $tmpColArray = array();
                    for ($k = 0; $k < $lenRowArray ; $k++) :                    
                        $tmpColArray[$k] = "";
                        for ($i = 0; $i < $uniqueSearchFieldsLen; $i++) :
                            // Take special column vector(s) according to the current searchfield (e.g. "cs_eid" of the customer statistic, etc.)
                            // Results in an 1-dim array with a string as representation of all "unique index fields"
                            // Attention: Content like "2007-01" has to be moved to "2008-01", therefore all time fields have to be manipulated !!!                            
                            $tmpColArray[$k] .= $rowArray[$k][$uniqueSearchFields[$i]];
                        endfor;
                    endfor;

                    // Define string of unique fields of "$rowArray2" for search
                    $tmpSearchString = "";
                    for ($i = 0; $i < $uniqueSearchFieldsLen; $i++) :                        
                        if ($uniqueSearchFields[$i] == "jb_finishtime" || $uniqueSearchFields[$i] == "cdt_logintime" || $uniqueSearchFields[$i] == "minutetext") :
                           $tmpYear = substr($rowArray2[$j][$uniqueSearchFields[$i]],0,4);
                           if (is_numeric($tmpYear)) :
                              $tmpYear += $iter;
                              // Replace year in content value the year used in first request
                              $rowArray2[$j][$uniqueSearchFields[$i]] = $tmpYear . substr($rowArray2[$j][$uniqueSearchFields[$i]],4);
                           endif;                               
                        endif;

                        $tmpSearchString .= $rowArray2[$j][$uniqueSearchFields[$i]];
                    endfor;

                    // Search for the value (e.g. "cs.cs_eid") in "$rowArray" and get the row number
                    // If found then transfer the number value of the interval to $rowArray,
                    // if not found then expand "$rowArray" according to the row of the interval before
                    $tmpFoundInArray = true;
                    $rowNum = array_search($tmpSearchString, $tmpColArray);
                    if ($rowNum === FALSE) :
                       $tmpFoundInArray = false;
                    endif;

                    if ($tmpFoundInArray) :
                       // Get fieldname(s) of the number field(s) like "count_jobs", "business_volume", etc.

                       // Number of jobs
                       $tmpFieldName = substr($fieldArray[($posOfLastSummationField)], strrpos($fieldArray[($posOfLastSummationField)],".") + 1);
                       $rowArray[$rowNum]["#" . ($year_from - $iter)] = $rowArray2[$j][$tmpFieldName];

                       if ($numOfSummationCols > 1) :
                          // Business volume
                          $tmpFieldName = substr($fieldArray[$posOfLastSummationField + 1], strrpos($fieldArray[$posOfLastSummationField + 1],".") + 1);
                          $rowArray[$rowNum][($year_from - $iter)] = $rowArray2[$j][$tmpFieldName];
                          
                          if ($showColMarkup) :
                             // Markup volume
                             $tmpFieldName = substr($fieldArray[$posOfLastSummationField + 2], strrpos($fieldArray[$posOfLastSummationField + 2],".") + 1);
                             $rowArray[$rowNum]["Z" . ($year_from - $iter)] = $rowArray2[$j][$tmpFieldName];
                          endif;
                       endif;
                    else :
                       // Expand array $rowArray
                       for ($k = 0; $k < ($posOfLastSummationField - 1) ; $k++) :
                           $tmpFieldName = substr($fieldArray[$k], strrpos($fieldArray[$k],".") + 1);
                           $rowArray[$lenRowArray][$tmpFieldName] = $rowArray2[$j][$tmpFieldName];
                           $tmpColArray[$k] = $rowArray[$k][$uniqueSearchFields[$i]];
                       endfor;

                       $tmpFieldName = substr($fieldArray[($posOfLastSummationField)], strrpos($fieldArray[($posOfLastSummationField)],".") + 1);
                       $rowArray[$lenRowArray]["#" . ($year_from - $iter)] = $rowArray2[$j][$tmpFieldName];
                       
                       if ($numOfSummationCols > 1) :
                          $tmpFieldName = substr($fieldArray[$posOfLastSummationField + 1], strrpos($fieldArray[$posOfLastSummationField + 1],".") + 1);
                          $rowArray[$lenRowArray][($year_from - $iter)] = $rowArray2[$j][$tmpFieldName];

                          if ($showColMarkup) :
                             $tmpFieldName = substr($fieldArray[$posOfLastSummationField + 2], strrpos($fieldArray[$posOfLastSummationField + 2],".") + 1);
                             $rowArray[$lenRowArray]["Z" . ($year_from - $iter)] = $rowArray2[$j][$tmpFieldName];
                          endif;
                       endif;
                    endif;
                endfor;
            endfor;
         endif;
         // **************************************************************
         // * End of preparation of output with intervals for comparison *
         // **************************************************************

         // Special (external) output formatting commands
         if ($specialAligns != "") : $aligns = $specialAligns; endif;

         // Generate list with header
         for ($i = 1; $i <= $f_numOfIntervals ; $i++) :
             $aligns .= ",r";
             if ($numOfSummationCols > 1) :
                $aligns .= ",r";
             endif;
         endfor;
         // $alignArray = spliti(",",$aligns);

         if ($mode == "" || !is_numeric($mode)) :         
            $mode = "2";                     // Output from MATRIX as table per default
         endif;         
         $sortDBField = "YES";            // Used in following include-file for sorting per column;

         // Only for output: Overwrite predefined output fields
         // if ($summationField2 == "stat.business_volume") :
            $tmpCurrYear = getDateTime("year");
            for ($k = ($tmpCurrYear - 10); $k < $tmpCurrYear; $k++) :
                $outputFormatField[$k] = "float_rounded_2";
            endfor;
         // endif;

         $postParserField = "";
         if ($userTypeName == "hq" && !$fileOutput) :
            if ($f_category == "3") :
               $postParserField = "cs.cs_eid";    // Customer
            elseif ($f_category == "2") :
               $postParserField = "cr.cr_eid";    // Courier
            endif;
         endif;

         include_once ("../include/inc_list_defineoutput.inc.php");

         // Post parsing if necessary
         if ($postParserField != "") :
            $tableBody = postParseStatisticDetails($tableBody);
         endif;

         if ($statisticAllValues) :
            if ($summationField == "stat.count_jobs") :
               $sumOfSummationField = number_format(round($sumOfSummationField,0), 0, ",", ".");
               for ($i = 0; $i < $summationFieldArrayLen; $i++) :
                   $sumOfSummationFieldArray[$i] = number_format(round($sumOfSummationFieldArray[$i],2), 2, ",", ".");
               endfor;
            endif;
            if ($summationField2 == "stat.turnover") :
               $sumOfSummationField2 = number_format(round($sumOfSummationField2,2), 2, ",", ".");
               for ($i = 0; $i < $summationFieldArray2Len; $i++) :
                   $sumOfSummationFieldArray2[$i] = number_format(round($sumOfSummationFieldArray2[$i],2), 2, ",", ".");
               endfor;
            endif;
            if ($summationField3 == "stat.remuneration") :
               $sumOfSummationField3 = number_format(round($sumOfSummationField3,2), 2, ",", ".");
               for ($i = 0; $i < $summationFieldArray3Len; $i++) :
                   $sumOfSummationFieldArray3[$i] = number_format(round($sumOfSummationFieldArray3[$i],2), 2, ",", ".");
               endfor;
            endif;
            if ($summationField4 == "stat.eau") :
               $sumOfSummationField4 = number_format(round($sumOfSummationField4,2), 2, ",", ".");
               for ($i = 0; $i < $summationFieldArray4Len; $i++) :
                   $sumOfSummationFieldArray4[$i] = number_format(round($sumOfSummationFieldArray4[$i],2), 2, ",", ".");
               endfor;
            endif;
            if ($summationField5 == "stat.bsg") :
               $sumOfSummationField5 = number_format(round($sumOfSummationField5,2), 2, ",", ".");
               for ($i = 0; $i < $summationFieldArray5Len; $i++) :
                   $sumOfSummationFieldArray5[$i] = number_format(round($sumOfSummationFieldArray5[$i],2), 2, ",", ".");
               endfor;
            endif;
            if ($summationField6 == "stat.service_price") :
               $sumOfSummationField6 = number_format(round($sumOfSummationField6,2), 2, ",", ".");
               for ($i = 0; $i < $summationFieldArray6Len; $i++) :
                   $sumOfSummationFieldArray6[$i] = number_format(round($sumOfSummationFieldArray6[$i],2), 2, ",", ".");
               endfor;
            endif;
            if ($summationField7 == "stat.service_remuneration_man") :
               $sumOfSummationField7 = number_format(round($sumOfSummationField7,2), 2, ",", ".");
               for ($i = 0; $i < $summationFieldArray7Len; $i++) :
                   $sumOfSummationFieldArray7[$i] = number_format(round($sumOfSummationFieldArray7[$i],2), 2, ",", ".");
               endfor;
            endif;
            if ($summationField8 == "stat.km") :
               $sumOfSummationField8 = number_format(round($sumOfSummationField8,2), 2, ",", ".");
               for ($i = 0; $i < $summationFieldArray8Len; $i++) :
                   $sumOfSummationFieldArray8[$i] = number_format(round($sumOfSummationFieldArray8[$i],2), 2, ",", ".");
               endfor;
            endif;
            if ($summationField9 == "stat.co2e") :
               $sumOfSummationField9 = number_format(round($sumOfSummationField9,2), 2, ",", ".");
               for ($i = 0; $i < $summationFieldArray9Len; $i++) :
                   $sumOfSummationFieldArray9[$i] = number_format(round($sumOfSummationFieldArray9[$i],2), 2, ",", ".");
               endfor;
            endif;
         else :
            if ($summationField == "stat.count_jobs") :
               $sumOfSummationField = number_format(round($sumOfSummationField,0), 0, ",", ".");
               for ($i = 0; $i < $summationFieldArrayLen; $i++) :
                   $sumOfSummationFieldArray[$i] = number_format(round($sumOfSummationFieldArray[$i],2), 2, ",", ".");
               endfor;
            endif;
            if ($summationField2 == "stat.business_volume") :
               $sumOfSummationField2 = number_format(round($sumOfSummationField2,2), 2, ",", ".");
               for ($i = 0; $i < $summationFieldArray2Len; $i++) :
                   $sumOfSummationFieldArray2[$i] = number_format(round($sumOfSummationFieldArray2[$i],2), 2, ",", ".");
               endfor;
            endif;
            if ($summationField3 == "stat.markup_volume") :
               $sumOfSummationField3 = number_format(round($sumOfSummationField3,2), 2, ",", ".");
               for ($i = 0; $i < $summationFieldArray3Len; $i++) :
                   $sumOfSummationFieldArray3[$i] = number_format(round($sumOfSummationFieldArray3[$i],2), 2, ",", ".");
               endfor;
            endif;
         endif;

         // Optional output to file
         if ($fileOutput) :

            // Remove old files
            foreach (glob(STATISTIC_PATH . "*.stat.csv") as $fileNameToBoRemoved) {
                if ((time() - filemtime($fileNameToBoRemoved)) > 60) :
                   if (file_exists($fileNameToBoRemoved)) :
                      unlink($fileNameToBoRemoved);
                   endif;
                endif;
            }

            // Define output parameters
            $delimiter = ';';
            $writeHeader = "YES";

            include_once ("../include/inc_list_defineoutput2file.inc.php");

            $outputLinesArrayLen = count($outputLinesArray);
            if ($outputLinesArrayLen > 0) :

               $f_fileName = "STATISTIK_" . date("YmdHis");
               $f_secretFileName = md5($f_fileName) . ".stat.csv";
               if ($outputHeader != "") :
                  writeToFile(STATISTIC_PATH . $f_secretFileName, $outputHeader);   // write header if requested
               endif;
               for ($i = 0; $i < $outputLinesArrayLen; $i++) :                   
                   writeToFile(STATISTIC_PATH . $f_secretFileName, $outputLinesArray[$i]);   // write statistic data
               endfor;
            else :
               $statusMessage = "Es wurden keine Daten gefunden! Eine Datei wurde deshalb nicht generiert!";
               $fileOutput = false;
            endif;
         endif;
      endif;
   endif;
endif;


// Javascript-function as template only for categorie depending on date-filter (not status-filter)
$onLoadCall = "displayStatusMessage();";

$js_date = "";
$js_date .= "<script src=\"../include/lib_global.js\" type=\"text/javascript\">\n";
$js_date .= "</script>\n";
$js_date .= "\n";
$js_date .= "<script type=\"text/javascript\">\n";
$js_date .= "<!--\n";
$js_date .= "function initForm() {\n";
$js_date .= "  fillDateFields(1,\"maincontent\",\"statistic\",\"\",\"day_from\",\"month_from\",\"year_from\",\"\",\"\",\"\");\n";
$js_date .= "  setDateTimeFields(\"maincontent\",\"statistic\",".$day_from.",".$month_from.",".$year_from.", \"\", \"\", \"day_from\", \"month_from\", \"year_from\", \"\", \"\", \"\");\n";
$js_date .= "  fillDateFields(1,\"maincontent\",\"statistic\", \"\", \"day_to\", \"month_to\", \"year_to\", \"\", \"\", \"\");\n";
$js_date .= "  setDateTimeFields(\"maincontent\",\"statistic\",".$day_to.",".$month_to.",".$year_to.", \"\", \"\", \"day_to\", \"month_to\", \"year_to\", \"\", \"\", \"\");\n";
$js_date .= "}\n";
$js_date .= "-->\n";
$js_date .= "</script>\n";

if ($noStatisticMenu == "") :
   $onLoadCall .= "initForm();";
endif;

if ($fileOutput) :
   $onLoadCall .= "downloadFile();";
endif;

if ($f_mode_statistic == "1") : 
   $onLoadCall .= "serviceList('on');";
else :
   $onLoadCall .= "serviceList('off');";
endif;

if ($f_groupLen > 0) : 
   $onLoadCall .= "groupList('on');";
else :
   $onLoadCall .= "groupList('off');";
endif;

if ($f_staticGroupLen > 0) : 
   $onLoadCall .= "staticGroupList('on');";
else :
   $onLoadCall .= "staticGroupList('off');";
endif;

if ($f_jb_serviceLen > 0) : 
   $onLoadCall .= "jbServiceList('on');";
else :
   $onLoadCall .= "jbServiceList('off');";
endif;

if ($f_jb_specificsLen > 0) :
   $onLoadCall .= "jbSpecificsList('on');";
else :
   $onLoadCall .= "jbSpecificsList('off');";
endif;


// Prepare chart output
$chartTitle = "";
$json = array();

if ($f_type_chart > 0) :
   $onLoadCall .= "openChart();";   
 
   $range_min = 0;
   $range_max = 0;
   $range_step = 1;
   $interval_from = PHP_INT_MAX;
   $interval_to = 0;
   $scale_factor_height = 6;
   if (is_numeric($rowArrayLen)) :
      $scale_factor_height = max((round(($rowArrayLen / 15), 0) * 3), 6);
   endif;
   $eidMappingArray = array();
   $eidMappingCounter = 0;

   // Summations
   $chartSummationArray = array();
   $chartSummationArray[] = $sumOfSummationField2;
   if ($summationFieldArrayLen > 0) :
      for ($i = 0; $i < $summationFieldArrayLen; $i++) :
          $chartSummationArray[] = $sumOfSummationFieldArray2[$i];
      endfor;
   endif;
   $chartSummationArray = array_reverse($chartSummationArray);
   $chartSummationArrayLen = count($chartSummationArray);

// echo $rowArrayLen . "\n\n";
// print_r($rowArray); echo "\n\n";
   // Generate point object
   for ($i = 0; $i < $rowArrayLen; $i++) :
       $businessVolumeNum  = round($rowArray[$i]["business_volume"],0);
       $businessVolumeText = number_format(round($rowArray[$i]["business_volume"],2), 2, ",", ".");
       $countJobs = $rowArray[$i]["count_jobs"];
       $range_max = max($range_max, $businessVolumeNum);

       // Normal statistic
       if ($f_category == "1") :
          $tmpFilter = "jobs";
          if ($f_statistic >= 31 && $f_statistic <= 34) : 
             $tmpFilter = "jb_finishtime";
             if ($f_statistic == 31) : 
                $chartTitle = getLngt("Monat");
             elseif ($f_statistic == 32) :
                $chartTitle = getLngt("Tag");
             elseif ($f_statistic == 33) :
                $chartTitle = getLngt("Kalenderwoche");
             elseif ($f_statistic == 34) :
                $chartTitle = getLngt("Halber Monat");
             endif;
          elseif ($f_filter4 == "1") : 
             $tmpFilter = "headquarters";
             $chartTitle = getLngt("Niederlassungen");
          elseif ($f_filter5 == "1") : 
             $tmpFilter = "branch";
             $chartTitle = getLngt("Branchen");
          elseif ($f_filter8 == "1") : 
             $tmpFilter = "emp_id";
             $chartTitle = getLngt("Mitarbeiter");
          endif;

          if ($f_type_chart == 1) :
             array_push($json,array("x" => utf8_encode($rowArray[$i][$tmpFilter]),"y" => $businessVolumeNum,"text" => utf8_encode($rowArray[$i][$tmpFilter]) . " : " . $businessVolumeText));
          elseif ($f_type_chart == 2) :
             if (!is_array($json[$i]["points"]) || $json[$i]["points"] == "") :
                $json[$i]["points"] = array();
                $json[$i]["name"] = utf8_encode($rowArray[$i][$tmpFilter]);
             endif;
             array_push($json[$i]["points"],array("x" => utf8_encode($rowArray[$i][$tmpFilter]),"y" => $businessVolumeNum));
          elseif ($f_type_chart == 10 || $f_type_chart == 11 || $f_type_chart == 12 || $f_type_chart == 13 || $f_type_chart == 14) :
             $json[$i]["points"] = array();
             for ($j = 0; $j <= $f_numOfIntervals; $j++) :
                 $tmpYear = $year_to - $f_numOfIntervals + $j;
                 if ($tmpYear == $year_to) :
                    $tmpBusinessVolumeNum  = $businessVolumeNum;
                    $tmpBusinessVolumeText = $businessVolumeText;
                 else :
                    $tmpBusinessVolumeNum  = round($rowArray[$i][$tmpYear],0);
                    $tmpBusinessVolumeText = number_format(round($rowArray[$i][$tmpYear],2), 2, ",", ".");
                 endif;
                 array_push($json[$i]["points"],array("x" => $tmpYear,"y" => $tmpBusinessVolumeNum));
                 $range_max = max($range_max, round(str_replace(",",".",$rowArray[$i][$tmpYear]),0));
             endfor;
             $json[$i]["name"] = utf8_encode($rowArray[$i][$tmpFilter]);
             if ($f_type_chart == 12 || $f_type_chart == 13 || $f_type_chart == 14) :
                $json[$i]["enableAnimation"] = utf8_encode("true");
                $json[$i]["opacity"] = 1;
                // $json[$i]["fill"] = utf8_encode("'#69D2E7'");
             endif;
             if ($f_type_chart == 13) :
                $json[$i]["type"] = utf8_encode("Area");
                $json[$i]["border"] = utf8_encode("{color: 'transparent'}");
                $json[$i]["opacity"] = 0.5;
             endif;
          endif;

       // Courier statistic
       elseif ($f_category == "2") :
          $chartTitle = getLngt("Transporteure");
          if ($f_statistic >= 11 && $f_statistic <= 14) : 
             $tmpFilter = "jb_finishtime";
             if ($f_statistic == 11) : 
                $chartTitle .= " " . getLngt("pro Monat");
             elseif ($f_statistic == 12) :
                $chartTitle .= " " . getLngt("pro Tag");
             elseif ($f_statistic == 13) :
                $chartTitle .= " " . getLngt("pro Kalenderwoche");
             elseif ($f_statistic == 14) :
                $chartTitle .= " " . getLngt("pro halbem Monat");
             endif;
          endif;

          if ($f_type_chart == 1) :
             array_push($json,array("x" => $rowArray[$i]["cr_eid"],"y" => $businessVolumeNum,"text" => $rowArray[$i]["cr_eid"] . " : " . utf8_encode($rowArray[$i]["usr_name"]) . ", " . utf8_encode($rowArray[$i]["usr_firstname"]) . " : " . $businessVolumeText));
          elseif ($f_type_chart == 2) :
             if (!is_array($json[$i]["points"]) || $json[$i]["points"] == "") :
                $json[$i]["points"] = array();
                $json[$i]["name"] = $rowArray[$i]["cr_eid"] . " : " . utf8_encode($rowArray[$i]["usr_name"]) . ", " . utf8_encode($rowArray[$i]["usr_firstname"]);
             endif;
             array_push($json[$i]["points"],array("x" => $rowArray[$i]["cr_eid"],"y" => $businessVolumeNum));
          elseif ($f_type_chart == 10 || $f_type_chart == 11 || $f_type_chart == 12 || $f_type_chart == 13 || $f_type_chart == 14) :
             if ($rowArray[$i]["jb_finishtime"] != "") :
                 $numJbFinishtime = preg_replace ("/ /", "", $rowArray[$i]["jb_finishtime"]);  // Remove blanks
                 $numJbFinishtime = preg_replace ("/-/", "", $numJbFinishtime);                // Remove sign "-"
                 $interval_from = min($interval_from, $numJbFinishtime);
                 $interval_to = max($interval_to, $numJbFinishtime);
                if (strlen($eidMappingArray[$rowArray[$i]["cr_eid"]]) == 0) :
                   $eidMappingArray[$rowArray[$i]["cr_eid"]] = $eidMappingCounter;
                   $json[$eidMappingCounter]["points"] = array();
                   $eidMappingCounter++;
                endif;
                array_push($json[$eidMappingArray[$rowArray[$i]["cr_eid"]]]["points"],array("x" => $numJbFinishtime, "y" => $businessVolumeNum));
                if ($json[$eidMappingArray[$rowArray[$i]["cr_eid"]]]["name"] == "") :
                   $json[$eidMappingArray[$rowArray[$i]["cr_eid"]]]["name"] = $rowArray[$i]["cr_eid"] . " : " . utf8_encode($rowArray[$i]["usr_name"]) . ", " . utf8_encode($rowArray[$i]["usr_firstname"]);
                   if ($f_type_chart == 13) :
                      $json[$eidMappingArray[$rowArray[$i]["cr_eid"]]]["type"] = utf8_encode("Area");
                      $json[$eidMappingArray[$rowArray[$i]["cr_eid"]]]["border"] = utf8_encode("{color: 'transparent'}");
                   endif;
                   if ($f_type_chart == 12 || $f_type_chart == 13 || $f_type_chart == 14) :
                      $json[$eidMappingArray[$rowArray[$i]["cr_eid"]]]["enableAnimation"] = utf8_encode("true");
                      $json[$eidMappingArray[$rowArray[$i]["cr_eid"]]]["opacity"] = 0.5;
                      // $json[$eidMappingArray[$rowArray[$i]["cr_eid"]]]["fill"] = utf8_encode("'#69D2E7'");
                   endif;
                endif;
             else :
                $json[$i]["points"] = array();
                for ($j = 0; $j <= $f_numOfIntervals; $j++) :
                    $tmpYear = $year_to - $f_numOfIntervals + $j;
                    if ($tmpYear == $year_to) :
                       $tmpBusinessVolumeNum  = $businessVolumeNum;
                       $tmpBusinessVolumeText = $businessVolumeText;
                    else :
                       $tmpBusinessVolumeNum  = round($rowArray[$i][$tmpYear],0);
                       $tmpBusinessVolumeText = number_format(round($rowArray[$i][$tmpYear],2), 2, ",", ".");
                    endif;
                    array_push($json[$i]["points"],array("x" => $tmpYear,"y" => $tmpBusinessVolumeNum));
                    $range_max = max($range_max, round(str_replace(",",".",$rowArray[$i][$tmpYear]),0));
                endfor;
                $json[$i]["name"] = $rowArray[$i]["cr_eid"] . " : " . utf8_encode($rowArray[$i]["usr_name"]) . ", " . utf8_encode($rowArray[$i]["usr_firstname"]);
                if ($f_type_chart == 12 || $f_type_chart == 13 || $f_type_chart == 14) :
                   $json[$i]["enableAnimation"] = utf8_encode("true");
                   $json[$i]["opacity"] = 1;
                   // $json[$i]["fill"] = utf8_encode("'#69D2E7'");
                endif;
                if ($f_type_chart == 13) :
                   $json[$i]["type"] = utf8_encode("Area");
                   $json[$i]["border"] = utf8_encode("{color: 'transparent'}");
                   $json[$i]["opacity"] = 0.5;
                endif;
             endif;
          endif;

       // Customer statistic
       elseif ($f_category == "3") :
          $chartTitle = getLngt("Kunden");
          if ($f_statistic == 61 || $f_statistic == 62 || $f_statistic == 64) : 
             $tmpFilter = "jb_finishtime";
             if ($f_statistic == 61) : 
                $chartTitle .= " " . getLngt("pro Monat");
             elseif ($f_statistic == 64) :
                $chartTitle .= " " . getLngt("pro Tag");
             elseif ($f_statistic == 62) :
                $chartTitle .= " " . getLngt("pro Kalenderwoche");
             endif;
          endif;

          if ($f_type_chart == 1) :
             array_push($json,array("x" => $rowArray[$i]["cs_eid"],"y" => $businessVolumeNum,"text" => $rowArray[$i]["cs_eid"] . " : " . utf8_encode($rowArray[$i]["cmp_comp"]) . " : " . $businessVolumeText));
          elseif ($f_type_chart == 2) :
             if (!is_array($json[$i]["points"]) || $json[$i]["points"] == "") :
                $json[$i]["points"] = array();
                $json[$i]["name"] = $rowArray[$i]["cs_eid"] . " : " . utf8_encode($rowArray[$i]["cmp_comp"]);
             endif;
             array_push($json[$i]["points"],array("x" => $rowArray[$i]["cs_eid"],"y" => $businessVolumeNum));
          elseif ($f_type_chart == 10 || $f_type_chart == 11 || $f_type_chart == 12 || $f_type_chart == 13 || $f_type_chart == 14) :
             if ($rowArray[$i]["jb_finishtime"] != "") :
                 $numJbFinishtime = preg_replace ("/ /", "", $rowArray[$i]["jb_finishtime"]);  // Remove blanks
                 $numJbFinishtime = preg_replace ("/-/", "", $numJbFinishtime);                // Remove sign "-"
                 $interval_from = min($interval_from, $numJbFinishtime);
                 $interval_to = max($interval_to, $numJbFinishtime);
                if (strlen($eidMappingArray[$rowArray[$i]["cs_eid"]]) == 0) :
                   $eidMappingArray[$rowArray[$i]["cs_eid"]] = $eidMappingCounter;
                   $json[$eidMappingCounter]["points"] = array();
                   $eidMappingCounter++;
                endif;
                array_push($json[$eidMappingArray[$rowArray[$i]["cs_eid"]]]["points"],array("x" => $numJbFinishtime, "y" => $businessVolumeNum));
                if ($json[$eidMappingArray[$rowArray[$i]["cs_eid"]]]["name"] == "") :
                   $json[$eidMappingArray[$rowArray[$i]["cs_eid"]]]["name"] = $rowArray[$i]["cs_eid"] . " : " . utf8_encode($rowArray[$i]["cmp_comp"]);
                   if ($f_type_chart == 13) :
                      $json[$eidMappingArray[$rowArray[$i]["cs_eid"]]]["type"] = utf8_encode("Area");
                      $json[$eidMappingArray[$rowArray[$i]["cs_eid"]]]["border"] = utf8_encode("{color: 'transparent'}");
                   endif;
                   if ($f_type_chart == 12 || $f_type_chart == 13 || $f_type_chart == 14) :
                      $json[$eidMappingArray[$rowArray[$i]["cs_eid"]]]["enableAnimation"] = utf8_encode("true");
                      $json[$eidMappingArray[$rowArray[$i]["cs_eid"]]]["opacity"] = 0.5;
                      // $json[$eidMappingArray[$rowArray[$i]["cs_eid"]]]["fill"] = utf8_encode("'#69D2E7'");
                   endif;
                endif;
             else :
                $json[$i]["points"] = array();
                for ($j = 0; $j <= $f_numOfIntervals; $j++) :
                    $tmpYear = $year_to - $f_numOfIntervals + $j;
                    if ($tmpYear == $year_to) :
                       $tmpBusinessVolumeNum  = $businessVolumeNum;
                       $tmpBusinessVolumeText = $businessVolumeText;
                    else :
                       $tmpBusinessVolumeNum  = round($rowArray[$i][$tmpYear],0);
                       $tmpBusinessVolumeText = number_format(round($rowArray[$i][$tmpYear],2), 2, ",", ".");
                    endif;
                    array_push($json[$i]["points"],array("x" => $tmpYear,"y" => $tmpBusinessVolumeNum));
                    $range_max = max($range_max, round(str_replace(",",".",$rowArray[$i][$tmpYear]),0));
                endfor;
                $json[$i]["name"] = $rowArray[$i]["cs_eid"] . " : " . utf8_encode($rowArray[$i]["cmp_comp"]);
                if ($f_type_chart == 12 || $f_type_chart == 13 || $f_type_chart == 14) :
                   $json[$i]["enableAnimation"] = utf8_encode("true");
                   $json[$i]["opacity"] = 1;
                   // $json[$i]["fill"] = utf8_encode("'#69D2E7'");
                endif;
                if ($f_type_chart == 13) :
                   $json[$i]["type"] = utf8_encode("Area");
                   $json[$i]["border"] = utf8_encode("{color: 'transparent'}");
                   $json[$i]["opacity"] = 0.5;
                endif;
             endif;
          endif;
       endif;
   endfor;

   $chartTitle .= " [" . getLngt("Gesamt") . ": " . implode(" | ", $chartSummationArray) . "]";
   $chartTitle = utf8_encode($chartTitle);

   if ($range_max == 0) :
      $range_max = 1000000;
   endif;
   // Depending on the chart type we have to scale $range_max with the summated values
   if ($f_type_chart == 12) :
      for ($j = 0; $j < $chartSummationArrayLen; $j++) :
          $range_max = max($range_max, round(str_replace(",",".",str_replace(".","",$chartSummationArray[$j])),0));
      endfor;
   endif;
   $precision = strlen($range_max) - 1;
   $range_max = $range_max * 1.1;
   $range_max = ceil($range_max / pow(10, $precision)) * pow(10, $precision);
   $range_step = ($range_max / 10);
   $precision2 = strlen($range_step);
   $range_step = floor($range_step / pow(10, ($precision2 - 1))) * pow(10, ($precision2 - 1));
/*
   $tmpFirstNumberOfRangeStep = intval(substr($range_step,0,1));
   if ($tmpFirstNumberOfRangeStep > 1) :
      $range_step = round(($range_step / $tmpFirstNumberOfRangeStep), 0);
   endif;
*/
   if ($interval_from == PHP_INT_MAX) :
      $interval_from = $year_to - $f_numOfIntervals;
   endif;
   if ($interval_to == 0) :
      $interval_to = $year_to;
   endif;
endif;

$json = json_encode($json);
// echo $json;
$json = urlencode($json);
// echo $json;
// echo $interval_from . " => " . $interval_to . "<br>";


// Load interface
if ($userTypeName == "hq") :
   include_once ("../statistic/statistic_interface_hq.inc.php");
else :
   include_once ("../statistic/statistic_interface_cs.inc.php");
endif;
?>

