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

include_once ("../include/global.inc.php");
include_once ("../include/auth.inc.php");
include_once ("../include/calendar.inc.php");


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act","f_year","f_month", "f_day", "f_time_from", "f_time_to", 
                         "f_holidays", "f_year2", "statusMessage", "deactivateMenu"));

getLanguage(__FILE__);

$pageTitel = getLngt("FEIERTAGE");
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");
getCurrentScript(__FILE__);

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

$currentYear = getDateTime("year");
$currentMonth = getDateTime("month");
$currentDay = getDateTime("day");
if ($f_year == "") : $f_year = $currentYear ; endif;
if ($f_month == "") : $f_month = getDateTime("month") ; endif;
if ($f_holidays == "") : $f_holidays = array(); endif;
$holidaysLen = count($f_holidays);
$output2 = "";
$output3 = "";

/*
$cmpComp = "";
$cmpComp2 = "";
if ($csId != "0") :    
   $cmpId = getFieldValueFromId("customer","cs_id",$csId,"cmp_id");
   $tmpFields = getFieldsValueFromId("company","cmp_id",$cmpId,array("cmp_comp","cmp_comp2"));
   $cmpComp = $tmpFields[0];
   $cmpComp2 = $tmpFields[1];
endif;
*/


// *** Storing-processes ***
// *** BEGIN ***************

// Store entries
if ($f_act != "" && $f_act == "save") :

   // Check consistency of the parameter
   if ($f_year >= $currentYear) :

      if ($f_holidays != "") :

         TA("B");

         // To reach more performance, first delete all entries of the year and then store the new list
         deleteStmt("publicholiday","ph_year = '" . $f_year . "' AND hq_id = '" . $hq_id . "'");

         // Iterate all months
         for ($i_month = 1; $i_month <= 12; $i_month++) :

             // Get number of days of the month
             $numOfDays = daysPerMonth($f_year, $i_month);

             // Iterate all days of the current month
             for ($i_day = 1; $i_day <= $numOfDays; $i_day++) :

                 // Search for the value in "$f_holidays" and get the key (index)
                 $j = array_search($i_month . "_" . $i_day, $f_holidays);
                 if (!($j === FALSE)) :

                    // insert new public holiday
                    list ($nameOfHoliday) = getHttpVars(array("f_". $i_month . "_" . $i_day));
                    $tmpFields = array("hq_id", $hq_id, "ph_year", $f_year, "ph_month", $i_month, "ph_day", $i_day, "ph_name", $nameOfHoliday);
                    insertStmt("publicholiday",$tmpFields);
                 endif;
             endfor;
          endfor;

          TA("C");
          TA("E");
       else :
          $statusMessage = getLngt("In der Vergangenheit liegende Tage werden nicht gespeichert!");
       endif;
   else :
      $statusMessage = getLngt("Vergangene Jahre können nicht geändert werden!");
   endif;
endif;

// *** END ***************


// Get all public holidays of the specified year
if (TRUE) :
   
   $sqlquery = "SELECT ph.ph_id, ph.ph_year, ph.ph_month, ph.ph_day, ph.ph_time_from, ph.ph_time_to, ph.ph_name"
             . " FROM publicholiday AS ph"
             . " WHERE hq_id = '" . $hq_id . "' AND ph.ph_year = '" . $f_year . "'"
             . " ORDER BY ph.ph_month, ph.ph_day, ph.ph_time_from";
             
   $result = $db->dbQ($sqlquery);

   // Get only first row of the result set
   $row = $result->fetch_assoc();

   // If activated, load data for initialization
   if ($f_act == "load" && $f_year2 != "") :

      $sqlquery2 = "SELECT ph.ph_id, ph.ph_year, ph.ph_month, ph.ph_day, ph.ph_time_from, ph.ph_time_to, ph.ph_name"
                 . " FROM publicholiday AS ph"
                 . " WHERE hq_id = '" . $hq_id . "' AND ph.ph_year = '" . $f_year2 . "'"
                 . " ORDER BY ph.ph_month, ph.ph_day, ph.ph_time_from";

      $result2 = $db->dbQ($sqlquery2);

      // Get only first row of the result set
      $row2 = $result2->fetch_assoc();
   endif;
   
   $output = "";
   
   // Define anchor links
   $monthAnchorLinks = getMonthAnchorLinks();

   // Iterate all months
   for ($i_month = 1; $i_month <= 12; $i_month++) :

       // Title of the month
       $output .= "<tr>\n";
       $output .= "<td class=\"f10bp1_blue\" colspan=\"3\"><a name=\"" . $i_month . "\">" . monthName($i_month) . "</a></td>\n";
       $output .= "<td><br><br>";       
       $output .= defineButtonType10(getLngt("Speichern"), "action_save", "finishPage('save','Wollen Sie die Einträge speichern?');", "100", "left", "3");
       $output .= "<br>" . $monthAnchorLinks . "</td>\n";
       
       $output .= "</tr>\n";

       // Get number of days of the month
       $numOfDays = daysPerMonth($f_year, $i_month);

       // Iterate all days of the current month
       for ($i_day = 1; $i_day <= $numOfDays; $i_day++) :

           $output .= "<tr>\n";
           $output .= "  <td align=\"right\" width=\"40\">" . $i_day . ".</td>\n";
           $output .= "  <td>" . weekDayNameMapping(getDateTime("format",array("0","0","0",$i_month,$i_day,$f_year),"l"),"1") . "</td>\n";

           $isChecked = "";
           $isDisabled = "";
           $nameOfHoliday = "";
           
           // Disable fields if date is in the past because they should not to be modified
           if ($f_year < $currentYear || ($f_year == $currentYear && $i_month < $currentMonth) ||
              ($f_year == $currentYear && $i_month == $currentMonth && $i_day <= $currentDay)) : 
              $isDisabled = " disabled";
           endif;           
           // Check single values according to the database result           
           if ($i_month == $row["ph_month"] && $i_day == $row["ph_day"]) :

              // Get values of the current row
              $isChecked = " checked";              
              $nameOfHoliday = $row["ph_name"];

              // Get next row
              $row = $result->fetch_assoc();

              if (!is_array($row)) : 
                 $row = array();
                 mcArrIsSet($row, "ph_month");
                 mcArrIsSet($row, "ph_day");
              endif;
           endif;
           
           // If initialization mode is active AND NOT disabled, check single values according to the database result of the second result
           if ($f_act == "load" && $f_year2 != "") :

              if ($i_month == $row2["ph_month"] && $i_day == $row2["ph_day"]) :

                 // Get values of the current row
                 if (!$isDisabled && !$isChecked) :

                    $isChecked = " checked";              
                    $nameOfHoliday = $row2["ph_name"];
                 endif;

                 // Get next row
                 $row2 = $result2->fetch_assoc();

                 if (!is_array($row2)) : 
                    $row2 = array();
                    mcArrIsSet($row2, "ph_month");
                    mcArrIsSet($row2, "ph_day");
                 endif;
              endif;
           endif;

           // Show enabled/disabled checkbox according to an existing db-entry
           $output .= "  <td align=\"center\" width=\"30\"><input type=\"checkbox\" name=\"f_holidays[]\" value=\"" . $i_month . "_" . $i_day . "\"" . $isChecked . " " . $isDisabled . "></td>\n";
           
           // Optional name of the public holiday
           $output .= "  <td><input type=\"text\" name=\"f_" . $i_month . "_" . $i_day . "\" value=\"" . $nameOfHoliday . "\" size=\"50\"" . $isDisabled . "></td>\n";
           
           $output .= "</tr>\n";
       endfor;
   endfor;
   $result->free();
endif;


// Get all years distinct
if (TRUE) :
   $sqlquery = "SELECT DISTINCT ph.ph_year"
             . " FROM publicholiday AS ph"
             . " WHERE hq_id = '" . $hq_id . "'"
             . " ORDER BY ph.ph_year";
             
   $result = $db->dbQ($sqlquery);

   $currentYearInList = FALSE;
   $nextYearInList = FALSE;

   // First pulldown for selecting the year to be displayed
   $output2 .= "<span class=\"f12bp1_blue\">" . getLngt("Auswahl Jahr") . "</span>&nbsp;&nbsp;";
   $output2 .= "<select name=\"f_year\" onChange=\"submit();\">\n";
   $output2 .= "  <option value=\"0\">" . getLngt("Default") . "</option>\n";       // Default option for initialization

   // Second pulldown for initializing of the current year
   $output3 .= "<select name=\"f_year2\" onChange=\"finishPage('load','" . getLngt("Wollen Sie die aktuellen Einträge überladen?") . "');\">\n";
   $output3 .= "  <option value=\"0\">" . getLngt("Default") . "</option>\n";       // Default option for initialization   

   while ($row = $result->fetch_assoc()):
         $isSelected = "";
         if ($f_year == $row["ph_year"]) : $isSelected = " selected"; endif;
         $output2 .= "  <option value=\"" . $row["ph_year"] . "\"" . $isSelected . ">" . $row["ph_year"] . "</option>\n";
         if ($currentYear == $row["ph_year"]) : $currentYearInList = TRUE; endif;
         if ($currentYear + 1 == $row["ph_year"]) : $nextYearInList = TRUE; endif;
         
         // Second pulldown
         if ($row["ph_year"] < $f_year) :
            $isSelected = "";
            if ($f_year2 == $row["ph_year"]) : $isSelected = " selected"; endif;
            $output3 .= "  <option value=\"" . $row["ph_year"] . "\"" . $isSelected . ">" . $row["ph_year"] . "</option>\n";
         endif;         
   endwhile;

   // add option for the current year if necessary
   if (!$currentYearInList) :
      $isSelected = "";
      if ($f_year == $currentYear) : $isSelected = " selected"; endif;
      $output2 .= "  <option value=\"" . $currentYear . "\"" . $isSelected . ">" . $currentYear . "</option>\n";
   endif;

   // add option for the next year if necessary   
   if (!$nextYearInList) :
      $isSelected = "";
      if ($f_year == $currentYear + 1) : $isSelected = " selected"; endif;
      $output2 .= "  <option value=\"" . ($currentYear + 1) . "\"" . $isSelected . ">" . ($currentYear + 1) . "</option>\n";
   endif;
   
   // First pulldown
   $output2 .= "</select>\n";
   
   // Second pulldown
   $output3 .= "</select>\n";

   
   $result->free();   
endif;


// Only for output
$title = "";
if ($f_year == "0") : 
   $title .= getLngt("(Default)");
else :
   $title .= $f_year;
endif;
?>


<html lang="de">
<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"); ?>

<script src="../include/checkFormTags.js" type="text/javascript"></script>
<script type="text/javascript">
<!--
// NAVIGATION
<?php echo $jsMenuOut; ?>

function finishPage(f_act,text) {
 if (confirm(text)) {
    document.forms[0].f_act.value = f_act;
    document.forms[0].submit();
 }
};
-->
</script>
<noscript>
  <center>
  <b><br>JavaScript ist nicht verf&uuml;gbar. Bitte aktivieren Sie JavaScript<br><br>
        in Ihrem Browser, damit diese Seite ordnungsgem&auml;&szlig; funktioniert!</b><br><br>
  </center>
</noscript>
</head>

<body onLoad="<?php echo $phpCurrentNavigationOnLoad ?>displayStatusMessage();">

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

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

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

<form action="../admin/public_holiday.php" method="post" target="">
  
  <input type="hidden" name="f_act" value="">
  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">
  
  <table border="0" width="100%">
    <tr>
      <td>
	      <table border="0">
	        <tr>
	          <td colspan="4">
	            <?php echo $output2 ?>
	          </td>
	        </tr>
          <?php echo $output ?>
	      </table>
      </td>
    </tr>
    <tr>
      <td>
      	<?php echo htmlDivLineSpacer("15px"); ?>
        <div style="float:left">
          <?php echo $output3 ?>
          &nbsp;&nbsp;&nbsp;
        </div>
        <?php echo defineButtonType10(getLngt("Einträge&nbsp;ins&nbsp;akt.&nbsp;Jahr&nbsp;integrieren"), "action_new", "finishPage('load','" . getLngt("Wollen Sie die aktuellen Einträge integrieren?") . "');", "250", "left", "3") ?>
      </td>
    </tr>
  </table>

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