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

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


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "day_from", "month_from", "year_from", "day_to", "month_to", "year_to", "fileOutput"));


$deactivateMenuStatic = "1";

$cs_out = true;
$cs_stat_out = true;

// Init for file output
$outputLinesArray = array();
$delimiter = ";";
$tmpOutputLinesArray_jb_1 = array();
$tmpOutputLinesArray_jb_2 = array();
$tmpOutputLinesArray_jb_3 = array();
$tmpOutputLinesArray_cs_1 = array();
$tmpOutputLinesArray_cs_2 = array();
$tmpOutputLinesArray_cs_3 = array();

// Optional output to file
if ($fileOutput == "" || count($fileOutput) == 0) :
   $fileOutput = false;
else: 
   $fileOutput = true;
endif;

// Generate menu with structure and links
$jsMenuStruct = array();
$jsSubMenu = array();
$menuOut = "";


// Check range 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") . " 00:00:00";
    $toDateRange = getDateTime("3") . " 23:59:59";
    
    $maskJoblistStartdateYesterday = getParameterValue("0", "MASK_JOBLIST_STARTDATE_YESTERDAY");

    $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) . " 00:00:00";
    $toDateRange = $year_to . "-" . pad($month_to,2) . "-" . pad($day_to,2) . " 23:59:59";
endif;

// Get date from datetime only
$tmpFromDate = substr($fromDateRange,0,10);
$tmpToDate = substr($toDateRange,0,10);

// $fromDateRange = "2011-01-01 00:00:00";
// $toDateRange = "2011-07-04 23:59:59";
// echo $fromDateRange . " " . $toDateRange . "<br><br>";


// ********************************
// Get interval of one year before
$day_from_year_before = $day_from;
$month_from_year_before = $month_from;
$year_from_year_before = ($year_from - 1);
$day_to_year_before = $day_to;
$month_to_year_before = $month_to;
$year_to_year_before = ($year_to - 1);
// Check for leap year
$currentYearIsLeapYearFrom = date("L", mktime(0, 0, 0, $month_from, $day_from, $year_from));
if ($currentYearIsLeapYearFrom == "1" && $month_from == "2" && $day_from == "29") :
   $day_from_year_before = "28";
endif;
$currentYearIsLeapYearTo = date("L", mktime(0, 0, 0, $month_to, $day_to, $year_to));
if ($currentYearIsLeapYearTo == "1" && $month_to == "2" && $day_to == "29") :
   $day_to_year_before = "28";
endif;
$yearBeforeIsLeapYearFrom = date("L", mktime(0, 0, 0, $month_from_year_before, $day_from_year_before, $year_from_year_before));
if ($yearBeforeIsLeapYearFrom == "1" && $month_from == "2" && $day_from == "28") :
   $day_from_year_before = "29";
endif;
$yearBeforeIsLeapYearTo = date("L", mktime(0, 0, 0, $month_to_year_before, $day_to_year_before, $year_to_year_before));
if ($yearBeforeIsLeapYearTo == "1" && $month_to == "2" && $day_to == "28") :
   $day_from_year_before = "29";
endif;
// Range one year before
$fromDateRangeYearBefore = $year_from_year_before . "-" . pad($month_from_year_before,2) . "-" . pad($day_from_year_before,2) . " 00:00:00";
$toDateRangeYearBefore = $year_to_year_before . "-" . pad($month_to_year_before,2) . "-" . pad($day_to_year_before,2) . " 23:59:59";
// Get date from datetime only
$tmpFromDateYearBefore = substr($fromDateRangeYearBefore,0,10);
$tmpToDateYearBefore = substr($toDateRangeYearBefore,0,10);
// ********************************


// Get all entries of logo_id = '95' between a specified date range
$sqlquery = "SELECT hq.hq_mnemonic, usr.usr_id, CONCAT(usr.usr_name, ', ', usr.usr_firstname) AS user, log.cs_id, cs.cs_eid, cmp.cmp_comp, log.logo_description"
             . " FROM phoenix_log.log AS log, phoenix.user AS usr, phoenix.customer AS cs, phoenix.company AS cmp, phoenix.headquarters AS hq"
             . " WHERE log.logo_id = '95' AND log.log_createtime >= '" . $fromDateRange . "' AND log.log_createtime <= '" . $toDateRange . "' AND"
             . "       log.hq_id = hq.hq_id AND log.usr_id = usr.usr_id AND log.cs_id = cs.cs_id AND cs.cmp_id = cmp.cmp_id"
             . " ORDER BY log.hq_id, user";

$result = $db->query($sqlquery);

if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

$statArray = array();
$usrIdArray = array();
$usrNameArray = array();
$hqMnemonicArray = array();
$cmpCompArray = array();    
$csEidArray = array();
$csStatArray = array();
$showUserInEveryCaseArray = array();
while ($row = $result->fetch_assoc()):
      $f_hq_mnemonic      = $row["hq_mnemonic"];
      $f_usr_id           = $row["usr_id"];
      $f_user             = $row["user"];
      $f_cs_id            = $row["cs_id"];
      $f_cs_eid           = $row["cs_eid"];
      $f_cmp_comp         = $row["cmp_comp"];
      $f_logo_description = $row["logo_description"];

      $descArray = getKeyValueArrayFromString($f_logo_description);
      // echo ($descArray["SRC"] == "" ? "_" : $descArray["SRC"]); echo "&nbsp;&nbsp;&nbsp;"; echo ($descArray["OLD"] == "" ? "_" : $descArray["OLD"]); echo "&nbsp;&nbsp;&nbsp;"; echo ($descArray["NEW"] == "" ? "_" : $descArray["NEW"]); echo "<br>";

      // if ($descArray["OLD"] == "") : $descArray["OLD"] = "0"; endif;   // No switch of the state, only a new customer entry

      $j = array_search($f_usr_id, $usrIdArray);
      if ($j === FALSE) :
         $usrIdArray[] = $f_usr_id;
         $usrNameArray[$f_usr_id] = $f_user;
         $hqMnemonicArray[$f_usr_id] = $f_hq_mnemonic;

         $statArray[$f_usr_id]["cs"]["0"] = "0";
         $statArray[$f_usr_id]["cs"]["1"] = "0";
         $statArray[$f_usr_id]["cs"]["2"] = "0";
         $statArray[$f_usr_id]["cs"]["3"] = "0";
         
         $statArray[$f_usr_id]["jb"]["0"] = "0";
         $statArray[$f_usr_id]["jb"]["1"] = "0";
         $statArray[$f_usr_id]["jb"]["2"] = "0";
         $statArray[$f_usr_id]["jb"]["3"] = "0";
      endif;

      // Statistic only for switch to real customer state (== "0")
      if ($descArray["NEW"] == "0" && $descArray["OLD"] != "") :
         ++$statArray[$f_usr_id][$descArray["SRC"]][$descArray["OLD"]];
         if ($cs_out) :
            $cmpCompArray[$f_usr_id][$descArray["SRC"]][$descArray["OLD"]][] = $f_cmp_comp;
            $csEidArray[$f_usr_id][$descArray["SRC"]][$descArray["OLD"]][] = $f_cs_eid;
            if ($cs_stat_out) :
               // Statistic business volume from 01.01. of the current year to the current day
               $statisticValue = getCsStatistic($f_cs_id, $tmpFromDate, $tmpToDate);
               $csStatArray[$f_usr_id][$descArray["SRC"]][$descArray["OLD"]][] = $statisticValue;
            endif;
         endif;
      endif;
endwhile;
$result->free();


// **** ADDING SALES EMPLOYEES ****
// Get all sales employees being associated to companies and merge not existing users (in $usrIdArray)
$usrIdSalesArray = getColVectorFromDB2ArrayByClause("company AS cmp, employee AS emp, user AS usr", "usr.usr_id", "cmp.emp_id_sales = emp.emp_id AND emp.usr_id = usr.usr_id", "", "", "DISTINCT");
$usrIdSalesArrayLen = count($usrIdSalesArray);
for ($i = 0; $i < $usrIdSalesArrayLen; $i++) :
      $currUsrId = $usrIdSalesArray[$i];
      $showUserInEveryCaseArray[$currUsrId] = "1";
      $j = array_search($currUsrId, $usrIdArray);
      if ($j === FALSE) :
         $usrIdArray[] = $currUsrId;
         $tmpUsrName = getFieldValueFromId("phoenix.user", "usr_id", $currUsrId, "usr_name");
         $tmpUsrFirstname = getFieldValueFromId("phoenix.user", "usr_id", $currUsrId, "usr_firstname");
         $usrNameArray[$currUsrId] = $tmpUsrName . ", " . $tmpUsrFirstname;
         $tmpHqId = getFieldValueFromId("user", "usr_id", $currUsrId, "hq_id");
         $hqMnemonicArray[$currUsrId] = getFieldValueFromId("headquarters", "hq_id", $tmpHqId, "hq_mnemonic");
      endif;
endfor;


$out = "<table>";
$usrIdArrayLen = count($usrIdArray);
for ($i = 0; $i < $usrIdArrayLen; $i++) :
    $currUsrId = $usrIdArray[$i];

    $stat_jb_1 = $statArray[$currUsrId]["jb"]["1"];
    $stat_jb_2 = $statArray[$currUsrId]["jb"]["2"];
    $stat_jb_3 = $statArray[$currUsrId]["jb"]["3"];
    
    // $stat_cs_0 = $statArray[$currUsrId]["cs"]["0"];
    $stat_cs_1 = $statArray[$currUsrId]["cs"]["1"];
    $stat_cs_2 = $statArray[$currUsrId]["cs"]["2"];
    $stat_cs_3 = $statArray[$currUsrId]["cs"]["3"];

    if ($cs_out) :
    
       mcArrIsSet($cmpCompArray, $currUsrId, array());
       mcArrIsSet($cmpCompArray[$currUsrId], "jb", array());
       mcArrIsSet($cmpCompArray[$currUsrId], "cs", array());
    
       $cmpComp_jb_1 = "";
       mcArrIsSet($cmpCompArray[$currUsrId]["jb"], "1", array());
       $arrayLen = count($cmpCompArray[$currUsrId]["jb"]["1"]);
       if ($arrayLen > 0) :
          for ($k = 0; $k < $arrayLen; $k++) :
              $cmpComp_jb_1 .= "<tr><td colspan=\"2\"><i>" . "&nbsp;&nbsp;- " . $cmpCompArray[$currUsrId]["jb"]["1"][$k] . " [" . $csEidArray[$currUsrId]["jb"]["1"][$k] . "]". ($cs_stat_out == true ? " [" . $csStatArray[$currUsrId]["jb"]["1"][$k] . "]" : "") ."</i></td></tr>";
              if ($fileOutput) :
                 $tmpOutputLinesArray_jb_1[$currUsrId][] = $cmpCompArray[$currUsrId]["jb"]["1"][$k] . $delimiter . $csEidArray[$currUsrId]["jb"]["1"][$k] . $delimiter . ($cs_stat_out == true ? $csStatArray[$currUsrId]["jb"]["1"][$k] : "") . $delimiter;
              endif;
          endfor;
       endif;

       $cmpComp_jb_2 = "";
       mcArrIsSet($cmpCompArray[$currUsrId]["jb"], "2", array());
       $arrayLen = count($cmpCompArray[$currUsrId]["jb"]["2"]);
       if ($arrayLen > 0) :
          for ($k = 0; $k < $arrayLen; $k++) :
              $cmpComp_jb_2 .= "<tr><td colspan=\"2\"><i>" . "&nbsp;&nbsp;- " . $cmpCompArray[$currUsrId]["jb"]["2"][$k] . " [" . $csEidArray[$currUsrId]["jb"]["2"][$k] . "]". ($cs_stat_out == true ? " [" . $csStatArray[$currUsrId]["jb"]["2"][$k] . "]" : "") ."</i></td></tr>";
              if ($fileOutput) :
                 $tmpOutputLinesArray_jb_2[$currUsrId][] = $cmpCompArray[$currUsrId]["jb"]["2"][$k] . $delimiter . $csEidArray[$currUsrId]["jb"]["2"][$k] . $delimiter . ($cs_stat_out == true ? $csStatArray[$currUsrId]["jb"]["2"][$k] : "") . $delimiter;
              endif;
          endfor;
       endif;
       
       $cmpComp_jb_3 = "";
       mcArrIsSet($cmpCompArray[$currUsrId]["jb"], "3", array());
       $arrayLen = count($cmpCompArray[$currUsrId]["jb"]["3"]);
       if ($arrayLen > 0) :
          for ($k = 0; $k < $arrayLen; $k++) :
              $cmpComp_jb_3 .= "<tr><td colspan=\"2\"><i>" . "&nbsp;&nbsp;- " . $cmpCompArray[$currUsrId]["jb"]["3"][$k] . " [" . $csEidArray[$currUsrId]["jb"]["3"][$k] . "]". ($cs_stat_out == true ? " [" . $csStatArray[$currUsrId]["jb"]["3"][$k] . "]" : "") ."</i></td></tr>";
              if ($fileOutput) :
                 $tmpOutputLinesArray_jb_3[$currUsrId][] = $cmpCompArray[$currUsrId]["jb"]["3"][$k] . $delimiter . $csEidArray[$currUsrId]["jb"]["3"][$k] . $delimiter . ($cs_stat_out == true ? $csStatArray[$currUsrId]["jb"]["3"][$k] : "") . $delimiter;
              endif;
          endfor;
       endif;

       $cmpComp_cs_1 = "";
       mcArrIsSet($cmpCompArray[$currUsrId]["cs"], "1", array());
       $arrayLen = count($cmpCompArray[$currUsrId]["cs"]["1"]);
       if ($arrayLen > 0) :
          for ($k = 0; $k < $arrayLen; $k++) :
              $cmpComp_cs_1 .= "<tr><td colspan=\"2\"><i>" . "&nbsp;&nbsp;- " . $cmpCompArray[$currUsrId]["cs"]["1"][$k] . " [" . $csEidArray[$currUsrId]["cs"]["1"][$k] . "]". ($cs_stat_out == true ? " [" . $csStatArray[$currUsrId]["cs"]["1"][$k] . "]" : "") ."</i></td></tr>";
              if ($fileOutput) :
                 $tmpOutputLinesArray_cs_1[$currUsrId][] = $cmpCompArray[$currUsrId]["cs"]["1"][$k] . $delimiter . $csEidArray[$currUsrId]["cs"]["1"][$k] . $delimiter . ($cs_stat_out == true ? $csStatArray[$currUsrId]["cs"]["1"][$k] : "") . $delimiter;
              endif;
          endfor;
       endif;

       $cmpComp_cs_2 = "";
       mcArrIsSet($cmpCompArray[$currUsrId]["cs"], "2", array());
       $arrayLen = count($cmpCompArray[$currUsrId]["cs"]["2"]);
       if ($arrayLen > 0) :
          for ($k = 0; $k < $arrayLen; $k++) :
              $cmpComp_cs_2 .= "<tr><td colspan=\"2\"><i>" . "&nbsp;&nbsp;- " . $cmpCompArray[$currUsrId]["cs"]["2"][$k] . " [" . $csEidArray[$currUsrId]["cs"]["2"][$k] . "]". ($cs_stat_out == true ? " [" . $csStatArray[$currUsrId]["cs"]["2"][$k] . "]" : "") ."</i></td></tr>";
              if ($fileOutput) :
                 $tmpOutputLinesArray_cs_2[$currUsrId][] = $cmpCompArray[$currUsrId]["cs"]["2"][$k] . $delimiter . $csEidArray[$currUsrId]["cs"]["2"][$k] . $delimiter . ($cs_stat_out == true ? $csStatArray[$currUsrId]["cs"]["2"][$k] : "") . $delimiter;
              endif;
          endfor;
       endif;
       
       $cmpComp_cs_3 = "";
       mcArrIsSet($cmpCompArray[$currUsrId]["cs"], "3", array());
       $arrayLen = count($cmpCompArray[$currUsrId]["cs"]["3"]);
       if ($arrayLen > 0) :
          for ($k = 0; $k < $arrayLen; $k++) :
              $cmpComp_cs_3 .= "<tr><td colspan=\"2\"><i>" . "&nbsp;&nbsp;- " . $cmpCompArray[$currUsrId]["cs"]["3"][$k] . " [" . $csEidArray[$currUsrId]["cs"]["3"][$k] . "]". ($cs_stat_out == true ? " [" . $csStatArray[$currUsrId]["cs"]["3"][$k] . "]" : "") ."</i></td></tr>";
              if ($fileOutput) :
                 $tmpOutputLinesArray_cs_3[$currUsrId][] = $cmpCompArray[$currUsrId]["cs"]["3"][$k] . $delimiter . $csEidArray[$currUsrId]["cs"]["3"][$k] . $delimiter . ($cs_stat_out == true ? $csStatArray[$currUsrId]["cs"]["3"][$k] : "") . $delimiter;
              endif;
          endfor;
       endif;
    endif;

    if ($showUserInEveryCaseArray[$currUsrId] == "1" || $stat_jb_1 > 0 || $stat_jb_2 > 0 || $stat_jb_3 > 0 || $stat_cs_1 > 0 || $stat_cs_2 > 0 || $stat_cs_3 > 0) :
    // if (true) :
    
       $out .= "<tr><td><b>" . $usrNameArray[$currUsrId] . "</b></td><td><b>[" . $hqMnemonicArray[$currUsrId] . "]</b></td></tr>";
       if ($fileOutput) :
          $tmpOutputLinesArrayUsrData = $usrNameArray[$currUsrId] . $delimiter . $hqMnemonicArray[$currUsrId] . $delimiter;
       endif;
       
       if ($stat_jb_1 > 0) :
          $out .= "<tr><td>" . "- Interessent zu Kunde über Auftrag:" . "</td><td>" . $stat_jb_1 . "</td></tr>";
          $tmpOutputLinesArraySwitchMode = "Interessent zu Kunde über Auftrag" . $delimiter;
          if ($cs_out) : 
             $out .= $cmpComp_jb_1; 
             if ($fileOutput) :
                $tmpLen = count($tmpOutputLinesArray_jb_1[$currUsrId]);
                for ($k = 0; $k < $tmpLen; $k++) :
                    $outputLinesArray[] = $tmpOutputLinesArrayUsrData . $tmpOutputLinesArraySwitchMode . $tmpOutputLinesArray_jb_1[$currUsrId][$k];
                endfor;
             endif;
          endif;
       endif;
       if ($stat_jb_2 > 0) :
          $out .= "<tr><td>" . "- Potentialkunde zu Kunde über Auftrag:" . "</td><td>" . $stat_jb_2 . "</td></tr>";
          $tmpOutputLinesArraySwitchMode = "Potentialkunde zu Kunde über Auftrag" . $delimiter;
          if ($cs_out) : 
             $out .= $cmpComp_jb_2; 
             if ($fileOutput) :
                $tmpLen = count($tmpOutputLinesArray_jb_2[$currUsrId]);
                for ($k = 0; $k < $tmpLen; $k++) :
                    $outputLinesArray[] = $tmpOutputLinesArrayUsrData . $tmpOutputLinesArraySwitchMode . $tmpOutputLinesArray_jb_2[$currUsrId][$k];
                endfor;
             endif;
          endif;
       endif;
       if ($stat_jb_3 > 0) :
          $out .= "<tr><td>" . "- Wunschkunde zu Kunde über Auftrag:" . "</td><td>" . $stat_jb_3 . "</td></tr>";
          $tmpOutputLinesArraySwitchMode = "Wunschkunde zu Kunde über Auftrag" . $delimiter;
          if ($cs_out) : 
             $out .= $cmpComp_jb_3; 
             if ($fileOutput) :
                $tmpLen = count($tmpOutputLinesArray_jb_3[$currUsrId]);
                for ($k = 0; $k < $tmpLen; $k++) :
                    $outputLinesArray[] = $tmpOutputLinesArrayUsrData . $tmpOutputLinesArraySwitchMode . $tmpOutputLinesArray_jb_3[$currUsrId][$k];
                endfor;
             endif;
          endif;
       endif;

       // if ($stat_cs_0 > 0) :
       //    $out .= "<tr><td>" . "- Neuanlage eines Kunden:" . "</td><td>" . $stat_cs_0 . "</td></tr>";
       // endif;
       if ($stat_cs_1 > 0) :
          $out .= "<tr><td>" . "- Interessent zu Kunde über Stammblatt:" . "</td><td>" . $stat_cs_1 . "</td></tr>";
          $tmpOutputLinesArraySwitchMode = "Interessent zu Kunde über Stammblatt" . $delimiter;
          if ($cs_out) : 
             $out .= $cmpComp_cs_1; 
             if ($fileOutput) :
                $tmpLen = count($tmpOutputLinesArray_cs_1[$currUsrId]);
                for ($k = 0; $k < $tmpLen; $k++) :
                    $outputLinesArray[] = $tmpOutputLinesArrayUsrData . $tmpOutputLinesArraySwitchMode . $tmpOutputLinesArray_cs_1[$currUsrId][$k];
                endfor;
             endif;
          endif;
       endif;
       if ($stat_cs_2 > 0) :
          $out .= "<tr><td>" . "- Potentialkunde zu Kunde über Stammblatt:" . "</td><td>" . $stat_cs_2 . "</td></tr>";
          $tmpOutputLinesArraySwitchMode = "Potentialkunde zu Kunde über Stammblatt" . $delimiter;
          if ($cs_out) : 
             $out .= $cmpComp_cs_2; 
             if ($fileOutput) :
                $tmpLen = count($tmpOutputLinesArray_cs_2[$currUsrId]);
                for ($k = 0; $k < $tmpLen; $k++) :
                    $outputLinesArray[] = $tmpOutputLinesArrayUsrData . $tmpOutputLinesArraySwitchMode . $tmpOutputLinesArray_cs_2[$currUsrId][$k];
                endfor;
             endif;
          endif;
       endif;
       if ($stat_cs_3 > 0) :
          $out .= "<tr><td>" . "- Wunschkunde zu Kunde über Stammblatt:" . "</td><td>" . $stat_cs_3 . "</td></tr>";
          $tmpOutputLinesArraySwitchMode = "Wunschkunde zu Kunde über Stammblatt" . $delimiter;
          if ($cs_out) : 
             $out .= $cmpComp_cs_3; 
             if ($fileOutput) :
                $tmpLen = count($tmpOutputLinesArray_cs_3[$currUsrId]);
                for ($k = 0; $k < $tmpLen; $k++) :
                    $outputLinesArray[] = $tmpOutputLinesArrayUsrData . $tmpOutputLinesArraySwitchMode . $tmpOutputLinesArray_cs_3[$currUsrId][$k];
                endfor;
             endif;
          endif;
       endif;


       // *********************************************************************************************************
       // * Check for existing customers the sales employee is associated to and add this information to the list *
       // *********************************************************************************************************
       $empIdSales = getFieldValueFromId("employee", "usr_id", $currUsrId, "emp_id");  // Get the emp_id of the current sales user

       $sqlquery = "SELECT cmp.cmp_comp, cs.cs_id, cs.cs_eid"
                 . " FROM  customer AS cs, company AS cmp"
                 . " WHERE cmp.emp_id_sales = '" . $empIdSales . "' AND cmp.cmp_id = cs.cmp_id"
                 . " ORDER BY cmp.cmp_comp";

       $result = $db->query($sqlquery);
       if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());

       $outSales = "";
       $outSalesHeader = true;
       while ($row = $result->fetch_assoc()):
             if ($outSalesHeader) :
                 $out .= "<tr><td>" . "- Umsatzzuwachs Bestandskunde(n):" . "</td><td>" . $stat_cs_3 . "</td></tr>";
                 $outSalesHeader = false;
             endif;
             $statisticValueCurrent = getCsStatistic($row["cs_id"], $tmpFromDate, $tmpToDate, "", "", "1");
             $statisticValueYearBefore = getCsStatistic($row["cs_id"], $tmpFromDateYearBefore, $tmpToDateYearBefore, "", "", "1");             
             $statisticValue = ($statisticValueCurrent - $statisticValueYearBefore);
             $statisticValue = number_format(round($statisticValue,2), 2, ",", ".");

             $out .= "<tr><td colspan=\"2\"><i>" . "&nbsp;&nbsp;- " . $row["cmp_comp"] . " [" . $row["cs_eid"] . "]". ($cs_stat_out == true ? " [" . $statisticValue . "]" : "") ."</i></td></tr>";
             if ($fileOutput) :
                $outputLinesArray[] = $tmpOutputLinesArrayUsrData . "Bestandskunde(n)" . $delimiter . $row["cmp_comp"] . $delimiter . $row["cs_eid"] . $delimiter . ($cs_stat_out == true ? $statisticValue : "") . $delimiter;
             endif;
       endwhile;
       $result->free();

       $out .= "<tr><td colspan=\"2\">&nbsp;</td></tr>";
    endif;
endfor;
$out .= "</table>";


$currentFrameName = "";  // Empty string for "main frame"
$filter_dateranges = "";
$js_date = "";

// Date-ranges 
$filter_dateranges .= "<td>" . getLngt("Von:") . "\n";
$filter_dateranges .= "<select name=\"day_from\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'tool', 'day_from', 'day_from', 'month_from', 'year_from', '', '', '')\"></select>\n";
$filter_dateranges .= "<select name=\"month_from\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'tool', 'month_from', 'day_from', 'month_from', 'year_from', '', '', '')\"></select>\n";
$filter_dateranges .= "<select name=\"year_from\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'tool', 'year_from', 'day_from', 'month_from', 'year_from', '', '', '')\"></select>\n";
$filter_dateranges .= "</td><td>&nbsp;&nbsp;" . getLngt("bis:") . "\n";
$filter_dateranges .= "<select name=\"day_to\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'tool', 'day_to', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
$filter_dateranges .= "<select name=\"month_to\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'tool', 'month_to', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
$filter_dateranges .= "<select name=\"year_to\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'tool', 'year_to', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
$filter_dateranges .= "</td>";

// Javascript-function as template only for
$js_date .= "<script type=\"text/javascript\">\n";
$js_date .= "<!--\n";
$js_date .= "function initForm() {\n";
$js_date .= "  fillDateFields(1,\"" . $currentFrameName . "\",\"tool\",\"\",\"day_from\",\"month_from\",\"year_from\",\"\",\"\",\"\");\n";
$js_date .= "  setDateTimeFields(\"" . $currentFrameName . "\",\"tool\",".$day_from.",".$month_from.",".$year_from.", \"\", \"\", \"day_from\", \"month_from\", \"year_from\", \"\", \"\", \"\");\n";
$js_date .= "  fillDateFields(1,\"" . $currentFrameName . "\",\"tool\", \"\", \"day_to\", \"month_to\", \"year_to\", \"\", \"\", \"\");\n";
$js_date .= "  setDateTimeFields(\"" . $currentFrameName . "\",\"tool\",".$day_to.",".$month_to.",".$year_to.", \"\", \"\", \"day_to\", \"month_to\", \"year_to\", \"\", \"\", \"\");\n";
$js_date .= "}\n";
$js_date .= "-->\n";
$js_date .= "</script>\n";


// Optional output to file
$outputLinesArrayLen = count($outputLinesArray);
$f_secretFileName = "";
$f_path = "../temp/download/";
if ($fileOutput) :

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

   if ($outputLinesArrayLen > 0) :

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


// Output
$onLoadCall = "startTimeout();initForm();displayStatusMessage();";
if ($fileOutput) :
   $onLoadCall .= "downloadFile();";
endif;
?>

<html>
<head>

<link rel="stylesheet" type="text/css" href="../css/phoenix.css">
<style type="text/css">
  <?php include_once ("../css/navigation.css.php"); ?>
</style>

<?php include_once ("../include/js_framework.inc.php"); ?>

<script src="../include/lib_global.js" type="text/javascript">
</script>

<script type="text/javascript">

var refreshStatus = 1;
var statusMessage = "<?php echo $statusMessage ?>";

function displayStatusMessage() {
 if (statusMessage != "") {
    alert(statusMessage);
 }
};

function startReload() {  
  if (refreshStatus == 1) {
     // self.location.reload();
     document.forms[0].submit();
  }
}

function startTimeout() {  
  self.setTimeout("startReload()", 180000);
}

function finishPage(f_act) {
	document.forms[0].f_act.value = f_act;
  document.forms[0].submit();
}

function downloadFile() {
  var widthPopupWin = 850;
  var heightPopupWin = 600;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;

  popupWin = window.open("../include/data_download.php?f_path=<?php echo $f_path ?>&f_fileName=<?php echo $f_secretFileName ?>", "","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};
</script>

<?php echo $js_date ?>

</head>


<body style="background:#777777; padding: 0px; margin: 0px; border: 0px" onLoad="<?php echo $onLoadCall ?>">

  <form name="tool" action="../tools/customer_switch_counter.php" method="post">

    <input type="hidden" name="f_act" value="">

    <center>
    	<br><br>
    	<span class="f12bp1_blue">Wechsel der Kundenstatus</span>
    	<br><br><br>
    	<?php echo $filter_dateranges ?>&nbsp;&nbsp;&nbsp;<input type="submit" value="Anzeigen">
    	<br><br><br>
      <?php echo getLngt("Angaben exportieren:") ?>&nbsp;<input class="f8np1" type="checkbox" name="fileOutput[]" value="1">
      <br><br><br>
      <?php echo $out ?>
    </center>

  </form>

</body>

</html>
