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

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


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

getSecHttpVars("1", array("f_act", "selYear", "selMonth", "selDay", "workMode",
                          "apId", "f_hour", "f_minute", "f_hour_to", "f_minute_to"));

// Initialisations
if ($selYear == "") : $selYear = date("Y"); endif;
if ($selMonth == "") : $selMonth = date("m"); endif;
if ($selDay == "") : $selDay = date("d"); endif;

if ($workMode == "") : $workMode = "0"; endif;   // rules the output and meaning of e.g. day links of the calendar

// Definiton of global parameters
include_once ("../include/inc_calendar.inc.php");

getLanguage(__FILE__);

// Functions

// Prints the headline with the selected month and the selected year
// $selYear   : Selected year
// $selMonth  : Selected month
// $cellWidth : Static width of the table cell
// $cellCol   : Colour of the cell
function printMonthYearHeader($selYear, $selMonth, $cellWidth = "80", $cellCol = "FF7777") {
  global $calMonthNames;
  $out = "<tr>";
  // $out .= "<td colspan=\"4\" width=\"" . $cellWidth . "\" align=\"center\" bgcolor=\"#" . $cellCol . "\"><b>" . $calMonthNames[$selMonth - 1] . "</b></td>"; 
  // $out .= "<td colspan=\"2\" align=\"center\" bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
  // $out .= "<td colspan=\"4\" width=\"" . $cellWidth . "\" align=\"center\" bgcolor=\"#" . $cellCol . "\"><b>" . $selYear . "</b></td>";
  $out .= "<td colspan=\"8\" align=\"center\" bgcolor=\"#" . $cellCol . "\"><b>" . $calMonthNames[$selMonth - 1] . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $selYear . "</b></td>"; 
  $out .= "</tr>";
  return $out;
}

// Prints the headline with the day names
// $outArray  : List with names (Monday, Tuesday, ... or Montag, Dienstag, ... etc.)
// $outMode   : Only the first letter of a day name will be displayed (= 1)
// $cellWidth : Static width of the table cell
// $cellCol   : Colour of the cell
function printWeekDayHeader($outArray, $outMode = "", $cellWidth = "40", $cellCol = "7777FF") {
  global $calCurrentWeekName;
  $lenOutArray = count($outArray);
  $out = "<tr>";	
  $out .= "<td width=\"" . $cellWidth . "\" align=\"center\" bgcolor=\"#77FF77\">" . $calCurrentWeekName . "</td>";
  for ($j = 0; $j < $lenOutArray; $j++) :
      if ($outMode == "1") : $outArray[$j] = substr($outArray[$j],0,2); endif;
      $out .= "<td width=\"" . $cellWidth . "\" align=\"center\" bgcolor=\"#" . $cellCol . "\">" . $outArray[$j] . "</td>";
  endfor;
  $out .= "</tr>";
  return $out;
}

// Gets exactly the value of one specified field from the specified row by key of a certain table
function getAppointmentsFromDB($selYearFrom, $selMonthFrom, $selDayFrom, $selYearTo = "", $selMonthTo = "", $selDayTo = "", $csId = "", $cscId = "", $apType = "") {
  global $db, $PHP_SELF;
  global $emp_id, $usr_id, $f_selUsrId, $f_hq_id;
  global $f_ap_visibility_search, $f_ap_cat_search_1, $f_ap_cat_search_2, $f_ap_cat_search_3, $f_ap_cat_search_4;

  $retArray = array();
  if (!is_array($f_ap_visibility_search)) : $f_ap_visibility_search = array(); endif;
  $dayStringFrom = $selYearFrom . "-" . pad($selMonthFrom,2,"0") . "-" . pad($selDayFrom,2,"0");
  $dayStringTo = $selYearTo . "-" . pad($selMonthTo,2,"0") . "-" . pad($selDayTo,2,"0");
  if ($selYearTo == "" || $selMonthTo == "" || $selDayTo == "") :
     $dayStringTo = $dayStringFrom;
  endif;

  // Filter to display appointments of other users
  $whereClauseCreatorFilter = " AND (ap.usr_id = '" . $f_selUsrId . "' OR ap.ap_participants LIKE '%," . $f_selUsrId . ",%') ";
  if ($f_selUsrId == "0") :
     $whereClauseCreatorFilter = "";
  endif;
  
  // Filter to display appointments of special type
  $whereClauseApType = "";
  if ($apType != "" && is_numeric($apType) && $apType > 0) :
     $whereClauseApType = " AND ap.ap_type = '" . $apType . "' ";
  endif;

  // Filter according to selected categories
  $whereClauseCategoryFilter = "";

  // State: Business, private
  if ($f_ap_cat_search_1 != "") : $whereClauseCategoryFilter .= " AND ap.ap_category_1 = '" . $f_ap_cat_search_1 . "' "; endif;  
  
  // ...
  // if ($f_ap_cat_search_2 != "") : $whereClauseCategoryFilter .= " AND ap.ap_category_2 = '" . $f_ap_cat_search_2 . "' "; endif;
  
  // Kind: Misc., Meeting, conference, visit, ...
  if ($f_ap_cat_search_3 != "") : $whereClauseCategoryFilter .= " AND ap.ap_category_3 = '" . $f_ap_cat_search_3 . "' "; endif;
  
  // Deadline monitoring
  if ($f_ap_cat_search_4 != "") : $whereClauseCategoryFilter .= " AND ap.ap_category_4 = '" . $f_ap_cat_search_4 . "' "; endif;

  // Visibility
  /*
  1 alle Einträge
  2   selbst erstellte Einträge
  3      nur für mich sichtbar
  4      nur für Teilnehmer sichtbar
  5      für alle sichtbar
  6   Einträge anderer Mitarbeiter
  7      ich bin Teilnehmer
  8      alle weiteren freigegebenen
  
  1  	nur für Teilnehmer
  2 	nur für mich
  3 	für alle
  */
  $whereClauseVisibilityFilter = "";
  $whereClauseVisibilityFilterArray = array();
  $lenApVisibilitySearch = count($f_ap_visibility_search);
  if ($lenApVisibilitySearch > 0) :
     for ($i = 0; $i < $lenApVisibilitySearch; $i++) :
         $tmpApVisibilityArray[$f_ap_visibility_search[$i]] = "1";
     endfor;
     if (!($tmpApVisibilityArray[3] == "1" && $tmpApVisibilityArray[4] == "1" && $tmpApVisibilityArray[5] == "1" &&
           $tmpApVisibilityArray[7] == "1" && $tmpApVisibilityArray[8])) :

        if ($tmpApVisibilityArray[3] == "1") :
           $whereClauseVisibilityFilterArray[] = " (ap.usr_id = '" . $usr_id . "' AND ap.ap_category_2 = '2') ";
        endif;
        if ($tmpApVisibilityArray[4] == "1") :
           $whereClauseVisibilityFilterArray[] = " (ap.usr_id = '" . $usr_id . "' AND ap.ap_category_2 = '1') ";
        endif;
        if ($tmpApVisibilityArray[5] == "1") :
           $whereClauseVisibilityFilterArray[] = " (ap.usr_id = '" . $usr_id . "' AND ap.ap_category_2 = '3') ";
        endif;
        
        if ($tmpApVisibilityArray[7] == "1") :
           $whereClauseVisibilityFilterArray[] = " (ap.usr_id != '" . $usr_id . "' AND ap.ap_participants LIKE '%," . $usr_id . ",%') ";
        endif;
        if ($tmpApVisibilityArray[8] == "1") :
           $whereClauseVisibilityFilterArray[] = " (ap.usr_id != '" . $usr_id . "' AND NOT (ap.ap_participants LIKE '%," . $usr_id . ",%')) ";
        endif;

        $whereClauseVisibilityFilter = " AND (" . implode(" OR ", $whereClauseVisibilityFilterArray) . ") ";
     endif;
  endif;

  // Check for special customer
  $whereClauseCs = "";
  if ($csId != "" && is_numeric($csId)) :
     $whereClauseCs = " AND ap.cs_id = '" . $csId . "' ";
  endif;

  // Check for special costcenter
  $whereClauseCsc = "";
  if ($cscId != "" && is_numeric($cscId)) :
     $whereClauseCsc = " AND ap.csc_id = '" . $cscId . "' ";
  endif;

  // Check for headquarters
  $whereClauseHq = "";
  if (count($f_hq_id) > 0) :
     $whereClauseHq = " AND ap.hq_id IN " . getSQLMandatorArray($f_hq_id) . " ";
  endif;

  $sqlStmt = "SELECT ap.ap_id, ap.ap_type, ap.ap_text, ap.ap_confirmed, ap.ap_execdate, ap.ap_enddate,"
             . "     cmp.cmp_id, cmp.cmp_comp, cmp.cmp_comp2, cs.cs_id, cs.cs_eid,"
             . "     ap.usr_id, usr.usr_firstname, usr.usr_name, ap.ap_participants, ap.csc_id,"
             . "     ap.ap_category_1, ap.ap_category_2, ap.ap_category_3, ap.ap_category_4,"
             . "     cs_usr.usr_firstname AS cs_usr_firstname, cs_usr.usr_name AS cs_usr_name,"
             . "     cs_usr.usr_phone AS cs_usr_phone, cs_usr.usr_phone2 AS cs_usr_phone2"
             . " FROM phoenix_group.appointment AS ap" 
             . "      LEFT JOIN phoenix.customer AS cs ON ap.cs_id = cs.cs_id"
             . "      LEFT JOIN phoenix.company AS cmp ON cs.cmp_id = cmp.cmp_id"
             . "      LEFT JOIN phoenix.user AS usr ON ap.usr_id = usr.usr_id"
             . "      LEFT JOIN phoenix.employee AS cs_emp ON cs.cs_admin = cs_emp.emp_id"
             . "      LEFT JOIN phoenix.user AS cs_usr ON cs_emp.usr_id = cs_usr.usr_id"
             . " WHERE ((ap.ap_execdate >= ' " . $dayStringFrom . " 00:00:00' AND"
             . "         ap.ap_execdate <= ' " . $dayStringTo . " 23:59:59') OR"
             . "        (ap.ap_execdate < ' " . $dayStringFrom . " 00:00:00' AND"
             . "         ap.ap_enddate >= ' " . $dayStringFrom . " 00:00:00'))"
             .         $whereClauseCategoryFilter . $whereClauseVisibilityFilter . $whereClauseCreatorFilter . $whereClauseCs . $whereClauseCsc . $whereClauseHq . $whereClauseApType
             . " ORDER BY ap.ap_execdate";
// echo $sqlStmt . "<br>";
  $result = $db->dbQ($sqlStmt);
  while ($row = $result->fetch_assoc()):
        $retArray[] = array($row["ap_id"], $row["ap_text"], $row["ap_execdate"], $row["cmp_id"], $row["cmp_comp"], $row["cmp_comp2"], $row["cs_id"], $row["cs_eid"], $row["ap_enddate"], $row["usr_id"], $row["usr_firstname"], $row["usr_name"], $row["ap_participants"], $row["ap_confirmed"], $row["cs_usr_firstname"], $row["cs_usr_name"], $row["cs_usr_phone"], $row["cs_usr_phone2"], $row["ap_category_1"], $row["ap_category_2"], $row["ap_category_3"], $row["ap_category_4"], $row["csc_id"], $row["ap_type"]);
  endwhile;
  $result->free();
  return $retArray;
}

// Modifies array according to the appointments starting and ending on different days
// $apArray = Array with appointments of the time interval (week, month, ...)
// $lowerRangeDate = Date of the beginning of the interval (week, month, ...)
// $upperRangeDate = Date of the end of the interval (week, month, ...)
function modifyIntervalAppointments2SingleDayAppointments($apArray, $lowerRangeDate, $upperRangeDate) {

  $tmpApArray = array();
  $lenApArray = count($apArray);  
  for ($i = 0; $i < $lenApArray; $i++) :

      $tmpExecDate = substr($apArray[$i][2],0,10);
      $tmpExecTime = substr($apArray[$i][2],11,5);
      $tmpEndDateTime = $apArray[$i][8];
      $tmpEndDate = substr($apArray[$i][8],0,10);

      if ($tmpExecDate == $tmpEndDate) :
         if ($lowerRangeDate <= $tmpExecDate && $tmpExecDate <= $upperRangeDate) :
            $tmpApArray[] = $apArray[$i];   // Start day of the appointment
         endif;
      else :
         $apArray[$i][8] = $tmpExecDate . " 23:59:59";
         if ($lowerRangeDate <= $tmpExecDate && $tmpExecDate <= $upperRangeDate) :
            $tmpApArray[] = $apArray[$i];   // Start day of the appointment
         endif;
         while ($tmpExecDate != $tmpEndDate) :
               $tmpExecDate = date("Y-m-d", mktime(0,0,0,substr($tmpExecDate,5,2),substr($tmpExecDate,8,2)+1,substr($tmpExecDate,0,4)));
               $apArray[$i][2] = $tmpExecDate . " 00:00:00";
               $apArray[$i][21] = "0";   // Do not display "alarm"
               if ($tmpExecDate == $tmpEndDate) :
                  $apArray[$i][8] = $tmpEndDateTime;
               else :
                  $apArray[$i][8] = $tmpExecDate . " 23:59:59";
               endif;
               if ($lowerRangeDate <= $tmpExecDate && $tmpExecDate <= $upperRangeDate) :
                  $tmpApArray[] = $apArray[$i];
               endif;
         endwhile;
      endif;
  endfor;
  
  // Sort $tmpApArray[] per "ExecDate" and restore to $apArray
  $apArray = array();   // First reset $apArray
  $lenTmpApArray = count($tmpApArray);
  for ($i = 0; $i < $lenTmpApArray; $i++) :
      $minDate = "2100-12-31 23:59:59";
      for ($j = 0; $j < $lenTmpApArray; $j++) :
         if ($tmpApArray[$j] != "") : 
            $minDate = min($minDate, $tmpApArray[$j][2]);
         endif;
      endfor;
      for ($j = 0; $j < $lenTmpApArray; $j++) :
         if ($tmpApArray[$j] != "") :
            if ($tmpApArray[$j][2] == $minDate) :
               $apArray[] = $tmpApArray[$j];
               $tmpApArray[$j] = "";
            endif;
         endif;
      endfor;
  endfor;
  return $apArray;
}

// Gets the appointments of one day
function getAppointmentsOfOneDay($selYear, $selMonth, $selDay, $csId = "") {
  $apArray = getAppointmentsFromDB($selYear, $selMonth, $selDay, $selYear, $selMonth, $selDay, $csId);  
  return $apArray;
}

// Gets the appointments of one week
function getAppointmentsOfOneWeek($selWeek, $selYear, $selMonth, $selDay, $csId = "") {
  global $calCurrentWeekNum, $calWeekDays;
  if ($selWeek == "") : $selWeek = $calCurrentWeekNum; endif;  
  // Get the first day ("Monday") of the specified week
  $firstDayOfWeek = calFirstDayNumOfWeek($selWeek, $selYear);
  // Compute interval to week (eq. 7 days)
  $tmpDatetime = mktime(0, 0, 0, $firstDayOfWeek[1], $firstDayOfWeek[0] + 6, $firstDayOfWeek[2]);  
  $weekBeginDate = date("Y-m-d", mktime(0, 0, 0, $firstDayOfWeek[1], $firstDayOfWeek[0], $firstDayOfWeek[2]));
  $weekEndDate = date("Y-m-d", mktime(0, 0, 0, $firstDayOfWeek[1], $firstDayOfWeek[0] + 6, $firstDayOfWeek[2]));
  // Get appointments of the specified week
  $apArray = getAppointmentsFromDB($firstDayOfWeek[2], $firstDayOfWeek[1], $firstDayOfWeek[0], date("Y", $tmpDatetime), date("m", $tmpDatetime), date("d", $tmpDatetime), $csId);
  // Modifies array according to the appointments starting and ending on different days
  $apArray = modifyIntervalAppointments2SingleDayAppointments($apArray, $weekBeginDate, $weekEndDate);
  return $apArray;
 }

// Gets the appointments of one month
function getAppointmentsOfOneMonth($selYear, $selMonth, $csId = "") {
  global $calCurrentWeekNum, $calWeekDays, $calMonthDays;
  // Get the calendar week of the first day of the selected month
  $calFirstWeekNumofTheMonth = calFirstWeekNumofMonth($selMonth, $selYear);  
  // Get the number of the first day of the selected month
  $calFirstDayNumOfTheMonth = calFirstDayNumOfMonth($selMonth, $selYear);
  // Get appointments of the specified month
  $apArray = getAppointmentsFromDB($selYear, $selMonth, "1", $selYear, $selMonth, $calMonthDays[$selMonth - 1], $csId);
  $lenApArray = count($apArray);
  $monthBeginDate = date("Y-m-d", mktime(0, 0, 0, $selMonth, "1", $selYear));
  $monthEndDate = date("Y-m-d", mktime(0, 0, 0, $selMonth, $calMonthDays[$selMonth - 1], $selYear));
  // Modifies array according to the appointments starting and ending on different days
  $apArray = modifyIntervalAppointments2SingleDayAppointments($apArray, $monthBeginDate, $monthEndDate);
  return $apArray;
 }

// Gets the appointments of one year
function getAppointmentsOfOneYear($selYear, $csId = "") {
  global $calCurrentWeekNum, $calWeekDays;
  global $calMonthNames, $calMonthDays;  
  $apArray = array();
  for ($j = 1; $j <= 12; $j++) :
      $apArray = array_merge($apArray, getAppointmentsOfOneMonth($selYear, $j, $csId));
  endfor;
  return $apArray;
}

// Gets an array with days of a specified month (and year), where there is at least one appointment per day
function getDaysWithAppointments($selYear, $selMonth, $csId = "") {
  global $db, $PHP_SELF;
  global $emp_id, $usr_id, $calMonthDays, $f_selUsrId;
  
  $dayArray = array();
  if ($f_selUsrId == "") : $f_selUsrId = $usr_id; endif;  
  if (substr($selMonth,0,1) == "0") : $selMonth = substr($selMonth,-1); endif;   // kind of typecast
  $tmpArray = getAppointmentsFromDB($selYear, $selMonth, 1, $selYear, $selMonth, $calMonthDays[$selMonth - 1], $csId);

  // Iterate all days of the current month displayed
  for ($i = 1; $i <= $calMonthDays[$selMonth - 1]; $i++) :
      $tmpDate = date("Y-m-d", mktime(0,0,0,$selMonth,$i,$selYear));
      
      $tmpArrayLen = count($tmpArray);
      for ($j = 0; $j < $tmpArrayLen; $j++) :
          $tmpExecdate = substr($tmpArray[$j][2],0,10);
          $tmpEnddate  = substr($tmpArray[$j][8],0,10);
          
          if ($tmpExecdate <= $tmpDate && $tmpDate <= $tmpEnddate) :
             mcArrIsSet($dayArray, $i);
             $dayArray[$i] = "1";   // appointment does exist on this day
          endif;
      endfor;
  endfor;
  return $dayArray;
}	

// Generates the output of all days of the selected month and year
// $selYear   : Selected year
// $selMonth  : Selected month
// $cellWidth : Static width of the table cell
// $cellCol   : Colour of the cell
// $appointmentLink           : If equals "" then only display the day without link according any logic (usage as "normal calendar")
// $checkExistingAppointments : If equals "" then do NOT check for appointments (usage as "normal calendar")
function printWeekDays($selYear, $selMonth ,$cellWidth = "40", $cellCol = "AAAAFF", $appointmentLink = "", $checkExistingAppointments = "", $csId = "") {
  global $calMonthDays;
  global $f_selUsrId, $f_ap_cat_search_1, $f_ap_cat_search_2, $f_ap_cat_search_3, $f_ap_cat_search_4;

  // Get the calendar week of the first day of the selected month
  $calFirstWeekNumofTheMonth = calFirstWeekNumofMonth($selMonth, $selYear);  
  // Get the number of the first day of the selected month
  $calFirstDayNumOfTheMonth = calFirstDayNumOfMonth($selMonth, $selYear);
  // Checks existence of appointments of the selected month if requested
  if ($checkExistingAppointments != "") :
     $dayArray = getDaysWithAppointments($selYear, $selMonth, $csId);
  endif;
  $dayCounter = 1;
  $out = "<tr>";
  for ($i = 1; $i < 7; $i++) :
     // Display the calendar week
     $out .= "<td width=\"" . $cellWidth . "\" align=\"center\" bgcolor=\"#AAFFAA\">";
     if ($appointmentLink == "1") :
        $tmpSelYearOnlyForDisplay = $selYear;
        // Only for the link adapt the year ...
        if ($selMonth == 12 && $calFirstWeekNumofTheMonth <= 2) : 
           $tmpSelYearOnlyForDisplay++; 
        elseif ($selMonth == 1 && $calFirstWeekNumofTheMonth >= 52) :
           $tmpSelYearOnlyForDisplay--;
        endif;
        /*
        $out .= "<a href=\"../groupware/appointment.php?viewMode=" . ec("2") . "&selWeek=" . ec($calFirstWeekNumofTheMonth) . "&selYear=" . ec($tmpSelYearOnlyForDisplay) . "&selMonth=" . ec($selMonth) . 
                                                                                "&f_selUsrId=" . $f_selUsrId . 
                                                                                "&f_ap_cat_search_1=" . ec($f_ap_cat_search_1) . "&f_ap_cat_search_2=" . ec($f_ap_cat_search_2) . "&f_ap_cat_search_3=" . ec($f_ap_cat_search_3) . 
                                                                                "\" target=\"_self\">" . $calFirstWeekNumofTheMonth . "</a>";
        */
        $out .=  "<a href=\"javascript:finishPageCalendarWeekLink('" . ec($calFirstWeekNumofTheMonth) . "','" . ec($tmpSelYearOnlyForDisplay) . "');\">" . $calFirstWeekNumofTheMonth . "</a>";
  // elseif ($appointmentLink == "2") :
  //   $out .= $calFirstWeekNumofTheMonth;
     else :
        $out .= $calFirstWeekNumofTheMonth;
     endif;
     $out .= "</td>";
     // Display the days of the calendar week
     for ($j = 1; $j <= 7; $j++) :
         if ((($i > 1) || ($i == 1 && $j >= $calFirstDayNumOfTheMonth)) && $dayCounter <= $calMonthDays[$selMonth - 1]) :
            $cellCol2 = $cellCol;
            if ($selYear == date("Y") && $selMonth == date("m") && $dayCounter == date("d")) :
               $cellCol2 = "FFFF00";  // Yellow
            else :
               if ($checkExistingAppointments != "") :
                  // if (!(array_search($dayCounter, $dayArray) === FALSE)) :
                  mcArrIsSet($dayArray, $dayCounter);
                  if ($dayArray[$dayCounter] == "1") :
                     $cellCol2 = "FFAAAA";  // Pink
                  endif;
               endif;
            endif;
            $out .= "<td width=\"" . $cellWidth . "\" align=\"center\" bgcolor=\"#" . $cellCol2 . "\">";
            if ($appointmentLink == "1") :
               /*
               $out .= "<a href=\"../groupware/appointment.php?viewMode=" . ec("0") . "&selYear=" . ec($selYear) . "&selMonth=" . ec($selMonth) . "&selDay=" . ec($dayCounter) . 
                                                                                      "&f_selUsrId=" . $f_selUsrId . 
                                                                                      "&f_ap_cat_search_1=" . ec($f_ap_cat_search_1) . "&f_ap_cat_search_2=" . ec($f_ap_cat_search_2) . "&f_ap_cat_search_3=" . ec($f_ap_cat_search_3) . 
                                                                                      "\" target=\"_self\">" . $dayCounter . "</a>";
               */
               $out .=  "<a href=\"javascript:finishPageCalendarDayLink('" . ec($dayCounter) . "');\">" . $dayCounter . "</a>";
            elseif ($appointmentLink == "2") :
               // $out .=  "<a href=\"javascript:setResubmissionDate('" . $selYear . "','" . $selMonth . "','" . $dayCounter . "');\">" . $dayCounter . "</a>";
               $out .=  "<a href=\"javascript:finishPageCalendarDayLink('" . ec($dayCounter) . "');\">" . $dayCounter . "</a>";
            else :
               $out .=  $dayCounter;
            endif;
            $out .= "</td>";
            $dayCounter++;
         else :
            $out .= "<td width=\"" . $cellWidth . "\" align=\"center\" bgcolor=\"#" . $cellCol . "\">&nbsp;</td>";
         endif;
     endfor;
     if ($i < 6) : $out .= "</tr><tr>"; endif;

     // Check especially for changing of the year
     if ($selMonth == 1 && $calFirstWeekNumofTheMonth >= 52) :
        $calFirstWeekNumofTheMonth = 0;
     endif;
     $calFirstWeekNumofTheMonth++;
     if ($selMonth == 12 && $calFirstWeekNumofTheMonth > calLastWeekNumofYear($selYear)) :
        $calFirstWeekNumofTheMonth = 1;
     endif;     
     
  endfor;
  $out .= "</tr>";
  return $out;
}

// Prints the action fields to select a special month and a special year
// $selYear   : Selected year
// $selMonth  : Selected month
// $cellWidth : Static width of the table cell
// $cellCol   : Colour of the cell
function printActionFields($selYear, $selMonth, $cellWidth = "80", $cellCol = "FF7777") {
  global $calMonthNames;
  $monthsToSelect = "<select class=\"f8np1\" name=\"selMonth\">" . addOptionsFromTable("metatype","mt_sort","mt_value","mt_sort","mt_type = 'cal_months'",(int)$selMonth) . "</select>";
  $yearToSelect = "<select class=\"f8np1\" name=\"selYear\">" . addOptionsFromRange(1971, (date("Y") + 10), $selYear) . "</select>";
  // $yearToSelect = "<input type=\"text\" name=\"selYear\" value=\"" . $selYear . "\" size=\"4\" maxlength=\"4\">";
  $out = "<tr>";
  $out .= "<td colspan=\"3\" width=\"" . $cellWidth . "\" align=\"center\" bgcolor=\"#" . $cellCol . "\">" . $monthsToSelect . "</td>"; 
  // $out .= "<td colspan=\"2\" align=\"center\" bgcolor=\"#" . $cellCol . "\"><input type=\"submit\" name=\"action\" value=\"Anz.\"></td>";
  $out .= "<td colspan=\"2\" align=\"center\" bgcolor=\"#" . $cellCol . "\">" . defineButtonType10(getLngt("Anz."), "action_show", "finishPage();", "60", "", "") . "</td>";
  $out .= "<td colspan=\"3\" width=\"" . $cellWidth . "\" align=\"center\" bgcolor=\"#" . $cellCol . "\">" . $yearToSelect . "</td>";
  $out .= "</tr>";
  return $out;
}


// ************************
// *** REPORT FUNCTIONS ***
// ************************

// Gets a report list according to a special customer
function getReportListStatement ($fromDateRange, $toDateRange, $rpObjType = "cs", $rpObjId = "", $rpType = "", $isMeta = "0", $csParentIdArray = array()) {
	global $db, $PHP_SELF;
	global $f_hq_id, $emp_id, $usr_id, $limitOfRowsDisplayed;

  if ($limitOfRowsDisplayed == "") : $limitOfRowsDisplayed = "50"; endif;

  if ($fromDateRange == "") :
     $currentMonth = getDateTime("month");
     if ($currentMonth >= 7) :
        $fromDateRange = getDateTime("year") . "-07-01" . " 00:00:00";
     else :
        $fromDateRange = getDateTime("year") . "-01-01" . " 00:00:00";
     endif;
  endif;
  if ($toDateRange == "") :
     $toDateRange = getDateTime("3") . " 23:59:59";
  endif;

  $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, " 
               . "usr.usr_firstname, usr.usr_name, usr.usr_phone, "
               . "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";
  $whereClause = "";
  $whereClauseRp = "";
  if ($rpObjType == "cs") :
     $fieldClause .= ", cmp.cmp_comp, cmp.cmp_comp2, cs.cs_eid AS eid";
     $fieldClause .= ", CONCAT(cmp.cmp_comp,',',cmp.cmp_comp2,',',cs.cs_eid) AS rp_data ";
     $fromClause = "phoenix.customer AS cs, phoenix.company AS cmp, ";
     if ($rpObjId != "") :
        $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;
     $whereClause = "rp.rp_objid = cs.cs_id AND cs.cmp_id = cmp.cmp_id AND ";
  elseif ($rpObjType == "cr") :
     $fieldClause .= ", cmp.cmp_comp, cmp.cmp_comp2, cr.cr_eid AS eid";
     $fieldClause .= ", CONCAT(cmp.cmp_comp,',',cmp.cmp_comp2,',',cr.cr_eid) AS rp_data ";
     $fromClause = "phoenix.courier AS cr, phoenix.company AS cmp, ";
     if ($rpObjId != "") :
        $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;
     $whereClause = "rp.rp_objid = cr.cr_id AND cr.cmp_id = cmp.cmp_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 ";

  $whereClause .= $whereClauseRp
                . $whereClause
                . "rp.hq_id IN " . getSQLMandatorArray($f_hq_id) . " AND rp.hq_id = hq.hq_id AND "
                . "rp.rp_createtime >= '$fromDateRange' AND rp.rp_createtime <= '$toDateRange'";

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

  // Confidential check
  /*
  if (!authCheckEmployeeRights($emp_id, "10")) :
     $whereClause .= " AND (rp.rp_confidential = '0' OR rp.usr_id = '" . $usr_id . "') ";
  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);
  return $sqlquery;
}

// Gets a report list according to a special customer
function getReportStatement ($rpId, $rpObjType = "cs") {
	global $db, $PHP_SELF;
	global $f_hq_id, $emp_id, $usr_id, $limitOfRowsDisplayed;

  $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, " 
               . "usr.usr_firstname, usr.usr_name, usr.usr_phone, "
               . "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";
  $whereClause = "";
  $orderByClause = "";

  if ($rpObjType == "cs") :
     $fieldClause .= ", cmp.cmp_comp, cmp.cmp_comp2, cs.cs_eid AS eid";
     $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 .= ", cmp.cmp_comp, cmp.cmp_comp2, cr.cr_eid AS eid";
     $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 ";
  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 ";
  $whereClause .= " rp.rp_objtype = '" . $rpObjType . "' AND rp.rp_id = '" . $rpId . "' AND "
                . $whereClause
                . "rp.hq_id = hq.hq_id ";

  $sqlquery = generateStatement($fieldClause,$fromClause,$whereClause,$orderByClause);
  return $sqlquery;
}
?>
