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

     File:           prs_edit_bedrijfadres.asp
     Description:    edit or add bedrijfadres
     Parameters:     badr_key     // bedrijfadres_key
                     bedrijf_key
     Context:
     Note:
*/
%>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file="../Shared/selector.inc" -->
<!-- #include file="../Shared/flexfiles.inc" -->
<!-- #include file="../Shared/calendar.inc" -->
<!-- #include file="../api2/api2.inc" -->
<!-- #include file="../Shared/bedrijfselector.inc" -->
<!-- #include file="../Shared/plaatsselector.inc" -->
<!-- #include file="../Shared/persoonselector.inc" -->
<%
FCLTHeader.Requires({ plugins:["jQuery"],
                      js: ["jquery.timepicker-table.js"],
                      css: ["timePicker-table.css"] })

var badr_key = getQParamInt("badr_key", -1);
var prs_bdrkey = getQParamInt("bedrijf_key", -1);
var autfunction = 'WEB_PRSMGT';
var authparams = user.checkAutorisation(autfunction);
user.auth_required_or_abort(authparams && authparams.PRSwritelevel < 9);

if (badr_key == -1)
{
  sql = "SELECT prs_bedrijf_naam, prs_bedrijf_intern"
      + "  FROM prs_bedrijf"
      + " WHERE prs_bedrijf_key = " + prs_bdrkey;
  oRs = Oracle.Execute(sql);
  var prs_bdrnaam = oRs("prs_bedrijf_naam").value;
  var isIntern = oRs("prs_bedrijf_intern").value == 1;
  oRs.Close();
  var loglevel = 0;  // defaultwaarde
}
else
{
  sql = "SELECT a.prs_bedrijfadres_key"
      + "     , a.prs_bedrijf_key"
      + "     , a.prs_bedrijf_key2"
      + "     , a.alg_district_key"
      + "     , a.alg_locatie_key"
      + "     , b.prs_bedrijf_naam"
      + "     , b.prs_bedrijf_intern"
      + "     , a.prs_bedrijfadres_type"
      + "     , a.mld_typeopdr_key"
      + "     , a.prs_bedrijfadres_url"
      + "     , a.prs_bedrijfadres_sender"
      + "     , a.prs_bedrijfadres_replyaddress"
      + "     , a.prs_bedrijfadres_username"
      + "     , a.prs_bedrijfadres_password"
      + "     , a.prs_bedrijfadres_authmethod"
      + "     , a.prs_bedrijfadres_oa_token_url"
      + "     , a.prs_bedrijfadres_oa_scope"
      + "     , a.prs_bedrijfadres_oa_resource"
      + "     , a.prs_bedrijfadres_ordermode"
      + "     , a.prs_bedrijfadres_soapversion"
      + "     , a.prs_bedrijfadres_soapaction"
      + "     , a.prs_bedrijfadres_certificate"
      + "     , a.prs_bedrijfadres_xsl"
      + "     , a.prs_bedrijfadres_error_handler"
      + "     , a.prs_bedrijfadres_ext"
      + "     , a.prs_bedrijfadres_lockuser_key"
      + "     , a.prs_bedrijfadres_locksecret"
      + "     , a.prs_bedrijfadres_lockexpire"
      + "     , a.prs_bedrijfadres_loglevel"
      + "     , a.prs_bedrijfadres_attachfile"
      + "     , a.prs_bedrijfadres_flexfiles"
      + "     , a.prs_bedrijfadres_encoding"
      + "     , a.prs_bedrijfadres_charset"
      + "     , a.prs_bedrijfadres_plugin"
      + "     , a.prs_bedrijfadres_plugindata"
      + "     , a.prs_bedrijfadres_startdatum"
      + "  FROM prs_bedrijfadres a"
      + "     , prs_bedrijf b"
      + " WHERE b.prs_bedrijf_key = a.prs_bedrijf_key"
      + "   AND prs_bedrijfadres_key = " + badr_key;
  var oRs = Oracle.Execute(sql);
  if (oRs.Eof)
    shared.record_not_found();

  var prs_bdrkey     = oRs("prs_bedrijf_key").Value;   // opdrachtnemer
  var prs_bdrkey2    = oRs("prs_bedrijf_key2").Value;  // opdrachtgever
  var prs_distr_key  = oRs("alg_district_key").Value;
  var prs_loc_key    = oRs("alg_locatie_key").Value;
  var prs_bdrnaam    = oRs("prs_bedrijf_naam").Value;
  var isIntern       = oRs("prs_bedrijf_intern").value == 1;
  var prs_type       = oRs("prs_bedrijfadres_type").Value;
  var prs_typeopdr   = oRs("mld_typeopdr_key").Value;
  var prs_url        = oRs("prs_bedrijfadres_url").Value;
  var prs_sender     = oRs("prs_bedrijfadres_sender").Value;
  var prs_reply      = oRs("prs_bedrijfadres_replyaddress").Value;
  var username       = oRs("prs_bedrijfadres_username").Value;
  var password       = oRs("prs_bedrijfadres_password").Value;
  var authmethod     = oRs("prs_bedrijfadres_authmethod").Value;
  var token_url      = oRs("prs_bedrijfadres_oa_token_url").Value;
  var oa_scope       = oRs("prs_bedrijfadres_oa_scope").Value;
  var oa_resource    = oRs("prs_bedrijfadres_oa_resource").Value;
  var prs_ordermode  = oRs("prs_bedrijfadres_ordermode").Value;
  var soapversion    = oRs("prs_bedrijfadres_soapversion").Value;
  var soapaction     = oRs("prs_bedrijfadres_soapaction").Value;
  var prs_cert       = oRs("prs_bedrijfadres_certificate").Value;
  var prs_xsl        = oRs("prs_bedrijfadres_xsl").Value;
  var prs_err        = oRs("prs_bedrijfadres_error_handler").Value;
  var prs_ext        = oRs("prs_bedrijfadres_ext").Value;
  var lockuser_key   = oRs("prs_bedrijfadres_lockuser_key").Value;
  var locksecret     = oRs("prs_bedrijfadres_locksecret").Value;
  var lockexpire     = oRs("prs_bedrijfadres_lockexpire").Value;
  var loglevel       = oRs("prs_bedrijfadres_loglevel").Value;
  var bijlage        = oRs("prs_bedrijfadres_attachfile").Value;
  var flexfiles      = oRs("prs_bedrijfadres_flexfiles").Value;
  var encoding       = oRs("prs_bedrijfadres_encoding").Value;
  var charset        = oRs("prs_bedrijfadres_charset").Value;
  var plugin         = oRs("prs_bedrijfadres_plugin").Value;
  var plugindata     = oRs("prs_bedrijfadres_plugindata").Value;
  var startdatum     = new Date(oRs("prs_bedrijfadres_startdatum").Value);

  oRs.Close();
}
%>
<html>
  <head>
<%
    FCLTHeader.Generate();
%>
<script type="text/javascript" >
    async function badr_submit()
    {
      if (!await validateForm("u2"))
        return false;

      $.post($("form[name=u2]")[0].action, $("[name=u2]").serialize(), FcltCallbackClose, "json");
    }

    function badr_cancel()
    {
      FcltMgr.closeDetail(window, { cancel: true } );
    }
    function typeChange()
    {
      var noTypeopdr = $("#prs_type").val() != "O" && $("#prs_type").val() != "OG";
      $("#prs_typeopdr").prop("disabled", noTypeopdr);
    }

    function protocolChange()
    {
      var currval = $("#prs_ordermode").val();
      if ($('#protocol').val() == "mailto:")
      {
        var options = [
          { value: '0', label: L("lcl_mail_ordermode0") },
          { value: '1', label: L("lcl_mail_ordermode1") }
        ];
      }
      else if ($("#protocol").val() == "https://")
      {
        // TODO: dit staat bij PutOrders, wat zijn dan netto nog de opties?
        // p_bedrijfadres.ordermode
        //              bit 0 [0=xml, 1 soap] (1)
        //              bit 1 [alleen voor mail attachment encryptie] (2)
        //              bit 2 [0=2*base64 encoding, 1=plain] (4)  JGL Aug-2016: komt volgens mij in de praktijk niet voor
        //              bit 3 [0=xml tag encoding, 1=plain] (8)
        var options = [
          { value: '0',  label: L("lcl_https_ordermode0") },
          { value: '1',  label: L("lcl_https_ordermode1") },
          { value: '5',  label: L("lcl_https_ordermode5") },  // 4+1
          { value: '13', label: L("lcl_https_ordermode13") }  // 8+4+1
        ];
      }
      else
      {
        var options = [];
      }
      $("#prs_ordermode").empty();
      options.forEach(option => {
        $("#prs_ordermode").append(`<option value="${option.value}">${option.label}</option>`);
      });
      $("#prs_ordermode").val(currval);

    }

    function authChange()
    {
      var oAuth = $("#authmethod").val() == "4";
      $("#token_url").prop("disabled", !oAuth);
      $("#oa_scope").prop("disabled", !oAuth);
      $("#oa_resource").prop("disabled", !oAuth);
      var upw = !oAuth;  // klopt dit?
      $("#prs_username").prop("disabled", !upw);
      $("#prs_password").prop("disabled", !upw);
    }

    $(function () {
        $("#selxsl").change(function () {
             $("#prs_xsl").val(this[this.selectedIndex].text);
        });
    });
    // initialize
     $(document).ready(function()
      {
          protocolChange();
      });
</script>
  </head>

  <body class="editmode">
<%
    SUBFRAME_START();
    var buttons =  [ {title: L("lcl_submit"), action:"badr_submit()", icon: "fa-fclt-save" }
                   , {title: L("lcl_cancel"), action:"badr_cancel()", icon: "fa-fclt-cancel" }
                   ];

    IFRAMER_HEADER(L("lcl_prs_bedrijfadres_frame"), buttons);
%>
      <form name="u2"
            action="prs_edit_bedrijfadres_save.asp?bedrijf_key=<%=prs_bdrkey%>&badr_key=<%=badr_key%>"
            method="post">
<%
        // De facilitorkant van de configuratie
        BLOCK_START("prsbedrijfadres", L("lcl_prs_basisblok"), {icon: "fa-tools"});
        ROFIELDTR("fld", L("prs_bedrijf_naam2"), prs_bdrnaam);
        // type
        if (isIntern)
        {
          sql = "SELECT 'E' prs_type"
              + ", " + safe.quoted_sql(L("lcl_prs_bedrijfadres_type_e_intern"))+" prs_type_oms"
              + "  FROM DUAL";  // Mareon only in feite
        }
        else
        {
          sql = "SELECT 'B' prs_type"
              + ", " + safe.quoted_sql(L("lcl_prs_bedrijfadres_type_b"))+" prs_type_oms"
              + "  FROM DUAL"
              + " UNION SELECT 'O',  " + safe.quoted_sql(L("lcl_prs_bedrijfadres_type_o"))+" FROM DUAL"
              + " UNION SELECT 'OG', " + safe.quoted_sql(L("lcl_prs_bedrijfadres_type_og"))+" FROM DUAL"
              + " UNION SELECT 'C',  " + safe.quoted_sql(L("lcl_prs_bedrijfadres_type_c"))+" FROM DUAL"
              + " UNION SELECT 'V',  " + safe.quoted_sql(L("lcl_prs_bedrijfadres_type_v"))+" FROM DUAL"
              + " UNION SELECT 'N',  " + safe.quoted_sql(L("lcl_prs_bedrijfadres_type_n"))+" FROM DUAL"
              + " UNION SELECT 'I',  " + safe.quoted_sql(L("lcl_prs_bedrijfadres_type_i"))+" FROM DUAL"
              + " UNION SELECT 'R',  " + safe.quoted_sql(L("lcl_prs_bedrijfadres_type_r"))+" FROM DUAL"
              + " ORDER BY 2";  // sortering is relevant
        }
        FCLTselector("prs_type"
                    , sql
                    , { initKey: prs_type
                      , label: L("lcl_prs_bedrijfadres_type")
                      , onChange: "typeChange()"
                      , emptyOption : prs_type?null:""
                      , required: !prs_type
                      }
                    );

        if (!isIntern)
        {
          // Opdrachttype
          sql = "SELECT mld_typeopdr_key"
              + ", "+ lcl.xsqla('t.mld_typeopdr_omschrijving', 't.mld_typeopdr_key')
              + " FROM mld_typeopdr t"
              + " ORDER BY 2";
          FCLTselector("prs_typeopdr"
                      , sql
                      , { initKey: prs_typeopdr
                        , label: L("lcl_mld_typeopdr")
                        , emptyOption : L("lcl_prs_bedrijfadres_type_o_other")

                        , initEmpty: true // Altijd lege waarde tonen, ook als er maar 1 waarde is.
                        , disable: (prs_type!="O" && prs_type!="OG") // Alleen voor bestelopdrachten te gebruiken.
                        }
                      );

          // District en/of Locatie
          FCLTplaatsselector(-1,
                            { districtkey: prs_distr_key,
                              locatiekey: prs_loc_key,
                              startlevel: 1, // District
                              eindlevel: 2 // Locatie
                            });

          FCLTbedrijfselector("prs_bdrkey2",
                              "sgComp",
                              { companyKey: prs_bdrkey2,
                                label: L("prs_bedrijf_naam1"),
                                filtercode: "I", // Interne bedrijven
                                autlevel: authparams.PRSreadlevel  //doet dit iets goeds eigenlijk?
                              });

          // with channel B the flexfiles value is interpreted as 0 = No, 1 = Yes (2 = not applicable)
          if (prs_type == "B")
          {
            sql = "SELECT         0, " + safe.quoted_sql(L("lcl_no")) + " FROM DUAL"
                + " UNION SELECT  1, " + safe.quoted_sql(L("lcl_Yes")) + " FROM DUAL"
                + " ORDER BY 1";
            var initkey = flexfiles == 1 ? 1 : 0;
          }
          else
          {
            var def = " (" + (S("puo_order_flexfiles")?L("lcl_yes"):L("lcl_no")) + ")";
            sql = "SELECT         0, " + safe.quoted_sql(L("lcl_default") + def) + " FROM DUAL"
                + " UNION SELECT  1, " + safe.quoted_sql(L("lcl_Yes")) + " FROM DUAL"
                + " UNION SELECT  2, " + safe.quoted_sql(L("lcl_No")) + " FROM DUAL"
                + " ORDER BY 1";
            var initkey = flexfiles || 0;
          }
          FCLTselector('flexfiles', sql,
                            { label:  L("lcl_puo_order_flexfiles"),
                              initKey: initkey
                            }
                        );
          FILEPICKERTR("bijlage", L("lcl_prs_bedrijfadres_bijlage"), bijlage, { "key": badr_key, "module": "BDRADR", "icon": "fa-file-lines", "defaultValue": L("lcl_prs_bedrijfadres_bijlage") });
        }

        FCLTcalendar( "startdate",
                      { label   : L("prs_bedrijf_startdatum"),
                        datum   : startdatum,
                        maxPast: 1,
                        timeField: true,
                        timeStep: 60,
                        startTime    : 0,
                        endTime      : 23
                      });

      BLOCK_END();

      // De andere kant van de configuratie
      BLOCK_START("prsbedrijfadrestech", L("lcl_prs_bedrijf_techblock"), {icon: "fa-wifi"});
        var protocol = "";
        var arr = (prs_url||"").split(":");
        if (arr.length > 1)
        {
            protocol = arr[0].toLowerCase() + ":";
            if (protocol != "mailto:" && protocol != "file:")
                protocol += "//";
            prs_url = prs_url.substr(protocol.length);
        }
        sql = "SELECT         'mailto:', 'mailto:', 10 FROM DUAL"
            + " UNION SELECT  'https://', 'https://', 20  FROM DUAL"
            + " UNION SELECT  'sftp://', 'sftp://', 30  FROM DUAL"
            + " UNION SELECT  'file:', 'file:', 40 FROM DUAL"
            + " UNION SELECT  'ftp://', 'ftp://', 50 FROM DUAL"
            + " ORDER BY 3";
        FCLTselector("protocol", sql,
                          { label: L("lcl_prs_bedrijfadres_protocol"),
                            initKey: protocol,
                            onChange: "protocolChange()",
                            initEmpty: !protocol,
                            required: !protocol
                          }
                       );
        RWFIELDTR("prs_url",       "fld", L("lcl_prs_bedrijfadres_url"),            prs_url,       {maxlength: 512, required: true});

        if (!isIntern)
        {
          // initial, replaced by protocolChange()
          sql = "SELECT        0, dummy FROM DUAL"
              + " UNION SELECT 1, dummy FROM DUAL"
              + " UNION SELECT 5, dummy FROM DUAL"
              + " UNION SELECT 13, dummy FROM DUAL"
              + " ORDER BY 1";

          //RWFIELDTR("xxprs_ordermode", "fld", 'xx '+L("lcl_prs_companies_order_mode"),        prs_ordermode, {maxlength: 3});
          FCLTselector("prs_ordermode", sql,
                            { label: L("lcl_prs_companies_order_mode"),
                              initKey: prs_ordermode
                            }
                      );
          RWFIELDTR("prs_sender",    "fld", L("lcl_prs_bedrijfadres_afzender"),       prs_sender,    {maxlength: 512, required: false, placeholder: S("puo_fromaddress")});
          RWFIELDTR("prs_reply",     "fld", L("lcl_prs_bedrijfadres_replyadres"),     prs_reply,     {maxlength: 512, required: false, placeholder: S("puo_replyaddress")});

// future use        RWFIELDTR("soapversion",   "fld", L("lcl_prs_bedrijfadres_soapversion"),    soapversion,      {maxlength: 10});
        RWFIELDTR("soapaction",    "fld", L("lcl_prs_bedrijfadres_soapaction"),     soapaction,       {maxlength: 128});
        sql = "SELECT        0, " + safe.quoted_sql(L("lcl_encoding_text_xml")) + " FROM DUAL"
            + " UNION SELECT 1, " + safe.quoted_sql(L("lcl_encoding_multipart_form")) + " FROM DUAL"
            + " UNION SELECT 2, " + safe.quoted_sql(L("lcl_encoding_application_json")) + " FROM DUAL"
            + " UNION SELECT 4, " + safe.quoted_sql(L("lcl_encoding_form_urlencoded")) + " FROM DUAL"
            + " ORDER BY 1";
        FCLTselector("encoding", sql,
                          { label: L("lcl_prs_bedrijfadres_encoding"),
                            initKey: encoding||0
                          }
                    );

          var selfilehtml = "";
          var props = flexProps("CUSTXSL", -1, null, null, {getFiles: true});
          if (props.files.length > 0)
          {
              var selfilehtml = "<select class='fld' id='selxsl'><option>" + L("lcl_prs_companies_xsl_choose") + "</option>";
              for (i=0; i<props.files.length; i++)
              {
                  var name = props.files[i].name;
                  if (name.match(/_20......_......\./)) // De backups: melding_20150122_154913.xsl
                      continue;                         // hoeven we niet
                  selfilehtml += "<option>" + safe.html("xsl/" + name) + "</option>";
              }
              selfilehtml += "</select>";
          }

          RWFIELDTR("prs_xsl",    "fld",      L("lcl_prs_companies_xsl"),           prs_xsl,  {maxlength: 256, reartext: selfilehtml});
          sql = api2.splitLOV2sql(L("lcl_prs_bedrijfadres_charsetLOV"));
          FCLTselector("charset", sql,
                    { label: L("lcl_prs_bedrijfadres_charset"),
                      initKey: charset,
                      emptyKey: '',
                      emptyOption: ''
                    });
          RWCHECKBOXTR("prs_err", "fldcheck", L("lcl_prs_companies_error_handler"), prs_err);
          RWFIELDTR("prs_ext",    "fldshort", L("lcl_prs_bedrijfadres_ext"),        prs_ext,  {maxlength: 10});
        }

        RWFIELDTR("plugin",    "fld", L("prs_bedrijfadres_plugin"),     plugin,       {maxlength: 320});
        RWTEXTAREATR("plugindata","fld", L("prs_bedrijfadres_plugindata"), plugindata,   {maxlength: 4000});
        RWFIELDTR("loglevel", "fldshort", L("lcl_prs_bedrijfadres_loglevel"), loglevel, {required: true});

      BLOCK_END();
      BLOCK_START("prsbedrijfadresauth", L("lcl_authenticatie"), {icon: "fa-face-zipper"});
        RWFIELDTR("prs_cert",     "fld", L("lcl_prs_companies_order_certificate"), prs_cert,      {maxlength: 255, placeholder: "My\\"});
        var LOV = L("lcl_prs_bedrijfadres_authmethodLOV"); // "0;Automatic;1;Forced Basic;2;Custom HTTP header;3;Add to xml;4;oAuth";
        var sql = api2.splitLOV2sql(LOV);
          FCLTselector('authmethod', sql,
                               {   label: L("lcl_prs_bedrijfadres_authmethod")
                                 , initKey: authmethod || 0
                                 , onChange: "authChange()"
                               });
        RWFIELDTR("prs_username",  "fld", L("lcl_prs_bedrijfadres_username"),       username,      {maxlength: 128});
        RWFIELDTR("prs_password",  "fld", L("lcl_prs_bedrijfadres_wachtwoord"),     password,      {maxlength: 320});
        RWFIELDTR("token_url", "fld", L("lcl_prs_bedrijfadres_oa_token_url"),   token_url,     {maxlength: 512});
        RWFIELDTR("oa_scope", "fld", L("lcl_prs_bedrijfadres_oa_scope"),       oa_scope,     {maxlength: 512});
        RWFIELDTR("oa_resource", "fld", L("lcl_prs_bedrijfadres_oa_resource"),    oa_resource,  {maxlength: 512});
      BLOCK_END();

      if (!isIntern)
      {
        BLOCK_START("prsbedrijfadresuser", L("lcl_prs_bedrijfadres_loginuser"), {icon: "fa-user-lock"});
          FCLTpersoonselector("lockuser_key",
                                "sgPerson",
                              { perslidKey: lockuser_key,
                                label: L("lcl_prs_bedrijfadres_lockuser")
                              });
          RWFIELDTR("locksecret", "fld", L("lcl_prs_bedrijfadres_locksecret"), locksecret);
          RWFIELDTR("lockexpire", "fldshort", L("lcl_prs_bedrijfadres_lockexpire"), lockexpire, {datatype: "number" });
        BLOCK_END();
      }
    IFACE.FORM_END();
%>
      </form>
    <% SUBFRAME_END(); %>
  </body>
</html>
<% ASPPAGE_END(); %>
