<?php
/*=======================================================================
 *
 * mf_history.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", "op",
                         "day_from", "month_from", "year_from", "day_to", "month_to", "year_to",
                         "f_mf_id", "f_prio", "f_state", "f_usr_type", "statusMessage",
                         "f_usr_sender", "f_usr_receiver", "f_filter", "f_msggrp",
                         "f_subject_group", "f_body_group", "f_cr_sid_msg", "f_reload"));

getLanguage(__FILE__);

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

// Filters
$whereClauseState = "";
$checkedStateArray = array();
// If NO checkbox is activated NO entry will be shown => Switch automatically to "SHOW ALL"
if ($f_state == "") : 
   $f_state = "1"; 
   for ($i = 0; $i <= $f_state; $i++) :
       $checkedStateArray[$i] = "checked";
   endfor;
   $whereClauseState .= " AND mf.mf_state <= '" . $f_state . "' ";
else :
   $stateFieldLength = count($f_state);
   if ($stateFieldLength > 0) :
      for ($i = 0; $i < $stateFieldLength; $i++) :
          $whereClauseState .= " mf.mf_state = '" . $f_state[$i] . "' ";
          if ($i < ($stateFieldLength - 1)) : $whereClauseState .= " OR "; endif;
          $checkedStateArray[$f_state[$i]] = "checked";
      endfor;
      $whereClauseState = "AND (" . $whereClauseState . ")";
   endif;
endif;

$whereClauseFilter = "";
if (!isset($f_filter) || $f_filter == "") : $f_filter = array(); endif;
$checkedFilterArray = array();
$filterFieldLength = count($f_filter);
if ($filterFieldLength > 0) :
   // 1. Filter   
   $j = array_search("0", $f_filter);
   if (!($j === FALSE)) :
      $checkedFilterArray[0] = "checked";
      $whereClauseFilter .= " AND mf.mf_type <> '1' ";
   endif;
   // 1. Filter   
   $j = array_search("1", $f_filter);
   if (!($j === FALSE)) :
      $checkedFilterArray[1] = "checked";
      $whereClauseFilter .= " AND mf.mf_type = '1' ";
   endif;
   // ... More filters ...
   // $checkedFilterArray[2] = "";
   // ...
else :
   // First call of the page, no reload
   if ($f_reload == "") :
      $checkedFilterArray[0] = "checked";
      $whereClauseFilter .= " AND mf.mf_type <> '1' ";
      $checkedFilterArray[1] = "";
   endif;
endif;

if ($f_prio == "") : $f_prio = "3"; endif;   // All msgs with this prio and higher (<= $f_prio)

if ($f_usr_type == "") : $f_usr_type = "0"; endif; // "0" = All msgs., ">0" = All msgs only with this user type (== $f_usr_type)


// Get the number of message groups according to the current mandator
$numOfMsgGroups = getCountOfTable("messagegroup", "hq_id = '" . $hq_id . "'");

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


// Initialisations
$limitOfRowsDisplayed = "1000";  // For limitation of the rows displayed
$f_subject_group = trim($f_subject_group);
$f_subject_group = str_replace("'", "", $f_subject_group);
$f_body_group = trim($f_body_group);
$f_body_group = str_replace("'", "", $f_body_group);

// Maximum of chars to be inserted into a message
$maxMsgLength = getParameterValue("0", "MESSAGE_MAX_BODY_LENGTH", $hq_id);
if ($maxMsgLength == "" || $maxMsgLength == "0") :
   $maxMsgLength = 250;
endif;
$f_body_group = substr($f_body_group,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("1") . "000000";
    $toDateRange = getDateTime("1") . "235959";
    
    $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) . "000000";
    $toDateRange = $year_to . pad($month_to,2) . pad($day_to,2) . "235959";
endif;


function postParseHistory ($textToParse) {
  $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. "mf_id", 1. "mf_usr_type", 2. "mf_state", 3. "usr_id_sender" , 4. "mf_pre_id" , 5. "usr_id_first_reader" , 6. "usr_id_answerer"
           $tmp = spliti(",",$tagContent);

           $tagContent = "";
           
           // If message is read
           if ($tmp[2] >= "2") :
              $usrNameFirstReader = "";
              if ($tmp[5] != "" && $tmp[5] > 0) :
                 $usrNameFirstReader = "&nbsp;[" . getFieldValueFromId("phoenix.user", "usr_id", $tmp[5], "usr_firstname") . "&nbsp;" . getFieldValueFromId("phoenix.user", "usr_id", $tmp[5], "usr_name") . "]";
              endif;
              $tagContent .= "- " . getLngt("Nachricht gelesen") . $usrNameFirstReader;
           endif;

           // If sender is courier ...
           if ($tmp[1] == "3") :

              // If message is read
              if ($tmp[2] < "2") :
                 $tagContent .= "<input type=\"button\" value=\"" . getLngt("Gelesen") . "\" onClick=\"javascript:finishPage('read','" . $tmp[0] . "','');\">\n";
              endif;

              // If message not is answered yet
              if ($tmp[2] < "3") :
                 $tagContent .= "<br>";
                 $tagContent .= "<input type=\"button\" value=\"" . getLngt("Antworten") . "\" onClick=\"javascript:finishPage('answered','" . $tmp[0] . "','" . $tmp[3] . "');\"><br>\n";
                 $tagContent .= "Betreff: <input type=\"text\" name=\"f_subject_" . $tmp[0] . "\" value=\"\" size=\"40\" maxlength=\"40\"><br>\n";
                 $tagContent .= getLngt("Text:") . " &nbsp;&nbsp;&nbsp;&nbsp;<input type=\"text\" name=\"f_body_" . $tmp[0] . "\" value=\"\" size=\"40\" maxlength=\"100\">\n";
              else :
                 $usrNameAnswerer = "";
                 if ($tmp[6] != "" && $tmp[6] > 0) :
                    $usrNameAnswerer = "&nbsp;[" . getFieldValueFromId("phoenix.user", "usr_id", $tmp[6], "usr_firstname") . "&nbsp;" . getFieldValueFromId("phoenix.user", "usr_id", $tmp[6], "usr_name") . "]";
                 endif;
                 $tagContent .= "<br>";                 
                 $tagContent .= "- " . getLngt("Nachricht beantwortet") . $usrNameAnswerer;
              endif;
           endif;

           // Show number of original request message 
           if ($tmp[4] > "0") :
               $tagContent .= "- " . getLngt("Anfragenachricht") . " " . $tmp[4] . "<br>";
           endif;

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

// Message was read by the employee
if ($f_act == "read") :

   if ($f_mf_id != "" && $f_mf_id != "0") :

      $mfState = getFieldValueFromId("phoenix_log.messageforum", "mf_id", $f_mf_id, "mf_state");

      // Message was not read or answered => Change "mf_state"
      if ($mfState < "2") :
         $res = updateStmt("phoenix_log.messageforum", "mf_id", $f_mf_id, array("mf_state", "2", "mf_acknowledge", $currentTime), "mf_state < '2'");
         if ($db->affected_rows == 1) :
            // Write first reader of the message
            $res = updateStmt("phoenix_log.messageforum", "mf_id", $f_mf_id, array("usr_id_first_reader", $usr_id));
         else :
            $statusMessage = getLngt("Nachricht wurde gerade als gelesen markiert! Bitte die Seite nochmal neu laden!");
         endif;
      else :
         $statusMessage = getLngt("Nachricht wurde gerade als gelesen markiert! Bitte die Seite nochmal neu laden!");
      endif;
   else :
      $statusMessage = getLngt("Intergritätsfehler! Die Nachricht konnte nicht referenziert werden!");
   endif;
endif;

// Message was answered by the employee
if ($f_act == "answered") :

   if ($f_mf_id != "" && $f_mf_id != "0") :

      list($f_subject, $f_body) = getSecHttpVars("1",array("f_subject_" . $f_mf_id, "f_body_" . $f_mf_id));
      $f_subject = str_replace("'", "", $f_subject);
      $f_body = str_replace("'", "", $f_body);

      $mfState = getFieldValueFromId("phoenix_log.messageforum", "mf_id", $f_mf_id, "mf_state");

      // Message was not answered => Change "mf_state"
      if ($mfState < "3") :
         // Change original message 
         $res = updateStmt("phoenix_log.messageforum", "mf_id", $f_mf_id, array("mf_state", "3", "usr_id_answerer", $f_usr_sender, "mf_acknowledge", $currentTime), "mf_state < '3'");
         if ($db->affected_rows == 1) :
            // Generate new message (the answer)
            insertStmt("phoenix_log.messageforum", array("mf_createtime", $currentTime, "usr_id_sender", $f_usr_sender, "hq_id", $hq_id, "usr_id_receiver", $f_usr_receiver, 
                                                         "mf_usr_type", "1", "mf_subject", $f_subject, "mf_body", $f_body, "mf_pre_id", $f_mf_id));
         else :
            $statusMessage = getLngt("Nachricht wurde gerade als beantwortet markiert! Bitte die Seite nochmal neu laden!");
         endif;
      else :
         $statusMessage = getLngt("Nachricht wurde gerade als beantwortet markiert! Bitte die Seite nochmal neu laden!");
      endif;
   else :
      $statusMessage = getLngt("Intergritätsfehler! Die Nachricht konnte nicht referenziert werden!");
   endif;
endif;

// Message to couriers belonging to one or more groups
if ($f_act == "sendmsg") :
   if ($f_body_group != "") :
      // Identify couriers belonging to at least one group
      $whereClauseMsggrp = "";      
      if ($f_cr_sid_msg == "") :
         $msggrpFieldLength = count($f_msggrp);
         if ($f_msggrp != "" && $msggrpFieldLength > 0) :
            for ($i = 0; $i < $msggrpFieldLength; $i++) :
                $whereClauseMsggrp .= " cr.cr_msggrp LIKE '%," . $f_msggrp[$i] . ",%' ";
                if ($i < ($msggrpFieldLength - 1)) : $whereClauseMsggrp .= " OR "; endif;
            endfor;
            $whereClauseMsggrp = "AND (" . $whereClauseMsggrp . ")";

            $tmpSqlquery = "SELECT DISTINCT cr.usr_id"
                           . " FROM  courier AS cr, company AS cmp"
                           . " WHERE cr.hq_id = '" . $hq_id . "' AND cmp.cmp_id = cr.cmp_id AND cmp.cmp_archived = '0' AND cmp.cmp_authenticated = '1' "
                           .   $whereClauseMsggrp
                           . " ORDER BY cr.cr_id";

            $result = $db->query($tmpSqlquery);
            if (DB::isError($result)) die ("$PHP_SELF 5: {$tmpSqlquery} " . $result->getMessage() . ": " . $tmpSqlquery);
            while ($row = $result->fetch_assoc()):
               insertStmt("phoenix_log.messageforum", array("mf_type", "1", "mf_createtime", $currentTime, "usr_id_sender", $f_usr_sender,
                                                            "hq_id", $hq_id, "usr_id_receiver", $row["usr_id"], "mf_usr_type", "1",
                                                            "mf_subject", $f_subject_group, "mf_body", $f_body_group, "mf_pre_id", "0"));
            endwhile;
            $result->free();

            // Initialisieren
            $f_subject_group = "";
            $f_body_group = "";

            $statusMessage = getLngt("Die Nachricht wurde verschickt!");
         else :
            $statusMessage = getLngt("Bitte selektieren Sie mindestens eine Nachrichtengruppe oder einen speziellen Transporteur!");
         endif;
      else :
         $tmpUsrId = getFieldValueFromId("courier", "cr_sid", $f_cr_sid_msg, "usr_id");
         insertStmt("phoenix_log.messageforum", array("mf_type", "0", "mf_createtime", $currentTime, "usr_id_sender", $f_usr_sender,
                                                      "hq_id", $hq_id, "usr_id_receiver", $tmpUsrId, "mf_usr_type", "1",
                                                      "mf_subject", $f_subject_group, "mf_body", $f_body_group, "mf_pre_id", "0"));
         $statusMessage = getLngt("Die Nachricht wurde an") . " " . $f_cr_sid_msg . " " . getLngt("verschickt!");
         
         // Initialisieren
         $f_subject_group = "";
         $f_body_group = "";
      endif;
   else :
      $statusMessage = getLngt("Bitte tragen Sie etwas in das Nachrichtenfeld ein!");
   endif;
endif;


// Message to all active couriers of all headquarters
if ($f_act == "sendAllActive") :
   if ($f_body_group != "") :

      // Get all active couriers
      $constAmStarttimeInDays = getParameterValue("0", "MESSAGE_MIN_DAYS_BEFORE", "0");
      if ($constAmStarttimeInDays == "" || !is_numeric($constAmStarttimeInDays)) : $constAmStarttimeInDays = 7; endif;
      $minAvailableTime = getDateTime("datetime_plus_offset", array(0,0,0,0,-($constAmStarttimeInDays),0), "Y-m-d H:i:s");
      $tmpSqlquery = "SELECT DISTINCT cr.usr_id"
                     . " FROM  courier AS cr, company AS cmp"
                     . " WHERE cr.cr_availabletime > '" . $minAvailableTime . "' AND cmp.cmp_id = cr.cmp_id AND cmp.cmp_archived = '0' AND cmp.cmp_authenticated = '1'"
                     . " ORDER BY cr.cr_id";

      $result = $db->query($tmpSqlquery);
      if (DB::isError($result)) die ("$PHP_SELF 5: {$tmpSqlquery} " . $result->getMessage() . ": " . $tmpSqlquery);
      while ($row = $result->fetch_assoc()):
         insertStmt("phoenix_log.messageforum", array("mf_type", "1", "mf_createtime", $currentTime, "usr_id_sender", $f_usr_sender,
                                                      "hq_id", $hq_id, "usr_id_receiver", $row["usr_id"], "mf_usr_type", "1",
                                                      "mf_subject", $f_subject_group, "mf_body", $f_body_group, "mf_pre_id", "0"));
      endwhile;
      $result->free();

      // Initialisieren
      $f_subject_group = "";
      $f_body_group = "";

      $statusMessage = getLngt("Die Nachricht wurde verschickt!");
   else :
      $statusMessage = getLngt("Bitte tragen Sie etwas in das Nachrichtenfeld ein!");
   endif;
endif;


   // --- MESSAGE HISTORY ------------------
   
   // From table "messageforum"
   $fieldClause = "mf.mf_id, mf.mf_createtime, mf.mf_expiration, mf.mf_delivery,mf.mf_acknowledge," . 
                  "mf.usr_id_sender, mf.usr_id_receiver, mf.usr_id_first_reader, mf.usr_id_answerer," .
                  "mf.mf_usr_type, mf.mf_state, mf.mf_prio, mf.mf_subject, mf.mf_body, mf.mf_pre_id," . 
                  "CONCAT(usr_s.usr_firstname,'<br>',usr_s.usr_name,'<br>',cr_s.cr_sid,'<br>',cr_s.cr_mobile_pda,'<br>',usr_s.usr_phone,'<br>',usr_s.usr_phone2) AS usr_from," . 
                  "CONCAT(usr_r.usr_firstname,'<br>',usr_r.usr_name,'<br>',cr_r.cr_sid,'<br>',cr_r.cr_mobile_pda,'<br>',usr_r.usr_phone,'<br>',usr_r.usr_phone2) AS usr_to," .
                  "CONCAT(mf.mf_id,',',mf.mf_usr_type,',',mf.mf_state,',',mf.usr_id_sender,',',mf.mf_pre_id,',',mf.usr_id_first_reader,',',mf.usr_id_answerer) AS mf_special";
   
   $fromClause = "phoenix_log.messageforum AS mf " .
                 "LEFT JOIN phoenix.user AS usr_s ON mf.usr_id_sender = usr_s.usr_id " .
                 "LEFT JOIN phoenix.courier AS cr_s ON usr_s.usr_id = cr_s.usr_id " .
                 "LEFT JOIN phoenix.user AS usr_r ON mf.usr_id_receiver = usr_r.usr_id " .
                 "LEFT JOIN phoenix.courier AS cr_r ON usr_r.usr_id = cr_r.usr_id ";

   $whereClause = "mf.hq_id = '" . $hq_id . "' AND ";
   $whereClause .= "mf.mf_createtime >= '$fromDateRange' AND mf.mf_createtime <= '$toDateRange' AND ";
   $whereClause .= "mf.mf_prio <= '" . $f_prio . "' " . $whereClauseState;
   $whereClause .= $whereClauseFilter;
   if ($f_usr_type != "0") :
      $whereClause .= " AND mf.mf_user_type = '" . $f_usr_type . "'";
   endif;

   $orderByClause = "mf.mf_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("Lfd")."&nbsp;&nbsp;",getLngt("Zeitpunkt")."&nbsp;&nbsp;",getLngt("Sender")."&nbsp;&nbsp;",getLngt("Empfänger")."&nbsp;&nbsp;",getLngt("Betreff")."&nbsp;&nbsp;",getLngt("Text")."&nbsp;&nbsp;",getLngt("Aktion"));
   $fieldArray = array("mf_id","mf_createtime","usr_from","usr_to","mf_subject","mf_body","mf_special");
   $aligns = "r,c,l,l,l,l,l,l";
   $alignArray = spliti(",",$aligns);
   $alignTitles = "center";
   $widths = "30,80,100,100,100,200,350";
   $widthArray = spliti(",",$widths);
   $summationField = "";
   $postParserField = "mf_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();
   
   
   // Message groups and mailing
   $outMsgGroups = addCheckboxesFromTable ("f_msggrp", "messagegroup", "msggrp_id", "msggrp_name", "msggrp_id", "hq_id =" . $hq_id, "", "<br><br>");
   
   // Special courier
   $outCouriers = "<select name=\"f_cr_sid_msg\" onChange=\"msgToSpecialCourier();\">\n";
   $outCouriers .= "<option value=\"\" selected>&nbsp;</option>\n";
$outCouriers .= "<option value=\"\"><b>" . getLngt("ONLINE:") . "</b></option>\n";   
   $outCouriers .= addOptionsFromTable("courier", "cr_sid", "cr_sid", "cr_sid", "cr_available = '1' AND hq_id = '" . $hq_id . "'", "");
$outCouriers .= "<option value=\"\">&nbsp;</option>\n";
$outCouriers .= "<option value=\"\"><b>" . getLngt("OFFLINE:") . "</b></option>\n";
$outCouriers .= addOptionsFromTable("courier", "cr_sid", "cr_sid", "cr_sid", "cr_available != '1' AND cr_sid != '' AND (NOT isnull(cr_availabletime)) AND cr_availabletime > '" . getDateTime("datetime_plus_offset", array(0,0,0,-1,0,0), $formatStr = "Y-m-d H:i:s") . "' AND hq_id = '" . $hq_id . "'", "");
   $outCouriers .= "</select>\n";
   
   // *** ONLY OUTPUT ***
   
   // Post parsing if necessary
   if ($postParserField != "") :
      $tableBody = postParseHistory($tableBody);
   endif;
   
   // Define output table
   $historyentry = $tableHeader . $tableBody;   
   
   $currentFrameName = "";  // Empty string for "main frame"
   
   // Date-ranges 
   $filter_dateranges = getLngt("Von:") . "\n";
   $filter_dateranges .= "<select name=\"day_from\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'mf_history', 'day_from', 'day_from', 'month_from', 'year_from', '', '', '')\"></select>\n";
   $filter_dateranges .= "<select name=\"month_from\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'mf_history', 'month_from', 'day_from', 'month_from', 'year_from', '', '', '')\"></select>\n";
   $filter_dateranges .= "<select name=\"year_from\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'mf_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 . "', 'mf_history', 'day_to', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
   $filter_dateranges .= "<select name=\"month_to\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'mf_history', 'month_to', 'day_to', 'month_to', 'year_to', '', '', '')\"></select>\n";
   $filter_dateranges .= "<select name=\"year_to\" class=\"f8np1\" onchange=\"fillDateFields(0, '" . $currentFrameName . "', 'mf_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 . "\",\"mf_history\",\"\",\"day_from\",\"month_from\",\"year_from\",\"\",\"\",\"\");\n";
   $js_date .= "  setDateTimeFields(\"" . $currentFrameName . "\",\"mf_history\",".$day_from.",".$month_from.",".$year_from.", \"\", \"\", \"day_from\", \"month_from\", \"year_from\", \"\", \"\", \"\");\n";
   $js_date .= "  fillDateFields(1,\"" . $currentFrameName . "\",\"mf_history\", \"\", \"day_to\", \"month_to\", \"year_to\", \"\", \"\", \"\");\n";
   $js_date .= "  setDateTimeFields(\"" . $currentFrameName . "\",\"mf_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"); ?>
</style>

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

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

<?php echo $js_date ?>

<script type="text/javascript">

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

var numOfMsgGroups = "<?php echo $numOfMsgGroups ?>";

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_Body.value == '') {
     	  doSubmit = false;
     	  alert('<?php echo getLngt("Bitte tragen Sie etwas in das Nachrichtenfeld 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_subject_group.value;
  f_Subject = f_Subject.replaceAll("'", "");
  var f_Body = document.forms[0].f_body_group.value;
  f_Body = f_Body.replaceAll("'", "");
  if (f_Body == '') {
  	  doSubmit = false;
  	  alert('<?php echo getLngt("Bitte tragen Sie etwas in das Nachrichtenfeld ein!") ?>');
  }
  if (doSubmit == true) {
  	 document.forms[0].f_subject_group.value = f_Subject;
  	 document.forms[0].f_body_group.value = f_Body;
     document.forms[0].submit();
  }
};

function finishPageAllActive() {
	var doSubmit = true;
  var f_Subject = document.forms[0].f_subject_group.value;
  f_Subject = f_Subject.replaceAll("'", "");
  var f_Body = document.forms[0].f_body_group.value;
  f_Body = f_Body.replaceAll("'", "");
  if (f_Body == '') {
  	  doSubmit = false;
  	  alert('<?php echo getLngt("Bitte tragen Sie zumindest etwas in das Nachrichtenfeld ein!") ?>');
  }
  if (doSubmit == true) {
  	 if (confirm('<?php echo getLngt("Soll die Nachricht jetzt an alle Fahrer verschickt werden?") ?>')) {
  	 	  document.forms[0].f_act.value = 'sendAllActive';
  	    document.forms[0].f_subject_group.value = f_Subject;
  	    document.forms[0].f_body_group.value = f_Body;
        document.forms[0].submit();
     }
  }
};

function msgToSpecialCourier() {
	// Deactivate checked groups if special courier is selected
	if (document.forms[0].f_cr_sid_msg.options[0].selected == false) {
     for (i = 0; i < numOfMsgGroups; i++) {
	     document.getElementsByName('f_msggrp[]')[i].checked = false;
	     document.getElementsByName('f_msggrp[]')[i].disabled = true;
     }
  } else {
     for (i = 0; i < numOfMsgGroups; i++) {
	     document.getElementsByName('f_msggrp[]')[i].disabled = false;
     }  	
  }
};

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

function openCourierMessagegroupList() {
  var widthPopupWin = 1200;
  var heightPopupWin = 1024;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/courier_msggroup_list.php","","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");
};

// ----------------------------------

var timer1;
var timer2;
var docTitle = document.title;
var docTitle2 = '<?php echo getLngt("**** NEUE NACHRICHT ****") ?>';
var blinkingActivated = false;
var timer1CallCounter = 0;
var timer1CallCounterMax = 10;
var notificationDisplayed = false;

var numOfNewMsgs = <?php echo getCountOfTable("phoenix_log.messageforum", "hq_id = '" . $hq_id . "' AND mf_createtime >= '" . getDateTime("3") . " 00:00:00' AND mf_createtime <= '" . getDateTime("3") . " 23:59:59' AND  mf_usr_type = '3' AND mf_state < '2'")?>;

/*
var timer2 = window.setInterval(
    function () {
      document.title = document.title === docTitle ? docTitle2 : docTitle;
    }, 500);
*/

// Start blinking header
function startBlinkingHeader () {
	if (!blinkingActivated) {
     timer2 = window.setInterval(
       function () {
         document.title = document.title === docTitle ? docTitle2 : docTitle;
         blinkingActivated = true;
       }, 500);
  }
}

// Stop blinking header
function stopBlinkingHeader () {
	if (blinkingActivated) {
     window.clearInterval(timer2);
     document.title = docTitle;
     blinkingActivated = false;
  }
}

function checkNewMfMsg () {
	// Get number of new messages from the devices
  ajaxRequestGet('../include/ajaxReqLib.php', 'mode=2&submode=1&db_table=phoenix_log.messageforum&db_return_field= ' + encodeURI(escape("COUNT(*) AS num")) + '&clause=' + encodeURI(escape("hq_id = '<?php echo $hq_id ?>' AND mf_createtime >= '<?php echo getDateTime("3") . " 00:00:00" ?>' AND mf_usr_type = '3' AND mf_state < '2'")));
  if (retValue != '' && !isNaN(retValue)) {
     if (retValue > 0) {
     	  if (retValue != numOfNewMsgs) {
     	     finishPageSubmit();	 
     	  } else {
     	  	 startBlinkingHeader();
     	  	 sendNotification();
     	  }
     } else {
  	    stopBlinkingHeader();
     }
  }
  timer1CallCounter++;
  if (timer1CallCounter == timer1CallCounterMax) {  	
  	 timer1CallCounter = 0;
  	 notificationDisplayed = false;
  }
}

function startTimeout () { 
	// Set timer for checking blinking state
  timer1 = window.setInterval("checkNewMfMsg()", 5000);
}

function ask_for_permission () {
  Notification.requestPermission(function(){});
}

function sendNotification () {
	if (!notificationDisplayed) {
		 notificationDisplayed = true;
     new Notification('<?php echo getLngt("NEUE NACHRICHT") ?>', {
       body: '<?php echo getLngt("Es liegt eine neue Fahrernachricht vor!") ?>'
     });     
  }
}
</script>

</head>

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

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

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

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

   <input type="hidden" name="f_act" value="">
   <input type="hidden" name="f_mf_id" value="">
   <input type="hidden" name="f_prio" value="<?php echo ec($f_prio) ?>">
   <input type="hidden" name="usr_type" value="<?php echo ec($usr_type) ?>">
   <input type="hidden" name="f_usr_sender" value="<?php echo ec($usr_id) ?>">
   <input type="hidden" name="f_usr_receiver" value="">
   <input type="hidden" name="f_reload" value="1">
   <?php echo $phpCurrentNavigationInputHidden ?>


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

   <!- Message groups -->
   <div>
     <!- Groups -->
     <div <?php echo setStyleHtmlDiv("250px","left"); ?>>
       <div class="f12bp1_blue">Gruppen</div>
       <?php echo htmlDivLineSpacer("15px"); ?>
       <?php echo $outMsgGroups ?>
     </div>
     <!- Message -->
     <div <?php echo setStyleHtmlDiv("450px","left"); ?>>
       <div class="f12bp1_blue"><?php echo getLngt("Nachricht") ?></div>
       <?php echo htmlDivLineSpacer("15px"); ?>
       <div <?php echo setStyleHtmlDiv("60px","left"); ?>><?php echo getLngt("Betreff:") ?></div>
       <div><input type="text" name="f_subject_group" value="<?php echo $f_subject_group ?>" size="45" maxlength="40"></div>
       <div <?php echo setStyleHtmlDiv("60px","left","150px"); ?>><?php echo getLngt("Text:") ?></div> 
       <div><textarea name="f_body_group" cols="40" rows="5"><?php echo $f_body_group ?></textarea><br>
            (<?php echo getLngt("Max.") ?> <?php echo $maxMsgLength ?> <?php echo getLngt("Zeichen") ?>)
       </div>
      <?php         
        // ADMIN-Button to send update message to ALL active couriers
        $allEmpIdRootArr = getColVectorFromDB2ArrayByClause("headquarters", "hq_admin", "", "", "");
        $allUsrIdRootArr = getColVectorFromDB2ArrayByClause("employee", "usr_id", "emp_id IN (" . implode(",", $allEmpIdRootArr) . ")", "", "");
        if (in_array($usr_id, $allUsrIdRootArr)) :
           echo htmlDivLineSpacer("20px");
           echo defineButtonType10(getLngt("Nachricht an ALLE aktiven Fahrer ALLER NLn"), "action_active_send", "finishPageAllActive();", "330", "left", "3");
        endif;
      ?>
     </div>
     <!- Actions -->
     <div>
       <div class="f12bp1_blue">&nbsp;</div>
       <?php echo htmlDivLineSpacer("15px"); ?>
       <?php echo defineButton(getLngt("Senden"), "action_send", "finishPage2();", "left", "", "", "", "75px"); ?>
       <div>&nbsp;</div>
       <?php echo htmlDivLineSpacer("20px"); ?>
       <div><?php echo getLngt("Nur senden an:") ?> <?php echo $outCouriers ?></div>
     </div>
   </div>

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

   <?php echo defineButton(getLngt("Zuordnungsliste"), "cr_msggrp_list", "openCourierMessagegroupList()", "", "", "", "", "150px"); ?>

   <?php echo htmlDivLineSpacer("30px","","left"); ?> 
  
   <div class="f12bp1_blue"><?php echo getLngt("Bisherige Nachrichten") ?></div> 
   
   <?php echo htmlDivLineSpacer("15px"); ?>
 
   
   <!- Date ranges -->
   <div>
     <?php echo $filter_dateranges ?>
   </div>
   <?php echo htmlDivLineSpacer("15px"); ?>

   <!- State / Filter -->
   <div>
     <!- State -->
     <div <?php echo setStyleHtmlDiv("150px","left"); ?>><?php echo getLngt("Nachrichtenstatus:") ?></div>
     <div>
        <?php echo getLngt("Noch nicht ausgelieferte ungelesene") ?>&nbsp;<input class="smaller" type="checkbox" name="f_state[]" value="0" <?php echo $checkedStateArray[0] ?>>
        &nbsp;&nbsp;
        <?php echo getLngt("Ausgelieferte ungelesene") ?>&nbsp;<input class="smaller" type="checkbox" name="f_state[]" value="1" <?php echo $checkedStateArray[1] ?>>
        &nbsp;&nbsp;
        <?php echo getLngt("Gelesene") ?>&nbsp;<input class="smaller" type="checkbox" name="f_state[]" value="2" <?php echo $checkedStateArray[2] ?>>
        &nbsp;&nbsp;
        <?php echo getLngt("Beantwortete") ?>&nbsp;<input class="smaller" type="checkbox" name="f_state[]" value="3" <?php echo $checkedStateArray[3] ?>>
     </div>
   </div>
   <div>
     <!- Filter -->
     <div <?php echo setStyleHtmlDiv("150px","left"); ?>><?php echo getLngt("Filter:") ?></div>
     <div>
        <?php echo getLngt("Zentralennachrichten ausblenden") ?>&nbsp;<input class="smaller" type="checkbox" name="f_filter[]" value="0" <?php echo $checkedFilterArray[0] ?>>
        &nbsp;&nbsp;
        <?php echo getLngt("Nur Zentralennachrichten anzeigen") ?>&nbsp;<input class="smaller" type="checkbox" name="f_filter[]" value="1" <?php echo $checkedFilterArray[1] ?>>
        &nbsp;&nbsp;
     </div>
   </div>

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

   <!- Actions -->
   <?php echo defineButton(getLngt("Aktualisieren"), "refresh", "finishPageSubmit()", "", "", "", "", "115px"); ?>
   
   <?php echo htmlDivLineSpacer("20px"); ?>
   
   <div>
     <div>
       <?php if ($rowCounter > 1000) : echo getLngt("Mehr als") . " " . $limitOfRowsDisplayed . " " . getLngt("Datensätze werden nicht dargestellt"); endif; ?>
       <?php echo htmlDivLineSpacer("20px"); ?>
     </div>
   </div>
   
   <!- History -->
   <div>
     <table cellspacing="0" cellpadding="0" vspace="0" hspace="0">
       <?php echo $historyentry ?>     
     </table>
   </div>
</div>

</form>

</div>

</body>

</html>
