<?php
/*=======================================================================
 *
 * report.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", "customerId", "cscIdRoot", "cscIdActual", "empIdMaster", "rpObjType", "rpObjId", "op",
                         "day_from", "month_from", "year_from", "day_to", "month_to", "year_to", 
                         "g_cs_eid", "g_csc_id", "g_cr_id", "g_cr_eid", "pt_id", "g_pt_cs_eid",
                         "f_hq_id", "f_text", "f_rpIdToRemove", "f_rpIdToUpdate", "f_rpIdToCopy", "f_rpReportType", 
                         "f_sort", "f_rp_stat_sort", "f_filter_rpType", "deactivateMenu", "f_rpstat_export", "f_rpstat_splitbyreporttype", 
                         "f_rpstat_splitbycmptype", "f_rpConfidential", "rpIdsFilter"));

$deactivateMenuStatic = "1";

getLanguage(__FILE__);

// Check for authentication access and granted rights
$usrAccessArray["hq"] = "1";
authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// TODo:
// MASK_CS_REPORT_FORMS_ENABLED  =>copy=>  MASK_CR_REPORT_FORMS_ENABLED
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// Init
if ($rpObjType == "") : $rpObjType = "cs"; endif;

$pageTitel = getLngt("BERICHTE");
$pageHeadline = "<span class=\"f12bp1_blue\">" . $pageTitel . ":</span>";
$authCheck = FALSE;
$hqId = "0";
$isMeta = "0";
$f_secretFileName = "";
$statisticValueCurrentYear = "";
$rpObjId = "";
$whereClauseRp = "";

if ($rpObjType == "cs") :
   $pageTitel = getLngt("KUNDENBERICHTE");
   $authCheck = authCheckEmployeeRights($emp_id, "0");
   $metatypeReportType = "report_type";    // metatype.mt_type
   $titleArrayObjName = getLngt("Kunde&nbsp;&nbsp;");
   
   // Parameters
   $constMaskRpReportFormsEnabled = getParameterValue("0", "MASK_CS_REPORT_FORMS_ENABLED", $hqId);
   $constMaskRpReportFormsMapping = getParameterValue("0", "MASK_CS_REPORT_FORMS_MAPPING", $hqId);
   $limitOfRowsDisplayed = getParameterValue("0", "MASK_CS_REPORT_ROWS_DISPLAYED", "0");    // For limitation of the rows displayed

   // Get the cs_id if "g_cs_eid" does exist
   $cs_id = "";
   if ($g_cs_eid != "") : 
      $cs_id = getFieldValueFromId("customer", "cs_eid", $g_cs_eid, "cs_id");
      $rpObjId = $cs_id;
   elseif ($g_csc_id != "") :
      $cs_id = getFieldValueFromId("costcenter", "csc_id", $g_csc_id, "cs_id");
      $rpObjId = $cs_id;
      $g_cs_eid = getFieldValueFromId("customer", "cs_id", $cs_id, "cs_eid");
   endif;
   
   // Get status of the customer according to being meta customer
   $csParentIdArray = array();
   if ($cs_id != "") :
      if (existsEntry("customer",array("cs_id_parent",$cs_id))) :
         $isMeta = "1";
         $csParentIdArray = getColVectorFromDB2Array("customer","cs_id_parent",$cs_id,"cs_id","");
         array_push($csParentIdArray, $cs_id);    // meta customer inclusive
      endif;
   endif;

   // Clause for report statistics
   if ($rpObjId != "") :
      $cmpId = getFieldValueFromId("customer", "cs_id", $cs_id, "cmp_id");
      $tmpFields = getFieldsValueFromId("company","cmp_id",$cmpId,array("cmp_comp","cmp_comp2"));
      $out_1 = "<a href=\"../admin/customer_special.php?companyId=" . ec($cmpId) . "\" target=\"_blank\">" . $tmpFields[0] . "</a>";
      $out_2 = $tmpFields[1];
   
      $whereClauseRp = " rp.rp_objtype = '" . $rpObjType . "' AND rp.rp_objid = '" . $rpObjId . "' AND ";
      if ($isMeta == "1") :
         $whereClauseRp = " rp.rp_objtype = '" . $rpObjType . "' AND rp.rp_objid IN (" . implode(",", $csParentIdArray) . ") AND ";
      endif;
   endif;

   // Statistic values of the customer
   if ($rpObjId != "") :
      // Statistic business volume from 01.01. of the current year to the current day
      $tmpFromDate = getDateTime("year") . "-01-01";
      $tmpToDate = getDateTime("3");
      $statisticValueCurrentYear = getCsStatistic ($rpObjId, $tmpFromDate, $tmpToDate);

      // Year before in the same interval
      $tmpFromDate = getDateTime("lastyear") . "-01-01";
      $tmpToDate = getDateTime("date_lastyear");
      $statisticValueLastYear = getCsStatistic ($rpObjId, $tmpFromDate, $tmpToDate);
      
      // Year before complete
      $tmpFromDate = getDateTime("lastyear") . "-01-01";
      $tmpToDate = getDateTime("lastyear") . "-12-31";
      $statisticValueLastYearComplete = getCsStatistic ($rpObjId, $tmpFromDate, $tmpToDate);
   endif;

   // Link to invoice data of the customer
   if ($rpObjId != "") :
      $invoiceOverview = "<a href=\"../invoice/invoice.php?currentNavigationItem=uebersicht&cs_eid=" . $g_cs_eid . "\" target=\"_blank\">" . getLngt("Rechnungsübersicht") . "</a>";
   endif;

elseif ($rpObjType == "cr") :
   $pageTitel = getLngt("TRANSPORTEURSBERICHTE");
   $authCheck = authCheckEmployeeRights($emp_id, "1");
   $metatypeReportType = "report_type_2";    // metatype.mt_type
   $titleArrayObjName = getLngt("Transporteur&nbsp;&nbsp;");
   
   // Parameters
   $constMaskRpReportFormsEnabled = getParameterValue("0", "MASK_CR_REPORT_FORMS_ENABLED", $hqId);
   $constMaskRpReportFormsMapping = getParameterValue("0", "MASK_CR_REPORT_FORMS_MAPPING", $hqId);
   $limitOfRowsDisplayed = getParameterValue("0", "MASK_CR_REPORT_ROWS_DISPLAYED", "0");    // For limitation of the rows displayed
   
   // Get the (g_)cr_eid if "g_cr_id" does exist
   if ($g_cr_id != "") : 
      $g_cr_eid = getFieldValueFromId("courier", "cr_id", $g_cr_id, "cr_eid");
      $rpObjId = $g_cr_id;
   endif;
   
   // Clause for report statistics
   if ($rpObjId != "") :
      $cmpId = getFieldValueFromId("courier", "cr_id", $g_cr_id, "cmp_id");
      $tmpFields = getFieldsValueFromId("company","cmp_id",$cmpId,array("cmp_comp","cmp_comp2"));
      $out_1 = $tmpFields[0];
      $out_2 = $tmpFields[1];
   
      $whereClauseRp = " rp.rp_objtype = '" . $rpObjType . "' AND rp.rp_objid = '" . $rpObjId . "' AND ";
      if (FALSE && $isMeta == "1") :
         $whereClauseRp = " rp.rp_objtype = '" . $rpObjType . "' AND rp.rp_objid IN (" . implode($crParentIdArray, ",") . ") AND ";
      endif;
   endif;
   
elseif ($rpObjType == "pt") :
   $pageTitel = getLngt("INTERESSENTENBERICHTE");
   $authCheck = authCheckEmployeeRights($emp_id, "0");
   $metatypeReportType = "report_type_3";    // metatype.mt_type
   $titleArrayObjName = getLngt("Interessent&nbsp;&nbsp;");
   
   // Parameters
   $constMaskRpReportFormsEnabled = getParameterValue("0", "MASK_PT_REPORT_FORMS_ENABLED", $hqId);
   $constMaskRpReportFormsMapping = getParameterValue("0", "MASK_PT_REPORT_FORMS_MAPPING", $hqId);
   $limitOfRowsDisplayed = getParameterValue("0", "MASK_PT_REPORT_ROWS_DISPLAYED", "0");    // For limitation of the rows displayed
   
   // Get the (g_)cr_eid if "g_cr_id" does exist
   if ($g_cr_id != "") : 
      $g_cr_eid = getFieldValueFromId("courier", "cr_id", $g_cr_id, "cr_eid");
      $rpObjId = $g_cr_id;
   endif;
   
   // Get the pt_id if "g_pt_cs_eid" does exist (e.g. init the page)
   if ($g_pt_cs_eid != "") : 
      $pt_id = getFieldValueFromId("prospect", "pt_cs_eid", $g_pt_cs_eid, "pt_id");
      $rpObjId = $pt_id;
   else :
      $g_pt_cs_eid = getFieldValueFromId("prospect", "pt_id", $pt_id, "pt_cs_eid");
      $rpObjId = $pt_id;
   endif;
   
   // Clause for report statistics
   if ($rpObjId != "") :
      $out_1 = getFieldValueFromId("prospect", "pt_id", $pt_id, "pt_cmp_comp");
      $out_2 = getFieldValueFromId("prospect", "pt_id", $pt_id, "pt_cmp_comp2");

      $whereClauseRp = " rp.rp_objtype = '" . $rpObjType . "' AND rp.rp_objid = '" . $rpObjId . "' AND ";
      if (FALSE && $isMeta == "1") :
         $whereClauseRp = " rp.rp_objtype = '" . $rpObjType . "' AND rp.rp_objid IN (" . implode($ptParentIdArray, ",") . ") AND ";
      endif;
   endif;
endif;

$pageHeadline .= " &nbsp;&nbsp;&nbsp;&nbsp;" . ($rpObjId != "" ? $tmpFields[0] . " " . $tmpFields[1] . "&nbsp;&nbsp;" : getLngt(" - ALLE -&nbsp;&nbsp;"));

include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");

getCurrentScript(__FILE__);

if (!$authCheck || !authCheckEmployeeRights($emp_id, "16")) : gotoReferer("1"); endif;


// Mandator filter (related here to the USER !!!)
if ($f_hq_id == "") : $f_hq_id = array(); endif;
if (count($f_hq_id) == 0) : array_push($f_hq_id, $hq_id); endif;
if ($f_rpReportType == "") : $f_rpReportType = "0"; endif;
if ($f_sort == "") : $f_sort = "0"; endif;                                   // ORDER BY column "$fieldArray[$f_sort]"
if ($f_rp_stat_sort == "") : $f_rp_stat_sort = ""; endif;                    // ORDER BY column "$fieldArray[$f_rp_stat_sort]"
if ($f_filter_rpType == "") : $f_filter_rpType = "0"; endif;                 // Filter "rp_reporttype"
if ($limitOfRowsDisplayed == "") : $limitOfRowsDisplayed = "1000"; endif;
$f_text = trim($f_text);                                                     // Text of an entry
if ($f_text) :
   $f_text = str_replace("'", "´", $f_text);
endif;
$confirmForNewAppointment = false;


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

// 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("1") . "000000";
    
    $currentMonth = getDateTime("month");
    if ($currentMonth >= 7) :
       $fromDateRange = getDateTime("year") . "0701" . "000000";
    else :
       $fromDateRange = getDateTime("year") . "0101" . "000000";
    endif;
    $toDateRange = getDateTime("1") . "235959";
 
    // $day_from = getDateTime("day");
    $day_from = "01";
    // $month_from = getDateTime("month");
    $month_from = "01";
    if ($currentMonth >= 7) : $month_from = "07"; endif;
    $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) . "000000";
    $toDateRange = $year_to . pad($month_to,2) . pad($day_to,2) . "235959";
endif;


// Get report types
$reportTypeArray = getColVectorFromDB2Array("metatype","mt_type",$metatypeReportType,"mt_value","mt_sort");
$reportTypeArray = array_merge (array(" "), $reportTypeArray);    // Inserts the first element to position "0" ("shift right")


// Checkbox
if ($f_rpConfidential == "" || count($f_rpConfidential) == 0) : $f_rpConfidential = "0"; else: $f_rpConfidential = "1"; endif;

// ***********
// * Actions *
// ***********

if ($f_act == "insertRpEntry") :
   if ($rpObjId != "" && $rpObjType != "") :
      if ($f_text != "") :
         $currentTime = getDateTime("0");
         // $execDatetime = getDateTime("format",array($f_hour,$f_minute,0,$selMonth,$selDay,$selYear),"Y-m-d H:i:s");
         // $endDatetime = getDateTime("format",array($f_hour_to,$f_minute_to,0,$selMonth,$selDay,$selYear),"Y-m-d H:i:s");
         
         insertStmt("phoenix_group.report_process", array("usr_id", $usr_id, "hq_id", $hq_id, "rp_reporttype", $f_rpReportType, "rp_text", $f_text,
                                                          "rp_createtime", $currentTime, "rp_objId", $rpObjId, "rp_objtype", $rpObjType, "rp_confidential", $f_rpConfidential));
         $rp_id_new = getLastInsertId();
         
         $f_rpReportType = "0";       // Reset Type
         $f_rpConfidential = "0";     // Reset Confidence
         $confirmForNewAppointment = true;

         // Get all appointments of the day the report is written. Get appointments associated to the customer of the inserted report only.
         $constMaskRpEnableDeactivationApWarning = getParameterValue("0", "MASK_RP_ENABLE_DEACTIVATION_APPOINTMENT_WARNING_OF_SAME_DAY", "0");
         if ($constMaskRpEnableDeactivationApWarning == "1") :
            $currentDate = getDateTime("3");
            $tmpApArray = getColVectorFromDB2ArrayByClause("phoenix_group.appointment", "ap_id", "cs_id = '" . $rpObjId . "' AND ap_execdate >= '" . $currentDate . " 00:00:00' AND ap_execdate <= '" . $currentDate . " 23:59:59' AND ap_category_4 = '1'", "", "");
            $tmpApArrayLen = count($tmpApArray);
            if ($tmpApArrayLen > 0) :
               updateStmt("phoenix_group.appointment","","",array("ap_category_4", "2"),"ap_id IN (" . implode(",", $tmpApArray) . ")");
            endif;
         endif;
      else:
        $statusMessage = getLngt("Erfassen Sie bitte einen Text für einen Kundeneintrag!");
      endif;
   else:
     $statusMessage = getLngt("Es wurde kein Kunde gewählt!");
   endif;
endif;

if ($f_act == "removeRpEntry") :
   if ($f_rpIdToRemove != "") :
      deleteStmt("phoenix_group.report_process","rp_id = ".$f_rpIdToRemove);
      $f_rpIdToRemove = "";  // Reset ID
   else:
     $statusMessage = getLngt("Es wurde kein Eintrag zum Löschen selektiert!");
   endif;
endif;

if ($f_act == "updateRpEntry") :
   if ($f_rpIdToUpdate != "" && $f_text != "") :
      updateStmt("phoenix_group.report_process", "rp_id", $f_rpIdToUpdate, array("rp_reporttype", $f_rpReportType, "rp_text", $f_text, "rp_confidential", $f_rpConfidential));
      $f_rpIdToUpdate = "";  // Reset ID
      $f_rpIdToCopy = "";    // Reset ID
      $f_rpReportType = "0";       // Reset Type
      $f_rpConfidential = "0";     // Reset Confidence
      $confirmForNewAppointment = true;
   else:
     $statusMessage = getLngt("Eine Aktualisierung fand nicht statt!");
   endif;
endif;

if ($f_act == "reportStatistic") :
   // Split statistic by report type
   if ($f_rpstat_splitbyreporttype == "" || count($f_rpstat_splitbyreporttype) == 0) : $f_rpstat_splitbyreporttype = false; else: $f_rpstat_splitbyreporttype = true; endif;
   // Split statistic by company type
   if ($f_rpstat_splitbycmptype == "" || count($f_rpstat_splitbycmptype) == 0) : $f_rpstat_splitbycmptype = false; else: $f_rpstat_splitbycmptype = true; endif;
   
   // Export report statistic data as CSV file
   if ($f_rpstat_export == "" || count($f_rpstat_export) == 0) : $f_rpstat_export = false; else: $f_rpstat_export = true; endif;

   $fieldClauseRpType = "";
   $fromClauseRpType = "";
   $groupByClauseRpType = "";
   $whereClauseRpType = "";
   $orderByClauseRpType = "";
   if ($f_rpstat_splitbyreporttype) :
      $fieldClauseRpType = "mt.mt_value,";
      $fromClauseRpType = ", metatype AS mt";
      $whereClauseRpType = " mt.mt_type = '" . $metatypeReportType . "' AND mt.mt_sort = rp.rp_reporttype AND ";
      $groupByClauseRpType = ", rp.rp_reporttype";
      $orderByClauseRpType = ", rp.rp_reporttype";
   endif;
   $fieldClauseCmpType =  "";
   $fromClauseCmpType = "";
   $whereClauseCmpType = "";
   $groupByClauseCmpType = "";
   $orderByClauseCmpType = "";
   if ($f_rpstat_splitbycmptype) :
      if ($rpObjType == "cs") :
         $fieldClauseCmpType = "mt2.mt_value AS mt2_value,";
         $fromClauseCmpType = ", customer AS cs, company AS cmp, metatype AS mt2";
         $whereClauseCmpType = "  rp.rp_objid = cs.cs_id AND cmp.cmp_id = cs.cmp_id AND mt2.mt_type = 'customer_type' AND mt2.mt_sort = cmp.cmp_type AND ";
         $groupByClauseCmpType = ", cmp.cmp_type";
         $orderByClauseCmpType = ", cmp.cmp_type";
      endif;
   endif;

   // Generate list with header
   $titleArray = array(getLngt("Zentrale&nbsp;&nbsp;"),getLngt("Name&nbsp;&nbsp;"),getLngt("Vorname&nbsp;&nbsp;"));
   $fieldArray = array("hq_name","usr_name","usr_firstname");
   $aligns = "l,l,l";
   $widths = "80,150,150";
   if ($f_rpstat_splitbyreporttype) :
      $titleArray[] = getLngt("Berichtstyp");
      $fieldArray[] = "mt_value";
      $aligns .= ",l";
      $widths .= ",150";
   endif;
   if ($f_rpstat_splitbycmptype) :
      if ($rpObjType == "cs") :
         $titleArray[] = getLngt("Kundentyp");
         $fieldArray[] = "mt2_value";
         $aligns .= ",l";
         $widths .= ",150";
      endif;
   endif;
   $titleArray[] = getLngt("Anzahl Berichte&nbsp;&nbsp;");
   $fieldArray[] = "reports";
   $aligns .= ",r";
   $widths .= ",100";
   
   $tmpSortField = "";
   if ($f_rp_stat_sort != "") :       
      if (false && $fieldArray[$f_rp_stat_sort] == "field_xxx") :
         $tmpSortField = "rp.rp_reporttype";
      else :
        $tmpSortField = $fieldArray[$f_rp_stat_sort];
      endif;
   endif;
   if ($tmpSortField == "") :
      $tmpSortField = "usr.usr_name, usr.usr_firstname" . $orderByClauseRpType . $orderByClauseCmpType;
   endif;
   $orderByClause = $tmpSortField;
   /*
   $sqlquery = "SELECT hq.hq_name, usr.usr_firstname, usr.usr_name, " . $fieldClauseRpType . $fieldClauseCmpType . " count(*) AS reports"
               . " FROM phoenix_group.report_process AS rp, phoenix.user AS usr, phoenix.headquarters AS hq" . $fromClauseRpType . $fromClauseCmpType
               . " WHERE rp.hq_id IN " . getSQLMandatorArray($f_hq_id) . " AND rp.hq_id = hq.hq_id AND"
               . "       rp.usr_id = usr.usr_id AND rp.rp_objtype = '" . $rpObjType . "' AND " . $whereClauseRp . $whereClauseRpType . $whereClauseCmpType
               . "       rp.rp_createtime >= '$fromDateRange' AND rp.rp_createtime <= '$toDateRange'"               
               . " GROUP BY usr.usr_id" . $groupByClauseRpType . $groupByClauseCmpType
               . " ORDER BY " . $orderByClause;
   */
   $sqlquery = "SELECT hq.hq_name, usr.usr_firstname, IF(LENGTH(CONCAT(usr.usr_firstname,usr.usr_name)) > 0, usr.usr_name, '" . getLngt("Nutzer gelöscht!") . "') AS usr_name, " . $fieldClauseRpType . $fieldClauseCmpType . " count(*) AS reports"
               . " FROM phoenix_group.report_process AS rp LEFT JOIN phoenix.user AS usr ON rp.usr_id = usr.usr_id, phoenix.headquarters AS hq" . $fromClauseRpType . $fromClauseCmpType
               . " WHERE rp.hq_id IN " . getSQLMandatorArray($f_hq_id) . " AND rp.hq_id = hq.hq_id AND"
               . "       rp.rp_objtype = '" . $rpObjType . "' AND " . $whereClauseRp . $whereClauseRpType . $whereClauseCmpType
               . "       rp.rp_createtime >= '$fromDateRange' AND rp.rp_createtime <= '$toDateRange'"               
               . " GROUP BY rp.hq_id, usr.usr_id" . $groupByClauseRpType . $groupByClauseCmpType
               . " ORDER BY " . $orderByClause;
// echo $sqlquery . "<br>";
   $result = $db->query($sqlquery);
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
   
   $alignArray = spliti(",",$aligns);
   $alignTitles = "center";
   $widthArray = spliti(",",$widths);
   $summationField = "reports";
   // $postParserField = "";
   $mode = "1";             // Output from DB-RESULT
   $fieldSortArray = $fieldArray;
   $sortDBField = "YES";    // Used in following include-file for sorting per column;
   $javaScriptFunctionNameForSort = "finishPageReportStatisticSort";
   include ("../include/inc_list_defineoutput.inc.php");
   $result->free();
   $sortDBField = "YES";                  // Reset
   $javaScriptFunctionNameForSort = "";   // Reset
   // Define output table
   $reportStatistic = $tableHeader . $tableBody;
   $tableHeader = "";
   $tableBody = "";
   // Checkboxes:
   // - Split by report category
   // - Export of the report statistic
   $reportStatistic .= "<table>";
   $reportStatistic .= "<tr><td>" . getLngt("Aufteilung nach Berichtstyp:") . "&nbsp;<input class=\"f8np1\" type=\"checkbox\" name=\"f_rpstat_splitbyreporttype[]\" value=\"1\" " . ($f_rpstat_splitbyreporttype == "1" ? "checked" : "") . "></td></tr>";
   if ($rpObjType == "cs") :
      $reportStatistic .= "<tr><td>" . getLngt("Aufteilung nach Kundentyp:") . "&nbsp;<input class=\"f8np1\" type=\"checkbox\" name=\"f_rpstat_splitbycmptype[]\" value=\"1\" " . ($f_rpstat_splitbycmptype == "1" ? "checked" : "") . "></td></tr>";
   endif;
   $reportStatistic .= "<tr><td>" . getLngt("Statistik exportieren:") . "&nbsp;<input class=\"f8np1\" type=\"checkbox\" name=\"f_rpstat_export[]\" value=\"1\"></td></tr>";
   $reportStatistic .= "</table>";

   // *** File output ***
   if ($f_rpstat_export) :
      // Remove old files
      foreach (glob("../temp/download/*.rpstat.csv") as $fileNameToBoRemoved) {
          if ((time() - filemtime($fileNameToBoRemoved)) > 60) :
             if (file_exists($fileNameToBoRemoved)) :
                unlink($fileNameToBoRemoved);
             endif;
          endif;
      }
      // 2nd request for file output
      $result = $db->query($sqlquery);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
      // Define output parameters
      $delimiter = ';';
      $writeHeader = "YES";
      $filename = "";
      $mode = "1";
      include_once ("../include/inc_list_defineoutput2file.inc.php");
      $outputLinesArrayLen = count($outputLinesArray);
      if ($outputLinesArrayLen > 0) :
         if ($filename == "") : $filename = getLngt("BERICHTSSTATISTIK"); endif;
         $f_fileName = $filename . "_" . date("YmdHis");
         // $f_secretFileName = md5($f_fileName) . ".rpstat.csv";
         $f_secretFileName = $f_fileName . ".rpstat.csv";      
         if ($outputHeader != "") :
            writeToFile("../temp/download/" . $f_secretFileName, $outputHeader);   // write header if requested
         endif;
         for ($i = 0; $i < $outputLinesArrayLen; $i++) :
             // Post parsing if necessary
             if ($postParserField != "") :
                if ($postParserFunction == "postParseReportStatistic") :
                   $outputLinesArray[$i] = postParseReportStatistic($outputLinesArray[$i]);
                endif;
             endif;
             writeToFile("../temp/download/" . $f_secretFileName, $outputLinesArray[$i]);   // write statistic data
         endfor;
      else :
         $statusMessage = getLngt("Es wurden keine Daten gefunden! Eine Datei wurde deshalb nicht generiert!");
         $f_rpstat_export = false;
      endif;
   endif;
endif;


function postParseHistory ($textToParse) {
	global $emp_id, $usr_id, $rpObjId, $reportTypeArray;
  $textToParse = trim($textToParse);

  if ($textToParse != "") :
     $count = 1;

     // 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);
           $tagContentArray = spliti(",",$tagContent);
           $tmpTagContent = $tagContentArray[0];
           $tmpTagUsrId = $tagContentArray[1];
           $tmpTagRpType = $tagContentArray[2];
           $tmpTagRpConfidential = $tagContentArray[3];

           if ($tmpTagContent != "") :

              // Set background color if <option>-element
	            $count_101 = getCountOfTable("metafieldvalue AS mtfv, metafieldcategorykey AS mtfck", "mtfv.mtfv_id = '" . $tmpTagContent . "' AND mtfv.mtfck_id = mtfck.mtfck_id AND mtfck.mtfc_id = '101'");
	            $count_102 = getCountOfTable("metafieldvalue AS mtfv, metafieldcategorykey AS mtfck", "mtfv.mtfv_id = '" . $tmpTagContent . "' AND mtfv.mtfck_id = mtfck.mtfck_id AND mtfck.mtfc_id = '102'");
	            $formularExistsStyle = "";
	            if ($count_101 > 0 || $count_102 > 0) : $formularExistsStyle = "style=\"background-color:#00FF00\""; endif;
	            $style_101 = "";
	            if ($count_101 == 0) : $style_101 = "style=\"background-color:#FFFFFF\""; endif;
	            $style_102 = "";
	            if ($count_102 == 0) : $style_102 = "style=\"background-color:#FFFFFF\""; endif;

              $tagContent = "";
              if ($reportTypeArray[$tmpTagRpType] != "") :
                 $tagContent = "<div><b>" . $reportTypeArray[$tmpTagRpType] . "</b></div>";
                 $tagContent .= "<div>&nbsp;</div>";
              endif;

              if ($rpObjId != "") :
                 if ($tmpTagUsrId == $usr_id) :
                    $tagContent .= defineButtonType10(getLngt("Entfernen"), "action_remove", "removeRpEntryFinishPage('" . $tmpTagContent . "');", "150");
                 endif;
                 if ($tmpTagUsrId == $usr_id || authCheckEmployeeRights($emp_id, "3")) :
                    $tagContent .= defineButtonType10(getLngt("Bearbeiten"), "action_edit", "copyRpEntryFinishPage('" . $tmpTagContent . "','" . $tmpTagRpConfidential . "');", "150");
                    $tagContent .= "<div>&nbsp;</div>";
                 endif;
                 $tagContent .= "<div>";
                 $tagContent .= "<select class=\"f8np1\" " . $formularExistsStyle . " name=\"f_sel_rpType_" . $count . "\" onchange=\"selectReportForm('" . $count . "','" . $tmpTagContent . "','0');\">";
                 $tagContent .= "  <option value=\"   \">" . getLngt("FORMULARAUSWAHL") . "</option>";
                 $tagContent .= "  <option value=\"101\" " . $style_101 . ">" . getLngt("Verkaufsbericht") . "</option>";
                 $tagContent .= "  <option value=\"102\" " . $style_102 . ">" . getLngt("Fahrzeugkontrolle") . "</option>";
                 $tagContent .= "</select>";
                 $tagContent .= "</div>";
              else :
                 $tagContent .= "<div>";
                 $tagContent .= "<select class=\"f8np1\" " . $formularExistsStyle . "name=\"f_sel_rpType_" . $count . "\" onchange=\"selectReportForm('" . $count . "','" . $tmpTagContent . "','1');\">";
                 $tagContent .= "  <option value=\"   \">" . getLngt("FORMULARAUSWAHL") . "</option>";
                 $tagContent .= "  <option value=\"101\" " . $style_101 . ">" . getLngt("Verkaufsbericht") . "</option>";
                 $tagContent .= "  <option value=\"102\" " . $style_102 . ">" . getLngt("Fahrzeugkontrolle") . "</option>";
                 $tagContent .= "</select>";
                 $tagContent .= "</div>";
              endif;
           endif;

           // Substitute text fragment
           $textToParse = substr_replace($textToParse, $tagContent, $beginTagPosBegin, $endTagPosEnd - $beginTagPosBegin);
        endif;
        $count++;
      }
  endif;
  return $textToParse;  
}

function postParseHistory2 ($textToParse) {
	global $emp_id, $usr_id, $rpObjId, $reportTypeArray;
  $textToParse = trim($textToParse);

  if ($textToParse != "") :
     $count = 1;

     // Iterate ALL occurrences of "<postparser2>...</postparser2>"
     while (!(strpos($textToParse, "<postparser2>") === FALSE)) {

        $beginTagPosBegin = strpos($textToParse, "<postparser2>");
        $beginTagPosEnd = $beginTagPosBegin + 13;
        $endTagPosBegin = strpos($textToParse, "</postparser2>");
        $endTagPosEnd = $endTagPosBegin + 14;

        if ($beginTagPosEnd < $endTagPosBegin) :
           $tagContent = substr($textToParse, $beginTagPosEnd, $endTagPosBegin - $beginTagPosEnd);
           $tagContentArray = explode("||",$tagContent);
           $tmpTagCmpComp = $tagContentArray[0];
           $tmpTagCmpComp2 = $tagContentArray[1];
           $tmpTagCsEid = $tagContentArray[2];
           $tmpTagCmpId = getFieldValueFromId("phoenix.customer", "cs_eid", $tmpTagCsEid, "cmp_id");

           if ($tmpTagCmpId != "") :
              $tagContent = "<a href=\"../admin/customer_special.php?companyId=" . ec($tmpTagCmpId) . "\" target=\"_blank\">" . $tmpTagCmpComp . "<br>" . $tmpTagCmpComp2 . "<br>" . $tmpTagCsEid . "</a>";
           endif;

           // Substitute text fragment
           $textToParse = substr_replace($textToParse, $tagContent, $beginTagPosBegin, $endTagPosEnd - $beginTagPosBegin);
        endif;
        $count++;
      }
  endif;
  return $textToParse;  
}

function postParseHistory3 ($textToParse) {
	global $emp_id, $usr_id, $rpObjId, $reportTypeArray;
  $textToParse = trim($textToParse);

  if ($textToParse != "") :
     $count = 1;

     // Iterate ALL occurrences of "<postparser3>...</postparser3>"
     while (!(strpos($textToParse, "<postparser3>") === FALSE)) {

        $beginTagPosBegin = strpos($textToParse, "<postparser3>");
        $beginTagPosEnd = $beginTagPosBegin + 13;
        $endTagPosBegin = strpos($textToParse, "</postparser3>");
        $endTagPosEnd = $endTagPosBegin + 14;

        if ($beginTagPosEnd < $endTagPosBegin) :
           $tagContent = substr($textToParse, $beginTagPosEnd, $endTagPosBegin - $beginTagPosEnd);
           $tagContent = trim($tagContent);

           if ($tagContent != "") :
              $tmpFields = getFieldsValueFromId("phoenix.couriervehicle","crvh_sid",$tagContent,array("cr_id","crvh_id","crvh_sid"));
              $courierId = $tmpFields[0];
              $crvhId = $tmpFields[1];
              $crvhSid = $tmpFields[2];
              if ($courierId != "") :
                 $tmpFields = getFieldsValueFromId("phoenix.courier","cr_id",$courierId,array("cr_eid","cmp_id"));
                 $courierEid = $tmpFields[0]; 
                 $companyId = $tmpFields[1];              
                 $tagContent = "&nbsp;<a href=\"../admin/courier_vehicle.php?courierId=" . ec($courierId) . "&f_crvh_id=" . $crvhId . "\" target=\"_blank\">" . $tagContent . "</a>&nbsp;&nbsp;"
                             . "[<a href=\"../admin/courier_special.php?companyId=" . ec($companyId) . "\" target=\"_blank\">" . $courierEid . "</a>]&nbsp;";
              endif;
           endif;

           // Substitute text fragment
           $textToParse = substr_replace($textToParse, $tagContent, $beginTagPosBegin, $endTagPosEnd - $beginTagPosBegin);
        endif;
        $count++;
      }
  endif;
  return $textToParse;  
}


   // --- REPORT PROCESS (HISTORY) ------------------

   // Check for generic metafield SQL JOIN
   $mtfSqlJoinArray = genericSqlMetafieldJoin("RP", $f_filter_rpType);

   // Generate list with header
   if ($rpObjId == "" || $isMeta == "1") :      
      $titleArray = array(getLngt("Nr.&nbsp;&nbsp;"),getLngt("Zeitpunkt&nbsp;&nbsp;"),getLngt("Zentrale&nbsp;&nbsp;"),$titleArrayObjName,getLngt("Mitarbeiter&nbsp;&nbsp;"),getLngt("Eintrag&nbsp;&nbsp;"),getLngt("Berichtstyp&nbsp;&nbsp;/&nbsp;&nbsp;Aktionen&nbsp;&nbsp;"));
      $fieldArray = array("rp_id","rp_createtime","hq_name","rp_data","usr_data","rp_text","rp_actions");
      $aligns = "r,c,c,c,c,l,c";
      $convertOutput = "0,0,0,0,0,1,0";
      $widths = "40,80,100,100,100,400,180";
   else :
      $titleArray = array(getLngt("Nr.&nbsp;&nbsp;"),getLngt("Zeitpunkt&nbsp;&nbsp;"),getLngt("Zentrale&nbsp;&nbsp;"),getLngt("Mitarbeiter&nbsp;&nbsp;"),getLngt("Eintrag&nbsp;&nbsp;"),getLngt("Berichtstyp&nbsp;&nbsp;/&nbsp;&nbsp;Aktionen&nbsp;&nbsp;"));
      $fieldArray = array("rp_id","rp_createtime","hq_name","usr_data","rp_text","rp_actions");
      $aligns = "r,c,c,c,l,c";
      $convertOutput = "0,0,0,0,1,0";
      $widths = "40,80,100,100,500,180";
   endif;
   if ($mtfSqlJoinArray[0] != "") :
      array_push($titleArray, getLngt($mtfSqlJoinArray[0]) . "&nbsp;");
      array_push($fieldArray, $mtfSqlJoinArray[1]);
      $aligns .= ",c";
      $convertOutput .= ",0";
      $widths .= ",80";
   endif;

   $alignArray = spliti(",",$aligns);
   $convertOutputArray = spliti(",",$convertOutput);

   // $fieldClause = "rp.rp_id, rp.hq_id, rp.rp_objid, rp.usr_id, rp.rp_reporttype, rp.rp_text, rp.rp_confidential, rp.rp_createtime " . ($mtfSqlJoinArray[2] != "" ? $mtfSqlJoinArray[2] : "") . ", "
   //              . "CONCAT(usr.usr_firstname,'<br>',usr.usr_name,'<br>',usr.usr_phone) AS usr_data, CONCAT(rp.rp_id,',',rp.usr_id,',',rp.rp_reporttype,',',rp.rp_confidential) AS rp_actions, hq.hq_name, ";
   $fieldClause = "rp.rp_id, rp.hq_id, rp.rp_objid, rp.usr_id, rp.rp_reporttype, rp.rp_text, rp.rp_confidential, rp.rp_createtime " . ($mtfSqlJoinArray[2] != "" ? $mtfSqlJoinArray[2] : "") . ", "
                . "IF (LENGTH(CONCAT(usr.usr_firstname,usr.usr_name)) > 0, CONCAT(usr.usr_firstname,'<br>',usr.usr_name,'<br>',usr.usr_phone), '" . getLngt("Nutzer gelöscht!") . "') AS usr_data, CONCAT(rp.rp_id,',',rp.usr_id,',',rp.rp_reporttype,',',rp.rp_confidential) AS rp_actions, hq.hq_name, ";
   if ($rpObjType == "cs") :
      $fieldClause .= "CONCAT(cmp.cmp_comp,'||',cmp.cmp_comp2,'||',cs.cs_eid) AS rp_data ";
      $fromClause = "phoenix.customer AS cs, phoenix.company AS cmp, ";
      $whereClause = "rp.rp_objid = cs.cs_id AND cs.cmp_id = cmp.cmp_id AND ";
   elseif ($rpObjType == "cr") :
      $fieldClause .= "CONCAT(cmp.cmp_comp,'||',cmp.cmp_comp2,'||',cr.cr_eid) AS rp_data ";
      $fromClause = "phoenix.courier AS cr, phoenix.company AS cmp, ";
      $whereClause = "rp.rp_objid = cr.cr_id AND cr.cmp_id = cmp.cmp_id AND ";
   elseif ($rpObjType == "pt") :
      $fieldClause .= "CONCAT(pt.pt_cmp_comp,'||',pt.pt_cmp_comp2,'||',pt.pt_cs_eid) AS rp_data ";
      $fromClause = "phoenix.prospect AS pt, ";
      $whereClause = "rp.rp_objid = pt.pt_id AND ";
   endif;

   $fromClause .= "phoenix.headquarters AS hq, phoenix_group.report_process AS rp "
                . "LEFT JOIN phoenix.user AS usr ON rp.usr_id = usr.usr_id "
                . ($mtfSqlJoinArray[3] != "" ? $mtfSqlJoinArray[3] : "");

   $whereClause .= $whereClauseRp
                 . $whereClause
                 . "rp.hq_id IN " . getSQLMandatorArray($f_hq_id) . " AND rp.hq_id = hq.hq_id AND rp.rp_objtype = '" . $rpObjType . "' "
                 . ($rpIdsFilter == "" ? " AND rp.rp_createtime >= '$fromDateRange' AND rp.rp_createtime <= '$toDateRange' " : "")
                 . ($mtfSqlJoinArray[4] != "" ? $mtfSqlJoinArray[4] : "");

   // Filter
   if (is_numeric($f_filter_rpType) && $f_filter_rpType > "0") :
      $whereClause .= " AND rp.rp_reporttype = '" . $f_filter_rpType . "' ";
   endif;

   // Confidential check
   if (!authCheckEmployeeRights($emp_id, "10")) :
      $whereClause .= " AND (rp.rp_confidential = '0' OR rp.usr_id = '" . $usr_id . "') ";
   endif;

   // Special filter by report IDs
   if ($rpIdsFilter != "") :
      $whereClause .= " AND rp.rp_id IN (" . $rpIdsFilter . ") ";
   endif;

   $tmpSortField = "rp.rp_createtime";
   if ($f_sort != "") :       
      if ($fieldArray[$f_sort] == "rp_actions") : 
         $tmpSortField = "rp.rp_reporttype";
      else :
        $tmpSortField = $fieldArray[$f_sort];
      endif;
   endif;
   $orderByClause = $tmpSortField . " DESC LIMIT 0," . $limitOfRowsDisplayed;

   $sqlquery = generateStatement($fieldClause,$fromClause,$whereClause,$orderByClause);
// echo $sqlquery . "<br>";
   // Send request to database
   $result = $db->query($sqlquery);

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

   $alignTitles = "center";   
   $widthArray = spliti(",",$widths);
   $summationField = "";
   $postParserField = "rp_actions";
   $postParserField2 = "rp_data";
   if ($mtfSqlJoinArray[0] != "") :
      $postParserField3 = $mtfSqlJoinArray[1];
   endif;
   $mode = "1";             // Output from DB-RESULT
   $fieldSortArray = $fieldArray;
   $sortDBField = "YES";    // Used in following include-file for sorting per column;
   // include ("../include/inc_list_defineoutput.inc.php");
   include ("../include/inc_list_defineoutput.inc.php");
   $result->free();


   // *** ONLY OUTPUT ***

   // Post parsing if necessary
   if ($postParserField != "") :
      $tableBody = postParseHistory($tableBody);
   endif;
   if ($postParserField2 != "") :
      $tableBody = postParseHistory2($tableBody);
   endif;
   if ($mtfSqlJoinArray[0] != "") :
      if ($postParserField2 != "") :
         $tableBody = postParseHistory3($tableBody);
      endif;
   endif;
   
   // Define output table
   $reportentries = $tableHeader . $tableBody;   
   $contentFrame = "";

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

   // 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,\"" . $contentFrame . "\",\"cs_report\",\"\",\"day_from\",\"month_from\",\"year_from\",\"\",\"\",\"\");\n";
   $js_date .= "  setDateTimeFields(\"" . $contentFrame . "\",\"cs_report\",".$day_from.",".$month_from.",".$year_from.", \"\", \"\", \"day_from\", \"month_from\", \"year_from\", \"\", \"\", \"\");\n";
   $js_date .= "  fillDateFields(1,\"" . $contentFrame . "\",\"cs_report\", \"\", \"day_to\", \"month_to\", \"year_to\", \"\", \"\", \"\");\n";
   $js_date .= "  setDateTimeFields(\"" . $contentFrame . "\",\"cs_report\",".$day_to.",".$month_to.",".$year_to.", \"\", \"\", \"day_to\", \"month_to\", \"year_to\", \"\", \"\", \"\");\n";
   $js_date .= "}\n";
   $js_date .= "-->\n";
   $js_date .= "</script>\n";
?>

<html>

<head>
<title><?php echo $pageTitel ?></title>

<style type="text/css">
  <?php include_once ("../css/phoenix.css.php"); ?>
  <?php include_once ("../css/navigation.css.php"); ?>
  <?php include_once ("../css/mc.css.php"); ?>
</style>

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

<style type="text/css">
.divpadding10 { padding-top:10px; padding-bottom:10px; padding-left:10px; padding-right:10px;}
input.minwidth { min-width:90px; }
</style>

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

<?php echo $js_date ?>

<script type="text/javascript">
<!--
// NAVIGATION
<?php echo $jsMenuOut; ?>

var popupWinMetaFieldSpecial = '';

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

function removeRpEntryFinishPage(rpIdToRemove) {
  if (confirm('<?php echo getLngt("Möchten Sie den Eintrag wirklich löschen?") ?>')) {
     document.forms[0].f_act.value='removeRpEntry';
     document.forms[0].f_rpIdToRemove.value=rpIdToRemove;
     document.forms[0].submit();
  }
};

function insertRpEntryFinishPage() {
	var doSubmit = true;
	var doAskForAnotherReportType = false;
	var nameOfReportType = '';
	var parItemMisc = '<?php echo getParameterValue("0", "MASK_CS_REPORTTYPE_MISC_ITEM", "0") ?>';
  for(i=0;i<document.forms[0].f_rpReportType.length;++i) {
     if (document.forms[0].f_rpReportType.options[i].selected == true) {
        
        if (document.forms[0].f_rpReportType.options[i].value == parItemMisc) {
           doAskForAnotherReportType = true;
           nameOfReportType = document.forms[0].f_rpReportType.options[i].text;
        };
     }
  }
  if (doAskForAnotherReportType) {
  	 doSubmit = false;
  	 if (confirm('<?php echo getLngt("Wollen Sie einen Bericht des Berichtstyps") ?> '  + nameOfReportType +  ' <?php echo getLngt("anfertigen?") ?>')) {
  	 	  doSubmit = true;
  	 }
  }
  if (doSubmit) {
     document.forms[0].f_act.value='insertRpEntry';
     document.forms[0].submit();
  }
};

function updateRpEntryFinishPage(rpIdToUpdate) {
	if (confirm('<?php echo getLngt("Änderungen speichern?") ?>')) {
     var mtfcMapping = new Array(<?php echo $constMaskRpReportFormsMapping ?>);
	   <?php if ($constMaskRpReportFormsEnabled == "1" && $f_rpIdToCopy != "") : ?>
       for(i=0;i<document.forms[0].f_rpReportType.length;++i) {
         if (document.forms[0].f_rpReportType.options[i].selected == true) {
            // optionVal = parseInt(document.forms[0].f_rpReportType.options[i].value);
            // optionVal = optionVal + 100;
            optionVal = parseInt(document.forms[0].f_rpReportType.options[i].value);
            if (mtfcMapping.length == 0) {
               optionVal = optionVal + 100;
            } else {
            	 optionVal = mtfcMapping[optionVal - 1];
            };
         }
       }
	     popupWinMetaFieldSpecial.document.forms[0].f_act.value = 'saveObjectData';
	     popupWinMetaFieldSpecial.document.forms[0].category.value = optionVal;
	     popupWinMetaFieldSpecial.document.forms[0].objId.value = rpIdToUpdate;
	     popupWinMetaFieldSpecial.document.forms[0].deactivateMenu.value = '1';
	     popupWinMetaFieldSpecial.finishPage();
	   <?php endif; ?>

     document.forms[0].f_act.value='updateRpEntry';
     document.forms[0].f_rpIdToUpdate.value=rpIdToUpdate;
     document.forms[0].f_rpIdToCopy.value='';
     document.forms[0].submit();
  }
}

function copyRpEntryFinishPage(rpIdToUpdate, rpConfidential) {
	// if (confirm('<?php echo getLngt("Eintrag wirklich bearbeiten?") ?>')) {
	   <?php if ($constMaskRpReportFormsEnabled == "1" && $f_rpIdToCopy != "") : ?>
       if (popupWinMetaFieldSpecial != '') {
       	  popupWinMetaFieldSpecial.close();
       }	
	   <?php endif; ?>
     document.forms[0].f_rpIdToCopy.value=rpIdToUpdate;
     if (rpConfidential == '1') {
        // document.forms[0].f_rpConfidential[0].checked = true;
        document.getElementsByName('f_rpConfidential[]')[0].checked = true;
     } else {
     	  // document.forms[0].f_rpConfidential[0].checked = false;
     	  document.getElementsByName('f_rpConfidential[]')[0].checked = false;
     }
     document.forms[0].submit();
  // }
}

function viewRpEntryFinishPage(rpIdToView, optionVal) {
	<?php if ($constMaskRpReportFormsEnabled == "1") : ?>
    if (popupWinMetaFieldSpecial != '') {
    	  popupWinMetaFieldSpecial.close();
    }
    var widthPopupWin = 900;
    var heightPopupWin = 870;
    var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
    var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
    var mtfcMapping = new Array(<?php echo $constMaskRpReportFormsMapping ?>);

    if (mtfcMapping.length == 0) {
       optionVal = optionVal + 100;
    } else {
    	  optionVal = mtfcMapping[optionVal - 1];
    };
    if (popupWinMetaFieldSpecial != '') {
    	  popupWinMetaFieldSpecial.close();
    }
    // Attention: $cs_id is NOT the ID saved according to the single report entry ...
    popupWinMetaFieldSpecial = window.open("../admin/metafield_special.php?deactivateMenu=1&category=" + optionVal + "&objId=" + rpIdToView + "&cascadingObjType=rp&hideButtons=1&editMode=2&specialPageTitle=<?php echo "Berichtsformular"; ?>" ,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
	<?php endif; ?>
}

function update_abort() {
	<?php if ($constMaskRpReportFormsEnabled == "1" && $f_rpIdToCopy != "") : ?>
    if (popupWinMetaFieldSpecial != '') {
    	  popupWinMetaFieldSpecial.close();
    }	
	<?php endif; ?>
	document.getElementsByName('f_rpConfidential[]')[0].checked = false;
  document.forms[0].submit();
}

function hqCheckAll(numOfHq) {
  for (i = 0; i < numOfHq; i++) {
	  document.getElementsByName('f_hq_id[]')[i].checked = true;
	}
}

function hqUncheckAll(numOfHq) {
  for (i = 0; i < numOfHq; i++) {
	  document.getElementsByName('f_hq_id[]')[i].checked = false;
  }
}

<?php if ($rpObjType == "cs") : ?>
function searchCsCsc() {
  var f_act = 'search';
  
  var widthPopupWin = 950;
  var heightPopupWin = 600;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/cs_csc_list.php?f_act=" + f_act + "&allowAllCustomerTypes=1&generic=0000000000001&callOpenerFunction=finishPage()",
    "","dependent=yes,width=" + widthPopupWin + ",height=" +
    heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin +
    ",scrollbars=yes");
};

function clearSpecialCustomer() {	
  document.forms[0].g_cs_eid.value='';
  document.forms[0].rpObjId.value='';
};

<?php elseif ($rpObjType == "cr") : ?>

function searchCr() {
  var f_act = 'search';
  
  var widthPopupWin = 950;
  var heightPopupWin = 600;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/courier_list.php?deactivateMenu=1&f_act=search&f_mode=3",
    "","dependent=yes,width=" + widthPopupWin + ",height=" +
    heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin +
    ",scrollbars=yes");
};

function clearSpecialCourier() {	
	document.forms[0].g_cr_id.value='';
  document.forms[0].g_cr_eid.value='';
  document.forms[0].rpObjId.value='';
};

<?php elseif ($rpObjType == "pt") : ?>

function searchPt() {
  var f_act = 'search';
  
  var widthPopupWin = 950;
  var heightPopupWin = 600;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/pt_list.php?f_act=" + f_act + "&generic=0000000010",
    "","dependent=yes,width=" + widthPopupWin + ",height=" +
    heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin +
    ",scrollbars=yes");
};

function clearSpecialProspect() {	
  document.forms[0].g_pt_cs_eid.value='';
  document.forms[0].pt_id.value='';
};

<?php endif; ?>

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

function finishPageSort(col) {
	document.forms[0].f_sort.value=col;
  finishPage();
};

function finishPageReportStatisticSort(col) {
  document.forms[0].f_act.value='reportStatistic';
	document.forms[0].f_rp_stat_sort.value=col;
  finishPage();
};

function finishPageRefresh() {
  document.forms[0].f_act.value='';
  // Deactivate all statistic checkboxes by refresh only
  var chckbx;
  chckbx = document.querySelector('input[name="f_rpstat_splitbyreporttype[]"]');
  if (chckbx) {
     chckbx.checked = false;
  }
  chckbx = document.querySelector('input[name="f_rpstat_splitbycmptype[]"]');
  if (chckbx) {
     chckbx.checked = false;
  }
  chckbx = document.querySelector('input[name="f_rpstat_export[]"]');
  if (chckbx) {
     chckbx.checked = false;
  }
  document.forms[0].submit();
};

function openReportForm(category, rpId, hideButtons) {
  var widthPopupWin = 900;
  var heightPopupWin = 870;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  if (popupWinMetaFieldSpecial != '') {
  	 popupWinMetaFieldSpecial.close();
  }
  // Attention: $cs_id is NOT the ID saved according to the single report entry ...
  if (category != '' && rpId != '') {
     popupWinMetaFieldSpecial = window.open("../admin/metafield_special.php?deactivateMenu=1&category=" + category + "&objId=" + rpId + "&cascadingObjType=rp&hideButtons=" + hideButtons + "&specialPageTitle=<?php echo getLngt("Berichtsformular"); ?>" ,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");	
  }
};

function selectReportForm(noOfElem, rpId, hideButtons) {
	var optionVal = '';
	var elem = eval('document.forms[0].f_sel_rpType_' + noOfElem);
	var len = elem.length;
  for(i=0;i<len;++i) {
    if (elem.options[i].selected == true) {      	
       optionVal = parseInt(elem.options[i].value);
    }
  }
  if (optionVal != '') {
  	 elem.options[0].selected = true;   // Reset because of reselection of the same element
     openReportForm(optionVal, rpId, hideButtons);
  }
};

function changeReportForm() {
	<?php if ($constMaskRpReportFormsEnabled == "1" && $f_rpIdToCopy != "") : ?>
	var optionVal;
  var widthPopupWin = 900;
  var heightPopupWin = 870;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var mtfcMapping = new Array(<?php echo $constMaskRpReportFormsMapping ?>);
  for(i=0;i<document.forms[0].f_rpReportType.length;++i) {
    if (document.forms[0].f_rpReportType.options[i].selected == true) {      	
       optionVal = parseInt(document.forms[0].f_rpReportType.options[i].value);
       if (mtfcMapping.length == 0) {
          optionVal = optionVal + 100;
       } else {
       	  optionVal = mtfcMapping[optionVal - 1];
       };
       if (popupWinMetaFieldSpecial != '') {
       	  popupWinMetaFieldSpecial.close();
       }
       // Attention: $cs_id is NOT the ID saved according to the single report entry ...
       popupWinMetaFieldSpecial = window.open("../admin/metafield_special.php?deactivateMenu=1&category=" + optionVal + "&objId=<?php echo $f_rpIdToCopy ?>&cascadingObjType=rp&hideButtons=1&specialPageTitle=<?php echo getLngt("Berichtsformular"); ?>" ,"","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
    }
  }
  <?php endif; ?>
};

function downloadReportStatisticFile() {
  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=EMC2/temp/download/&f_fileName=<?php echo $f_secretFileName ?>", "","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

function newAppointmentExec() {
  if (opener != undefined && opener.document.forms[0].name == 'appointment') {
  	 <?php if ($rpObjType == "cs") : ?>
       opener.document.forms[0].g_cs_eid.value = '<?php echo $g_cs_eid ?>';
     <?php endif; ?>
     opener.toggleDisplay('1');
     window.close();
  } else {
  	 <?php if ($rpObjType == "cs") : ?>
       window.location.href = '../groupware/appointment.php?currentNavigationItem=vertrieb&g_cs_eid=<?php echo $g_cs_eid ?>&displayStateOverrule=1';
     <?php endif; ?>
  }
}

function confirmForNewAppointment() {
  vConfirmFunc('<?php echo getLngt("Möchten Sie einen neuen Termin anlegen?") ?>', newAppointmentExec, 160, '');
}
-->
</script>

</head>

<body onLoad="<?php echo $phpCurrentNavigationOnLoad ?>initForm();<?php if ($f_rpstat_export) : echo "downloadReportStatisticFile();"; endif;?><?php if ($f_rpIdToCopy != "") : echo "changeReportForm();"; endif; ?><?php if ($confirmForNewAppointment) : echo "confirmForNewAppointment();"; endif; ?>">

<?php echo $phpMenuOut ?>
<?php echo $phpReducedMenuOut ?>
<?php echo $phpPageTitelOut ?>

<div class="mc_page-header">
  <?php echo $pageHeadline ?>
</div>

<div class="maincontent mc_elem" name="maincontent" id="maincontent">

<form name="cs_report" action="../groupware/report.php" method="post" target="">

  <input type="hidden" name="f_act" value="">
  <input type="hidden" name="rpObjType" value="<?php echo $rpObjType ?>">
  <input type="hidden" name="rpObjId" value="<?php echo ec($rpObjId) ?>">
  <input type="hidden" name="op" value="<?php echo ec($op) ?>">
  <input type="hidden" name="f_rpIdToRemove" value="">
  <input type="hidden" name="f_rpIdToUpdate" value="">
  <input type="hidden" name="f_rpIdToCopy" value="">
  <input type="hidden" name="contentFrame" value="<?php echo ec($contentFrame) ?>">
  <input type="hidden" name="f_sort" value="<?php echo $f_sort ?>">
  <input type="hidden" name="f_rp_stat_sort" value="<?php echo $f_rp_stat_sort ?>">
  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">

  <?php echo htmlDivLineSpacer("20px"); ?>

  <!- Title -->
  <div class="f10bp1_blue">
    <div style="float:left">
      <?php if ($rpObjType == "cs") : ?>
        <input type="text" name="g_cs_eid" value="<?php echo $g_cs_eid ?>" size="10" readonly>&nbsp;&nbsp;
      <?php elseif ($rpObjType == "cr") : ?>
        <input type="hidden" name="g_cr_id" value="<?php echo $g_cr_id ?>">
        <input type="text" name="g_cr_eid" value="<?php echo $g_cr_eid ?>" size="10" readonly>&nbsp;&nbsp;
      <?php elseif ($rpObjType == "pt") : ?>
        <input type="hidden" name="pt_id" value="<?php echo ec($pt_id) ?>">
        <input type="text" name="g_pt_cs_eid" value="<?php echo $g_pt_cs_eid ?>" size="10" readonly>&nbsp;&nbsp;
      <?php endif; ?>
    </div>
    <?php 
      if ($rpObjType == "cs") :
         echo defineButtonType10("...", "action_search", "searchCsCsc();", "20", "left", "2");
      elseif ($rpObjType == "cr") :
         echo defineButtonType10("...", "action_search", "searchCr();", "20", "left", "2");
      elseif ($rpObjType == "pt") :
         echo defineButtonType10("...", "action_pt_search", "searchPt();", "20", "left", "2");
      endif;
    ?>
    <div>
      <?php if ($rpObjType == "cs") : ?>
        <a href="javascript:clearSpecialCustomer();" tabindex="340"><img src="../images/waste.png" border="0" height="15" width="12"></a>
      <?php elseif ($rpObjType == "cr") : ?>
        <a href="javascript:clearSpecialCourier();" tabindex="340"><img src="../images/waste.png" border="0" height="15" width="12"></a>
      <?php elseif ($rpObjType == "pt") : ?>
        <a href="javascript:clearSpecialProspect();" tabindex="340"><img src="../images/waste.png" border="0" height="15" width="12"></a>
      <?php endif; ?>
    </div>
  </div>

  <?php echo htmlDivLineSpacer("20px", "", "left"); ?>

  <?php if ($statisticValueCurrentYear != "") : ?>
    <div class="f8np1">
    	  [<?php echo getLngt("Umsatz im laufenden Jahr bis heute:"); ?> &nbsp;<?php echo $statisticValueCurrentYear; ?>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|
    	   <?php echo getLngt("Umsatz im letzen Jahr in demselben Zeitraum:") ?> &nbsp;<?php echo $statisticValueLastYear; ?>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|
    	   <?php echo getLngt("Gesamtumsatz im letzen Jahr:") ?> &nbsp;<?php echo $statisticValueLastYearComplete; ?>]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    	  [<?php echo $invoiceOverview; ?>]
    </div>
    <?php echo htmlDivLineSpacer("20px"); ?>
  <?php endif; ?>

   <!- Date-ranges -->
  <div class="f10bp1_blue">
    <?php echo $filter_dateranges ?>
  </div>

  <?php echo htmlDivLineSpacer("20px"); ?>  

   <!- Actions -->
  <div>
    <?php echo defineButtonType10(getLngt("Aktualisieren"), "action_cr_search", "finishPageRefresh();", "100", "left", "5") ?>
    <?php echo defineButtonType10(getLngt("Schließen"), "action_cr_search", "window.close();", "100", "left", "20") ?>
    <?php echo defineButtonType10(getLngt("Berichtsstatistik"), "action_cr_search", "reportStatistic();", "130", "left") ?>
  </div>
  
  <?php echo htmlDivLineSpacer("30px", "", "left"); ?>
   
  <!-- Headquarters checkboxes -->
  <?php if (authCheckEmployeeRights($emp_id, "10")) : ?>
    <?php echo getHeadquartersCheckboxes($f_hq_id); ?>
    <?php echo htmlDivLineSpacer("30px", "", "left"); ?>
  <?php endif; ?>
    
  <?php 
    if ($rowCounter > 1000) : 
       echo "<div>" . getLngt("Mehr als") . " " . $limitOfRowsDisplayed . " " . getLngt("Datensätze werden nicht dargestellt") . "</div>";
       echo htmlDivLineSpacer("20px", "", "left");
    endif;
  ?>

  <?php if ($f_act == "reportStatistic") : ?>
    <!- Statistic -->
    <div>
      <table cellspacing="0" cellpadding="0" vspace="0" hspace="0">
        <tr><td class="f10bp1_blue"><?php echo getLngt("Statistik") ?><br><br></td></tr>
        <?php echo $reportStatistic ?>
      </table>
    </div>
    <?php echo htmlDivLineSpacer("30px", "", "left") ?>
   <?php endif; ?>
   
   <!- Reports -->
   <div>
     <table cellspacing="0" cellpadding="0" vspace="0" hspace="0">
       <tr>
         <td class="f10np1_blue" colspan="5">
           <span class="f10bp1_blue"><?php echo getLngt("Berichte") ?></span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
           <?php echo getLngt("Berichtstypfilter") ?>&nbsp;&nbsp;<?php echo "<select class=\"f8np1\" name=\"f_filter_rpType\"><option value=\"0\">Alle</option>" . addOptionsFromTable("metatype","mt_sort","mt_value","mt_value","mt_type = '" . $metatypeReportType . "'",$f_filter_rpType) . "</select><br><br><br><br>"; ?>
         </td>
       </tr>
       <?php echo $reportentries ?>     
     </table>
   </div>
     
   <!- Insert Entry -->
   <?php if ($rpObjId != "") : ?>
     <div>
       <table align="left" border="0" width="100%">
         <tr>
           <td align="center" valign="top">
             <b>Text:</b><br><br>
             <textarea name="f_text" cols="100" rows="10"><?php 
                 // To edit a single entry copy the text to the textarea field
                 if ($f_rpIdToCopy != "") : 
                    echo getFieldValueFromId("phoenix_group.report_process", "rp_id", $f_rpIdToCopy, "rp_text");
                 endif;
               ?></textarea>
           </td>
           <td align="left" valign="center">
             <?php 
               if ($f_rpIdToCopy == "") :
                 echo getLngt("Berichtstyp:") . "<br><br>";
                 echo "<select class=\"f8np1\" name=\"f_rpReportType\">" . addOptionsFromTable("metatype","mt_sort","mt_value","mt_value","mt_type = '" . $metatypeReportType . "'",$f_rpReportType) . "</select><br><br><br><br>";
                 echo defineButtonType10(getLngt("Bericht&nbsp;speichern"), "action_insert", "insertRpEntryFinishPage();", "150");
                 echo "<br>";
                 echo getLngt("Vertraulich:") . " <input class=\"f8np1\" type=\"checkbox\" name=\"f_rpConfidential[]\" value=\"\" " . ($f_rpConfidential == "1" ? "checked" : "") . ">";
               else :
                 echo getLngt("Berichtstyp:") . "<br><br>";
                 $f_rpReportType = getFieldValueFromId("phoenix_group.report_process", "rp_id", $f_rpIdToCopy, "rp_reporttype");
                 echo "<select class=\"f8np1\" name=\"f_rpReportType\" onChange=\"changeReportForm();\">" . addOptionsFromTable("metatype","mt_sort","mt_value","mt_value","mt_type = '" . $metatypeReportType . "'",$f_rpReportType) . "</select><br><br><br><br>";
                 echo defineButtonType10(getLngt("Abbrechen"), "action_abort", "update_abort();", "150");
                 echo "<br>";
                 echo defineButtonType10(getLngt("Änderung&nbsp;speichern"), "action_modify", "updateRpEntryFinishPage(" . $f_rpIdToCopy . ");", "150");
                 echo "<br>";
                 echo getLngt("Vertraulich:") . " <input class=\"f8np1\" type=\"checkbox\" name=\"f_rpConfidential[]\" value=\"\" " . ($f_rpConfidential == "1" ? "checked" : "") . ">";
               endif;
             ?>
           </td>
         </tr>
       </table>
     </div>
   <?php endif; ?>

</form>
</div>
</body>

</html>
