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

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


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "customerId", "cscIdRoot", "cscIdActual", 
                         "day_from", "month_from", "year_from", "day_to", "month_to", "year_to",
                         "f_tif_id", "f_tif_subject", "f_tif_text", "f_tif_unerasable", "statusMessage",
                         "f_emp_id_insert", "f_hq_id_insert", "f_filter", "f_emp_id_creator",
                         "f_tif_unerasable", "f_tifIdToRemove"));

getLanguage(__FILE__);

$pageTitel = getLngt("MITTEILUNGEN");
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, "18", "1");

// Get the emp_id of the root admin because he/she is allowed to change a password of an employee
$empIdRootAdmin = getEmpIdOfRootAdmin($userTypeName);

if ($f_hq_id_insert == "") : $f_hq_id_insert = 0; endif;
if ($f_emp_id_insert == "") : $f_emp_id_insert = 0; endif;
if ($f_tif_unerasable == "") : $f_tif_unerasable = 0; endif;


// Get the current time
$currentTime = getDateTime("0");

// Remove all old ticker messages automatically by calling this script (!!!)
// Without calling this script the table "tickerforum" can not increase!
deleteStmt("phoenix_group.tickerforum","tif_endtime < '" . $currentTime . "' AND tif_unerasable != '1'");

// Initialisations
$limitOfRowsDisplayed = "300";  // For limitation of the rows displayed
$f_tif_subject = trim($f_tif_subject);
$f_tif_text = trim($f_tif_text);
$f_tif_text = str_replace("'", "", $f_tif_text);
// $f_tif_text = str_replace("\"", '', $f_tif_text);

// Maximum of chars to be inserted into a message
$maxMsgLength = getParameterValue("0", "NEWSTICKER_MAX_BODY_LENGTH", $hq_id);
if ($maxMsgLength == "" || $maxMsgLength == "0") :
   $maxMsgLength = 1000;
endif;
$f_tif_text = substr($f_tif_text,0,$maxMsgLength);

// 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("3") . " 00:00:00";
    $toDateRange = getDateTime("3") . " 23:59:59";
    
    $day_from = getDateTime("day");
    $month_from = getDateTime("month");
    $year_from = getDateTime("year");
    $day_to = getDateTime("day");
    $month_to = getDateTime("month");
    $year_to = getDateTime("year");
else :
    $fromDateRange = $year_from . "-" . pad($month_from,2) . "-" . pad($day_from,2) . " 00:00:00";
    $toDateRange = $year_to . "-" . pad($month_to,2) . "-" . pad($day_to,2) . " 23:59:59";
endif;


function postParseHistory ($textToParse) {
	global $empIdRootAdmin, $emp_id;
	
  $textToParse = trim($textToParse);
  if ($textToParse != "") :
  
     // 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);           

           // $tagContent contains 0. "tif_id", 1. "hq_id", 2. "emp_id", 3. "emp_id_creator"
           $tmp = spliti(",",$tagContent);

           // Init
           $tagContent = "";

           // Response           
           $tagContent .= "<button type=\"button\" class=\"buttonAction\" onClick=\"respondCreator('" . $tmp[3] . "');\">" . getLngt("Antworten") . "</button>";

           // Remove message, created by myself only
           $buttonClass = "buttonActionDisabled";
           if ($emp_id == $tmp[3] || ($empIdRootAdmin != "" && $emp_id == $empIdRootAdmin)) :
              $buttonClass = "buttonAction";
           endif;
           $tagContent .= "<button type=\"button\" class=\"" . $buttonClass . "\" onClick=\"removeTifEntryFinishPage('" . $tmp[0] . "');\">" . getLngt("Entfernen") . "</button>";

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


// Remove newsticker entry
if ($f_act == "removeTifEntry") :
   if ($f_tifIdToRemove != "") :
      deleteStmt("phoenix_group.tickerforum","tif_id = ".$f_tifIdToRemove);
      $f_tifIdToRemove = "";  // Reset ID
   else:
     $statusMessage = getLngt("Es wurde kein Eintrag zum Löschen selektiert!");
   endif;
endif;

// Message to couriers belonging to one or more groups
if ($f_act == "sendmsg") :
   if ($f_tif_text != "") :
      if ($toDateRange >= $currentTime) :

         $statusMessage = getLngt("Die Tickermeldung wurde eingestellt!");

         // If the message was inserted for a special employee, a potential headquarter information will be deleted
         if ($f_emp_id_insert != "" && $f_emp_id_insert != "0" && $f_hq_id_insert != "" && $f_hq_id_insert != "0") :
            $f_hq_id_insert = "0";
            $statusMessage .= " " . getLngt("Es wurde ein bestimmter Empfänger selektiert, deshalb wird die Zentralenauswahl verworfen!");
         endif;

         if (substr($fromDateRange, 0, 10) < substr($currentTime, 0, 10)) :
            $fromDateRange = $currentTime;
            if (authCheckEmployeeRights($emp_id, "10")) :
               $statusMessage .= " " .  getLngt("Der Startzeitpunkt wurde auf den aktuellen Zeitpunkt gelegt, da ein vergangenes Startdatum nicht zulässig ist!");
            endif;
         endif;

         insertStmt("phoenix_group.tickerforum", array("hq_id", $f_hq_id_insert, "emp_id", $f_emp_id_insert, "emp_id_creator", $emp_id,
                                                       "tif_createtime ", $currentTime, "tif_starttime", $fromDateRange, "tif_endtime", $toDateRange,
                                                       "tif_subject", "", "tif_text", $f_tif_text, "tif_unerasable", $f_tif_unerasable));
         // Initialisieren
         $f_tif_subject = "";
         $f_tif_text = "";
      else :
         $statusMessage = getLngt("Das Endedatum sollte nicht in der Vergangenheit liegen!");
      endif;
   else :
      $statusMessage = getLngt("Bitte erfassen Sie erst einen neuen Eintrag!");
   endif;
endif;


// --- Current newsticker data ------------------
if (true) :
   // From table "messageforum"
   $fieldClause = "hq.hq_name, tif.tif_id, tif.hq_id, tif.emp_id, tif.emp_id_creator,tif.tif_createtime," . 
                  "LEFT(tif.tif_starttime, 10) AS tif_starttime, LEFT(tif.tif_endtime, 10) AS tif_endtime, tif.tif_subject, tif.tif_text, tif.tif_unerasable," .
                  "CONCAT(usr_s.usr_firstname,'<br>',usr_s.usr_name,'<br>','[',hq_s.hq_mnemonic,']') AS usr_from," . 
                  "CONCAT(usr_r.usr_firstname,'<br>',usr_r.usr_name,'<br>','[',hq_r.hq_mnemonic,']') AS usr_to," .
                  "CONCAT(tif.tif_id,',',tif.hq_id,',',tif.emp_id,',',tif.emp_id_creator) AS tif_special";
   
   $fromClause = "phoenix_group.tickerforum AS tif " .
                 "LEFT JOIN phoenix.headquarters AS hq ON tif.hq_id = hq.hq_id " .
                 "LEFT JOIN phoenix.employee AS emp_s ON tif.emp_id_creator = emp_s.emp_id " .
                 "LEFT JOIN phoenix.user AS usr_s ON emp_s.usr_id = usr_s.usr_id " .
                 "LEFT JOIN phoenix.headquarters AS hq_s ON usr_s.hq_id = hq_s.hq_id " .
                 "LEFT JOIN phoenix.employee AS emp_r ON tif.emp_id = emp_r.emp_id " .
                 "LEFT JOIN phoenix.user AS usr_r ON emp_r.usr_id = usr_r.usr_id " .
                 "LEFT JOIN phoenix.headquarters AS hq_r ON usr_r.hq_id = hq_r.hq_id ";

   // $whereClause = "tif.tif_createtime >= '$fromDateRange' AND tif.tif_createtime <= '$toDateRange'";
   $whereClause = "tif.tif_unerasable != '1'";
   $whereClause .= " AND (tif.emp_id_creator = '" . $emp_id . "' OR tif.emp_id = '" . $emp_id . "' OR"
                 . "     ( (isnull(tif.emp_id) OR tif.emp_id = '0') AND tif.hq_id = '" . $hq_id . "') OR"
                 . "     ( (isnull(tif.emp_id) OR tif.emp_id = '0') AND (isnull(tif.hq_id) OR tif.hq_id = '0') ) )";

   $orderByClause = "tif.tif_createtime 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());

   // Generate list with header
   $titleArray = array(getLngt("Erstellung")."&nbsp;&nbsp;",getLngt("Gültig von")."&nbsp;&nbsp;",getLngt("bis")."&nbsp;&nbsp;",getLngt("Absender")."&nbsp;&nbsp;",getLngt("an&nbsp;Zentrale")."&nbsp;&nbsp;",getLngt("an&nbsp;Empfänger")."&nbsp;&nbsp;",getLngt("Mitteilung")."&nbsp;&nbsp;",getLngt("Aktionen"));
   $fieldArray = array("tif_createtime","tif_starttime","tif_endtime","usr_from","hq_name","usr_to","tif_text","tif_special");
   $aligns = "c,c,c,c,c,c,l,c";
   if ($empIdRootAdmin != "" && $emp_id == $empIdRootAdmin) :
      $titleArray = array_merge(array(getLngt("Nr.")."&nbsp;&nbsp;"), $titleArray);
      $fieldArray = array_merge(array("tif_id"), $fieldArray);
      $aligns = "r," . $aligns;
   endif;
   $alignArray = spliti(",",$aligns);
   $alignTitles = "center";
   $widths = "30,80,80,80,100,100,100,400,200";
   $widthArray = spliti(",",$widths);
   $summationField = "";
   $postParserField = "tif_special";
   $mode = "1";             // Output from DB-RESULT
   $sortDBField = "";       // Used in following include-file for sorting per column;
   include ("../include/inc_list_defineoutput.inc.php");

   $result->free();
endif;   

   
// *** ONLY OUTPUT ***

// Post parsing if necessary
if ($postParserField != "") :
   $tableBody = postParseHistory($tableBody);
   $tableBody = nl2br($tableBody);
endif;


// Define output table
$historyentry = $tableHeader . $tableBody;   

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

// Date-ranges 
$filter_dateranges = getLngt("Gültig von") . "\n";
$filter_dateranges .= "<select name=\"day_from\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'tif_history', 'day_from', 'day_from', 'month_from', 'year_from', '', '', '')\"></select>\n";
$filter_dateranges .= "<select name=\"month_from\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'tif_history', 'month_from', 'day_from', 'month_from', 'year_from', '', '', '')\"></select>\n";
$filter_dateranges .= "<select name=\"year_from\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'tif_history', 'year_from', 'day_from', 'month_from', 'year_from', '', '', '')\"></select>\n";
$filter_dateranges .= "</td><td>&nbsp;&nbsp;" . getLngt("bis:") . "\n";
$filter_dateranges .= "<select name=\"day_to\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'tif_history', 'day_to', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
$filter_dateranges .= "<select name=\"month_to\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'tif_history', 'month_to', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
$filter_dateranges .= "<select name=\"year_to\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'tif_history', '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,\"" . $currentFrameName . "\",\"tif_history\",\"\",\"day_from\",\"month_from\",\"year_from\",\"\",\"\",\"\");\n";
$js_date .= "  setDateTimeFields(\"" . $currentFrameName . "\",\"tif_history\",".$day_from.",".$month_from.",".$year_from.", \"\", \"\", \"day_from\", \"month_from\", \"year_from\", \"\", \"\", \"\");\n";
$js_date .= "  fillDateFields(1,\"" . $currentFrameName . "\",\"tif_history\", \"\", \"day_to\", \"month_to\", \"year_to\", \"\", \"\", \"\");\n";
$js_date .= "  setDateTimeFields(\"" . $currentFrameName . "\",\"tif_history\",".$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>

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

  .buttonAction, .buttonActionDisabled
    { height:25px; width:100px;
      font-size:8pt; font-family:Verdana,Helvetica,Arial; font-style:normal; font-weight:normal;
      vertical-align:middle;
      color:#ffffff;
    }
  .buttonAction 
    { background-color:<?php echo $constMenuBackground[2] ?>; }
  .buttonActionDisabled 
    { background-color:#999999; pointer-events: none; }
</style>

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

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

<?php echo $js_date ?>

<script type="text/javascript">

// NAVIGATION
<?php echo $jsMenuOut; ?>

function finishPage(f_act, mf_id, usr_id_receiver) {
	var doSubmit = true;
  document.forms[0].f_act.value = f_act;
  document.forms[0].f_mf_id.value = mf_id;
  document.forms[0].f_usr_receiver.value = usr_id_receiver;
  
  if (f_act == 'answered') {
  	 var f_Subject = eval('document.forms[0].f_subject_' + mf_id);
  	 var f_Body = eval('document.forms[0].f_body_' + mf_id);
     if (f_Subject.value == '' || f_Body.value == '') {
     	  doSubmit = false;
     	  alert('<?php echo getLngt("Bitte tragen Sie etwas in die Felder Betreff und Text ein!") ?>');
     }
  }
  if (doSubmit == true) {
     document.forms[0].submit();
  }
};

function finishPage2() {
	var doSubmit = true;	
	document.forms[0].f_act.value = 'sendmsg';
	// var f_subject = document.forms[0].f_tif_subject;
  // $('#f_tif_text').val(encodeURI(escape($('#f_tif_text').val())));
  $('#f_tif_text').val(trim($('#f_tif_text').val()));
  var f_text = trim($('#f_tif_text').val());
  if (f_text.value == '') {
  	  doSubmit = false;
  	  alert('<?php echo getLngt("Bitte tragen Sie einen Mitteilungstext ein!") ?>');
  }
  if (doSubmit == true) {
     document.forms[0].submit();
  }
};

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

function setSelectboxAttr (elem_id) {
  if (elem_id != '') {
      if ($(elem_id).children("option:selected").val() != '0') {
         $(elem_id).css("background-color", "#ffff77");
      } else {
  	     $(elem_id).css("background-color", "#ff7777");
      };
  };
}

function respondCreator (empIdCreator) {
	setSelectedValue('f_emp_id_insert', empIdCreator);
	setSelectboxAttr('#f_emp_id_insert');  // Set the background color
	$('#f_tif_text').focus();
}

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

function execBodyOnLoad() {
	initForm();
	setSelectboxAttr('#f_emp_id_insert');
	displayStatusMessage();
	$('#f_tif_text').focus();
}
</script>

</head>

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

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

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

<form name="tif_history" action="../admin/newsticker.php" method="post" target="">

   <input type="hidden" name="f_act" value="">
   <input type="hidden" name="f_tif_id" value="">
   <input type="hidden" name="f_tifIdToRemove" value="">
   <?php echo $phpCurrentNavigationInputHidden ?>


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

   <!- Message -->
   <div class="f12bp1_blue"><?php echo getLngt("Mitteilungen") ?></div>
   <?php echo htmlDivLineSpacer("15px"); ?>
   
   <div>
     <div 
     	  <?php echo setStyleHtmlDiv("150px","left"); ?>><?php echo getLngt("Neue Nachricht:") ?>
     	  <?php echo htmlDivLineSpacer("30px"); ?>
     	  <?php echo defineButton(getLngt("Senden"), "action_send", "finishPage2();", "left", "", "", "", "115px"); ?>
     	</div>
     <div>
       <?php echo "<textarea id=\"f_tif_text\" name=\"f_tif_text\" cols=\"100\" rows=\"10\">" . $f_tif_text . "</textarea>"; ?>
     </div>     
   </div>
   <?php echo htmlDivLineSpacer("10px"); ?>
   <div>
   	 <div <?php echo setStyleHtmlDiv("150px","left"); ?>>&nbsp;</div>
     <div style="float:left">
   	   <!- Date ranges -->
       <?php echo $filter_dateranges ?>     	
     	 &nbsp;&nbsp;&nbsp;
     	 <!-- According to mandator rights a ticker message can be sent to all employees of ALL headquarters -->
       <?php if (authCheckEmployeeRights($emp_id, "10")) : ?>
         <?php echo getLngt("Zentrale") ?>:&nbsp;
     	   <select id="f_hq_id_insert" name="f_hq_id_insert">
     	  	 <option value="0" selected><?php echo getLngt("Alle") ?></option>
     	  	 <?php echo addOptionsFromTable("headquarters","hq_id","hq_mnemonic","hq_id","",$hq_id); ?>
     	   </select>
     	   &nbsp;&nbsp;&nbsp;
     	   <?php echo getLngt("Empfänger") ?>:&nbsp;
     	   <select id="f_emp_id_insert" name="f_emp_id_insert" onchange="setSelectboxAttr('#f_emp_id_insert');">
     	  	 <option value="0" selected><?php echo getLngt("Alle") ?></option>
           <?php echo addOptionsFromTable("user AS usr, employee AS emp, headquarters AS hq","emp.emp_id","CONCAT(usr_name,', ',usr_firstname,' [',hq_mnemonic,']') AS usr_combined","usr.usr_name","usr.usr_type = '1' AND usr.hq_id = hq.hq_id AND emp.usr_id = usr.usr_id ", ""); ?>
     	   </select>
       <?php else : ?>
         <?php echo getLngt("Empfänger") ?>:&nbsp;
     	   <select id="f_emp_id_insert" name="f_emp_id_insert" onchange="setSelectboxAttr('#f_emp_id_insert');">
     	  	 <option value="0" selected><?php echo getLngt("Alle") ?></option>
           <?php echo addOptionsFromTable("user AS usr, employee AS emp","emp.emp_id","CONCAT(usr_name,', ',usr_firstname) AS usr_combined","usr.usr_name","usr.hq_id = '" . $hq_id . "' AND usr.usr_type = '1' AND emp.usr_id = usr.usr_id ", ""); ?>
     	   </select>
       <?php endif; ?>
       &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
     </div>
     <?php /* echo defineButton(getLngt("Senden"), "action_send", "finishPage2();", "left", "", "", "", "75px"); */ ?>
   </div>

   <?php echo htmlDivLineSpacer("40px","","left"); ?>
 
   <div class="f12bp1_blue"><?php echo getLngt("Bisherige Nachrichten") ?></div>
   <?php echo htmlDivLineSpacer("20px"); ?>
   <?php echo defineButton(getLngt("Aktualisieren"), "action_submit", "finishPageSubmit()", "", "", "", "", "115px"); ?>

   <div>
     <?php 
       if ($rowCounter > 1000) : 
          echo getLngt("Mehr als") . " " . $limitOfRowsDisplayed . " " . getLngt("Datensätze werden nicht dargestellt"); 
          echo htmlDivLineSpacer("20px");
       endif;
     ?>
   </div>

   <!- History -->
   <div>
     <table cellspacing="0" cellpadding="0" vspace="0" hspace="0">
       <?php echo $historyentry ?>     
     </table>
   </div>
</div>

</form>

</div>

</body>

</html>