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


include_once ("../include/mcglobal.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 ("../include/email/htmlMimeMail.php");
include_once ("../include/services_func.inc.php");


$autoMode = true;
$hasAccess = false;
if (!isset($argv[1]) || $argv[1] == "") :
   include_once ("../include/auth.inc.php");
   $usrAccessArray["hq"] = "1";
   authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
   authCheckEmployeeRights($emp_id, "8", "1");
   $autoMode = false;
   $hasAccess = true;
else :
   if ($argv[1] == "acapella7890") :
       $hasAccess = true;
   endif;
endif;


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, $f_priceMode, $f_editCsMode, $station_based_group_field, $f_bookedJobsOnly, $f_permanentJobsOnly;
   global $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;
   global $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;

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


if ($hasAccess) :

   // Get current requested headquarters from call
   $currHqId = trim($argv[2]);
   
   // Date range
   $argvFromDate = trim($argv[3]);
   $argvToDate = trim($argv[4]);
    
   // Init system parameter
   $path = "../temp/download/";
   $f_secretFileName = "NL_" . str_replace("-","",getDateTime("date_yesterday_currentmonth_currentyear")) . ".csv";   
   $idArray = array();
   $fieldArray = array();
   $titleArray = array();
   $fieldSortArray = array();
   $fieldSqlArray = array();
   $alignArray = array();
   $currDateTime = getDateTime("0");
   
   // Init global parameter for script
   $aligns = "";
   $f_statusMode = "2";  // Exported jobs
   $f_dateMode = "2";  // "creating date", "booking date", "finish date" [default], "export date", "order_date"
   $f_showDateAndTime = "0";  // Clock time restriction (0 = none)
   $f_crvh_sid = "";  // Filter for special vehicle SID
   $f_direction_sort = "0";  // ORDER BY ASC or DESC"
   $f_filter = "0";  // Filter (Split for vehicletype, start zipcode, etc.)
   $f_filter2 = "0";  // Filter (Split for "Aufträge und Gutschriften") (0 = none)
   $f_filter3 = "0";  // Filter (Split for "Fahrzeugkategorie" ["jb_type"]) (0 = none)
   $f_filter4 = "0";  // Filter (Split for headquarters) (0 = none)
   $f_filter5 = "0";  // Filter (Split for branches) (0 = none)
   $f_filter6 = "0";  // Filter (Split for carriers [ONLY customer statistics]) (0 = none)
   $f_filter7 = "1";  // Filter (Split for vehicles) (0 = none)
   $f_filter8 = "0";  // Filter (Split for employees) (0 = none)
   $f_filter9 = "0";  // Filter (Split for job types ["jb_type"]) (0 = none)
   $f_filter10 = "0";  // Filter (Split for costcenter ["csc_id_payer" / "csc_id_related"]) (0 = none)
   $f_filter12 = "1";  // Filter (Split for partner provision) (0 = none)
   $f_price_formular = "0";  // Computation of the price (0 = jb_totalprice)
   $f_filter_a = "0";  // Subfilter to $f_filter (Kind of vehicletype [Requested or real]) (0 = none)
   $f_filter_interval = "0";  // Filter (Split for time intervals) (0 = none)
   $g_crvh_filter = "";  // Vehicle filter  ("" = default)
   $f_mode_statistic = "0";  // Normal statistic (0 = default, 1 = calculator)
   $f_filter_calc = "0";  // (0 = none)
   $f_service = "0";  // Service for "service statistic" (0 = none)
   $f_servicetype = "0";  // Servicetype for "service statistic" (0 = none)
   $f_jb_service = array();  // Job service array as filter (empty array = default)
   $f_split_jb_services = "0";  // Filter (Split for job services) (0 = none)
   $f_jb_specifics = array();  // Job specifics used as filter (empty array = default)
   $f_cs_meta = "0";  // Filter (Split for sub customers ["meta-customer"]) (0 = none)
   $f_cr_meta = "0";  // Filter (Split for driver) (0 = none)
   $f_cr_parent = "";  // Every courier or driver OR cumulation by parent ("" = default)
   $f_cr_pda_actions = "0";  // Filter for courier action statistics (absolute/relative per job) (0 = none)
   $f_show_invoice_address = "0";
   $f_show_delivery_address = "0";
   $summationField = "stat.count_jobs";
   $summationField2 = "stat.business_volume";
   $uniqueSearchFields = array();
   $hour_from = "";
   $minute_from = "";
   $hour_to = "";
   $minute_to = "";
   $fromTimeRange = "";
   $toTimeRange = "";
   $f_cmp_new_date = "";  // Filter (Only new data set since date)
   $f_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;
   $f_priceMode = "0";  // 0 = business volume, 1 = Cartage, 2 = EAU, 3 = BSG

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

   $csEid = "";
   $crEid = "";
   $orderByClause = "cr_sid";

   // Decimal for ROUND()
   $roundDec = 2;

   // Output matrix
   $matrix = array();  // array("","Monat Vorjahr","Vormonat","Aktueller Monat IST","Aktueller Monat SOLL")
   $output = "";

   // FILTER
   $filterAlignOffset = 0;  // Activating more filters will change the column
   // 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;
   // Output regarding 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;

   // Exclude special vehicles (e.g.: SID=1888)
   $avoidSpecialVehicles =  true;
   $excludedVehicles = getParameterValue("0", "EMAIL_CRVHSID_NO_MAIL", "0");  // "Meta-Global" <=> hq_id = 0
   $excludedVehiclesArr = explode(",", $excludedVehicles);


   // **** Business volume ****   
   $globalParArray = statisticSetGlobalParameterArray();
   $f_category = "2";
   $f_statistic = "10";
   $idArrayLen = getCategoryDBFields($f_statistic);
   // Date range
   if ($argvFromDate != "" && $argvToDate != "") :
      $fromDateRange = $argvFromDate;
      $toDateRange = $argvToDate;
   else :
      // Default: Single day yesterday
      $fromDateRange = getDateTime("date_yesterday_currentmonth_currentyear");
      $toDateRange = getDateTime("date_yesterday_currentmonth_currentyear");
   endif;
   // Add clock time
   if (substr($fromDateRange,-8) != "00:00:00") :
      $fromDateRange .= " 00:00:00";
   endif;
   if (substr($toDateRange,-8) != "23:59:59") :
      $toDateRange .= " 23:59:59";
   endif;
   // Format date for output
   $fromDateRangeOut = substr($argvFromDate,8,2) . "." . substr($argvFromDate,5,2) . "." . substr($argvFromDate,0,4);
   $toDateRangeOut = substr($argvToDate,8,2) . "." . substr($argvToDate,5,2) . "." . substr($argvToDate,0,4);

   $businessVolume = getStatistic($globalParArray, $f_statistic, $fromDateRange, $toDateRange, $csEid, $crEid, $orderByClause);

   $businessVolume = $businessVolume[0];
   $businessVolumeLen = count($businessVolume);

   // Output
   $matrix[0][0] = "EID";
   $matrix[0][1] = "Name";
   $matrix[0][2] = "Vorname";
   $matrix[0][3] = "Firma UN";
   $matrix[0][4] = "Fahrzeug";
   $matrix[0][5] = "Fahrzeugtyp";
   $matrix[0][6] = "Aufträge";
   $matrix[0][7] = "KM";
   $matrix[0][8] = "KM Preis";
   $matrix[0][9] = "Nettoumsatz";
   $matrix[0][10] = "Nettofrachtvergütung";
   $matrix[0][11] = "Prozentsatz";
   $matrix[0][12] = "Prozentsatz Soll";
   $matrix[0][13] = "Partnerprovision";
   $matrix[0][14] = "Auszahlung";
   $matrix[0][15] = "EAU";
   $matrix[0][16] = "EAU Soll";
   $matrix[0][17] = "EAU Delta";
   $matrix[0][18] = "BSG [%]";
   $matrix[0][19] = "Niederlassung";

   $matrixAlignArr = array("left","left","left","left","left","left","right","right","right","right","right","right","right","right","right","right","right","right","right","left");

   for ($i = 0; $i < $businessVolumeLen; $i++) :
       $j = $i + 1;
       $matrix[$j][0] = $businessVolume[$i]["cr_eid"];
       $matrix[$j][1] = $businessVolume[$i]["usr_name"];
       $matrix[$j][2] = $businessVolume[$i]["usr_firstname"];
       $matrix[$j][3] = $businessVolume[$i]["cr_cmp_comp"];
       $matrix[$j][4] = $businessVolume[$i]["cr_sid"];
       $matrix[$j][5] = $businessVolume[$i]["vht_id"];              
       $matrix[$j][6] = $businessVolume[$i]["count_jobs"];
       $matrix[$j][7] = 0;  // Init
       $matrix[$j][8] = 0;  // Init
       $matrix[$j][9] = $businessVolume[$i]["business_volume"];
       $matrix[$j][10] = 0;  // Init
       $matrix[$j][11] = 0;  // Init
       $matrix[$j][12] = 0;  // Init
       $matrix[$j][13] = ($businessVolume[$i]["jb_crvh_partner_commission"] == "" ? "ZERO" : $businessVolume[$i]["jb_crvh_partner_commission"]);
       $matrix[$j][14] = 0;  // Init
       $matrix[$j][15] = 0;  // Init
       $matrix[$j][16] = 0;  // Init
       $matrix[$j][17] = 0;  // Init
       $matrix[$j][18] = 0;  // Init
       $matrix[$j][19] = ""; // Init
   endfor;


   // **** Cartage volume ****
   $f_priceMode = "1";  // 0 = business volume, 1 = Cartage, 2 = BSG
   $globalParArray = statisticSetGlobalParameterArray();
   $f_category = "2";
   $f_statistic = "10";
   $idArrayLen = getCategoryDBFields($f_statistic);

   $cartageVolume = getStatistic($globalParArray, $f_statistic, $fromDateRange, $toDateRange, $csEid, $crEid, $orderByClause);

   $cartageVolume = $cartageVolume[0];
   $cartageVolumeLen = count($cartageVolume);

   $matrixLen = count($matrix);
   for ($m = 1; $m < $matrixLen; $m++) :
       for ($i = 0; $i < $cartageVolumeLen; $i++) :
       
           // Check empty value
           if ($cartageVolume[$i]["jb_crvh_partner_commission"] == "") : $cartageVolume[$i]["jb_crvh_partner_commission"] = "ZERO"; endif;
       
           // Check row matches having the same EID, SID and partner provision. Triple will be unique only.
           if ($matrix[$m][0] == $cartageVolume[$i]["cr_eid"] && $matrix[$m][4] == $cartageVolume[$i]["cr_sid"] && $matrix[$m][13] == $cartageVolume[$i]["jb_crvh_partner_commission"]) :
              $matrix[$m][10] = $cartageVolume[$i]["business_volume"];
              if ($matrix[$m][9] != 0) :
                 $matrix[$m][11] = (100-(($matrix[$m][10]/$matrix[$m][9]) * 100));
              else :
                 $matrix[$m][11] = 0;
              endif;

              // Get partner commission and invoice vehicle type
              $crvhPartnerCommission = $matrix[$m][13];
              $vhtName = "";
              $crId = getFieldValueFromClause("courier", "cr_id", "cr_eid = '" . $matrix[$m][0] . "'");  // AND cr_sid != ''
              if ($crId != "" && $crId > "0") :              
                 // Get hq_id of the courier
                 if ($currHqId != "" && is_numeric($currHqId)) :
                    $crHqId = $currHqId;
                 else :
                    $crHqId = getFieldValueFromId("courier","cr_id",$crId,"hq_id");
                 endif;
                 $crHqMnemonic = "";
                 if ($crHqId != "" && is_numeric($crHqId)) :
                    $crHqMnemonic = getFieldValueFromId("headquarters","hq_id",$crHqId,"hq_mnemonic");
                 endif;

                 // Get partner commission
                 if ($crvhPartnerCommission == "ZERO" || !is_numeric($crvhPartnerCommission)) :
                    // $crSid = getFieldValueFromId("courier","cr_id",$crId,"cr_sid");                 
                    $crSid = $cartageVolume[$i]["cr_sid"];
                    if ($crSid != "") :
//                       $crvhPartnerCommission = getFieldValueFromClause("couriervehicle", "crvh_partner_commission", "cr_id = '" . $crId . "' AND crvh_sid = '" . $crSid . "'");
                    endif;
                 endif;

                 // Get (invoice) vehicle type
                 $vhtId = getFieldValueFromId("courier","cr_id",$crId,"vht_id_inv");
                 if (($vhtId == "" || $vhtId == "0") && $crSid != "") :
                    $vhtId = getFieldValueFromClause("couriervehicle", "vht_id", "cr_id = '" . $crId . "' AND crvh_sid = '" . $crSid . "'");
                 endif;
                 if ($vhtId != "" && $vhtId > "0") :
                    // Get name of the vehicle type
                    $vhtName = getFieldValueFromClause("metatype", "mt_value", "mt_type = 'vehicletype' AND mt_sort = '" . $vhtId . "'");

                    // Get "km-Preis" and "Globaler<br>Frachtverg.-Abschlag [%] 	" from service matrix
                    $matrix[$m][8] = 0;
                    $matrix[$m][12] = 0;
                    // ATTENTION: Special treatment regarding potential increase of type numbers e.g. with factor 10 in the future
                    if ($vhtName != "" && (($vhtId >= "1" && $vhtId <= "9") || $vhtId == "11")) :
                       // Get "km-Preis"
                       $srvId = getFieldValueFromClause("service", "srv_id", "srv_mode = '0' AND hq_id = '" . $crHqId . "' AND srv_name = 'km-Preis'");
                       $srvtId = getFieldValueFromClause("servicetype", "srvt_id", "srvt_mode = '0' AND hq_id = '" . $crHqId . "' AND srvt_name = '" . $vhtName . "'");
                       $matrix[$m][8] = getServiceValues($srvId, $srvtId, 0, $crHqId, $currDateTime, "1");

                       // Get "Globaler<br>Frachtverg.-Abschlag [%]"
                       $srvId = getFieldValueFromClause("service", "srv_id", "srv_mode = '0' AND hq_id = '" . $crHqId . "' AND srv_name = 'Globaler<br>Frachtverg.-Abschlag [%]'");
                       // $srvtId = getFieldValueFromClause("servicetype", "srvt_id", "srvt_mode = '0' AND hq_id = '" . $crHqId . "' AND srvt_name = '" . $vhtName . "'");
                       $tmpPrices = getServiceValues($srvId, $srvtId, 0, $crHqId, $currDateTime, "3");
                       $matrix[$m][12] = $tmpPrices[1];
                    endif;
                 endif;
              endif;
              if ($crvhPartnerCommission == "" || $crvhPartnerCommission == "ZERO") : $crvhPartnerCommission = 0; endif;
              // $matrix[$m][13] = $crvhPartnerCommission;
              $matrix[$m][5] = $vhtName;
              $matrix[$m][19] = $crHqMnemonic;

              // Payout   ROUND(jb.jb_cr_price * (1 + (crvh.crvh_partner_commission / 100)), 2) AS payout
              $matrix[$m][14] = $matrix[$m][10] * (1 + ($crvhPartnerCommission / 100));

              // EAU   ROUND(jb.jb_totalprice - (jb.jb_cr_price * (1 + (crvh.crvh_partner_commission / 100))), 2) AS eau
              $matrix[$m][15] = $matrix[$m][9] - $matrix[$m][14];

              // EAU Soll
              $matrix[$m][16] = $matrix[$m][9] * ($matrix[$m][12] / 100);

              // EAU Delta
              $matrix[$m][17] = $matrix[$m][15] - $matrix[$m][16];

              // BSG   ROUND(((jb.jb_totalprice - (jb.jb_cr_price * (1 + (crvh.crvh_partner_commission / 100)))) / jb.jb_totalprice) * 100, 2)
              if ($matrix[$m][9] != 0) :
                 $matrix[$m][18] = (($matrix[$m][9] - $matrix[$m][14]) / $matrix[$m][9]) * 100;
              else :
                 $matrix[$m][18] = "0";
              endif;
           endif;
       endfor;
   endfor;
   
   
   // **** KM ****
   $f_priceMode = "11";  // 11 = KM
   $globalParArray = statisticSetGlobalParameterArray();
   $f_category = "2";
   $f_statistic = "10";
   $idArrayLen = getCategoryDBFields($f_statistic);

   $km = getStatistic($globalParArray, $f_statistic, $fromDateRange, $toDateRange, $csEid, $crEid, $orderByClause);

   $km = $km[0];
   $kmLen = count($km);

   $matrixLen = count($matrix);
   for ($m = 1; $m < $matrixLen; $m++) :
       for ($i = 0; $i < $kmLen; $i++) :
       
           // Check empty value
           if ($km[$i]["jb_crvh_partner_commission"] == "") : $km[$i]["jb_crvh_partner_commission"] = "ZERO"; endif;
       
           // Check row matches having the same EID, SID and partner provision. Triple will be unique only.
           if ($matrix[$m][0] == $km[$i]["cr_eid"] && $matrix[$m][4] == $km[$i]["cr_sid"] && $matrix[$m][13] == $km[$i]["jb_crvh_partner_commission"]) :
              // Get km
              $matrix[$m][7] = $km[$i]["business_volume"];
           endif;
       endfor;
   endfor;
   

   // Format output of the fields
   for ($m = 1; $m < $matrixLen; $m++) :
       $matrix[$m][7] = number_format(round($matrix[$m][7],$roundDec), $roundDec, ",", ".");
       $matrix[$m][8] = number_format(round($matrix[$m][8],$roundDec), $roundDec, ",", ".");
       $matrix[$m][9] = number_format(round($matrix[$m][9],$roundDec), $roundDec, ",", ".");
       $matrix[$m][10] = number_format(round($matrix[$m][10],$roundDec), $roundDec, ",", ".");
       $matrix[$m][11] = number_format(round($matrix[$m][11],$roundDec), $roundDec, ",", ".");
       $matrix[$m][12] = number_format(round($matrix[$m][12],$roundDec), $roundDec, ",", ".");
       if ($matrix[$m][13] == "" || $matrix[$m][13] == "ZERO") : $matrix[$m][13] = 0; endif;
       $matrix[$m][13] = number_format(round($matrix[$m][13],$roundDec), $roundDec, ",", ".");
       $matrix[$m][14] = number_format(round($matrix[$m][14],$roundDec), $roundDec, ",", ".");
       $matrix[$m][15] = number_format(round($matrix[$m][15],$roundDec), $roundDec, ",", ".");
       $matrix[$m][16] = number_format(round($matrix[$m][16],$roundDec), $roundDec, ",", ".");
       $matrix[$m][17] = number_format(round($matrix[$m][17],$roundDec), $roundDec, ",", ".");
       $matrix[$m][18] = number_format(round($matrix[$m][18],$roundDec), $roundDec, ",", ".");
   endfor;
   
  
   // Define potential hidden cols
   $hiddenCols = array();
   // $hiddenCols = array("4","8","12");


   // Define HTML output and CSV matrix
   $csvMatrix = array();
   $csvHeadline = "ÜBERSICHT UMSÄTZE/FRACHTVERGÜTUNGEN" . ($hqName != "" ? " [" . $hqName . "] " : " ") . "für den Zeitraum " . $fromDateRangeOut . " bis " . $toDateRangeOut;
   $output .= $csvHeadline . "<br><br><br><br>";
   if (!$autoMode) :
      $output .= "Ausgeführt von: " . $usrFirstname . " " . $usrName . "<br><br>";
   endif;
   $output .= "<table style=\"border:1px solid #7777FF; border-collapse:collapse; background-color:#CCCCFF;\" border=\"1\">";
   // $output .= "<tr><td> </td><td colspan=\"4\" align=\"center\"><b>" . "Umsatz " . $hqName . "</b></td><td colspan=\"4\" align=\"center\"><b>" . "Anzahl Aufträge" . "</b></td><td colspan=\"4\" align=\"center\"><b>" . "Durchschnittlicher Auftragswert" . "</b></td><tr>";
   // $output .= "<tr><td class=\"td_border td_cell\"> </td><td colspan=\"3\" class=\"td_border td_cell\" align=\"center\"><b>" . "Umsatz " . $hqName . "</b></td><td colspan=\"3\" class=\"td_border td_cell\" align=\"center\"><b>" . "Anzahl Aufträge" . "</b></td><td colspan=\"3\" class=\"td_border td_cell\" align=\"center\"><b>" . "Durchschnittlicher Auftragswert" . "</b></td><tr>";
   for ($i = 0; $i < $matrixLen; $i++) :
       // Avoid special vehicles
       if (!$avoidSpecialVehicles || !(in_array($matrix[$i][4], $excludedVehiclesArr))) :
          $output .= "<tr>";
          for ($j = 0; $j < 20; $j++) :       
              $k = array_search($j, $hiddenCols);
              if ($k === FALSE) :
	               $output .= "<td class=\"td_border td_cell\" align=\"" . $matrixAlignArr[$j] . "\">" . $matrix[$i][$j] . "</td>";
	            endif;
          endfor;
          $output .= "</tr>";
          $csvMatrix[] = $matrix[$i];
       endif;
   endfor;
   $output .= "</table>";


   // **** Generate CSV output (lines) and write file ****
   // $csvHeadline = implode(";", $matrix[0]);
   $lineArray = convertMatrixToCsv ($csvMatrix, "", ";", $hiddenCols);
   $lineArrayLen = count($lineArray);
   for ($i = 0; $i < $lineArrayLen; $i++) :
       writeToFile($path . $f_secretFileName, $lineArray[$i]);
   endfor;


   // **** Send CSV file per mail ****
   $mailObj = new htmlMimeMail();
   $mailCssFontType = "Calibri, Arial, Verdana, Helvetica, sans-serif";

   $mailtext  = "<html><head><meta text/html>";
   $mailtext .= "<style type=\"text/css\">";
   $mailtext .= ".f8np1 { font-family: " . $mailCssFontType . "; font-size: 8pt; font-weight: normal; padding: 1px}";
   $mailtext .= ".f8bp1 { font-family: " . $mailCssFontType . "; font-size: 8pt; font-weight: bold; padding: 1px}";
   $mailtext .= ".f10np1 { font-family: " . $mailCssFontType . "; font-size: 10pt; font-weight: normal; padding: 1px}";
   $mailtext .= ".f10bp1 { font-family: " . $mailCssFontType . "; font-size: 10pt; font-weight: bold; padding: 1px}";
   $mailtext .= ".f8np1_red { font-family: " . $mailCssFontType . "; font-size: 8pt; font-weight: normal; padding: 1px; color: #FF0000;}";

   $mailtext .= " table { border-width: 2px; border-style: solid; border-color: white; }";
   $mailtext .= " .td_border { border-width: 2px; border-style: solid; border-color: white; }";
   $mailtext .= " .td_cell { padding: 5px; }";

   $mailtext .= "</style>";
   $mailtext .= "</head><body><h4>";
   $mailtext .= $output;
   $mailtext .= "</h4></body></html>";

   if (!$autoMode) :
      // $mailtext .= "Ausgeführt von: " . $usrFirstname . " " . $usrName;
   endif;
   
   $mailObj->setHtml($mailtext, null, "./");

   // Sender of the mail   
   if ($currHqId != "") :
      $mailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $currHqId);
   endif;
   if ($mailSenderAddress == "" || !checkEmailFormat($mailSenderAddress)) :
      $mailSenderAddress = "support@assecutor.de";
   endif;
$mailSenderAddress = "support@assecutor.de";  // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
   $mailObj->setFrom($mailSenderAddress);

   // Receiver of the mail
   $mailReceiverAddressArray = array("support@assecutor.de");
   if ($currHqId != "" && is_numeric($currHqId)) :
      $mailReceiverAddress = getParameterValue("0", "MAIL_CRON_203_TO_ADDRESS", $currHqId);
   endif;
   if ($mailReceiverAddress == "") :
      $mailReceiverAddress = getParameterValue("0", "MAIL_CRON_203_TO_ADDRESS", "0");
   endif;
   if ($mailReceiverAddress != "") :
      $mailReceiverAddressArray = spliti(",",$mailReceiverAddress);
   endif;

   // Set From address
   $mailObj->setFrom($mailSenderAddress);

   // Set Cc address
   $mailCcAddress = getParameterValue("0", "MAIL_CC_ADDRESS", "0");
$mailCcAddress = "";  // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
   if ($mailCcAddress != "" && checkEmailFormat($mailCcAddress)) :
      $mailObj->setCc($mailCcAddress);
   endif;

   // Set Bcc address
   $mailBccAddress = getParameterValue("0", "MAIL_BCC_ADDRESS", "0");
// $mailBccAddress = "";  // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$mailBccAddress = "admin@assecutor.de";
   if ($mailBccAddress != "" && checkEmailFormat($mailBccAddress)) :
      $mailObj->setBcc($mailBccAddress);
   endif;            

   // Subject of the email
   $mailSubject = "ÜBERSICHT UMSÄTZE/FRACHTVERGÜTUNGEN" . ($hqName != "" ? " [" . $hqName . "] " : " ") . "für den Zeitraum " . $fromDateRangeOut . " bis " . $toDateRangeOut;
   $mailObj->setSubject($mailSubject);

   // Attachment
   if ($f_secretFileName != "") :
      if (file_exists($path . $f_secretFileName)) :
         $attachment = $mailObj->getFile($path . $f_secretFileName);
         // $mailObj->addAttachment($attachment, $f_secretFileName, $f_mimetype . $f_charset);
         $mailObj->addAttachment($attachment, $f_secretFileName, 'text/csv');
      endif;
   endif;

// $mailReceiverAddressArray = array("mv@assecutor.de");
// $mailReceiverAddressArray = array("mv@assecutor.de","ca@assecutor.de","ingo.kublenz@stadtbote.de");
   $mailResult = $mailObj->send($mailReceiverAddressArray, 'smtp');

   if ($mailResult) :
      // $mailsendStatus = getLngt("Die Nachricht wurde versandt!");
      // Write logdata into log database
      // writeToLogDB("22",$currentHqId,$job_id,$currentSessionUsrId,"","","",$f_email . "|STATION");
   else :
      // $mailsendStatus = getLngt("Die Nachricht konnte nicht gesendet werden!");
      // Write logdata into log database
      // writeToLogDB("23",$currentHqId,$job_id,$currentSessionUsrId,"","","",$f_email . "|STATION");
   endif;
   
   $mailObj = NULL;
   if (file_exists($path . $f_secretFileName)) :
      unlink($path . $f_secretFileName);
   endif;

   // OUTPUT
   if (!$autoMode) :
      echo $mailtext;
   endif;
endif;
?>
