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

    Description:    Beheer van technische adressen (waar PutOrders naartoe stuurt)

    Context:

    Notes:          TODO voor MVP
                    - Afhankelijkheid van prs_bedrijf_intern (isinternal) in prs_bedrijf
                    - 0: extern bedrijf, dan de klassieke kanalen, en alleen bij kanaal O de keuze voor opdrachttype
                    - 1: intern bedrijf, dan alleen channel = E (mag fixed)
                    - 2: Extern systeem, dan alleen channel = G (mag fixed)
*/
%>

<!-- #include file="../scf/scaffolding.inc" -->
<!-- #include file="../api2/model_prs_bedrijfadres.inc" -->
<!-- #include file="./prs_bedrijfadres_templates.inc" -->

<%

var canImport = user.has("WEB_IMPORT");
var model = new model_prs_bedrijfadres();
var scf_mode = getQParam("mode", "");
var isclone = getQParamInt("scf_clone", 0);

var bdradr_key = getQParamInt("companyconnect", getQParamInt("id", -1));
if (bdradr_key > 0)
{
    var sql = "SELECT prs_bedrijf_key,"
            + "       prs_bedrijfadres_template,"
            + "       prs_bedrijfadres_type"
            + "  FROM prs_bedrijfadres"
            + " WHERE prs_bedrijfadres_key = " + bdradr_key;
    var oRs = Oracle.Execute(sql)
    var bdr_key = oRs("prs_bedrijf_key").Value;
    var adres_type = oRs("prs_bedrijfadres_type").Value;
    var template = oRs("prs_bedrijfadres_template").Value;
    oRs.Close()
}
else
{
    var bdr_key = getQParamInt("company", -1);   // als die gegeven is, ben ik een subtab en mag ik mezelf onderdrukken
    var adres_type = getQParamSafe("adres_type", "");
    var template = getQParamSafe("template", "");
}

var hidefields = "";

if (template)
{
    var tpl = bdr_templates[template];
    model.fields["template"].LOV = template + ";" + tpl.name;
    model.fields["template"].defaultvalue = template;
    model.fields["template"].showtransit = true;
    if (isclone)
        model.fields["template"].hidden_fld = true; // zodat wel opgeslagen
    else
        model.fields["template"].readonly = true;

    hidefields = tpl.hidefields || "";
    for (var ov in tpl.overrules)
    {
        var overrule = tpl.overrules[ov];
        for (var nm in overrule)
        {
            if (ov == "internalcomment")
                continue;
            if (ov == "plugindata" && nm == 'defaultvalue' && typeof overrule[nm] == 'object')
            {
                model.fields[ov][nm] = JSON.stringify(overrule[nm], null, 4); // plugindata moet string worden maar we staan JSON toe in het config bestand
            }
            else
            {
                model.fields[ov][nm] = overrule[nm];
            }
        }
    }
}

model.hook_post_post = function (params, jsondata, key)
{
    if (params.cloning)
        return;

    var tpl = bdr_templates[jsondata.template || "generic"];
    if (tpl.extraevents)
    {
        var extraevents = tpl.extraevents.split(",");
        for (var i = 0; i < extraevents.length; i++)
        {
            var sql = "INSERT INTO prs_bedrijfadres_srtnoti"
                    + "        (prs_bedrijfadres_key, fac_srtnotificatie_key)"
                    + "  SELECT " + key + ", fac_srtnotificatie_key"
                    + "    FROM fac_srtnotificatie"
                    + "   WHERE fac_srtnotificatie_code = " + safe.quoted_sql(extraevents[i]);
            Oracle.Execute(sql);
        }
    }
}

if (adres_type)
{
    model.fields["channel"].defaultvalue = adres_type;
    model.fields["channel"].showtransit = true;
    if (isclone)
        model.fields["channel"].hidden_fld = true; // zodat wel opgeslagen
    else
        model.fields["channel"].readonly = true;

    var xmlnodes = "";
    switch (adres_type)
    {
        case "B":
            xmlnodes = 'bestelopdr';
            // discipline is te ingewikkeld.
            hidefields = "lockuser,locksecret,lockexpire,ordertype,discipline,company2";
                break;
        case "C":
            xmlnodes = 'contract';
            hidefields = "lockuser,locksecret,lockexpire,ordertype";
            model.fields["discipline"].label = L("cnt_discipline")
            model.fields["discipline"].foreign = { tbl: "cnt_v_aanwezigdiscipline",
                                                    key: "ins_discipline_key",
                                                    desc: "ins_discipline_omschrijving" };
            break;
        case "O":
            // hidefields is al gezet door template
            xmlnodes = 'opdracht';
            model.fields["discipline"].label = L("mld_discipline")
            model.fields["discipline"].foreign = "mld_discipline";
            break;
        case "R":
            xmlnodes = 'reservering';
            // discipline is te ingewikkeld. Zie PROCEDURE res.notifyreserveringbedrijven
            hidefields = "lockuser,locksecret,lockexpire,ordertype,discipline";
            break;
        case "G": // generiek mag alle notificaties
            hidefields = "lockuser,locksecret,lockexpire,ordertype,company2";
            break;
        case "S": // Systeem mag alleen notificaties die een receiver hebben (want receiver-->bedrijf-->technisch adres)
            xmlnodes = "melding,opdracht,reservering,xreservering,bestelling,bestelopdr,afspraak,bezoeker,deel,controle,contract,perslid";
            hidefields = "lockuser,locksecret,lockexpire,ordertype,company2";
            break;
        default:
            hidefields = "lockuser,locksecret,lockexpire,ordertype,company2";
            delete model.includes["srtnotifications"];  // "N", "V", "I", "P" helemaal geen subtabje aanbieden?
    }
    if (xmlnodes)
    {
        model.includes.srtnotifications.model.fields.srtnotification.foreign.where += " AND fac_srtnotificatie_xmlnode IN ({0})".format(safe.quoted_sql_join(xmlnodes.split(",")));
    }
    hidefields = hidefields.split(",");
    for (var i = 0; i < hidefields.length; i++)
        delete model.fields[hidefields[i]];
}

var block_be_lev_buttons = [];
if (bdr_key > 0)
{
    var sql = "SELECT prs_bedrijf_intern"
            + "  FROM prs_bedrijf"
            + " WHERE prs_bedrijf_key = " + bdr_key;
    var oRs = Oracle.Execute(sql)
    var prs_bedrijf_intern = oRs("prs_bedrijf_intern").Value || 0;
    oRs.Close;

    // ============================
    var buttons = [];
    if (!adres_type && scf_mode == 'edit' && getQParamInt("scf_multi", 0) == 0) // dan eerst adres_type vragen
    {
        if (prs_bedrijf_intern == 0) // gewone externe
        {
            // gewoon extern kan geen 'E'RP of 'G'eneriek
            model.fields["channel"].LOV = api2.filterLOV(model.fields["channel"].LOV, "V,B,R,C,O,P"); // 'N' Notificatie en 'I' IOT hebben we (PF/JGL) anno 2025 niet direct een usecase voor. Even weglaten.
            var split = api2.splitLOV(model.fields["channel"].LOV);
            var buttontitle = L("lcl_prs_bedrijfadres_type");
            for (var v in split)
            {
                buttons.push({  //icon: "fa-users",
                                title: split[v],
                                action: "adres_type='" + v + "';$('div#act_modal').dialog('close').remove();"
                             });
            }
        }
        else if (prs_bedrijf_intern == 1) // interne
        {
            //model.fields["channel"].LOV = api2.filterLOV(model.fields["channel"].LOV, "E,S"); // E is ERP, custom code van MARX.
            model.fields["channel"].hidden_fld = true;
            model.fields["channel"].defaultvalue = "S";                                       // 'S' is systeemnotificaties naar persoon->afdeling->bedrijf (vervanger prs_perslid_systeemadres)
            model.fields["template"].hidden_fld = true;
            model.fields["template"].defaultvalue = 'generic';
        }
        else if (prs_bedrijf_intern == 2) // 'generiek' voor systeembedrijven
        {
            model.fields["channel"].hidden_fld = true;
            model.fields["channel"].defaultvalue = "G";
            model.fields["template"].hidden_fld = true;
            model.fields["template"].defaultvalue = 'generic';
        }
    }
    else if (!template && adres_type == "O" && scf_mode == 'edit') // dan eerst template vragen
    {
        var buttontitle = L("lcl_prs_bedrijfadres_template");
        for (v in bdr_templates)
        {
            var button = {
                            title: bdr_templates[v].name,
                            action: "template='" + v + "';$('div#act_modal').dialog('close').remove();"
                         };
            if (!bdr_templates[v].licensed)
            {
                button.action = "null";
                button.xclass = "btn_disabled";
            }
            buttons.push(button);
        }
    }

    var id = getQParamInt("id", -1);
    if (mode == "edit" && id > 0)
    {
        block_be_lev_buttons = [ { "icon": "fa-fclt-edit", "title":L("lcl_reset"), "tooltip": L("lcl_bedrijfadres_reset_token"), "action": "resetLockSecret(" + id + ");" } ];
    }
}
else
{
    delete model.REST_POST;
}

var params =  {
            "search": {
                "autosearch": true,
                "transit": [
                    "isinternal",
                    "company"
                ],
                "filters": [
                    "channel",
                    "company",  // of systeem
                    "ordertype",
                    //"name",
                    "district",
                    "location",
                    "company2"
                    ]
                },
            "transit": {
                "isinternal" : prs_bedrijf_intern  // ik probeer ook maar wat
            },
            "list": {
                "columns": [
                    //"name",
                    "template",
                    "channel",
                    "ordertype",  // te specifiek voor een algemeen overzicht?
                    "discipline",
                    "district",
                    "location",
                    "company2",
                    "address",
                    "stylesheet",
                    "startdate"
                    // "srtnotifications.srtnotification" // Lelijk doordat lcl.l(fac_srtnotificatie_oms) er achter geplakt wordt
                ]
            },
            "edit": {
                "modal": false,
                "requires": {
                    "js": [
                        "./prs_bedrijfadres.js"
                    ]
                }
            },
            "layout": {
                "block": [
                    {   "blockid": "ba_basis",
                        "label": L("lcl_prs_basisblok"),
                        "icon": "fa-tools",
                        "ishtmlsafe": true,
                        "fields": [
                            "id",
                            "template",
                            "company", // TODO: readonly?
                            //"name",  // if generiek
                            "channel",
                            "ordertype",
                            "discipline",
                            "district",
                            "location",
                            "company2",
                            "sendattachment", // TODO: bijlagemeesturenLOV() heeft parameter prs_type?
                            "attachfile",
                            "startdate"
                        ]
                    },
                    {   "blockid": "ba_tech",
                        "label": L("lcl_prs_bedrijf_techblock") + (S("puo_forceorderaddress")?"<br>Let op: puo_forceorderaddress is " + S("puo_forceorderaddress"):""),
                        "icon": "fa-wifi",
                        "ishtmlsafe": true,
                        "fields": [
                            "address",
                            "ordermode",
                            "sender",
                            "replyaddress",
                            "soapaction",
                            "encoding",
                            "stylesheet",
                            "charset",
                            "xslerrorhandler",
                            "extension",
                            "plugin",
                            "plugindata",
                            "loglevel"
                        ]
                    },
                    {   "blockid": "ba_auth",
                        "label": L("lcl_authenticatie"),
                        "icon": "fa-face-zipper",
                        "ishtmlsafe": true,
                        "fields": [
                            "certificate",
                            "authmode",
                            "username",
                            "password",
                            "oa_token_url",
                            "oa_scope",
                            "oa_resource"
                        ]
                    },
                    {   "blockid": "ba_lev",
                        "label": L("lcl_prs_bedrijfadres_loginuser"),
                        "icon": "fa-user-lock",
                        "ishtmlsafe": true,
                        "buttons": block_be_lev_buttons,
                        "fields": [
                            "lockuser",
                            "locksecret",
                            "lockexpire"
                        ]
                    }
                ]
            }
        }

if (!(bdr_key > 0))
    params.list.columns.unshift("company");  // vooraan toevoegen

if (canImport) {
    params.list.roundtripCode = "BEDRIJFADRES";
}


var id = getQParamInt("id", -1);
if (id > 0)
{
    var urole = getQParamSafe("urole", "fe");
    var page = protectQS.create("../shared/status_info.asp?badr_key=" + id + "&urole=" + urole);
    params.wrap = { "frames": [] };
    params.wrap.frames.push({
        "url": page,
        "icon": "fa-list",
        "title": L("lcl_tracking"),
        "autfunction": model.authfunction
    });
}

if (buttons && buttons.length)
{
    transitParam = buildTransitParam(["mode", "isinternal", "company", "disc_key"])

    FCLTHeader.Requires({plugins: ["suggest", "jQuery"],
                            js: ["jquery-ui.js"],
                            css: ["../shared/suggest/suggest.css"]}); // css for childframes})

%>
    <html>
    <head>
    <%  FCLTHeader.Generate() %>
        <script>
            var adres_type = "<%=safe.jsstring(adres_type)%>";
            var template = "<%=adres_type?"generic":""%>"; // als je 'Escape' drukt.
            function dialogClose()
            {
                if (!adres_type)
                {
                    FcltMgr.closeDetail(window, { cancel: true, panelModalCool: true } );
                }
                else
                {
                    if (adres_type != "O")
                        template = "generic";
                    window.location.href = "prs_bedrijfadres.asp?urole=<%=urole%><%=transitParam%>&adres_type=" + adres_type + "&template=" + template;
                }
            }
            //$(function() opent onderin het scherm
            $(window).on("load", function()
                {
                    var params = { title: "<%=safe.jsstring(buttontitle)%>",
                                    modal: true,
                                    width: 365,
                                    resizable: false,
                                    close: dialogClose,
                                    create: FcltMgr.fnCreateCloseButton("div#act_modal")
                                    };
                    $('div#act_modal').dialog(params).dialog('open');
                });
        </script>
    </head>
    <body>
        <div id="act_modal">
<%          CreateButtons(buttons, { vertical: 1, isDialog: true, showIcons: true } );
%>
        </div>
<%
      PAGE_START({ pageHeader: { icon:  "fa-users" , title: L("lcl_prs_bedrijfadres_frame") } });

       var page="../shared/empty.html";  // Achtergrondpagina tijdens popup keuze
      IFRAMER("resroomframe", page, { FcltClose: "roomClose" });
      //======================================

      PAGE_END(); %>
  </body>
</html>
<%
}
else // gewoon
{
    scaffolding(model, params);
}
%>
<% ASPPAGE_END(); %>
