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

     File:               cnt_split.asp
     Description:        Splitten van een contract door aanpassen huidige contract en het aanmaken van een nieuw (gesplit) contract.
     Parameters:         cnt_key              Contract key
     Context:
     Note:
*/ %>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file="../Shared/kenmerk_common.inc" -->
<!-- #include file="../Shared/calendar.inc" -->
<!-- #include file="cnt.inc" -->

<%
var cnt_key_arr = getQParamIntArray("cnt_key");

var split_info = { multi: cnt_key_arr.length > 1,
                   ingesloten: [],
                   mindate: null,
                   maxdate: null,
                   internnr: null,
                   kosten: null
                 }

if (split_info.multi) {
  var minmaxdate_valid = false;
  for (var i=0; i<cnt_key_arr.length; i++)
  {
    cnt_key = cnt_key_arr[i];

    var this_cnt = cnt.func_enabled_contract(cnt_key);  // Wat heb ik zoal aan rechten op dit contract?
    if (this_cnt.canSplit) {
      split_info.ingesloten.push(cnt_key);
    }
  }

  if (split_info.ingesloten.length > 0) {
    var sql = "SELECT MAX(cnt_contract_looptijd_van) mindate"
            + "     , MIN(cnt_contract_looptijd_tot) maxdate"
            + "  FROM cnt_contract"
            + " WHERE cnt_contract_key IN (" + split_info.ingesloten.join(",") + ")";
    var oRs = Oracle.Execute(sql);
    split_info.mindate = new Date(oRs("mindate").Value);
    split_info.maxdate = new Date(oRs("maxdate").Value);
    oRs.Close();
    minmaxdate_valid = (split_info.mindate < split_info.maxdate);
  }

  user.auth_required_or_abort(split_info.ingesloten.length > 0 && minmaxdate_valid);
}
else {
  var cnt_key = cnt_key_arr[0];
  var this_cnt = cnt.func_enabled_contract(cnt_key); // Wat heb ik zoal aan rechten op dit contract?
  user.auth_required_or_abort(this_cnt.canSplit);    // Kan ik dit contract splitten

  var sql = "SELECT cnt_contract_looptijd_van mindate"
          + "     , cnt_contract_looptijd_tot maxdate"
          + "     , cnt_contract_nummer_intern"
          + "     , COALESCE(cnt_contract_kosten, 0) kosten"
          //+ "     , CASE WHEN cnt_contract_termijntermijn IS NULL"
          //      + "      THEN cnt_contract_looptijd_tot + (cnt_contract_looptijd_tot - cnt_contract_looptijd_van + 1)"
          //      + "      ELSE cnt.cnt_getTermijndatum(cnt_contract_looptijd_tot,  cnt_contract_termijntermijn, 1)"
          //      + " END  verlengd"
          + "  FROM cnt_contract"
          + " WHERE cnt_contract_key = " + cnt_key;
  var oRs = Oracle.Execute(sql);
  // bestaat zeker
  split_info.ingesloten.push(cnt_key);
  split_info.mindate  = new Date(oRs("mindate").value);
  split_info.maxdate  = new Date(oRs("maxdate").value);
  split_info.internnr = oRs("cnt_contract_nummer_intern").value;
  split_info.kosten   = oRs("kosten").value;
  //split_info.verlengd = new Date(oRs("verlengd").Value);
  oRs.Close();
}

%>
<html>
  <head>
<%  FCLTHeader.Generate()
    var submitting = getQParamInt("submit", 0) == 1;
    if (submitting)
    {
      protectRequest.validateToken();
      splitmode = getFParamSafe("splitmode", "S");
      splitdate = getFParamDate("splitdate");
      if (splitmode == "S")
        splitdate.setDate(splitdate.getDate() + 1); // Startdatum nieuwe contract is 1 dag later dan einddatum oude contract bij splitsen.
      cnt_amount = getFParam("cnt_amount", "LEEG"); // Hier nog geen replace(...) en parseFloat(...) doen omdat parameter leeg kan zijn.
      if (cnt_amount == "" || cnt_amount == "LEEG") // 0 mag wel!
        cnt_amount = "null";
      else
      {
        cnt_amount = parseFloat(cnt_amount.replace(/,/g,"."));
      }

      var msg = "";
      if (  (splitmode == "S" && split_info.mindate <= splitdate && splitdate <= split_info.maxdate)
         || (splitmode == "V" && split_info.maxdate < splitdate)
         )
      { // splitsdatum moet tussen begin- en einddatum van contract liggen.
        // verlengdatum moet na einddatum van contract liggen.
        for (var i=0; i<split_info.ingesloten.length; i++) {
          sql = "BEGIN cnt.splitscontract (" + split_info.ingesloten[i] + ", " + splitdate.toSQL() + "," + user_key + "," + cnt_amount + "); END;";
          oRs = Oracle.Execute(sql);

          sql = "SELECT cnt.getnieuwsteversiekey(" + split_info.ingesloten[i] + ") newkey FROM DUAL";
          oRs = Oracle.Execute(sql);
          var newkey = oRs("newkey").value;
          oRs.Close();

          sql = "SELECT cnt_contract_nummer_intern"
              + "     , cnt_contract_versie"
              + "     , cnt_contract_omschrijving"
              + "  FROM cnt_contract"
              + " WHERE cnt_contract_key = " + newkey;
          var oRs = Oracle.Execute(sql);
          var newcontract = { nummer: oRs("cnt_contract_nummer_intern").Value
                            , versie: oRs("cnt_contract_versie").Value
                            , omschr: oRs("cnt_contract_omschrijving").Value
                            };
          oRs.Close();

          if (split_info.ingesloten[i] != newkey) {
            var flexsql = "SELECT k_old.cnt_kenmerk_key k_old"
                        + ", k_old.cnt_kenmerk_key k_new"
                        + " FROM cnt_srtkenmerk t"
                        + ", cnt_discipline s"
                        + ", cnt_kenmerk k_old"
                        + ", cnt_contract c_old"
                        + " WHERE c_old.cnt_contract_key = " + split_info.ingesloten[i]
                        + " AND s.ins_discipline_key = c_old.ins_discipline_key"
                        + " AND (k_old.cnt_srtcontract_key = s.ins_discipline_key OR k_old.cnt_srtcontract_key IS NULL)"
                        + " AND t.cnt_srtkenmerk_kenmerktype IN ('F', 'E', 'M') "
                        + " AND k_old.cnt_kenmerk_verwijder IS NULL "
                        + " AND k_old.cnt_srtkenmerk_key = t.cnt_srtkenmerk_key "
                        + " AND t.cnt_srtkenmerk_verwijder IS NULL";
            CopyFlexFolders("CNT", "C", split_info.ingesloten[i], "C", newkey, flexsql);
          }
        }
        var cnt_fullnr = newcontract.nummer + "." + newcontract.versie;
        if (splitmode == "S")
        {
          msg = split_info.ingesloten.length === 1 ? L("lcl_cnt_contract_split_success1").format(toDateString(splitdate, true), cnt_fullnr)
                                                   : L("lcl_cnt_contract_split_success").format(split_info.ingesloten.length, toDateString(splitdate, true));
        }
        else
        {
          msg = split_info.ingesloten.length === 1 ? L("lcl_cnt_contract_verleng_success1").format(toDateString(splitdate, true), cnt_fullnr)
                                                   : L("lcl_cnt_contract_verleng_success").format(split_info.ingesloten.length, toDateString(splitdate, true));
        }
      }
      else {
        if (splitmode == "S")
        {
          msg = split_info.ingesloten.length === 1 ? L("lcl_cnt_contract_split_warning1") : L("lcl_cnt_contract_split_warning");
        }
        else
        {
          msg = split_info.ingesloten.length === 1 ? L("lcl_cnt_contract_verleng_warning1") : L("lcl_cnt_contract_verleng_warning");
        }
      }
      %><script>FcltMgr.closeDetail(window, { refresh: true, warning: "<%=safe.jsstring(msg)%>" } ); </script><%
      Response.End;
    }
    else
    { %>
      <script type="text/javascript">
        var split_info = JSON.parse("<%=safe.jsstring(JSON.stringify(split_info))%>");

        function checkInput()
        {
          if ($("#cnt_amount") && $("#cnt_amount")[0] && $("#cnt_amount").val() != "")
          {
            var amount = $("#cnt_amount").val();
            if (amount < 0 || amount > <%=safe.jsfloat(split_info.kosten)%>)
            {
              FcltMgr.alert(L("lcl_cnt_exceed_cnt_kosten"));
              $("#cnt_amount")[0].select();
              $("#cnt_amount")[0].focus();
              return false;
            }
          }
          return true;
        }

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

          if (!checkInput())
            return false;

          document.forms.u2.submit();
        }

        function zetSplitmode()
        {
            console.log(split_info);
            if ($("input[name='splitmode']:checked").val() == "S")
            {
                $("#show_splitdate").datepicker("option", "minDate", new Date(split_info.mindate))
                                    .datepicker("option", "maxDate", new Date(split_info.maxdate))
                                    .datepicker("setDate", new Date());
                $("label[for=show_splitdate]").text(L("lcl_cnt_einddatum_old_cnt"));
                $("label[for=cnt_amount]").text(L("lcl_cnt_eindbedrag_old_cnt") + " " + L("lcl_valutasign"));
                $("label[for=cnt_amount]").closest("tr").show();
            }
            else
            {
                $("#show_splitdate").datepicker("option", "minDate", new Date(split_info.maxdate))
                                    .datepicker("option", "maxDate", null)
                                    .datepicker("setDate", null);
                $("label[for=show_splitdate]").text(L("lcl_cnt_einddatum_new_cnt"));
                $("label[for=cnt_amount]").closest("tr").hide();
            }
        }

      </script>
<%  } %>
  </head>

  <body class="fclt-modal" id="mod_cntsplit">
  <% MODAL_START(); %>
    <form name=u2 action=cnt_split.asp?submit=1&cnt_key=<%=split_info.ingesloten%> method="post">
<%
      MODAL_BLOCK_START("cntSplit", L("lcl_cnt_newversion_make") + (split_info.multi ? "" : split_info.internnr), {icon: "fa-file-plus"});
      RWRADIOTR( "splitmode"
               , { label: L("lcl_cnt_contract_huidig")
                 , initval: "S"
                 , onchange: "zetSplitmode()"
                 , radios: [ {id: "splits",  rval: "S", label: L("lcl_cnt_contract_huidig_split")}
                           , {id: "verleng", rval: "V", label: L("lcl_cnt_contract_huidig_verleng")}
                           ]
                 }
               );

      var defaultdatum = new Date;  // vandaag
      FCLTcalendar( "splitdate",
          { label : L("lcl_cnt_einddatum_old_cnt"),
            datum: defaultdatum,
            initEmpty: (defaultdatum > split_info.maxdate || defaultdatum < split_info.mindate),
            minDate : split_info.mindate,
            maxDate: split_info.maxdate,
            timeField: false,
            autoopen: false,
            required: true
          });

      if (!split_info.multi && split_info.kosten > 0)
        RWFIELDTR("cnt_amount", "fldcntamount fldshort", L("lcl_cnt_eindbedrag_old_cnt") + " " + L("lcl_valutasign"), "", {datatype: "currency"});

      MODAL_BLOCK_END();
      IFACE.FORM_END();
%>
    </form>
<%
SIMPLE_BLOCK_START();
CreateButtons([ { title: L("lcl_submit"), action: "cnt_split_submit()", importance: 1, icon: "fa-fclt-save" },
                { title: L("lcl_cancel"), action: "FcltMgr.closeDetail(window, { cancel: true })",  icon: "fa-fclt-cancel", importance: 3} ]);
SIMPLE_BLOCK_END();
%>
<% MODAL_END(); %>
  </body>
</html><% ASPPAGE_END(); %>
