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


include_once ("../include/mcglobal.inc.php");
include_once ("../include/inc_parseXML.inc.php");
// include_once ("../include/inc_parseXML_MC.inc.php");  // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// include_once ("../include/inc_mtf_func.inc.php");
include_once ("../include/html.inc.php");
include_once ("../include/inc_dbinspector.inc.php");
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");
// include_once ("../statistic/statistic_sql_MC.inc.php");  // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!



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

$debug = false;
$debugOut = "";

$lineFeed = "\n";

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

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

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

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

function statisticSetGlobalParameterArray () {
   global $aligns, $f_statusMode, $f_dateMode, $f_showDateAndTime, $f_crvh_sid, $f_direction_sort;
   global $f_filter, $f_filter2, $f_filter3, $f_filter4, $f_filter5, $f_filter6, $f_filter7, $f_filter8, $f_filter9, $f_filter10;
   global $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;
   global $f_cs_meta, $f_cr_meta, $f_cr_parent, $f_cr_pda_actions, $f_show_invoice_address, $f_show_delivery_address, $summationField, $summationField2, $uniqueSearchFields;
   global $hour_from, $minute_from, $hour_to, $minute_to, $fromTimeRange, $toTimeRange, $f_cmp_new_date, $f_cs_become_cs_date, $f_net_gross;
   global $f_group, $f_groupLen, $f_staticGroup, $f_staticGroupLen;

   $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);
  return $globalParArray;
}


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

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

statisticRequestLogFile($currentTime . " - " . $currentClientIP);
statisticRequestLogFile($statisticReq);


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

getLanguage(__FILE__);
getCurrentScript(__FILE__);

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

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

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

// *** Parse request ***
$statisticArray = xml2array($statisticReq);


// *** Convert result array to usable parameters ***
// * Authentication data *
// Generic fields for multiple types
$authType        = strtolower(convertSpecial($statisticArray["xml"]["statistic"]["auth"]["auth_type"]));
if ($authType == "") : $authType = "cs"; endif;
$authId          = convertSpecial($statisticArray["xml"]["statistic"]["auth"]["auth_id"]);
$authEid         = convertSpecial($statisticArray["xml"]["statistic"]["auth"]["auth_eid"]);
if ($authEid == "" && $authId != "") :
   if ($authType == "cr") :
      $authEid = getFieldValueFromId("courier","cr_id",$authId,"cr_eid");
   else :
      $authEid = getFieldValueFromId("customer","cs_id",$authId,"cs_eid");
   endif;
endif;
if ($authId == "") :
   if ($authType == "cr") :
      $authId = getFieldValueFromId("courier","cr_eid",$authEid,"cr_id");
   else :
      $authId = getFieldValueFromId("customer","cs_eid",$authEid,"cs_id");
   endif;
endif;

$usrAccount     = convertSpecial($statisticArray["xml"]["statistic"]["auth"]["account"]);
$usrPassword    = convertSpecial($statisticArray["xml"]["statistic"]["auth"]["password"]);
$sessionId      = convertSpecial($statisticArray["xml"]["statistic"]["auth"]["session_id"]);
// Optional customer group data (needed to find e.g. an article price automatically). Has to be set explicitly, because a customer could belong to more groups !!!!
$groupId      = convertSpecial($statisticArray["xml"]["statistic"]["auth"]["group_no"]);
$groupName    = convertSpecial($statisticArray["xml"]["statistic"]["auth"]["group_name"]);
if ($groupId != "" && is_numeric($groupId)) :
   $groupName = getFieldValueFromId("groups","grp_id",$groupId,"grp_name");
elseif ($groupName != "") :
   $groupId = getFieldValueFromId("groups","grp_name",$groupName,"grp_id");
endif;
// Reset customer group data if it could not be identified
if ($groupId == "" || $groupName == "") :
   $groupId = "";
   $groupName = "";
endif;

// Get optional authentication data for session with passphrase (!!!!)
// $sessionId      = convertSpecial($statisticArray["xml"]["statistic"]["auth"]["session_id"]);
$passPhrase     = convertSpecial($statisticArray["xml"]["statistic"]["auth"]["passphrase"]);


// Get data of the customer you will get the statistic response for.
// If NOT authentication type "2" (session and passphrase) is requested, map $objXXXX to special requested customer or contractor (!!!!)
$objType = convertSpecial($statisticArray["xml"]["statistic"]["obj_type"]);
$objId   = convertSpecial($statisticArray["xml"]["statistic"]["obj_id"]);
$objEid  = convertSpecial($statisticArray["xml"]["statistic"]["obj_eid"]);

if ($objType == "") : $objType = "cs"; endif;

if ($objType == "cs") :
   if ($objId != "" && $objEid == "") :
      $objEid = getFieldValueFromId("customer","cs_id",$objId,"cs_eid");
   elseif ($objEid != "" && $objId == "") :
      $objId = getFieldValueFromId("customer","cs_eid",$objEid,"cs_id");
   endif;
elseif ($objType == "cr") :
   if ($objId != "" && $objEid == "") :
      $objEid = getFieldValueFromId("courier","cr_id",$objId,"cr_eid");
   elseif ($objEid != "" && $objId == "") :
      $objId = getFieldValueFromId("courier","cr_eid",$objEid,"cr_id");
   endif;
endif;

$debugOut .= "authType: " . $authType . "<br>\n";
$debugOut .= "authId: " . $authId . "<br>\n";
$debugOut .= "authEid: " . $authEid . "<br>\n";
$debugOut .= "usrAccount: " . $usrAccount . "<br>\n";
$debugOut .= "usrPassword: " . $usrPassword . "<br>\n";
$debugOut .= "sessionId: " . $sessionId . "<br>\n";
$debugOut .= "passPhrase: " . $passPhrase . "<br>\n";
$debugOut .= "objType: " . $objType . "<br>\n";
$debugOut .= "objId: " . $objId . "<br>\n";
$debugOut .= "objEid: " . $objEid . "<br>\n";


// ******************
// * AUTHENTICATION *
// ******************

// If authentication type "2" is requested (session and passphrase), check user data of a special "general" object (customer, contractor) defined in the database
$authCheckState = "0";
if ($passPhrase != "" && checkRequestAuthenticationData2($sessionId, $passPhrase)) :
   // Authentication mode "2" is ok, but check for "general" customer to have access to request for data of another object (!!!!)
// !!!! ACHTUNG: DAS "true" rausnehmen !!!!!!!!!!!!!!!!!!!!!!!!!!!
   if (true || checkRequestAuthenticationData($usrAccount, $usrPassword, $sessionId, $authId, $authType)) :
      $authCheckState = "2";
   endif;
endif;
// If authentication type "1" is requested (user, password, session), the requested object in $objXXXX has to be the same as in authentication data
if ($authCheckState == "0") :
   // The $objXXXX has to be the same object requested for. It has to be the same in authentication data
   $objType = $authType;
   $objId = $authId;
   $objEid = $authEid;
   if ($authCheckState == "0" && checkRequestAuthenticationData($usrAccount, $usrPassword, $sessionId, $authId, $authType)) :
      $authCheckState = "1";
   endif;
endif;


// One of both authentication types has to grant access
if ($authCheckState == "1" || $authCheckState == "2") :

   $debugOut .= "Authentication OKAY!<br>\n";
   $debugOut .= "Authentication type: " . $authCheckState . "<br><br>\n";
  
   $debugOn = convertSpecial($statisticArray["xml"]["statistic"]["debug_on"]);
   if (strtoupper($debugOn) == "YES" || strtoupper($debugOn) == "ON") :
      $debug = true;
   endif;

   if ($debug) :
      print_r($statisticArray); echo "<br><br><br>\n\n\n";
   endif;

   if ($objType == "cs") :
      $csId = $objId;
      $csEid = $objEid;
   elseif ($objType == "cr") :
      $crId = $objId;
      $crEid = $objEid;
   endif;

   // Get current global number of THIS database instance
   $constGlobalDbInstNo = getParameterValue("0", "GLOBAL_UNIQUE_DB_INSTANCE_NO", "0", "0");

   // Date range and optional time range
   $day_from      = convertSpecial($statisticArray["xml"]["statistic"]["day_from"]);
   $month_from    = convertSpecial($statisticArray["xml"]["statistic"]["month_from"]);
   $year_from     = convertSpecial($statisticArray["xml"]["statistic"]["year_from"]);
   $day_to        = convertSpecial($statisticArray["xml"]["statistic"]["day_to"]);
   $month_to      = convertSpecial($statisticArray["xml"]["statistic"]["month_to"]);
   $year_to       = convertSpecial($statisticArray["xml"]["statistic"]["year_to"]);

   $hour_from     = convertSpecial($statisticArray["xml"]["statistic"]["hour_from"]);
   $minute_from   = convertSpecial($statisticArray["xml"]["statistic"]["minute_from"]);
   $hour_to       = convertSpecial($statisticArray["xml"]["statistic"]["hour_to"]);
   $minute_to     = convertSpecial($statisticArray["xml"]["statistic"]["minute_to"]);

   $debugOut .= "csId: " . $csId . "<br>\n"; $debugOut .= "csEid: " . $csEid . "<br>\n"; $debugOut .= "crId: " . $crId . "<br>\n"; $debugOut .= "crEid: " . $crEid . "<br>\n";
   $debugOut .= "day_from: " . $day_from . "<br>\n"; $debugOut .= "month_from: " . $month_from . "<br>\n"; $debugOut .= "year_from: " . $year_from . "<br>\n";
   $debugOut .= "day_to: " . $day_to . "<br>\n"; $debugOut .= "month_to: " . $month_to . "<br>\n"; $debugOut .= "year_to: " . $year_to . "<br>\n";
   $debugOut .= "hour_from: " . $hour_from . "<br>\n"; $debugOut .= "minute_from: " . $minute_from . "<br>\n"; $debugOut .= "hour_to: " . $hour_to . "<br>\n"; $debugOut .= "minute_to: " . $minute_to . "<br>\n";

   // If day time has NO restriction then init (00:00:00 - 23:59:59)
   $f_showDateAndTime = convertSpecial($statisticArray["xml"]["statistic"]["day_time_restriction"]);
   if ($f_showDateAndTime == "") :
      $f_showDateAndTime = "0";
   endif;

   // 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;

   $debugOut .= "fromDateRange: " . $fromDateRange . "<br>\n";
   $debugOut .= "toDateRange: " . $toDateRange . "<br>\n";

   // Decimal for ROUND()   
   $roundDec = convertSpecial($statisticArray["xml"]["statistic"]["round_dec"]);
   if ($roundDec == "" || !is_numeric($roundDec)) :
      $roundDec = 2;
   endif;

   if ($objId != "" && $objEid != "") :

      // ................
   endif;

// echo $debugOut . "<br>\n<br>\n";

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

   // Get current requested headquarters from call
   $currHqId = trim($argv[2]);
   if ($currHqId == "" || !is_numeric($currHqId)) :
      if ($csId != "" && is_numeric($csId)) :
         $currHqId = getFieldValueFromId("customer","cs_id",$csId,"hq_id");
      elseif ($crId != "" && is_numeric($crId)) :
         $currHqId = getFieldValueFromId("courier","cr_id",$crId,"hq_id");
      endif;
   endif;
   $debugOut .= "currHqId: " . $currHqId . "<br>\n";


   // Init system parameter
   $path = "../temp/download/";
   // $f_secretFileName = "NL_" . str_replace("-","",getDateTime("date_yesterday_currentmonth_currentyear")) . ".csv";
   $f_secretFileName = "STAT_" . $authId . "_" . $currentTime . ".csv";
   $aligns = convertSpecial($statisticArray["xml"]["statistic"]["aligns"]);
   $f_statistic = convertSpecial($statisticArray["xml"]["statistic"]["statistic_format"]);                   // Statistic format [30 = Anzahl und Nettoumsätze | 10 = Anzahl und Nettoumsätze pro Transporteur | 60 = Anzahl und Nettoumsätze pro Kunde]
   $f_statusMode = convertSpecial($statisticArray["xml"]["statistic"]["status_mode"]);                       // All jobs, finished jobs only, exported jobs only
   if ($f_statusMode == "") : $f_statusMode = "1"; endif;
   $f_dateMode = convertSpecial($statisticArray["xml"]["statistic"]["date_mode"]);                           // "creating date", "booking date", "finish date" [default], "export date", "order_date"
   if ($f_dateMode == "") : $f_dateMode = "2"; endif;
   $f_crvh_sid = convertSpecial($statisticArray["xml"]["statistic"]["crvh_sid"]);                            // Filter for special vehicle SID
   $f_direction_sort = convertSpecial($statisticArray["xml"]["statistic"]["direction_sort"]);                // ORDER BY ASC or DESC"
   if ($f_direction_sort == "") : $f_direction_sort = "0"; endif;
   $f_filter = convertSpecial($statisticArray["xml"]["statistic"]["filter"]);                                // Filter (Split for vehicletype, start zipcode, etc.)
   if ($f_filter == "") : $f_filter = "0"; endif;
   $f_filter2 = convertSpecial($statisticArray["xml"]["statistic"]["filter2"]);                              // Filter (Split for "Aufträge und Gutschriften") (0 = none)
   if ($f_filter2 == "") : $f_filter2 = "0"; endif;
   $f_filter3 = convertSpecial($statisticArray["xml"]["statistic"]["filter3"]);                              // Filter (Split for "Fahrzeugkategorie" ["jb_type"]) (0 = none)
   if ($f_filter3 == "") : $f_filter3 = "0"; endif;
   $f_filter4 = convertSpecial($statisticArray["xml"]["statistic"]["filter4"]);                              // Filter (Split for headquarters) (0 = none)
   if ($f_filter4 == "") : $f_filter4 = "0"; endif;
   $f_filter5 = convertSpecial($statisticArray["xml"]["statistic"]["filter5"]);                              // Filter (Split for branches) (0 = none)
   if ($f_filter5 == "") : $f_filter5 = "0"; endif;
   $f_filter6 = convertSpecial($statisticArray["xml"]["statistic"]["filter6"]);                              // Filter (Split for carriers [ONLY customer statistics]) (0 = none)
   if ($f_filter6 == "") : $f_filter6 = "0"; endif;
   $f_filter7 = convertSpecial($statisticArray["xml"]["statistic"]["filter7"]);                              // Filter (Split for vehicles) (0 = none)
   if ($f_filter7 == "") : $f_filter7 = "0"; endif;
   $f_filter8 = convertSpecial($statisticArray["xml"]["statistic"]["filter8"]);                              // Filter (Split for employees) (0 = none)
   if ($f_filter8 == "") : $f_filter8 = "0"; endif;
   $f_filter9 = convertSpecial($statisticArray["xml"]["statistic"]["filter9"]);                              // Filter (Split for job types ["jb_type"]) (0 = none)
   if ($f_filter9 == "") : $f_filter9 = "0"; endif;
   $f_filter10 = convertSpecial($statisticArray["xml"]["statistic"]["filter10"]);                            // Filter (Split for costcenter ["csc_id_payer" / "csc_id_related"]) (0 = none)
   if ($f_filter10 == "") : $f_filter10 = "0"; endif;
   $f_price_formular = convertSpecial($statisticArray["xml"]["statistic"]["price_formular"]);                // Computation of the price (0 = jb_totalprice)
   if ($f_price_formular == "") : $f_price_formular = "0"; endif;
   $f_filter_a = convertSpecial($statisticArray["xml"]["statistic"]["filter_a"]);                            // Subfilter to $f_filter (Kind of vehicletype [Requested or real]) (0 = none)
   if ($f_filter_a == "") : $f_filter_a = "0"; endif;
   $f_filter_interval = convertSpecial($statisticArray["xml"]["statistic"]["filter_interval"]);              // Filter (Split for time intervals) (0 = none)
   if ($f_filter_interval == "") : $f_filter_interval = "0"; endif;
   $g_crvh_filter = convertSpecial($statisticArray["xml"]["statistic"]["crvh_filter"]);                      // Vehicle filter  ("" = default)
   $f_mode_statistic = convertSpecial($statisticArray["xml"]["statistic"]["mode_statistic"]);                // Normal statistic (0 = default, 1 = calculator)
   if ($f_mode_statistic == "") : $f_mode_statistic = "0"; endif;
   $f_filter_calc = convertSpecial($statisticArray["xml"]["statistic"]["filter_calc"]);                      // (0 = none)
   if ($f_filter_calc == "") : $f_filter_calc = "0"; endif;
   $f_service = convertSpecial($statisticArray["xml"]["statistic"]["service"]);                              // Service for "service statistic" (0 = none)
   if ($f_service == "") : $f_service = "0"; endif;
   $f_servicetype = convertSpecial($statisticArray["xml"]["statistic"]["servicetype"]);                      // Servicetype for "service statistic" (0 = none)
   if ($f_servicetype == "") : $f_servicetype = "0"; endif;
   $f_jb_service_str = convertSpecial($statisticArray["xml"]["statistic"]["jb_service"]);                    // Job service array as filter (empty array = default)
   $f_jb_service = "";
   if ($f_jb_service_str != "") :
      $f_jb_service = explode(",", $f_jb_service_str);
   endif;
   $f_split_jb_services = convertSpecial($statisticArray["xml"]["statistic"]["split_jb_services"]);          // Filter (Split for job services) (0 = none)
   if ($f_split_jb_services == "") : $f_split_jb_services = "0"; endif;
   $f_jb_specifics_str = convertSpecial($statisticArray["xml"]["statistic"]["jb_specifics"]);                // Job specifics used as filter (empty array = default)
   $f_jb_specifics = "";
   if ($f_jb_specifics_str != "") :
      $f_jb_specifics = explode(",", $f_jb_specifics_str);
   endif;
   $f_cs_meta = convertSpecial($statisticArray["xml"]["statistic"]["cs_meta"]);                              // Filter (Split for sub customers ["meta-customer"]) (0 = none)
   if ($f_cs_meta == "") : $f_cs_meta = "0"; endif;
   $f_cr_meta = convertSpecial($statisticArray["xml"]["statistic"]["cr_meta"]);                              // Filter (Split for driver) (0 = none)
   if ($f_cr_meta == "") : $f_cr_meta = "0"; endif;
   $f_cr_parent = convertSpecial($statisticArray["xml"]["statistic"]["cr_parent"]);                          // Every courier or driver OR cumulation by parent ("" = default)
   $f_cr_pda_actions = convertSpecial($statisticArray["xml"]["statistic"]["cr_pda_actions"]);                // Filter for courier action statistics (absolute/relative per job) (0 = none)
   if ($f_cr_pda_actions == "") : $f_cr_pda_actions = "0"; endif;
   $f_show_invoice_address = convertSpecial($statisticArray["xml"]["statistic"]["show_invoice_address"]);
   if ($f_show_invoice_address == "") : $f_show_invoice_address = "0"; endif;
   $f_show_delivery_address = convertSpecial($statisticArray["xml"]["statistic"]["show_delivery_address"]);
   if ($f_show_delivery_address == "") : $f_show_delivery_address = "0"; endif;
   $summationField = "stat.count_jobs";
   $summationField2 = "stat.business_volume";
   $uniqueSearchFields = array();
   $f_cmp_new_date = convertSpecial($statisticArray["xml"]["statistic"]["cmp_new_date"]);                    // Filter (Only new data set since date)
   $f_cs_become_cs_date = convertSpecial($statisticArray["xml"]["statistic"]["cs_become_cs_date"]);          // Filter (Only new customers since date)
   $f_net_gross = "0";
   $f_group = array();
   $f_groupLen = 0;
   $f_staticGroup = array();
   $f_staticGroupLen = 0;

   $debugOut .= "f_statistic: " . $f_statistic . "<br>\n";

   // Init "Local" parameters
   $hqName = "GESAMT";
   $hqMnemonic = "GESAMT";
   if ($currHqId != "" && is_numeric($currHqId)) : 
      $hqMnemonic = getFieldValueFromId("headquarters","hq_id",$currHqId,"hq_mnemonic");
      $hqName = getFieldValueFromId("headquarters","hq_id",$currHqId,"hq_name");
      if ($hqMnemonic == "" && $hqName == "") :
         $currHqId = "";
      endif;
   endif;
   if ($currHqId == "") :
      $f_hq_id = getColVectorFromDB2ArrayByClause("headquarters", "hq_id", "", "", "", "");
   else :
      $f_hq_id = array($currHqId);
   endif;

   $orderByClause = "";


   // **** Current month of last year ****
   $xmlStatistic = "";
   $globalParArray = statisticSetGlobalParameterArray();
   // !!!!
   // ATTENTION: 
   // For auth by contractor the customer statistic has to be called WITH value in $crEid AND
   // for auth by customer the contractor statistic has to be called WITH value in $csEid !!!!
   // !!!!
   $f_category = "3";    // [1 = Auftrag | 2 = Transporteure | 3 = Kunden]   
   if ($objType == "cs") :
      $f_category = "3";
      if ($f_statistic == "") : 
         $f_statistic = "60";
      endif;
   elseif ($objType == "cr") :
      $f_category = "2";
      if ($f_statistic == "") : 
         $f_statistic = "10";
      endif;
   endif;   
   $idArrayLen = getCategoryDBFields($f_statistic);

   $statOut = getStatistic($globalParArray, $f_statistic, $fromDateRange . " 00:00:00", $toDateRange . " 23:59:59", $csEid, $crEid, $orderByClause);

   // Output
   $statisticXML = mcArray2Xml($statOut[0], "", $lineFeed);
   // $xmlStatistic .= "<count_jobs>" . number_format($statOut[0][0]["count_jobs"], 0, ",", ".") . "</count_jobs>";
   // $xmlStatistic .= "<business_volume>" . number_format($statOut[0][0]["business_volume"], $roundDec, ",", ".") . "</business_volume>";
   // $xmlStatistic .= number_format(round(($statOut[0][0]["business_volume"] / $yesterdayCurrentMonthLastYear[0][0]["count_jobs"]),$roundDec), $roundDec, ",", ".");

   // if (file_exists($path . $f_secretFileName)) :
   //    unlink($path . $f_secretFileName);
   // endif;

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

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

// Output
$statisticResponse .= "<xml>";   
if ($errLen > 0) :
   statisticRequestLogFile("ERRORS", 1);
   $statisticResponse .= "<state>NOT OK</state>";
   $statisticResponse .= "<errors>";
   for ($i = 0; $i < $errLen; $i++) :
       $statisticResponse .= "<error>";
       $statisticResponse .= "<err_no>" . $err[$i][0] . "</err_no>";
       $statisticResponse .= "<err_desc><![CDATA[" . mcEncode($err[$i][1]) . "]]></err_desc>";
       $statisticResponse .= "</error>";
       if ($debug) :
          $statisticResponse .= "<debug>" . $debugOut . "</debug>";
       endif;
       statisticRequestLogFile($err[$i][0] . " : " . mcEncode($err[$i][1]), 1);
   endfor;
   $statisticResponse .= "</errors>";
else :
   $statisticResponse .= "<state>OK</state><statistic>" . $xmlStatistic . "</statistic>";
   if ($debug) :
      $statisticResponse .= "<debug>" . $debugOut . "</debug>";
   endif;
   $statisticResponse .= $statisticXML;
endif;
$statisticResponse .= "</xml>";

// Log entries
statisticRequestLogFile($statisticResponse);    // Write response into log
statisticRequestLogFile("___________________________________________________________________________________");

// Return output
echo $statisticResponse;


/*
// REQUEST
<xml>
  <statistic>                                                 // Statistic request.
    <auth>                                                    // Identifikation des Objektes (Kunde, Unternehmer, etc.)
      <auth_type>....</auth_type>                             // Object type ("cs" [or "empty"] = customer, "cr" = contractor, etc.).
      <auth_id>....</auth_id>                                 // Object ID (Internal ID) regarding the type
      <auth_eid>....</auth_eid>                               // Object EID (Unique) regarding the type
      <account>....</account>                                 // Eingetragener Benutzer für den Kunden => cs.cs_admin => emp.emp_id => emp.usr_id => usr.usr_id => usr.usr_account
      <password>....</password>                               // Passwort für den Benutzer             => usr.usr_password
      <session_id>....</session_id>                           // Zusätzliche Session-ID, die mit dem Kunden ausgehandelt wurde   [mandatory]
      <costcenter_name>....</costcenter_name>                 // Kostenstellenname {"abcd", "efgh", ...} => Mapping csc_id   [optional]
      <group_no>....</group_no>                               // Nummer der Kundengruppe (Bei einer automatischen Preisfindung muss entweder <group_no> oder <group_name> gesetzt sein)
      <group_name>....</group_name>                           // Name der Kundengruppe (Bei einer automatischen Preisfindung muss entweder <group_name> oder <group_no> gesetzt sein)
    </auth>                                        

    <debug_on>....</debug_on>                                 // Activates debug output ("ON" or "YES")

    <operation>GENERATE</operation>                           // Operation (GETs auth header if object does exist or GENERATEs auth header, default is "GET" if emty tag)

    <obj_type>....</obj_type>                                 // Type of the object ("cs" = empty = default = customer, "cr" = contractor, etc.)
    <obj_id>....</obj_id>                                     // ID of the object (Either ID or EID has to exist)
    <obj_eid>....</obj_eid>                                   // EID of the object (Either ID or EID has to exist)

    <day_from>....</day_from>
    <month_from>....</month_from>
    <year_from>....</year_from>
    <day_to>....</day_to>
    <month_to>....</month_to>
    <year_to>....</year_to>
    
    <hour_from>....</hour_from>
    <minute_from>....</minute_from>
    <hour_to>....</hour_to>
    <minute_to>....</minute_to>
    <day_time_restriction>....</day_time_restriction>
    
    <round_dec>....</round_dec>
    
    <aligns>....</aligns>
    <status_mode>....</status_mode>
    <date_mode>....</date_mode>
    <crvh_sid>....</crvh_sid>
    <direction_sort>....</direction_sort>
    <filter>....</filter>
    <filter2>....</filter2>
    <filter3>....</filter3>
    <filter4>....</filter4>
    <filter5>....</filter5>
    <filter6>....</filter6>
    <filter7>....</filter7>
    <filter8>....</filter8>
    <filter9>....</filter9>
    <filter10>....</filter10>
    <price_formular>....</price_formular>
    <filter_a>....</filter_a>
    <filter_interval>....</filter_interval>
    <crvh_filter>....</crvh_filter>
    <mode_statistic>....</mode_statistic>
    <filter_calc>....</filter_calc>
    <service>....</service>
    <servicetype>....</servicetype>
    <jb_service>....</jb_service>
    <split_jb_services>....</split_jb_services>
    <jb_specifics>....</jb_specifics>
    <cs_meta>....</cs_meta>
    <cr_meta>....</cr_meta>
    <cr_parent>....</cr_parent>
    <cr_pda_actions>....</cr_pda_actions>
    <show_invoice_address>....</show_invoice_address>
    <show_delivery_address>....</show_delivery_address>
    <cmp_new_date>....</cmp_new_date>
    <cs_become_cs_date>....</cs_become_cs_date>
  </statistic>
</xml>


// RESPONSE (GENERATE and GET)
<xml>
  <state>OK</state>

  <statistic>
    <auth>
      <customer>....</customer>                             // EID of the customer
      <account>....</account>                               // Account
      <password>....</password>                             // Password
      <session_id>....</session_id>                         // Session ID
      <costcenter_name>....</costcenter_name>               // Costcenter name
    </auth>
  </statistic>
</xml>
*/
?>
