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

    File:               shared/queuemail.asp
    Description:        Zet een e-mail notifatie in de queue. Die wordt later verstuurd
                        door het PutOrders notificatieproces
    Parameters:         defemail_key met key van de user waar de mail naar toe moet
                        defemail (rechtstreeks het e-mail adres)
    Context:
    Note:               Bij meldingen, opdrachten en reserveringen kunnen ook bijlagen worden meegestuurd.

*/ %>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file="../Shared/selector.inc" -->
<!-- #include file="../Shared/persoonselector.inc" -->
<!-- #include file="../Shared/bedrijfselector.inc" -->
<!-- #include file="../Shared/kenmerk_common.inc" -->
<!-- #include file="../Shared/FlexFiles.inc" -->
<!-- #include file="../Shared/notes.inc" -->
<!-- #include file="../fin/fin.inc" -->
<!-- #include file="../ins/ins.inc" -->
<!-- #include file="../mld/mld.inc" -->
<!-- #include file="../res/res.inc" -->

<%
protectQS.verify(); // tamper check
FCLTHeader.Requires({ plugins:["jQuery"],
                      js: ["notes.js"]
                    });

var defaultemail = getQParam("defemail","");
var defemail_type = getQParam("defemail_type", "P");
var defemail_key = getQParamInt("defemail_key", -1);

var pcode = getQParamSafe("pcode", "");
var pmodule = getQParamSafe("pmodule", "");
var pniveau = getQParamSafe("pniveau", "");
var pkey = getQParamInt("key", -1);
var subject = getQParam("subject", "");
var mailfrom = getQParamInt("mailfrom", 0) == 1;
var xkey = getQParamInt("xkey", -1);
var pshowcompany = getQParamInt("pshowcompany", 0) == 1;
var extratext = getQParam("extratext", "");

// Ben ik voor deze module een prof (FO of BO), en mag ik dus afmeldteksten kiezen
// en attachments selecteren?
var xfunc = user.func_enabled("*", null, null, user_key);
var isProfessional = false;
var canWriteNote = true;
switch (pmodule)
{
  case "RES":
        var this_res = res.func_enabled(xkey);
        isProfessional = this_res.canReadFO || this_res.canReadBO;
        break;
  case "MLD": switch (pniveau)
              {
                case "M":
                    var this_mld = mld.func_enabled_melding(pkey);
                    isProfessional = this_mld.canFOread || this_mld.canBOread;
                    canWriteNote = this_mld.canWriteNotes;
                    break;
                case "O":
                    var this_opdr = mld.func_enabled_opdracht(pkey);
                    isProfessional = this_opdr.canReadBOF || this_opdr.canReadORD;
                    break;
              };
              break;
  case "FIN": var this_fin = fin.func_enabled_factuur(pkey);
              isProfessional = this_fin.canFORead || this_fin.canBORead;
              break;
  case "BES": isProfessional = xfunc.canRead("WEB_BESFOF"); break;  /* unsupported yet */
  case "PRS": isProfessional = xfunc.canRead("WEB_PRSSYS"); break;  /* unsupported yet */
}

function inArrayElm(needle, haystack, elmname)
{   // Zoeken in een array van objecten op een waarde van een element.
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i][elmname] == needle) return true;
    }
    return false;
}

function bestandenlijst(pmodule, pniveau, pkey)
{   // flexfiles.inc/flexProps() niet bruikbaar omdat die niet over kenmerken heen kan zoeken
    // Kan nu wel omdat de bestanden uit fac_bijlagen worden gelezen.
    // Als hier ook bestanden moeten worden opgenomen die niet in fac_bijlagen staan, dan moet toch weer terug gegrepen worden op fso.
    var bestandlijst = [];
    if (pmodule && pniveau)
    {
        var refkey = (pmodule == "RES" ? xkey : pkey);
        var bestandlijst = flexProps(pmodule, refkey, null, pniveau, {kenmerk_geldig: true});
    }
    return bestandlijst;
}

// Bij MLD-meldingen worden ook de bestanden van de 'parents' aangeboden
function bestandenlijstALL(pmodule, pniveau, pkey, pnoWorkflow)
{
    function sort_name(a,b)
    {
        if (a.name < b.name) return -1;
        if (a.name > b.name) return 1;
        return 0;
    }

    var bestandlijst = bestandenlijst(pmodule, pniveau, pkey);
    if (pmodule == "MLD" && pniveau == "M" && !pnoWorkflow && S("mld_show_parent_attachments"))
    {
        var mld_lijst = mld.executedworkflowsteps(pkey, true);
        for (var i=0; i<mld_lijst.length; i++)
        {
            var sk = mld_lijst[i].key;
            var mld_attachlijst = bestandenlijst(pmodule, pniveau, sk);
            for (var j=0; j<mld_attachlijst.files.length; j++)
            {
                if ( !inArrayElm(mld_attachlijst.files[j].key, bestandlijst.files, "key") )
                {
                    bestandlijst.files.push(mld_attachlijst.files[j]);
                }
            }
        }
    }
    bestandlijst.files.sort(sort_name);
    return bestandlijst;
}


%>
  <html>
    <head>
<%    // Bepaal default email
      // Third party present
      if (pcode == "MLDMAI")
      {
            var mld_info_ext = mld.mld_melding_info(pkey);
      }
      if (pcode == "MLDMAI" && mld_info_ext.canholdthirdparty && mld_info_ext.email_ext)
      {
        defaultemail = mld_info_ext.email_ext;
      }
      else if (defemail_key > 0)
      {
        if (defemail_type == "C")
        {
          var sql = " SELECT replace(c.prs_contactpersoon_email, ' ', '') AS email"
                  + " FROM prs_contactpersoon c"
                  + " WHERE c.prs_contactpersoon_key = " + defemail_key;
        }
        else if (defemail_type == "B")
        {
          var sql = " SELECT replace(b.prs_bedrijf_email, ' ', '') AS email"
                  + " FROM prs_bedrijf b"
                  + " WHERE b.prs_bedrijf_key = " + defemail_key;
        }
        else if (defemail_type == "P")
        {
          var sql = " SELECT replace(p.prs_perslid_email, ' ', '') AS email"
                  + " FROM prs_perslid p"
                  + " WHERE p.prs_perslid_key = " + defemail_key;
        }
        oRs = Oracle.Execute(sql);
        defaultemail = oRs("email").Value;
        oRs.Close();
      }

      FCLTHeader.Generate();
%>
      <script type='text/javascript'>
        $(function()
        {
            $("textarea").resize(function () { FcltMgr.resized(window) } );
            $("textarea").autogrow();
            $("#emails").focus();
        });

<%      if (pshowcompany)
        { %>
          function onChangeComp()
          {
            // Vul email van bedrijf in
            $("#emails").val($("#emailbedrijf").val());

            // Wis Persoon
            sgPerson.setValue(-1, "");
          }
<%      } %>

        function onChangePerson()
        {
          // Vul email van persoon in
          if ($("#emailpersoon").val())
          {
            var current_val = ($("#emails").val() != "" ? $("#emails").val() + "; " : "");
            $("#emails").val(current_val + $("#emailpersoon").val());
            $("#sName_key_show").val("");
            $("textarea").autogrow();
          }

<%        if (pshowcompany)
          { %>

            // Wis Bedrijf
            sgComp.setValue(-1, "");
<%        } %>
        }

        function PasteFromSelectbox()
        {
          if ($("#stdopmerk :selected").val() > -1)
          {
            $(".mail_notes").focus();
            var PastedText = $("#stdopmerk :selected")[0].getAttribute("afmeldtekstoms");
            $(".mail_notes").val($(".mail_notes").val() + ($(".mail_notes").val() != ""? "\n" : "") + PastedText);
          }
        }

        async function queueSubmit()
        {
            // Standaard checks op verplichte velden, datum formaat, numeriek en float formaat, currency formaat.
            if (!await validateForm("u2"))
                return false;

            if (!new RegExp("<%=safe.jsstring(S("email_regexp"))%>", "ig").test($("#emails").val()))
            {
                FcltMgr.alert(L("lcl_invalid_email"));
                return false;
            }
            else
            {
<%
                if (pcode == "CNTMAI" || pcode == "FINMAI" || pcode == "INSMAI" || pcode == "MLDMAI" || pcode == "ORDMAI")
                {
                    var save_note_url;
                    switch (pcode) {
                        case "CNTMAI": save_note_url = "../cnt/cnt_edit_note_save.asp?mailed=1&cnt_key=" + pkey;   break;
                        case "FINMAI": save_note_url = "../fin/fin_edit_note_save.asp?mailed=1&fin_key=" + pkey;   break;
                        case "INSMAI": save_note_url = "../ins/ins_edit_note_save.asp?mailed=1&ins_key=" + pkey;   break;
                        case "MLDMAI": save_note_url = "../mld/mld_edit_note_save.asp?mailed=1&mld_key=" + pkey;   break;
                        case "ORDMAI": save_note_url = "../mld/opdr_edit_note_save.asp?mailed=1&opdr_key=" + pkey; break;
                    }
%>
                    if ($(".mail_notes").length > 0 && $(".mail_notes").val().trim() != "")
                    {
                        var data = $("[type=checkbox], [name^=has_], #note, [name=<%=protectRequest.theVar%>]").serialize();
                        var url = "<%=save_note_url%>";
<%                      if (pcode == "MLDMAI")
                        { %>
                        if ($("form").attr("action") && $("form").attr("action").indexOf("opdr_edit_note_save.asp?") > -1) /* ReplyToAll uitvoerders */
                            url = "../mld/" + $("form").attr("action") + "&mailed=1";
<%                      } %>
                        $.post(url,
                               data,
                               FcltCallbackAndThenAlways(queueSubmitCallback),
                               "json");
                        return true; // disable button
                    }
                    else
                    {
                        var data = { success: true,
                                     note_key: <%=xkey %>
                                   };
                        queueSubmitCallback(data);
                    }
<%
                }
                else
                {
%>
                    var data = { success: true,
                                 note_key: <%=xkey %>
                               };
                    queueSubmitCallback(data);
<%
                }
%>
            }
        }

        function queueSubmitCallback(data)
        {
            if (data.note_key > -1 )
            {
                $("#xkey").val(data.note_key);
            }

            var xurl = "queuemail_save.asp?key=<%=pkey%>&pcode=<%=pcode%>&pmodule=<%=pmodule%>&pniveau=<%=pniveau%>";
            $.post(xurl,
                   $("[name=u2]").serialize(),
                   FcltCallbackAndThenAlways(queueMailClose),
                   "json");
        }

        function queueMailClose(data)
        {
            var emails = $("#emails").val();
            var maillist = "\n" + emails.replace(/\;/g, "\n");

            FcltMgr.closeDetail(window, { emails: maillist,
                                          key: "<%=pkey%>" });
        }

        function queueCancel()
        {
          FcltMgr.closeDetail(window, { cancel: true, key: "<%=pkey%>" } );
        }

        function chooseEmailCallbackRefresh(data)
        {
          FcltMgr.alert(data.email);
        }

      </script>
    </head>

    <body class="fclt-modal" id="mod_queuemail">
<%    MODAL_START(); %>
        <form name="u2" id="u2" method="post">
            <input type="hidden" id="orgsubject" name="orgsubject" value="<%=safe.htmlattr(subject)%>">
            <input type="hidden" id="xkey" name="xkey" value="<%=xkey%>">
            <input type="hidden" name="module" id="module" value="<%=pmodule.toLowerCase()%>">
            <input type="hidden" name="<%=pmodule.toLowerCase()%>_key" id="<%=pmodule.toLowerCase()%>_key" value="<%=pkey%>">
            <input type="hidden" name="note_key" id="note_key" value="-1">
<%
          MODAL_BLOCK_START("emailInput", subject, { icon: "fa-envelope" });

            // Heeft vakgroep een mailadres
            var mail_disc = null;
            if (pmodule == "MLD")
            {
                var sql_v = "SELECT ins_discipline_email"
                          + "     , ins_discipline_email"
                          + "     , 3";
                if (pniveau== "M")
                {
                    sql_v += " FROM ins_tab_discipline d"
                          + "     , mld_stdmelding s"
                          + "     , mld_melding m"
                          + " WHERE d.ins_discipline_email IS NOT NULL"
                          + "   AND d.ins_discipline_key = s.mld_ins_discipline_key"
                          + "   AND s.mld_stdmelding_key = m.mld_stdmelding_key"
                          + "   AND m.mld_melding_key = " + pkey;
                }
                else if (pniveau== "O")
                {
                    sql_v += " FROM ins_tab_discipline d"
                          + "     , mld_stdmelding s"
                          + "     , mld_melding m"
                          + "     , mld_opdr o"
                          + " WHERE d.ins_discipline_email IS NOT NULL"
                          + "   AND d.ins_discipline_key = s.mld_ins_discipline_key"
                          + "   AND s.mld_stdmelding_key = m.mld_stdmelding_key"
                          + "   AND m.mld_melding_key = o.mld_melding_key"
                          + "   AND o.mld_opdr_key = " + pkey;
                }
                var oRs_v = Oracle.Execute(sql_v);
                if (!oRs_v.eof)
                    mail_disc = oRs_v("ins_discipline_email").Value;
                oRs_v.Close();
            }

            if (extratext != "") {
              ROTEXTAREATR("fld",L("lcl_noti_email_extratext") ,extratext, {});
            }
            
            if (mailfrom && (S("replyaddress") || S("fin_replyaddress") || mail_disc))
            {
                // <!-- Namens -->
                var sendorder = S("queuemail_sender_order").toUpperCase();
                var sql = "SELECT prs_perslid_email"
                        + "     , prs_perslid_email"
                        + "     , " + ( sendorder.indexOf("U")>=0 ? sendorder.indexOf("U") : 11)
                        + "  FROM prs_perslid"
                        + " WHERE prs_perslid_key = " + user_key
                        + "   AND prs_perslid_email IS NOT NULL"
                        + ( S("replyaddress")
                          ?   " UNION "
                            + "SELECT " + safe.quoted_sql(S("replyaddress"))
                            + "     , " + safe.quoted_sql(S("replyaddress"))
                            + "     , " + ( sendorder.indexOf("R")>=0 ? sendorder.indexOf("R") : 12)
                            + "  FROM DUAL"
                          : ""
                          )
                        + ((pmodule == "FIN" && S("fin_replyaddress"))
                           ?   " UNION "
                            + "SELECT " + safe.quoted_sql(S("fin_replyaddress"))
                            + "     , " + safe.quoted_sql(S("fin_replyaddress"))
                            + "     , " + ( sendorder.indexOf("R")>=0 ? sendorder.indexOf("R") : 12)
                            + "  FROM DUAL"
                          : ""
                          )
                        + ( mail_disc
                          ?   " UNION "
                            + "SELECT " + safe.quoted_sql(mail_disc)
                            + "     , " + safe.quoted_sql(mail_disc)
                            + "     , " + ( sendorder.indexOf("C")>=0 ? sendorder.indexOf("C") : 13)
                            + "  FROM DUAL"
                          : ""
                          )
                        + " ORDER BY 3";
                var sql_t = "SELECT COUNT(*) aantal FROM (" + sql +")";
                var oRs_t = Oracle.Execute(sql_t);
                if (oRs_t("aantal").Value > 0)
                {
                    FCLTselector("namens",
                                 sql,
                                 { label: L("lcl_noti_email_namens") }
                                );
                }
                oRs_t.Close();
            }

            // <!-- Naam -->
            if (S("show_perslidselector_by_mail"))
            {
                FCLTpersoonselector("sName_key",
                                    "sgPerson",
                                    { perslidKey: -1,
                                      label: L("lcl_name"),
                                      onChange: "onChangePerson",
                                      trclass: "more",
                                      filtercode: "MAIL",
                                      extracode: "E",
                                      extraParamField: "emailpersoon",
                                      whenEmpty: L("lcl_search_generic")  // want filter
                                    });
            }
            // <!-- Bedrijf -->
            if (pshowcompany)
            {
                FCLTbedrijfselector("sComp_key",
                                    "sgComp",
                                    { companyKey: -1,
                                      label: L("lcl_company"),
                                      onChange: "onChangeComp",
                                      extracode: "E",
                                      trclass: "more",
                                      extraParamField: "emailbedrijf",
                                      whenEmpty: L("lcl_search_generic")
                                    });
            }
            RWTEXTAREATR("emails",
                         "fldtxt required",
                         L("lcl_noti_sendto"),
                         defaultemail,
                         {html: "rows='2' cols='60'", no_bb_codes: true} // kan hier nog iets een nieuwe regel forceren?
                        );

%>

            <tr>
              <td class="label"><label for="subject"><%=L("lcl_noti_sendsubject")%></label></td>
              <td>
                <input class="fld" type="text" id="subject" name="subject" value="<%=safe.htmlattr(subject)%>">
              </td>
            </tr>
<%

            // standaard afmeldteksten
            if (pmodule == "MLD" && isProfessional)
            {
                if (pniveau == "M")
                {
                  var sql = "SELECT ma.mld_afmeldtekst_key"
                          + "     , " + lcl.xsqla("ma.mld_afmeldtekst_naam", "ma.mld_afmeldtekst_key")
                          + "     , " + lcl.xsql("ma.mld_afmeldtekst_omschrijving", "ma.mld_afmeldtekst_key") + " afmeldtekstoms"
                          + "     , 2 src"
                          + "  FROM mld_melding mm"
                          + "     , mld_stdmelding sm"
                          + "     , mld_afmeldtekst ma"
                          + " WHERE mm.mld_stdmelding_key = sm.mld_stdmelding_key"
                          + "   AND (  (ma.mld_stdmelding_key = mm.mld_stdmelding_key)"
                          + "       OR (ma.mld_stdmelding_key IS NULL AND ma.mld_ins_discipline_key = sm.mld_ins_discipline_key)"
                          + "       OR (ma.mld_stdmelding_key IS NULL AND ma.mld_ins_discipline_key IS NULL)"
                          + "       )"
                          + "   AND BITAND(ma.mld_afmeldtekst_usefor, 8) = 8"
                          + "   AND mm.mld_melding_key = " + pkey;
                }
                else
                {
                  var sql = "SELECT ma.mld_afmeldtekst_key"
                          + "     , " + lcl.xsqla("ma.mld_afmeldtekst_naam", "ma.mld_afmeldtekst_key")
                          + "     , " + lcl.xsql("ma.mld_afmeldtekst_omschrijving", "ma.mld_afmeldtekst_key") + " afmeldtekstoms"
                          + "     , 2 src"
                          + "  FROM mld_opdr mo"
                          + "     , mld_melding mm"
                          + "     , mld_stdmelding sm"
                          + "     , mld_afmeldtekst ma"
                          + " WHERE mm.mld_stdmelding_key = sm.mld_stdmelding_key"
                          + "   AND (  (ma.mld_stdmelding_key = mm.mld_stdmelding_key)"
                          + "       OR (ma.mld_stdmelding_key IS NULL AND ma.mld_ins_discipline_key = sm.mld_ins_discipline_key)"
                          + "       OR (ma.mld_stdmelding_key IS NULL AND ma.mld_ins_discipline_key IS NULL)"
                          + "       )"
                          + "   AND BITAND(ma.mld_afmeldtekst_usefor, 16) = 16"
                          + "   AND mo.mld_opdr_key = " + pkey
                          + "   AND mm.mld_melding_key = mo.mld_melding_key";
                }
                sql += " ORDER BY 4,2";
                var oRs = Oracle.Execute(sql);
                var show_afmeldtekst = !oRs.eof;
                oRs.Close()
                if (show_afmeldtekst)
                {
                    FCLTselector("stdopmerk",
                                 sql,
                                 { label: L("lcl_mld_inf_std_opm"),
                                   initKey: -1,
                                   emptyOption: "",
                                   extraParamValue: "afmeldtekstoms",
                                   onChange: "PasteFromSelectbox()"
                                 });
                }
            }

            // Notitie
            if ((pcode == "MLDMAI" && canWriteNote) || pcode == "ORDMAI" || pcode == "CNTMAI" || pcode == "FINMAI" || pcode == "INSMAI")
            {
              var notelcl;
              switch (pcode)
              {
                case "CNTMAI": notelcl = L("lcl_cnt_note");break;
                case "FINMAI": notelcl = L("lcl_fin_note");break;
                case "INSMAI": notelcl = L("lcl_ins_note");break;
                case "MLDMAI":
                case "ORDMAI": notelcl = L("lcl_mld_note");break;
              }

              RWTEXTAREATR("note",
                           "fldtxt mail_notes",
                           notelcl,
                           "",
                           {html: "rows='2' cols='60'"}
                          );
              var mld_info = { noWorkflow: true };
              if (pcode == "MLDMAI" || pcode == "ORDMAI")
              {
                if (pcode == "MLDMAI")
                    mld_info = mld_info_ext || mld.mld_melding_info(pkey);

                Response.Write("<tr><td></td><td>");
                notes.note_toggles(pcode == "MLDMAI" ? "MLD" : "OPDR", { pkey: pkey });
                Response.Write("</td></tr>");
              }
            }

            // Bijlagen meesturen.
            if (isProfessional || (pmodule == "MLD" && pniveau == "O" && this_opdr.canReadAny))
            {
                checklist = ( (pcode == "MLDMAI" || pcode == "ORDMAI" || pcode == "CNTMAI" || pcode == "FINMAI")
                            ? bestandenlijstALL(pmodule, pniveau, pkey, mld_info.noWorkflow)
                            : bestandenlijstALL(pmodule, pniveau, pkey, true)
                            );
                for (i=0; i<checklist.files.length; i++)
                {
                    var label = (i==0 ? "<label>" + L("lcl_appendixes") + "</label>" : "&nbsp;");
                    var fid   = "kmnr"+i;
                    var fkey  = checklist.files[i].key;
                    var fnaam = checklist.files[i].name;
                    var sz = (Math.ceil(checklist.files[i].size / 1024));
%>
                    <tr>
                      <td><%=label%></td>
                      <td>
                        <% CHECKBOX("fldcheck", fid, false, {keyvalue: fkey }) %>
                        <label for="<%=fid%>"><%="{0} ({1} kB)".format(safe.html(fnaam), sz)%></label>
                      </td>
                    </tr>
<%
                }
%>
                    <input type="hidden" id="cnt_kmnr" name="cnt_kmnr" value="<%=checklist.files.length%>">
<%
            }
          MODAL_BLOCK_END();
          SIMPLE_BLOCK_START();
            var buttons =  [ { title: L("lcl_noti_send"), id: "btn_send", icon: "fa-paper-plane", action: "queueSubmit()", singlepress: true, importance: 1 },
                            { title: L("lcl_cancel"), id: "btn_cancel", icon: "fa-fclt-cancel", action: "queueCancel()", importance: 3 }];
            CreateButtons(buttons, { isModal: true, showIcons: true });
          SIMPLE_BLOCK_END();

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