<%@language = "javascript" %>
<% /*
     $Revision$
     $Id$

    File:               msg_message._saveasp
    Description:        Opslaan van een nieuw(!) bericht
    Parameters:
    Context:            Save script van msg_edit_message.asp
    Note:               Persoonlijk portal bericht en email worden opgeslagen in msg_message (voor reply)
                        Persoonlijk portal bericht en email worden 'verstuurd' via fac.putnotificationsrtprio
                            en worden dan verstuurd via e-mail of web_usermessages
                        Algemene portal berichten worden opgeslagen in FAC_NIEUWS
*/ %>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file="../shared/save2db.inc" -->

<%
FCLTHeader.Requires({ plugins:[], js: [] })

// this could be a reply to an existing message, or a brandnew message (key=-1).
var message_reply = getQParamInt("message_reply", 0) == 1;
var message_key = getQParamInt("message_key", -1);

var perslid_key = getFParamInt("perslid_key", -1);
var district_key = getFParamInt("districtkey", -1);
var location_key = getFParamInt("locatiekey", -1);
var bld_key = getFParamInt("gebouwkey", -1);

var vandatum = getFParamDate("datefrom", null); // periode tot
var totdatum = getFParamDate("dateto", null); // Periode van

var sendMailOption = getFParamInt("cb_email", -1) == 1;
var sendSMSOption = getFParamInt("cb_sms", -1) == 1;
var sendMessageOption = getFParamInt("cb_fmessage", -1) == 1;
var sendPortalOption = getFParamInt("cb_portal", -1) == 1;

// Voor nieuwe berichten vereisen we autorisatie, voor replies niet meer
// @@todo: urole gebruiken, ook MSGUSE onderkennen? We zijn geen mailbox
if (message_key == -1)
{
  var autfunction = "WEB_MSGBOF";
  var authparams = user.checkAutorisation(autfunction);
}

//Bepaal naar wie het bericht moet
var groep_list = getFParamIntArray("msggroup", []);

var subject = "" + getFParam("subject");
var message = "" + getFParam("ta_message");
var priority = getFParamInt("priority", -1);

var lsender;
var new_message_key = 0;
var mes = '';
var count_mes = 0;

if (message_reply)
{  // the sender of the original message will be the receiver
  sql = " SELECT m.prs_perslid_key"
      + " FROM   msg_message m"
      + " WHERE  msg_message_key = " + message_key;
  oRsMes = Oracle.Execute(sql);
  if ( !oRsMes.eof ) {
      receiver_key = oRsMes(0).value;
  } else {
      receiver_key = "-1";
      eval("internal_error");
  }
  oRsMes.Close();
}
else
{
  receiver_key = perslid_key;  // sent to given person (if given)
  sent_to = "";
}

var receivers = false;
if (sendMessageOption || sendMailOption || sendSMSOption)
{
  var sql_exclude = " AND NOT EXISTS"
                  + " (SELECT 1"
                  + "    FROM prs_perslid g"
                  + "   WHERE g.prs_perslid_key = p.prs_perslid_key"
                  + "     AND (  g.prs_perslid_systeemadres IS NOT NULL"
                  + "         OR g.prs_perslid_flags <> 0"
                  + "         OR substr(g.prs_perslid_oslogin,1,1) = '_'"
                  + "         )"
                  + " )"

  if (receiver_key != -1)
  {
    sent_to = "Message to one person";
    sql = "SELECT " + receiver_key + " prs_perslid_key FROM DUAL";
  }
  else
  {
    if ((district_key == -1) && (groep_list.length == 0))
    {
      sent_to = "Message to *all* persons";
      sql =    "SELECT prs_perslid_key"
            + " FROM fac_v_webgebruiker p"
            + " WHERE 1=1"
            + sql_exclude
            + " GROUP BY p.prs_perslid_key"
            + " ORDER BY p.prs_perslid_key";
    }
    else
    {
      if (groep_list.length == 0)
      {
        sent_to = "Message to all persons of a one district/location/building";
        if (bld_key != -1)
        {
          sent_to = "Message to all persons of a one builing";
          sql =    "SELECT p.prs_perslid_key"
                + " FROM   prs_v_perslidwerkplek_gegevens p"
                + " WHERE  p.alg_gebouw_key = " + bld_key
                + " AND    p.prs_perslid_key IS NOT NULL"
                + sql_exclude
                + " ORDER BY p.prs_perslid_key";               /// Denk ik
        }
        else if (location_key != -1)
        {
          sent_to = "Message to all persons of a one location";
          sql =    "SELECT p.prs_perslid_key"
                + " FROM   prs_v_perslidwerkplek_gegevens p"
                + " WHERE  p.alg_locatie_key = " + location_key
                + " AND    p.prs_perslid_key IS NOT NULL"
                + sql_exclude
                + " ORDER BY p.prs_perslid_key";
        }
        else
        {
          sent_to = "Message to all persons of a one district";
          sql =    "SELECT p.prs_perslid_key"
                + " FROM   prs_v_perslidwerkplek_gegevens p, alg_district d, alg_locatie l"
                + " WHERE  p.alg_locatie_key = l.alg_locatie_key "
                + " AND    l.alg_district_key = d.alg_district_key "
                + " AND    p.prs_perslid_key IS NOT NULL"
                + " AND    d.alg_district_key = " + district_key
                + sql_exclude
                + " ORDER BY p.prs_perslid_key";
        }
      }
      else
      {
        if ((bld_key != -1) && (groep_list.length > 0))
        {
            sent_to = "Message to all persons of one or more authorization groups connected to one building";
            sql =    "SELECT p.prs_perslid_key"
                  + " FROM   fac_gebruikersgroep p, prs_v_perslidwerkplek_gegevens p2 "
                  + " WHERE  fac_groep_key IN (" + groep_list.join(",") + ")"
                  + " AND    p2.alg_gebouw_key = " + bld_key
                  + " AND    p.prs_perslid_key = p2.prs_perslid_key "
                  + sql_exclude
                  + " GROUP BY p.prs_perslid_key"
                  + " ORDER BY p.prs_perslid_key";
        }
        else if ((location_key != -1) && (groep_list.length > 0))
        {
          sent_to = "Message to all persons of one or more authorization groups connected to one location";
          sql =    "SELECT p.prs_perslid_key"
                + " FROM   fac_gebruikersgroep p, prs_v_perslidwerkplek_gegevens p2 "
                + " WHERE  fac_groep_key IN (" + groep_list.join(",") + ")"
                + " AND    p2.alg_locatie_key = " + location_key
                + " AND    p.prs_perslid_key = p2.prs_perslid_key "
                + sql_exclude
                + " GROUP BY p.prs_perslid_key"
                + " ORDER BY p.prs_perslid_key";
        }
        else if ((district_key != -1) && (groep_list.length > 0))
        {
          sent_to = "Message to all persons of one or more authorization groups connected to one district";
          sql =    "SELECT p.prs_perslid_key"
                + " FROM   fac_gebruikersgroep p, prs_v_perslidwerkplek_gegevens p2, alg_district d, alg_locatie l "
                + " WHERE  fac_groep_key IN (" + groep_list.join(",") + ")"
                + " AND    p2.alg_locatie_key = l.alg_locatie_key"
                + " AND    d.alg_district_key = " + district_key
                + " AND    l.alg_district_key = d.alg_district_key "
                + " AND    p.prs_perslid_key = p2.prs_perslid_key "
                + sql_exclude
                + " GROUP BY p.prs_perslid_key"
                + " ORDER BY p.prs_perslid_key";
        }
        else
        {
          sent_to = "Message to all persons of a one or more authorization groups";
          sql =   "SELECT prs_perslid_key"
               + " FROM   fac_gebruikersgroep p"
               + " WHERE  fac_groep_key IN (" + groep_list.join(",") + ")"
               + sql_exclude
               + " GROUP BY p.prs_perslid_key"
               + " ORDER BY p.prs_perslid_key";
        }
      }
    }
  }
  // sql levert u de keys van alle geadresseerden
  oRs4 = Oracle.Execute(sql);
  if (!oRs4.eof) {
     receivers = true;
  }

  // var sql is now again free to use
  __Log('message sent_to = '+sent_to);

  var next_perslid_key = -1;
  if (subject != "")
    mess_text_dsc = subject;
  else
    mess_text_dsc = L("lcl_mes_notification") + ' ' + user.naam();

  if (receivers)
  {
    var msgfields = [ { dbs: "msg_message_key",        typ: "key",     seq: "msg_s_msg_message_key" },
                      { dbs: "prs_perslid_key",        typ: "key",     val: user_key },
                      { dbs: "msg_message_oms",        typ: "varchar", frm: "ta_message",   len: 4000 },
                      { dbs: "msg_message_replykey",   typ: "key",     val: message_key }, // het originele bericht is de reply-key
                      { dbs: "msg_message_onderwerp",  typ: "varchar", frm: "subject",      len: 80 },
                      { dbs: "msg_message_prioriteit", typ: "number",  frm: "priority",     val: -1 },
                      { dbs: "msg_message_url",        typ: "varchar", frm: "ilink",        len: 255 }
                    ]
    var msgIns = buildInsert("msg_message", msgfields);
    var new_message_key = msgIns.sequences["msg_message_key"];
    Oracle.Execute(msgIns.sql);
  }

  while (!oRs4.eof)
  {
    // notificeer iedere ontvanger
    receiver_key = oRs4("prs_perslid_key").value;
    if (next_perslid_key != receiver_key)
    {
      // only 1 message for 1 <prs_perslid> and not 1 message for 1 <prs_werkplek>
      // PF 2-7-2009 0:41:48: ik zou zeggen dat je dan je query beter moet formuleren..

      // We zeggen: als replies mogelijk zijn is de afzender de huidige user,
      // anders is het de standaard/systeem afzender
      // @@TODO: hier zijn calls over, kijken of hieruit blijkt of men dit zo wil
      if (S("msg_reply_enabled") == '1') {
          lsender = user.prs_perslid_email();
      } else {
          lsender = null;
      }

      sql = "BEGIN fac.putnotificationsrtprio("
            + user_key
            + ", " + receiver_key
            + ", 'MESMES'"
            + ", " + new_message_key
            + ", " + safe.quoted_sql(mess_text_dsc)    // als je deze null maakt wordt wel de srtnotificatietekst gebruikt. Wat is beter?
            + ", " + (0 + (sendMailOption == "1"? 2 : 0) + (sendMessageOption == "1"? 1 : 0) + (sendSMSOption == "1"? 4 : 0) )
            + ", NULL"
            + ", NULL"
            + ", NULL"
            + ", " + priority
            + ", "+ (lsender ? safe.quoted_sql(lsender) : "NULL") + "); END;"
      Oracle.Execute(sql);
    }
    next_perslid_key = receiver_key;

    count_mes = count_mes + 1;
    oRs4.MoveNext();
  }
  oRs4.Close();
}

if (count_mes == 1)
  mes = L("lcl_mes_is_send");
else
  mes = L("lcl_mes_is_send2");
mes = '' + count_mes + mes
if (!receivers && !sendPortalOption)
  mes = L("lcl_mes_no_receivers");

if (sendPortalOption)
{
  // voeg voor de juiste scope toe aan fac_nieuws tabel
  // kijk alleen naar district/locatie/gebouw
  sql = "INSERT INTO fac_nieuws ("
      + "fac_nieuws_titel, fac_nieuws_omschrijving,"
      + " fac_nieuws_van, fac_nieuws_tot, prs_perslid_key, "
      + " fac_nieuws_onrgoed_key, fac_nieuws_onrgoed_niveau)"
      + " VALUES ("
      +   safe.quoted_sql(subject.substr(0,100))
      + "," + safe.quoted_sql(message.substr(0,4000))

  if (vandatum)
    sql += ", "+vandatum.toSQL(true)
  else
    sql += ", NULL"

	if (totdatum)
    sql += ", " + totdatum.toSQL(true)
  else
    sql += ", NULL"

  sql += ", "+user_key

  if (bld_key != -1)
    sql += ", " + bld_key + ", 'G'";
  else if (location_key != -1)
    sql += ", " + location_key + ", 'L'";
  else if (district_key != -1)
    sql += ", " + district_key + ", 'D'";
  else
    sql += ", NULL, NULL";   // for ALL users

  sql += ")";

  oRs = Oracle.Execute(sql);

  mes += "\n" + L("lcl_msg_onportal");
}

%>
<html>
  <head>
    <% FCLTHeader.Generate() %>
    <script type="text/javascript">
        $(document).ready(function () {
                 FcltMgr.closeDetail(window, { msg_key: <%=new_message_key%>, warning: "<%=safe.jsstring(mes)%>" });
            })
    </script>
  </head>
  <body>
  </body>
</html>
