/**
 * @copyright 2021 Double Bastion LLC <www.doublebastion.com>
 *
 * @author Double Bastion LLC
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

$(document).ready(function() {

  // Get admin settings
  var userid = "<?php p($userId); ?>";
  var baseUrlget = OC.generateUrl('/apps/sms_relentless/user/getadminsettings');

  $.ajax({
     method: 'GET',
     url: baseUrlget + '/' + userid,
     contentType: 'application/json',
     success: function(settingsadm) {

          $("#telapi_key").val(settingsadm.telapi_key);
          $("#tel_pub_key").val(settingsadm.tel_pub_key);
          $("#telapi_url_rec").val(settingsadm.telapi_url_rec);
          $("#telapi_url").val(settingsadm.telapi_url);
          $("#messaging_profile_id").val(settingsadm.messaging_profile_id);
          $("#nexapi_key").val(settingsadm.nexapi_key);
          $("#nexapi_secret").val(settingsadm.nexapi_secret);
          $("#nexapi_url_rec").val(settingsadm.nexapi_url_rec);
          $("#nexapi_url").val(settingsadm.nexapi_url);
          $("#twilapi_key").val(settingsadm.twilapi_key);
          $("#twilapi_secret").val(settingsadm.twilapi_secret);
          $("#twilapi_url_rec").val(settingsadm.twilapi_url_rec);
          $("#twilapi_url").val(settingsadm.twilapi_url);
          $("#flowapi_key").val(settingsadm.flowapi_key);
          $("#flowapi_secret").val(settingsadm.flowapi_secret);
          $("#flowapi_url_rec").val(settingsadm.flowapi_url_rec);
          $("#flowapi_url").val(settingsadm.flowapi_url);
          $("#tel_sender_name").val(settingsadm.tel_sender_name);
          $("#nex_sender_name").val(settingsadm.nex_sender_name);
          $("#twil_sender_name").val(settingsadm.twil_sender_name);

          if (settingsadm.show_all_messages == 1) {
              $("#showallmessages").attr("checked", true);
          } else {
              $("#showallmessages").attr("checked", false);
          }

          var crntadmDispName = settingsadm.admdisplayname;
          var allRestrictions = settingsadm.restrictions;
          var allGroups = settingsadm.allgroups;
          var allUsers = settingsadm.allusers;
          var allGroupswadm = settingsadm.allgroupswadm;
          var allUserswadm = settingsadm.alluserswadm;
          var tnxallowedgrp = settingsadm.allowedkeysuse.tnx_groups_allowed;
          var tnxallowedusr = settingsadm.allowedkeysuse.tnx_users_allowed;
          var plvallowedgrp = settingsadm.allowedkeysuse.plv_groups_allowed;
          var plvallowedusr = settingsadm.allowedkeysuse.plv_users_allowed;
          var twlallowedgrp = settingsadm.allowedkeysuse.twl_groups_allowed;
          var twlallowedusr = settingsadm.allowedkeysuse.twl_users_allowed;
          var flrallowedgrp = settingsadm.allowedkeysuse.flr_groups_allowed;
          var flrallowedusr = settingsadm.allowedkeysuse.flr_users_allowed;

          // List all the groups and users allowed to access the API keys, for each provider
          if (tnxallowedgrp) {
              var tnxallowedgrparr = tnxallowedgrp.split("|");
              for (var g = 0; g < tnxallowedgrparr.length; g++) {
                   $("#alwdakeyGrps-tnx").append("<div class='selectedGrps'>"+ tnxallowedgrparr[g] +"<img id='rmvGrp-tnx-"+ tnxallowedgrparr[g] +"' class='removeGroup' src='/apps/sms_relentless/img/closewnd.svg' title='Remove this group'></div>");
              }
          }

          if (tnxallowedusr) {
              var tnxallowedusrarr = tnxallowedusr.split("|");
              for (var g = 0; g < tnxallowedusrarr.length; g++) {
                   $("#alwdakeyUsrs-tnx").append("<div class='selectedUsrs'>"+ tnxallowedusrarr[g] +"<img id='rmvUsr-tnx-"+ tnxallowedusrarr[g] +"' class='removeUser' src='/apps/sms_relentless/img/closewnd.svg' title='Remove this user'></div>");
              }
          }

          if (plvallowedgrp) {
              var plvallowedgrparr = plvallowedgrp.split("|");
              for (var g = 0; g < plvallowedgrparr.length; g++) {
                   $("#alwdakeyGrps-plv").append("<div class='selectedGrps'>"+ plvallowedgrparr[g] +"<img id='rmvGrp-plv-"+ plvallowedgrparr[g] +"' class='removeGroup' src='/apps/sms_relentless/img/closewnd.svg' title='Remove this group'></div>");
              }
          }

          if (plvallowedusr) {
              var plvallowedusrarr = plvallowedusr.split("|");
              for (var g = 0; g < plvallowedusrarr.length; g++) {
                   $("#alwdakeyUsrs-plv").append("<div class='selectedUsrs'>"+ plvallowedusrarr[g] +"<img id='rmvUsr-plv-"+ plvallowedusrarr[g] +"' class='removeUser' src='/apps/sms_relentless/img/closewnd.svg' title='Remove this user'></div>");
              }
          }

          if (twlallowedgrp) {
              var twlallowedgrparr = twlallowedgrp.split("|");
              for (var g = 0; g < twlallowedgrparr.length; g++) {
                   $("#alwdakeyGrps-twl").append("<div class='selectedGrps'>"+ twlallowedgrparr[g] +"<img id='rmvGrp-twl-"+ twlallowedgrparr[g] +"' class='removeGroup' src='/apps/sms_relentless/img/closewnd.svg' title='Remove this group'></div>");
              }
          }

          if (twlallowedusr) {
              var twlallowedusrarr = twlallowedusr.split("|");
              for (var g = 0; g < twlallowedusrarr.length; g++) {
                   $("#alwdakeyUsrs-twl").append("<div class='selectedUsrs'>"+ twlallowedusrarr[g] +"<img id='rmvUsr-twl-"+ twlallowedusrarr[g] +"' class='removeUser' src='/apps/sms_relentless/img/closewnd.svg' title='Remove this user'></div>");
              }
          }

          if (flrallowedgrp) {
              var flrallowedgrparr = flrallowedgrp.split("|");
              for (var g = 0; g < flrallowedgrparr.length; g++) {
                   $("#alwdakeyGrps-flr").append("<div class='selectedGrps'>"+ flrallowedgrparr[g] +"<img id='rmvGrp-flr-"+ flrallowedgrparr[g] +"' class='removeGroup' src='/apps/sms_relentless/img/closewnd.svg' title='Remove this group'></div>");
              }
          }

          if (flrallowedusr) {
              var flrallowedusrarr = flrallowedusr.split("|");
              for (var g = 0; g < flrallowedusrarr.length; g++) {
                   $("#alwdakeyUsrs-flr").append("<div class='selectedUsrs'>"+ flrallowedusrarr[g] +"<img id='rmvUsr-flr-"+ flrallowedusrarr[g] +"' class='removeUser' src='/apps/sms_relentless/img/closewnd.svg' title='Remove this user'></div>");
              }
          }


          // Create a list with all the available groups, excluding the admin group
          var grpsListItemswadm = "";
          $.each(allGroupswadm, function(key, value) {
                 grpsListItemswadm += "<div class='groupsList'>"+ value +"</div>";
          });

          // Create a list with all the available users, excluding the admins
          var usersListItemswadm = "";
          $.each(allUserswadm, function(key, usrval) {
                 usersListItemswadm += "<div class='usersList'>"+ usrval +"</div>";
          });
          

          function showListsalwdk() {

              // Append the list of available groups to the table of groups and users allowed to use the API keys
              $('[id^="showakeyGrps-"]').click(function() {
                 var crtid = $(this).attr("id").split("-")[1];
                 $("#grpsadapik-"+ crtid).remove();
                 $("#showakeyGrps-"+ crtid).append("<div id='grpsadapik-"+ crtid +"' class='grpsList'>"+ grpsListItemswadm +"</div>");
                 $("#adminOverlay").remove();
                 $("#app-content").append("<div id='adminOverlay'></div>");
                 $("#adminOverlay").css({ "width" : parseInt($("#sms_relentless_adm").width() + 400) +"px", "height" : $("#sms_relentless_adm").height() +"px" });

                 $("#adminOverlay").click(function() { 
                    $("#adminOverlay").remove();
                    $("#grpsadapik-"+ crtid).remove();
                    $("#usrsadapik-"+ crtid).remove();
                 });

                 // Select a group
                 $(".groupsList").click(function() {
                    var slctdGrp = $(this).text();
                    $("#grpsadapik-"+ crtid).remove();
                    var addedTxtgrp = $("#alwdakeyGrps-"+ crtid).text();

                    if (addedTxtgrp.indexOf(slctdGrp) == -1) {
                        $("#alwdakeyGrps-"+ crtid).append("<div class='selectedGrps'>"+ slctdGrp +"<img id='rmvGrp-"+ crtid +"-"+ slctdGrp +"' class='removeGroup' src='/apps/sms_relentless/img/closewnd.svg' title='Remove this group'></div>");
                    } else { showAlert("That group has already been added!"); }

                    // Remove a group from list
                    $('[id^="rmvGrp-"]').click(function() {
                       $(this).closest(".selectedGrps").remove();
                    });
                 });

              });

              // Append the list of available users to the table of groups and users allowed to use the API keys
              $('[id^="showakeyUsrs-"]').click(function() {

                 var crtidusr = $(this).attr("id").split("-")[1];
                 $("#usrsadapik-"+ crtidusr).remove();
                 $("#showakeyUsrs-"+ crtidusr).append("<div id='usrsadapik-"+ crtidusr +"' class='usrsList'>"+ usersListItemswadm +"</div>");
                 $("#adminOverlay").remove();
                 $("#app-content").append("<div id='adminOverlay'></div>");
                 $("#adminOverlay").css({ "width" : parseInt($("#sms_relentless_adm").width() + 400) +"px", "height" : $("#sms_relentless_adm").height() +"px" });

                 $("#adminOverlay").click(function() { 
                    $("#adminOverlay").remove(); 
                    $("#grpsadapik-"+ crtidusr).remove();
                    $("#usrsadapik-"+ crtidusr).remove();
                 });

                 // Select a user
                 $(".usersList").click(function() {
                    var slctdUsr = $(this).text();
                    var addedTxtusr = $("#alwdakeyUsrs-"+ crtidusr).text();

                    if (addedTxtusr.indexOf(slctdUsr) == -1) {
                        $("#alwdakeyUsrs-"+ crtidusr).append("<div class='selectedUsrs'>"+ slctdUsr +"<img id='rmvUsr-"+ crtidusr +"-"+ slctdUsr +"' class='removeUser' src='/apps/sms_relentless/img/closewnd.svg' title='Remove this user'></div>");
                    } else { showAlert("That user has already been added!"); }

                    // Remove a user from list
                    $('[id^="rmvUsr-"]').click(function() {
                       $(this).closest(".selectedUsrs").remove();
                    });
                 });

              });

              // Remove a group from the list 
              $('[id^="rmvGrp-"]').click(function() {
                 $(this).closest(".selectedGrps").remove();
              });

              // Remove a user from the list
              $('[id^="rmvUsr-"]').click(function() {
                 $(this).closest(".selectedUsrs").remove();
              });

          }
          showListsalwdk();


          // Save the data
          function saveAlwdRow() {
             $('[id^="alwdrstsave-"]').unbind("click");
             $('[id^="alwdrstsave-"]').click(function(event) {

                 event.preventDefault();
                 var crntprov = $(this).attr("id").replace("alwdrstsave-", "");
                 
                 if ($(this).attr("value") == "Save") {

                     var selGroups = [];
                     $("#alwdakeyGrps-"+ crntprov +" .selectedGrps").each(function() {
                        selGroups.push($(this).text());
                     });
                     if (selGroups.length == 0) { selGroups.push(""); }

                     var selUsers = [];
                     $("#alwdakeyUsrs-"+ crntprov +" .selectedUsrs").each(function() {
                        selUsers.push($(this).text());
                     });
                     if (selUsers.length == 0) { selUsers.push(""); }

                     // Check if the access key fields have been left empty
                     if (crntprov == 'tnx' && ($("#telapi_key").val().trim() == '' || $("#tel_pub_key").val().trim() == '' || $("#messaging_profile_id").val().trim() == '')) {
                         showAlert("Please first fill in the fields: 'Telnyx API Secret Key', 'Telnyx Account Public Key' and 'Messaging Profile ID'");
                         return;
                     } else if (crntprov == 'plv' && ($("#nexapi_key").val().trim() == '' || $("#nexapi_secret").val().trim() == '')) {
                         showAlert("Please first fill in the fields: 'Plivo Auth ID' and 'Plivo Auth Token'.");
                         return;
                     } else if (crntprov == 'twl' && ($("#twilapi_key").val().trim() == '' || $("#twilapi_secret").val().trim() == '')) {
                         showAlert("Please first fill in the fields: 'Twilio Account SID' and 'Twilio Auth Token'.");
                         return;
                     } else if (crntprov == 'flr' && ($("#flowapi_key").val().trim() == '' || $("#flowapi_secret").val().trim() == '')) {
                         showAlert("Please first fill in the fields: 'Flowroute Access Key' and 'Flowroute Secret Key'.");
                         return;
                     }

                     var saveAlwdUrl = OC.generateUrl('/apps/sms_relentless/user/updatekeysallowedusers');

                     var alwddatatosend = { 
                              userId: userid,
                              groups: selGroups,
                              users: selUsers,
                              provider: crntprov
                     };

	             $.ajax({
	                   method: 'PUT',
	                   url: saveAlwdUrl + '/' + userid,
	                   contentType: 'application/json',
	                   data: JSON.stringify(alwddatatosend),
                           success: function(messagesent) {
                                        if (messagesent == 'success') {
                                            showAlert('The allowed groups and users have been successfully saved to the database!');
                                        } else if (messagesent != 'success' && messagesent != 'failure') {
                                            showAlert(messagesent);
                                        } else if (messagesent == 'failure') {
                                            showAlert('Error while trying to save the allowed groups and users!');
                                        }
                           },
	                   error: function() {
		                        showAlert('Error while attempting to save the allowed groups and users! You can check the Nextcloud log to find more details about this issue.');
	                   }
	             });

                     $(this).attr("value", "Edit");

                } else {

                     $("#alwdrstsave-"+ crntprov).attr("value", "Save");
                }

             });
          }
          saveAlwdRow();



          // Phone number restrictions

          // Create a list with all the available groups
          var grpsListItems = "";
          $.each(allGroups, function(key, value) {
                 grpsListItems += "<div class='groupsList'>"+ value +"</div>";
          });

          // Create a list with all the available users
          var usersListItems = "";
          $.each(allUsers, function(key, usrval) {
                 usersListItems += "<div class='usersList'>"+ usrval +"</div>";
          });


          if (allRestrictions.length > 0) {
              var restrNmb = allRestrictions.length;
          } else {
              var restrNmb = 0;
          }


	  // List the access restrictions for groups and users
          if (restrNmb == 0) {

              $("#phoneNmbrRestr").append("<tr><td><input type='text' class='restrAuthor' value='"+ crntadmDispName +"' disabled></td><td><select id='rstphn-"+ restrNmb +"' class='restrPhoneNmbr'></select></td><td><div id='rstgrp-"+ restrNmb +"' class='restrGroups'></div></td><td><div id='showGrps-"+ restrNmb +"' class='showAllGroups'><img src='/apps/sms_relentless/img/group.svg' style='cursor:pointer' title='Show all groups'></div></td><td><div id='rstusr-"+ restrNmb +"' class='restrUsers'></div></td><td><div id='showUsr-"+ restrNmb +"' class='showAllUsers'><img src='/apps/sms_relentless/img/user.svg' style='cursor:pointer' title='Show all users'></div></td><td><img id='rmRow-"+ restrNmb +"' class='removeRow' src='/apps/sms_relentless/img/closewnd.svg' title='Remove this row from the database' style='cursor:pointer;margin:6px 7px 0px 6px;'></td><td><input type='submit' id='rstsave-"+ restrNmb +"' class='saveRestrictions' value='Save' title='Save Row' /></td></tr>");
	      $("#phoneNmbrRestr").append("<div><img id='addRestrRow' src='/apps/sms_relentless/img/add.svg' title='Add Row'></div>");

          } else {

	      for (k = 0; k < restrNmb; k++) {

                   if (allRestrictions[k].groups) {
                       var groupsfdbpre = allRestrictions[k].groups.split("|");
                       var groupsfdb = "";
                       for (var g = 0; g < groupsfdbpre.length; g++) {
                            groupsfdb += "<div class='selectedGrps'>"+ groupsfdbpre[g] +"<img id='rmvGrp-"+ groupsfdbpre[g] +"' class='removeGroup' src='/apps/sms_relentless/img/closewnd.svg' title='Remove this group'></div>";
                       }
                   } else { var groupsfdb = ""; }

                   if (allRestrictions[k].users) {
                       var usersfdbpre = allRestrictions[k].users.split("|");
                       var usersfdb = "";
                       for (var u = 0; u < usersfdbpre.length; u++) {
                            usersfdb += "<div class='selectedUsrs'>"+ usersfdbpre[u] +"<img id='rmvUsr-"+ usersfdbpre[u] +"' class='removeUser' src='/apps/sms_relentless/img/closewnd.svg' title='Remove this user'></div>";
                       }
                   } else { var usersfdb = ""; }

		   $("#phoneNmbrRestr").append("<tr><td><input type='text' class='restrAuthor' value='"+ allRestrictions[k].saved_by_dsplname +"' disabled></td><td><select id='rstphn-"+ k +"' class='restrPhoneNmbr' style='pointer-events:none'><option selected>"+ allRestrictions[k].phone_number +"</option></select></td><td><div id='rstgrp-"+ k +"' class='restrGroups'>"+ groupsfdb +"</div></td><td><div id='showGrps-"+ k +"' class='showAllGroups'><img src='/apps/sms_relentless/img/group.svg' style='cursor:pointer' title='Show all groups'></div></td><td><div id='rstusr-"+ k +"' class='restrUsers'>"+ usersfdb +"</div></td><td><div id='showUsr-"+ k +"' class='showAllUsers'><img src='/apps/sms_relentless/img/user.svg' style='cursor:pointer' title='Show all users'></div></td><td><img id='rmRow-"+ k +"' class='removeRow' src='/apps/sms_relentless/img/closewnd.svg' title='Remove this row from the database' style='cursor:pointer;margin:6px 7px 0px 6px;'></td><td><input type='submit' id='rstsave-"+ k +"' class='saveRestrictions' value='Edit' title='Edit Row' /></td></tr>");
              }
              $("#phoneNmbrRestr").append("<div><img id='addRestrRow' src='/apps/sms_relentless/img/add.svg' title='Add Row'></div>");
          }


          // Get the available phone numbers from all providers associated with the access keys entered on the Settings page
          $("#phoneNumberTh").addClass('icon-loading');
          var getnumbersUrl = OC.generateUrl("/apps/sms_relentless/user/getsmsnumbers");
          var numbersListItems = '';

	  $.ajax({
		  url: getnumbersUrl + '/' + userid,
		  type: "POST",
		  cache: false,
		  processData: false,
		  contentType: false,
		  success: function(currentnmbrs) {

                                    $("#phoneNumberTh").removeClass('icon-loading');

				    // Create a list with all the available phone numbers
                                    numbersListItems = "<option value='' selected>Select phone number</option>";

				    $.each(currentnmbrs, function(key, indsmsnmb) {
					   numbersListItems += "<option value='"+ indsmsnmb +"'>"+ indsmsnmb +"</option>";
				    });

				    if (restrNmb == 0) { var indRow = 0; } else { var indRow = parseInt(restrNmb + 1); }

				    // Append the list of available phone numbers
				    $("#rstphn-"+ indRow).empty();
				    $("#rstphn-"+ indRow).append(numbersListItems);
        
		  },
		  error: function() {
                                    $("#phoneNumberTh").removeClass('icon-loading'); 
                                    showAlert("Error while attempting to retrieve the available phone numbers!");
                  }
          });


          function showLists() {

              // Append the list of available groups to the restrictions table
              $('[id^="showGrps-"]').click(function() {
                 var crtnmbr = $(this).attr("id").replace("showGrps-", "");
                 $("#grpL-"+ crtnmbr).remove();
                 $("#showGrps-"+ crtnmbr).append("<div id='grpL-"+ crtnmbr +"' class='grpsList'>"+ grpsListItems +"</div>");
                 $("#adminOverlay").remove();
                 $("#app-content").append("<div id='adminOverlay'></div>");
                 $("#adminOverlay").css({ "width" : parseInt($("#sms_relentless_adm").width() + 400) +"px", "height" : $("#sms_relentless_adm").height() +"px" });

                 $("#adminOverlay").click(function() { 
                    $("#adminOverlay").remove(); 
                    $("#grpL-"+ crtnmbr).remove(); 
                    $("#usrL-"+ crtnmbr).remove();
                 });

                 // Select a group
                 $(".groupsList").click(function() {
                    var slctdGrp = $(this).text();
                    $("#grpL-"+ crtnmbr).remove();
                    var addedTxtgrp = $("#rstgrp-"+ crtnmbr).text();

                    if (addedTxtgrp.indexOf(slctdGrp) == -1) {
                        $("#rstgrp-"+ crtnmbr).append("<div class='selectedGrps'>"+ slctdGrp +"<img id='rmvGrp-"+ slctdGrp +"' class='removeGroup' src='/apps/sms_relentless/img/closewnd.svg' title='Remove this group'></div>");
                    } else { showAlert("That group has already been added!"); }

                    // Remove a group from list
                    $('[id^="rmvGrp-"]').click(function() {
                       $(this).closest(".selectedGrps").remove();
                    });
                 });

              });

              // Append the list of available users to the restrictions table
              $('[id^="showUsr-"]').click(function() {

                 var ctusrnmbr = $(this).attr("id").replace("showUsr-", "");
                 $("#usrL-"+ ctusrnmbr).remove();
                 $("#showUsr-"+ ctusrnmbr).append("<div id='usrL-"+ ctusrnmbr +"' class='usrsList'>"+ usersListItems +"</div>");
                 $("#adminOverlay").remove();
                 $("#app-content").append("<div id='adminOverlay'></div>");
                 $("#adminOverlay").css({ "width" : parseInt($("#sms_relentless_adm").width() + 400) +"px", "height" : $("#sms_relentless_adm").height() +"px" });

                 $("#adminOverlay").click(function() { 
                    $("#adminOverlay").remove(); 
                    $("#grpL-"+ ctusrnmbr).remove(); 
                    $("#usrL-"+ ctusrnmbr).remove();
                 });

                 // Select a user
                 $(".usersList").click(function() {
                    var slctdUsr = $(this).text();
                    var addedTxtusr = $("#rstusr-"+ ctusrnmbr).text();

                    if (addedTxtusr.indexOf(slctdUsr) == -1) {
                        $("#rstusr-"+ ctusrnmbr).append("<div class='selectedUsrs'>"+ slctdUsr +"<img id='rmvUsr-"+ slctdUsr +"' class='removeUser' src='/apps/sms_relentless/img/closewnd.svg' title='Remove this user'></div>");
                    } else { showAlert("That user has already been added!"); }

                    // Remove a user from list
                    $('[id^="rmvUsr-"]').click(function() {
                       $(this).closest(".selectedUsrs").remove();
                    });
                 });

              });

              // Remove a group from the list 
              $('[id^="rmvGrp-"]').click(function() {
                 $(this).closest(".selectedGrps").remove();
              });

              // Remove a user from the list
              $('[id^="rmvUsr-"]').click(function() {
                 $(this).closest(".selectedUsrs").remove();
              });

          }
          showLists();


          // Save the data
          function saveRestrRow() {
             $('[id^="rstsave-"]').unbind("click");
             $('[id^="rstsave-"]').click(function(event) {

                 event.preventDefault();
                 var crntrwnmbr = $(this).attr("id").replace("rstsave-", "");

                 if ($(this).attr("value") == "Save") {

                     var phoneNmbr = $("#rstphn-"+ crntrwnmbr).val();
                     var slctdGroups = [];
                     $("#rstgrp-"+ crntrwnmbr +" .selectedGrps").each(function() {
                        slctdGroups.push($(this).text());
                     });
                     var slctdUsers = [];
                     $("#rstusr-"+ crntrwnmbr +" .selectedUsrs").each(function() {
                        slctdUsers.push($(this).text());
                     });

                     if (phoneNmbr != '') {

                       if (slctdGroups.length > 0 || slctdUsers.length > 0) {

                         var saveRestrUrl = OC.generateUrl('/apps/sms_relentless/user/updatenumberrestrictions');

                         var datatosend = { 
                              userId: userid,
                              savedByDsplname: crntadmDispName,
                              phoneNumber: phoneNmbr,
                              groups: slctdGroups,
                              users: slctdUsers
                         };

	                 $.ajax({
	                   method: 'PUT',
	                   url: saveRestrUrl + '/' + userid,
	                   contentType: 'application/json',
	                   data: JSON.stringify(datatosend),
                           success: function(messagetosend) {
                                        if (messagetosend == 'success') {
                                            showAlert('The restrictions have been successfully saved to the database!');
                                        } else {
                                            showAlert('Error while trying to save the restrictions!');
                                        }
                           },
	                   error: function() {
		                        showAlert('Error while attempting to save the restrictions! You can check the Nextcloud log to find more details about this issue.');
	                   }
	                 });

                       } else { showAlert("You must select at least a group or a user in order to restrict the use of a phone number."); return; }

                     } else { showAlert("Please select a phone number!"); return; }

                     $(this).attr("value", "Edit");

                } else {

                     $("#rstsave-"+ crntrwnmbr).attr("value", "Save");
                }

             });
          }
          saveRestrRow();

          // Remove a row
          function removeRestrRow() {

               $('[id^="rmRow-"]').click(function() {

                  var slctRowRmv = $(this).attr("id").replace("rmRow-", "");
                  var crntPhNmbr = $("#rstphn-"+ slctRowRmv).val();

                  confirmAlert("Do you really want to remove this row from the database ?");

                  $("#confirmCancel").click(function() { $("#alertMsgOverlay").remove(); $("#alertConfMessage").remove(); });

                  $("#confirmOk").click(function() {

                      $("#alertMsgOverlay").remove();
                      $("#alertConfMessage").remove();

                      var rmvRestrUrl = OC.generateUrl('/apps/sms_relentless/user/removenumberrestrictions');
                      $.ajax({
                           url: rmvRestrUrl + '/' + userid,
                           method: "POST",
                           dataType: "text",
                           data: { phoneNumber: crntPhNmbr },
                           success: function(delresult) {

                                             if (delresult.indexOf("success") > -1) {
                                                 showAlert("The restriction has been removed successfully!");
                                                 $("#rstphn-"+ slctRowRmv).closest("tr").remove();
                                             } else {
                                                 showAlert("Error while trying to remove restriction data!");
                                             }
                           },
                           error: function() { showAlert("Error while attempting to remove restriction data! You can check the Nextcloud log to find more details about this issue."); }
                       });
                  });
               });
          }
          removeRestrRow();

          // Add a new row
	  $("#addRestrRow").click(function() {
              if ($("#phoneNmbrRestr").find("tr:last-child").find(".restrPhoneNmbr").length > 0) {
                  var lastrstAuth = $("#phoneNmbrRestr").find("tr:last-child").find(".restrPhoneNmbr").attr("id").replace("rstphn-", "");
                  var indRowAdd = parseInt(lastrstAuth + 1);
              } else { var indRowAdd = 0; }
	      $("#phoneNmbrRestr").append("<tr><td><input type='text' class='restrAuthor' value='"+ crntadmDispName +"' disabled></td><td><select id='rstphn-"+ indRowAdd +"' class='restrPhoneNmbr'>"+ numbersListItems +"</select></td><td><div id='rstgrp-"+ indRowAdd +"' class='restrGroups'></div></td><td><div id='showGrps-"+ indRowAdd +"' class='showAllGroups'><img src='/apps/sms_relentless/img/group.svg' style='cursor:pointer' title='Show all groups'></div></td><td><div id='rstusr-"+ indRowAdd +"' class='restrUsers'></div></td><td><div id='showUsr-"+ indRowAdd +"' class='showAllUsers'><img src='/apps/sms_relentless/img/user.svg' style='cursor:pointer' title='Show all users'></div></td><td><img id='rmRow-"+ indRowAdd +"' class='removeRow' src='/apps/sms_relentless/img/closewnd.svg' title='Remove this row from the database' style='cursor:pointer;margin:6px 7px 0px 6px;'></td><td><input type='submit' id='rstsave-"+ indRowAdd +"' class='saveRestrictions' value='Save' title='Save Row' /></td></tr>");
              showLists();
              saveRestrRow();
              removeRestrRow();

              // Check if the same phone number has been already restricted
              $("#rstphn-"+ indRowAdd).change(function() {
                 var selectedPhNmbr = $("#rstphn-"+ indRowAdd).val();
                 var allPHoneRestr = $("#phoneNmbrRestr").find("tr").find(".restrPhoneNmbr");
                 var phNmbrChck = 0;
                 allPHoneRestr.each(function() {
                    var slctdphnmbr = ($(this).val())? $(this).val() : $(this).text();
                    if (selectedPhNmbr == slctdphnmbr) { phNmbrChck++; }
                 });

                 if (phNmbrChck == 2) {
                     showAlert("This phone number is already in the list of restricted phone numbers. Please edit its own row, or choose a different phone number to restrict.");
                     $(this).val('');
                     return;
                 }
              });
	  });

     },
     error: function() {
                showAlert('Error while getting the admin settings! You can check the Nextcloud log to find more details about this issue.');
     }
  });



  // Save admin settings
  function randomStr(strlength) {
        var fintext = "";
        var keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        for (var i = 0; i < strlength; i++) {
             fintext += keyspace.charAt(Math.floor(Math.random() * keyspace.length));
        }
        return fintext;
  }

  $("#generate_tel_rcpt").on("click", function(event) {

     var teltokenrec = randomStr(70);
     var telnyxwhurlrec = window.location.origin + OC.generateUrl('/apps/sms_relentless/api/recsmstel?telrecparam=') + teltokenrec;

     $("#telapi_url_rec").val(telnyxwhurlrec);
  });

  $("#copyToClipboardtel").on("click", function(event) {
     var $tempEl = $("<input>");
     $("body").append($tempEl);
     $tempEl.val($("#telapi_url_rec").val()).select();
     document.execCommand("Copy");
     $tempEl.remove();
     showAlert("The link has been copied to your clipboard!");
  });

  $("#generate_tel_delrcpt").on("click", function(event) {

     var teltoken = randomStr(70);
     var telnyxwhurl = window.location.origin + OC.generateUrl('/apps/sms_relentless/api/recdeliverytel?teldrparam=') + teltoken;

     $("#telapi_url").val(telnyxwhurl);
  });

  $("#generate_nex_rcpt").on("click", function(event) {

     var plivotokenrec = randomStr(70);
     var plivowhurlrec = window.location.origin + OC.generateUrl('/apps/sms_relentless/api/recsmsnex?plivorecparam=') + plivotokenrec;

     $("#nexapi_url_rec").val(plivowhurlrec);
  });

  $("#copyToClipboardnex").on("click", function(event) {
     var $tempElpl = $("<input>");
     $("body").append($tempElpl);
     $tempElpl.val($("#nexapi_url_rec").val()).select();
     document.execCommand("Copy");
     $tempElpl.remove();
     showAlert("The link has been copied to your clipboard!");
  });

  $("#generate_nex_delrcpt").on("click", function(event) {

     var plivotoken = randomStr(70);
     var plivodrwhurl = window.location.origin + OC.generateUrl('/apps/sms_relentless/api/recdeliverynex?plivodrparam=') + plivotoken;

     $("#nexapi_url").val(plivodrwhurl);
  });

  $("#generate_twil_rcpt").on("click", function(event) {

     var twiltokenrec = randomStr(35);
     var twilwhurlrec = window.location.origin + OC.generateUrl('/apps/sms_relentless/api/recsmstwil?twilrecparam=') + twiltokenrec;

     $("#twilapi_url_rec").val(twilwhurlrec);
  });

  $("#copyToClipboardtwil").on("click", function(event) {
     var $tempElpl = $("<input>");
     $("body").append($tempElpl);
     $tempElpl.val($("#twilapi_url_rec").val()).select();
     document.execCommand("Copy");
     $tempElpl.remove();
     showAlert("The link has been copied to your clipboard!");
  });

  $("#generate_twil_delrcpt").on("click", function(event) {

     var twiltoken = randomStr(35);
     var twildrwhurl = window.location.origin + OC.generateUrl('/apps/sms_relentless/api/recdeliverytwil?twildrparam=') + twiltoken;

     $("#twilapi_url").val(twildrwhurl);
  });

  $("#generate_flow_rcpt").on("click", function(event) {

     var flowtokenrec = randomStr(70);
     var flowwhurlrec = window.location.origin + OC.generateUrl('/apps/sms_relentless/api/recsmsflow?flowrecparam=') + flowtokenrec;

     $("#flowapi_url_rec").val(flowwhurlrec);
  });

  $("#copyToClipboardflow").on("click", function(event) {
     var $tempElpl = $("<input>");
     $("body").append($tempElpl);
     $tempElpl.val($("#flowapi_url_rec").val()).select();
     document.execCommand("Copy");
     $tempElpl.remove();
     showAlert("The link has been copied to your clipboard!");
  });

  $("#generate_flow_delrcpt").on("click", function(event) {

     var flowtoken = randomStr(70);
     var flowdrwhurl = window.location.origin + OC.generateUrl('/apps/sms_relentless/api/recdeliveryflow?flowdrparam=') + flowtoken;

     $("#flowapi_url").val(flowdrwhurl);
  });


  $("#save_admin_settings").on("click", function(event) {

    event.preventDefault();
    OC.msg.startAction('#smsr_save_msg', t('sms_relentless', 'Saved'));

    var baseUrlsv = OC.generateUrl('/apps/sms_relentless/user/updateadminsettings');

    var showallmsgs = 0;
    if ($("#showallmessages").is(':checked')) {
        showallmsgs = 1;
    }

    var telsenderinit = $("#tel_sender_name").val();
    var telsenderproc = telsenderinit.replace(/[^A-Za-z 0-9]/g, '');

    var nexsenderinit = $("#nex_sender_name").val();
    var nexsenderproc = nexsenderinit.replace(/[^A-Za-z 0-9]/g, '');

    var twilsenderinit = $("#twil_sender_name").val();
    var twilsenderproc = twilsenderinit.replace(/[^A-Za-z 0-9]/g, '');

    var datatosave = {
                      userId: userid,
                      telapiKey: $("#telapi_key").val(),
                      telPubKey: $("#tel_pub_key").val(),
                      telapiUrlRec: $("#telapi_url_rec").val(),
                      telapiUrl: $("#telapi_url").val(),
                      messagingProfileId: $("#messaging_profile_id").val(),
                      nexapiKey: $("#nexapi_key").val(),
                      nexapiSecret: $("#nexapi_secret").val(),
                      nexapiUrlRec: $("#nexapi_url_rec").val(),
                      nexapiUrl: $("#nexapi_url").val(),
                      twilapiKey: $("#twilapi_key").val(),
                      twilapiSecret: $("#twilapi_secret").val(),
                      twilapiUrlRec: $("#twilapi_url_rec").val(),
                      twilapiUrl: $("#twilapi_url").val(),
                      flowapiKey: $("#flowapi_key").val(),
                      flowapiSecret: $("#flowapi_secret").val(),
                      flowapiUrlRec: $("#flowapi_url_rec").val(),
                      flowapiUrl: $("#flowapi_url").val(),
                      telSenderName: telsenderproc,
                      nexSenderName: nexsenderproc,
                      twilSenderName: twilsenderproc,
                      showAllMessages: showallmsgs
    };


    $.ajax({
       method: 'PUT',
       url: baseUrlsv + '/' + userid,
       contentType: 'application/json',
       data: JSON.stringify(datatosave),
       success: function() {
       },
       error: function() {
            showAlert('Error while attempting to save the settings! You can check the Nextcloud log to find more details about this issue.');
       }
    });

  });

  function showAlert(alertText) {

     let alertwnd = "<div id='alertMessage'>";
     alertwnd += "<a id='closeAlertWnd' title='Close this window'></a>";
     alertwnd += "<div id='alertTextWrap'>"+ alertText +"</div>";
     alertwnd += "<input type='submit' id='alertOk' value='OK'>";
     alertwnd += "</div>";

     $("#content").append("<div id='alertMsgOverlay'></div>");
     $("#content").append(alertwnd);

     let topDist = parseInt((window.innerHeight / 2).toFixed(2) - 152) +"px";
     let leftDist = parseInt((window.innerWidth / 2).toFixed(2) - 150) +"px";
     $("#alertMessage").css({ "top" : topDist, "left" : leftDist });

     $("#closeAlertWnd").click(function() { $("#alertMsgOverlay").remove(); $("#alertMessage").remove(); });
     $("#alertMsgOverlay").click(function() { $("#alertMsgOverlay").remove(); $("#alertMessage").remove(); });
     $("#alertOk").click(function() { $("#alertMsgOverlay").remove(); $("#alertMessage").remove(); });
  }

  function confirmAlert(alertText) {

     let alertwndcf = "<div id='alertConfMessage'>";
     alertwndcf += "<a id='closeAlertWndcf' title='Close this window'></a>";
     alertwndcf += "<div id='alertTextWrap'>"+ alertText +"</div>";
     alertwndcf += "<div id='cancelOkWrap'><input type='submit' id='confirmCancel' value='Cancel'>";
     alertwndcf += "<input type='submit' id='confirmOk' value='OK'></div>";
     alertwndcf += "</div>";

     $("#content").append("<div id='alertMsgOverlay'></div>");
     $("#content").append(alertwndcf);

     let topDist = parseInt((window.innerHeight / 2).toFixed(2) - 152) +"px";
     let leftDist = parseInt((window.innerWidth / 2).toFixed(2) - 150) +"px";
     $("#alertConfMessage").css({ "top" : topDist, "left" : leftDist });

     $("#closeAlertWndcf").click(function() { $("#alertMsgOverlay").remove(); $("#alertConfMessage").remove(); });
     $("#alertMsgOverlay").click(function() { $("#alertMsgOverlay").remove(); $("#alertConfMessage").remove(); });
  }

});
