<%@ LANGUAGE = JavaScript %>
<% /*
     $Revision$
     $Id$

    Description: Bewerken van een bestaand portalbericht
    Parameters:  nieuws_key (optioneel) voor bewerken
    Context:
    Note:        Dit mogen alleen MSGBOF gebruikers doen
                 Het portal bericht zit in de tabel FAC_NIEUWS

*/ %>

<!-- #include file="../Shared/common.inc"-->
<!-- #include file="../Shared/persoonselector.inc" -->
<!-- #include file="../Shared/plaatsselector.inc" -->
<!-- #include file="../Shared/selector.inc" -->
<!-- #include file="../Shared/iface.inc"-->
<!-- #include file="../Shared/calendar.inc"-->
<!-- #include file="../msg/msg.inc"-->
<!-- #include file="../mld/mld.inc"-->
<!-- #include file="../Shared/FlexFiles.inc"-->

<%
FCLTHeader.Requires({plugins:["jQuery"]});

var nieuws_key  = getQParamInt("nieuws_key", -1);
var mld_key     = getQParamInt("mld_key", -1);
var modal       = getQParamInt("modal", 0) == 1;

var district_key = -1;
var locatie_key = -1;
var gebouw_key = -1;
var verdieping_key = -1;

var key_sender   = null;
var mess_dsc     = null;
var action_datum = null;
var subject      = null;
var image        = null;
var sender_name  = null;
var vandate    = null;
var totdate    = null;
var plaatsniveau = null;
var plaatskey    = null;
var autgroep_key = null;
var fac_nieuws_groep_key = null;

var xfunc = user.func_enabled2("MSG");
user.auth_required_or_abort(xfunc.canRead("WEB_MSGBOF") || xfunc.canWrite("WEB_MSGUSE")); // Voor portalberichten || community berichten

// Default-waarde;
var nieuws_show;
if (xfunc.canRead("WEB_MSGBOF")) {
  nieuws_show = 3;
} else if (xfunc.canWrite("WEB_MSGUSE")) {
  nieuws_show = 4;
}

// Zo maar even;
var ALGreadlevel = Math.min(xfunc.authparams("WEB_MSGBOF").ALGreadlevel, xfunc.authparams("WEB_MSGUSE").ALGreadlevel);

var multiSel = true;

var grp_sql = "SELECT fac_nieuws_groep_key"
            + "     , fac_nieuws_groep_omschrijving"
            + "  FROM fac_nieuws_groep";

if (nieuws_key === -1 && mld_key > 0) {
  var alg_sql = "SELECT COALESCE(m.mld_alg_onroerendgoed_keys, m.mld_alg_locatie_key) onrgoed_keys"
              + "     , COALESCE(a.alg_type, 'L') alg_type"
              + "  FROM mld_melding m"
              + "     , alg_v_allonroerendgoed a"
              + " WHERE m.mld_alg_onroerendgoed_keys = a.alg_onroerendgoed_keys(+)"
              + "   AND mld_melding_key = " + mld_key;
  var alg_oRs = Oracle.Execute(alg_sql);
  if (!alg_oRs.EOF) {
    plaatsniveau = alg_oRs("alg_type").Value;
    plaatskey    = alg_oRs("onrgoed_keys").Value;
  }
  alg_oRs.Close();
  vandate = new Date(); // Vast goed hier

  if (S("ai_enabled") & 16) {
    var groups = {};
    var grp_oRs = Oracle.Execute(grp_sql);
    while (!grp_oRs.EOF) {
      groups[safe.htmlattr(grp_oRs("fac_nieuws_groep_key").Value)] = safe.htmlattr(grp_oRs("fac_nieuws_groep_omschrijving").Value);
      grp_oRs.MoveNext();
    }
    grp_oRs.Close();
    var input = {
      "mld_data": mld.getmldjson(mld_key),
      "bericht_categorieen": groups
    };

    var result = shared.promptAI(JSON.stringify(input), { "instructions": L("lcl_mld_publish_portal_message_instructions"), "response_format": "json_object" });
    if (result.success) {
      try {
        var content = JSON.parse(result.content);
        subject = content.onderwerp || null;
        fac_nieuws_groep_key = content.categorie || null;
        image = content.icon || null;
        mess_dsc = content.berichttekst || null;
        totdate = (content.periode_tot || null) === null ? null : new Date(content.periode_tot || null);
      } catch (e) {
        // Dan niet
      }
    }
  }
} else if (nieuws_key > 0) {  // message known, existing, so read or reply
  multiSel = false;
  var sql = "SELECT f.prs_perslid_key, "
          + "       f.fac_nieuws_key, "
          + "       f.fac_nieuws_omschrijving, "
          + "       f.fac_nieuws_aanmaak, "
          + "       f.fac_nieuws_titel, "
          + "       f.fac_nieuws_image, "
          + "       f.fac_nieuws_van, "
          + "       f.fac_nieuws_tot, "
          + "       f.fac_nieuws_onrgoed_niveau, "
          + "       f.fac_nieuws_onrgoed_key, "
          + "       f.fac_groep_key, "
          + "       f.fac_nieuws_show, "
          + "       f.fac_nieuws_groep_key, "
          + "       pf.prs_perslid_naam_full "
          + "  FROM fac_nieuws f, "
          + "       prs_v_perslid_fullnames_all pf "
          + "       WHERE F.PRS_PERSLID_KEY = PF.PRS_PERSLID_KEY(+) "
          + "       AND f.fac_nieuws_key = " + nieuws_key;
  var oRsMes = Oracle.Execute(sql);

  key_sender   = oRsMes("prs_perslid_key").value;
  mess_dsc     = oRsMes("fac_nieuws_omschrijving").value;
  action_datum = oRsMes("fac_nieuws_aanmaak").value;
  subject      = oRsMes("fac_nieuws_titel").value;
  image        = oRsMes("fac_nieuws_image").value;
  sender_name  = oRsMes("prs_perslid_naam_full").value;
  vandate    = oRsMes("fac_nieuws_van").value != null ? new Date(oRsMes("fac_nieuws_van").value) : null;
  totdate    = oRsMes("fac_nieuws_tot").value != null ? new Date(oRsMes("fac_nieuws_tot").value) : null;
  plaatsniveau = oRsMes("fac_nieuws_onrgoed_niveau").value;
  plaatskey    = oRsMes("fac_nieuws_onrgoed_key").value;
  autgroep_key = oRsMes("fac_groep_key").value;
  nieuws_show  = oRsMes("fac_nieuws_show").Value;
  fac_nieuws_groep_key  = oRsMes("fac_nieuws_groep_key").Value;

  oRsMes.Close();
}

switch (plaatsniveau) {
  case 'D': district_key = plaatskey;   break;
  case 'L': locatie_key = plaatskey;    break;
  case 'G': gebouw_key = plaatskey;     break;
  case 'V': verdieping_key = plaatskey; break;
  case 'R': // Mogelijk vanuit een melding
    var sql_ver = "SELECT alg_verdieping_key FROM alg_ruimte WHERE alg_ruimte_key = " + plaatskey;
    var oRs_ver = Oracle.Execute(sql_ver);
    if (!oRs_ver.EOF) {
      verdieping_key = oRs_ver("alg_verdieping_key").Value;
    }
    oRs_ver.Close();
    break;
}

var allowHtml = action_datum != null && S("fac_html_strictness") == 0; // Deprecated, maar nog wel backwards compatible voor oude berichten
if (allowHtml) {
  var sql_v = "SELECT adm_tracking_date" // Berichten gemaakt voor deze datum mogen nog html bevatten
            + "  FROM adm_tracking"
            + " WHERE adm_tracking_name = 'upgrade20232.inc'";
  var oRs_v = Oracle.Execute(sql_v);
  if (!oRs_v.EoF) {
    allowHtml = new Date(action_datum).getTime() < new Date(oRs_v("adm_tracking_date").Value).getTime();
  }
  oRs_v.Close();
}

%>
<html>
<head>
<%
   FCLTHeader.Generate();
%>
<script type="text/javascript">

  async function msg_submit()
  {
    if (!await validateForm("u2"))
      return false;
    $.post($("form[name=u2]")[0].action, $("[name=u2]").serialize(), FcltCallbackClose, "json");
  }

  function msgCancel ()
  {
    FcltMgr.closeDetail(window, { cancel: true } );
  }

  function refresh_pvimage(json) {
    if (json.delete) {
      $("#pvimage").empty();
    } else {
      var $newImg = null;
      if (json.icon) {
        $newImg = $(I(json.icon));
      } else if (json.deepUrl) {
        $newImg = $("<img src='" + json.deepUrl + "'>");
      }
      var $currentImg = $(".fclt-news-card > :is(i, img):first-child");
      if ($newImg != null) {
        if ($currentImg.length) {
          $currentImg.replaceWith($newImg);
        } else {
          $(".fclt-news-card").prepend($newImg);
        }
      }
    }
  }

  function preview()
  {
<%  if (allowHtml) { %>
      $(".fclt-news-content").html($("#ta_message").val());
      FcltMgr.resized();
<%  } else { %>
      $.post(
        "../Shared/get_shared_info.asp",
        {
          req_info: "eval_bb_code",
          module: "MSG",
          key: <%=nieuws_key%>,
          input: $('#ta_message').val()
        },
        function (json) {
          $(".fclt-news-content").html(json.fclthtml);
          FcltMgr.resized();
        }
      );
<%  } %>
    $(".fclt-news-header h2").text($("#subject").val());
    $(".nieuwsbody").addClass("newsgrp" + $("#nwsgroup").val());
    $(".fclt-news-header > div > span:first").text($("#nwsgroup :selected").text());
  }

  $(function()
  {
    $("textarea").resize(function () { FcltMgr.resized(window) } );
    $("textarea").autogrow();
    $("#pvgrp").text($("#nwsgroup :selected").text());
  });

</script>
</head>

<body<%=modal ? ' id="mod_nieuws"' : ''%> class="editmode">
<% var buttons =  [ {title: L("lcl_submit"), icon: "fa-fclt-save", action:"msg_submit()" },
                     {title: L("lcl_cancel"), icon: "fa-fclt-cancel",    action:"msgCancel()"}
                   ]
SUBFRAME_START();
  IFRAMER_HEADER(L("lcl_msg_portal_frame"), buttons);%>

    <form name="u2"
          action="fac_edit_nieuws_save.asp?nieuws_key=<%=nieuws_key%>"
          method="post"
          target="hidFrameSubmit"
          onSubmit="msg_submit()">
<%  if (nieuws_key === -1 && mld_key > 0) {
%>    <input type="hidden" name="mld_melding_key" value="<%=mld_key%>"><%
    }
    if (nieuws_show === 4) { // Alleen community dus
%>        <input type="hidden" name="nieuws_show" value="4"><%
    } else {

      BLOCK_START("msgMessage", L("lcl_msg_datum"), {icon: "fa-calendar"});
          var group = { name: "nieuws_show", label: L("lcl_msg_nieuws_show"), mask: 7, defaultmask: nieuws_show, bits: [] };
          if (xfunc.canRead("WEB_MSGBOF")) {
            group.bits.push({ "mask": 1, "label": L("lcl_msg_nieuws_portal") });
            group.bits.push({ "mask": 2, "label": L("lcl_msg_nieuws_blogpagina") });
          }
          if (xfunc.canWrite("WEB_MSGUSE")) {
            group.bits.push({ "mask": 4, "label": L("lcl_msg_community") });
          }
          GROUP_CHECK(group, "", nieuws_show, {}, nieuws_key);
          FCLTcalendar( "datefrom",
                        { label : L("lcl_period_from"),
                          datum: vandate,
                          initEmpty: vandate === null,
                          volgnr: 1
                        });
          FCLTcalendar( "dateto",
                        { label : L("lcl_period_to"),
                          datum: totdate,
                          initEmpty: totdate === null,
                          volgnr: 2
                        });
      BLOCK_END();
      BLOCK_START("msgPrs", L("lcl_msg_groep"), {icon: "fa-users"});
          sql = "SELECT fac_groep_key, fac_groep_omschrijving, fac_groep_upper"
              + "  FROM fac_groep"
              + " ORDER BY 3";

          FCLTselector("msggroup", sql,
                          { label: L("fac_groep"),
                            multi: multiSel,
                            initKey: autgroep_key,
                            emptyOption: ""
                          }
                        );
      BLOCK_END();

      BLOCK_START("msgAlg", L("lcl_msg_plaats"), {icon: "fa-map-marker-alt"});
        FCLTplaatsselector  (ALGreadlevel, { startlevel: 1, eindlevel:4, districtkey: district_key, locatiekey: locatie_key, gebouwkey: gebouw_key, verdiepingkey: verdieping_key});
      BLOCK_END();
    }
    BLOCK_START("msgMessage", L("lcl_mes_message"), {icon: "fa-envelope", wide: true});
      RWFIELDTR("subject",  "fld",          L("lcl_mes_subject"),        subject, {required: true, maxlength: 100});
      FCLTselector("nwsgroup", grp_sql,
                      { label: L("fac_nieuws_groep"),
                        initKey: fac_nieuws_groep_key,
                        emptyOption: ""
                      }
                    );
      RWSYMBOLTR("image", L("lcl_image"), image, { "module": "NEWS", "key": nieuws_key, "callback": "refresh_pvimage" });
      RWTEXTAREATR("ta_message", "fldtxt required", L("lcl_mes_message"), mess_dsc, { "bb_codes": !allowHtml, "no_bb_codes": allowHtml, "upload_params": { "module": "MSG", "refkey": nieuws_key }, "placeholder": L("lcl_mes_empty") });

      var safe_oms = safe.fclthtml(mess_dsc, { "file_params": { "key": nieuws_key, "module": "MSG" } });
      var nieuwstitel = safe.html(subject);
      var community = false;
      if (nieuws_show & 4) {
          community = true;
      }

      var detail_html_arr = [];
      if (fac_nieuws_groep_key != null) {
          var oRs_grp = Oracle.Execute(grp_sql + " WHERE fac_nieuws_groep_key = " + fac_nieuws_groep_key);
          detail_html_arr.push("<span>" + safe.html(oRs_grp("fac_nieuws_groep_omschrijving").Value) + "</span>");
          oRs_grp.Close();
      }
      if (vandate != null) {
          detail_html_arr.push("<span>" + toDateString(vandate, true, true) + "</span>");
      }
      if (community && sender_name != null) {
          detail_html_arr.push("<span>" + safe.html(sender_name) + "</span>");
      }

      var news_header_html = '<div class="fclt-news-header">'
                            + '  <h2>' + nieuwstitel + '</h2>'
                            + '  <div>'
                            + '    ' + detail_html_arr.join(" | ")
                            + '  </div>'
                            + '</div>';
      var news_content_html = '<div class="fclt-news-content">' + safe_oms + '</div>';

      var news_html = '<div class="carousel-item active">'
                    + '    <div class="card fclt-news-card">'
                    + SYMBOL(image, { "module": "NEWS", "key": nieuws_key })
                    + news_header_html
                    + news_content_html
                    + '    </div>'
                    + '</div>';

      news_html = '<div class="carousel-inner">'
                + news_html
                + '</div>';
%>
  <tr>
    <td colspan="2">
      <input type='button' class='button' value='<%=L("lcl_msg_preview")%>' onclick="preview()">
      <div class="fclt-news-body">
        <div class="container fclt-container-md">
            <div id="fclt-news-carousel" class="carousel slide">
                <%=news_html%>
            </div>
        </div>
      </div>
    </td>
  </tr>

<%
   BLOCK_END();
IFACE.FORM_END();
%>
</form>
<% SUBFRAME_END(); %>
</body>
</html>
<% ASPPAGE_END(); %>
