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

    File:               pda/bericht.asp
    Description:        Add/wijzig bericht (Mobile version)
    Parameters:         msg_key voor bestaand bericht
                        msg_key=-1 voor nieuwe bericht
*/ %>
<!-- #include file="../Shared/common.inc" -->
<!-- #include file="./mobile.inc" -->
<!-- #include file="./iface.inc" -->
<!-- #include file="../Shared/FlexFiles.inc" -->
<!-- #include file="../MSG/msg.inc" -->
<!-- #include file="../PRS/prs.inc" -->
<!-- #include file="../Shared/selector.inc" -->

<%

var msg_key = getQParamInt("msg_key", -1);
var mode = getQParamSafe("mode", (msg_key == -1 ? "edit" : "show"));
var SHOW_TYPE = getQParamInt("show_type", 4); // Constante

var authparams = user.checkAutorisation("WEB_MSGUSE");
var this_msg = msg.func_enabled(msg_key);
user.auth_required_or_abort(mode == "edit" ? this_msg.canChange : this_msg.canRead);

if (msg_key > 0) {
  var msg_info = msg.msg_info(msg_key, { "withReplies": mode == "show" });
} else {
  var msg_info = {
    author_key: user_key,
    msg_type: SHOW_TYPE,
    category: L("fac_nieuws_groep"),
    msg_created: new Date(),
    my_like: 0,
    like_count: 0,
    my_reply_count: 0,
    reply_count: 0
  }
}
%>
<html>
  <head>
  <% FCLTMHeader.Generate({}); %>
    <script>
<%  if (mode == "show") { %>

      function viewMsg(e) {
        let msg_key = $(this).closest("article").get(0).dataset.key;
        let url = "bericht.asp?msg_key=" + msg_key;
        for (var i in e.data) {
          url += "&" + i + "=" + e.data[i];
        }
        window.location.href = url;
      }

      function react() {
        react_type = this.dataset.type || "like";
        let msg_key = $(this).closest("article").get(0).dataset.key;
        let data = {
            action: "msg_react",
            react_type: react_type,
            msg_key: msg_key
        };
        <% protectRequest.dataToken("data"); %>
        $.post("get_mobile_ajax.asp",
            data,
            reactCallback,
            "json");
      }

      function reactCallback(json) {
        if (json.success) {
          var $this_reaction = $("article[data-key=" + json.msg_key + "]")
                                .find(".msg-reaction[data-type=" + json.react_type.toLowerCase() + "]");
          $this_reaction.get(0).dataset.count = json.msg_count;
          $this_reaction.find("i").toggleClass("fal", !json.state)
                                  .toggleClass("far", json.state);
        }
      }

      function msg_delete() {
        let msg_key = $(this).closest("article").get(0).dataset.key;
        let data = {
            action: "msg_delete",
            msg_key: msg_key
        };
        <% protectRequest.dataToken("data"); %>

        FcltMgr.confirm(L("lcl_msg_del_confirm"), () => {
          $.post("get_mobile_ajax.asp",
              data,
              FcltCallbackAndThen(() => { window.location.href = "berichten.asp"; }),
              "json");
        });
      }

      function openReplies() {
        $(".msg-edit-reply").removeClass("invisible");
        $(".msg-edit-reply textarea").focus();
      }

      async function replySubmit() {
        if (!await validateForm("reply-form")) {
          return false;
        }
        $.post("../MSG/fac_edit_nieuws_save.asp",
                $("#reply-form").serialize(),
                FcltCallbackRefresh,
                "json");
      }

      $(() => {
        $(".msg-reaction").on("click", react);
        $(".msg-reactions").one("click", openReplies);
        $(".msg-action-edit").on("click", { "mode": "edit" }, viewMsg);
        $(".msg-action-delete").on("click", msg_delete);
      });

<%  }  else if (mode == "edit") { %>

      var untouched = true;
      var uploads = [];
      function cancel() {
        var autoconfirm =
          !$("[name=image]").length &&
          !$("#subject").val() &&
          !$("#ta_message").val();
        FcltMgr.confirm(L("lcl_msg_del_concept"), { "autoconfirm": untouched || autoconfirm }, () => {
          window.history.back();
        })
      }

      function msgUpload() {
        $("#msgimg").trigger("click");
      }

      function doUpload() {
        if (this.value) { /* Niets doen bij 'Annuleren' */
          untouched = false;
          uploads.push(
            new Promise((resolve, reject) => {
              $.when(
                $.ajax({
                  url: "<%=protectQS.create("../Shared/UploadForm_save.asp?module=NEWS&key=" + msg_key + "&usenow=1")%>",
                  type: "POST",
                  data: new FormData(document.getElementById("msg-form")),
                  cache: false,
                  contentType: false,
                  processData: false,
                  success: FcltCallbackAndThen(uploadDone)
                }).done(resolve)
              );
            })
          );
        }
      }

      function uploadDone(json) {
        if (json?.safefilename[0]) {
          $("[name=image]").remove();
          $("form").append($('<input type="hidden" name="image" value="' + safe.htmlattr(json.safefilename[0]) + '">'));
          $(".msg-image > :is(.msg-img-upload, i, img):first-child").replaceWith("<img src='" + json.deepUrl[0] + "'>");
        }
      }

      function onChangeCategorie() {
        $(".msg-category").text($("#nwsgroup :selected").text());
      }

      async function msgSubmit() {

        await Promise.all(uploads);

        if (!await validateForm("msg-form")) {
          return false;
        }
        $.post("../MSG/fac_edit_nieuws_save.asp?nieuws_key=<%=msg_key%>",
                $("#msg-form").serialize(),
                FcltCallbackAndThen(msgSubmitCallback),
                "json");
      }

      function msgSubmitCallback() {
        window.location.href = "berichten.asp";
      }

      $(() => {
        $(".msg-image.tappable").on("click", msgUpload);
        $("#msgimg").on("change", doUpload);
        $("#subject").on("input", () => { untouched = false; $(".card-title").html(safe.html($("#subject").val())); });
        $("#ta_message").on("input", () => { untouched = false; $(".card-descr").html(safe.html($("#ta_message").val()).replace(/\n/g, "<br>")); });

        onChangeCategorie(); /* Alvast invullen */
      });
<%   } %>

    </script>
  </head>
  <body class="body-msg">
<%
    PAGE_START();
    if (mode == "edit" || msg_key == -1) {
      HEADER({
        title: L("lcl_msg_new"),
        useraction: { action: "cancel()", icon: "fa-times" }
      });
      CONTENT_START();
      FORM_START("msg-form", { "action": "../MSG/fac_edit_nieuws_save.asp?nieuws_key=" + msg_key, "method": "POST" });
%>    <input type="file" name="msgimg" id="msgimg" accept="image/*">
<%    HIFIELD("nieuws_show", msg_info.msg_type);
      HIFIELD("fac_nieuws_key", msg_key);

      var sql = "SELECT * FROM fac_nieuws_groep";
      FCLTselector("nwsgroup",
                    sql,
                    { label: L("fac_nieuws_groep"),
                      initKey: msg_info.category_key || -1,
                      onChange: "onChangeCategorie()",
                      mobile: true
                    });
%>
        <div class="msg-image flex-center tappable">
<%        if (msg_key != -1) {
            Response.Write(SYMBOL(msg_info.msg_image || msg_info.msg_image_src, { "module": "NEWS", "key": msg_key }));
          }
          if (mode == "edit" && !(msg_info.msg_image || msg_info.msg_image_src)) { %>
            <div class="msg-img-upload flex-center">
                <span class="flex-center"><%=I("fa-camera fa-3x")%></span>
            </div>
<%        } %>
        </div>
<%
      RWFIELD("subject", L("lcl_mes_subject"), msg_info.msg_subject || "", { "pclass": "required" });
      RWFIELD("ta_message", L("lcl_message"), msg_info.msg_omschrijving || "", { "multi": true, "pclass": "required msg-main-body" });
%>    <a onclick="mobile.button.click(event, this)" mobClick="msgSubmit()" class="primary-action-button msg-post-msg" data-ajax="false" singlepress="true"><%=I("fa-paper-plane")%></a><%
      IFACE.FORM_END();
      FORM_END();
      CONTENT_END();
    } else if (msg_key > 0) {
      HEADER({
        title: L("lcl_message"),
        back: true
      });
    }

    CONTENT_START();
      CARDS_WRAPPER_START();
        msg.print_mobile_msg(msg_key, mode, msg_info);
      CARDS_WRAPPER_END();
    CONTENT_END();

    FOOTER();
    PAGE_END();
  PDA_PAGE_END();
%>
	</body>
</html>
<% ASPPAGE_END(); %>
