/**
 * @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() {

  var userid = "<?php p($userId); ?>";
  var isadm = '';

  // Get personal settings
  var baseUrlget = OC.generateUrl('/apps/sms_relentless/user/getsettings');

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

         // Add the webhook URLs section, if the user is not an admin
         if (settingsfromdb.adminornot == 'reguser') {

             isadm = 'reguser';

             $("#appTitlePrg").append('<p id="settings-dscr"><h3>Enter your options in the fields from below. As a non-admin user, you can use any of the SMS service providers from \
                  below (Telnyx/Plivo/Twilio/Flowroute), on the condition that an admin has shared with you his API keys for that provider. If an admin has shared with you his API \
                  keys for a provider, to be able to use them properly, you will have to generate the two webhook URLs for that provider by clicking the corresponding \
                  "Generate new webhook URL ..." buttons from below, then click "Save" at the bottom of this page:</h3></p><br>');

             $("#nadmProvSection").append('<div class="providerSettings"><p><label for="telapi_url_rec" class="setlabeltext"><b>Telnyx webhook URL for incoming SMS/MMS</b> (Generate \
                  the URL by pressing the button from below. Don\'t forget to also click the \'Save\' button at the bottom of this page after entering all the options, to save \
                  all the settings to the database.)</label></p> \
                  <input type="button" id="generate_tel_rcpt" class="generateUrl" value="Generate new webhook URL for incoming SMS/MMS" /> \
                  <input type="text" class="smsr_textboxspec" id="telapi_url_rec" name="telapi_url_rec" autocomplete="false" /> \
                  <span id="copyToClipboardtel" class="icon icon-clippy" title="Copy to clipboard"></span><br><br> \
                  \
                  <p><label for="telapi_url" class="setlabeltext"><b>Telnyx webhook URL for delivery receipts</b> (This URL will be included by SMS Relentless in message sending \
                  requests, so that Telnyx will know where to send the delivery receipts. Just generate it by pressing the button from below. Don\'t forget to click the \'Save\' \
                  button at the bottom of this page after entering all the options, to save all the settings to the database.)</label></p> \
                  <input type="button" id="generate_tel_delrcpt" class="generateUrl" value="Generate new webhook URL for delivery receipts" /> \
                  <input type="text" id="telapi_url" name="telapi_url" autocomplete="false" /></div><br><br> \
                  \
                  <div class="providerSettings"><p><label for="nexapi_url_rec" class="setlabeltext"><b>Plivo webhook URL for incoming SMS/MMS</b> (Generate the URL by pressing \
                  the button from below. Don\'t forget to also click the \'Save\' button at the bottom of this page after entering all the options, to save all the settings \
                  to the database.)</label></p> \
                  <input type="button" id="generate_nex_rcpt" class="generateUrl" value="Generate new webhook URL for incoming SMS/MMS" /> \
                  <input type="text" class="smsr_textboxspec" id="nexapi_url_rec" name="nexapi_url_rec" autocomplete="false" /> \
                  <span id="copyToClipboardnex" class="icon icon-clippy" title="Copy to clipboard"></span><br><br> \
                  \
                  <p><label for="nexapi_url" class="setlabeltext"><b>Plivo webhook URL for delivery receipts</b> (This URL will be included by SMS Relentless in message sending \
                  requests, so that Plivo will know where to send the delivery receipts. Just generate it by pressing the button from below. Don\'t forget to click the \'Save\' \
                  button at the bottom of this page after entering all the options, to save all the settings to the database.)</label></p> \
                  <input type="button" id="generate_nex_delrcpt" class="generateUrl" value="Generate new webhook URL for delivery receipts" /> \
                  <input type="text" id="nexapi_url" name="nexapi_url" autocomplete="false" /></div><br><br> \
                  \
                  <div class="providerSettings"><p><label for="twilapi_url_rec" class="setlabeltext"><b>Twilio webhook URL for incoming SMS/MMS</b> (Generate the URL by pressing \
                  the button from below. Don\'t forget to also click the \'Save\' button at the bottom of this page after entering all the options, to save all the settings to \
                  the database.)</label></p> \
                  <input type="button" id="generate_twil_rcpt" class="generateUrl" value="Generate new webhook URL for incoming SMS/MMS" /> \
                  <input type="text" class="smsr_textboxspec" id="twilapi_url_rec" name="twilapi_url_rec" autocomplete="false" /> \
                  <span id="copyToClipboardtwil" class="icon icon-clippy" title="Copy to clipboard"></span><br><br> \
                  \
                  <p><label for="twilapi_url" class="setlabeltext"><b>Twilio webhook URL for delivery receipts</b> (This URL will be included by SMS Relentless in message sending \
                  requests, so that Twilio will know where to send the delivery receipts. Just generate it by pressing the button from below. Don\'t forget to click the \'Save\' \
                  button at the bottom of this page after entering all the options, to save all the settings to the database.)</label></p> \
                  <input type="button" id="generate_twil_delrcpt" class="generateUrl" value="Generate new webhook URL for delivery receipts" /> \
                  <input type="text" id="twilapi_url" name="twilapi_url" autocomplete="false" /></div><br><br> \
                  \
                  <div class="providerSettings"><p><label for="flowapi_url_rec" class="setlabeltext"><b>Flowroute webhook URL for incoming SMS/MMS</b> (Generate the URL by pressing \
                  the button from below. Don\'t forget to also click the \'Save\' button at the bottom of this page after entering all the options, to save all the settings to \
                  the database.)</label></p> \
                  <input type="button" id="generate_flow_rcpt" class="generateUrl" value="Generate new webhook URL for incoming SMS/MMS" /> \
                  <input type="text" class="smsr_textboxspec" id="flowapi_url_rec" name="flowapi_url_rec" autocomplete="false" /> \
                  <span id="copyToClipboardflow" class="icon icon-clippy" title="Copy to clipboard"></span><br><br> \
                  \
                  <p><label for="flowapi_url" class="setlabeltext"><b>Flowroute webhook URL for delivery receipts</b> (This URL will be included by SMS Relentless in message sending \
                  requests, so that Flowroute will know where to send the delivery receipts. Just generate it by pressing the button from below. Don\'t forget to click the \'Save\' \
                  button at the bottom of this page after entering all the options, to save all the settings to the database.)</label></p> \
                  <input type="button" id="generate_flow_delrcpt" class="generateUrl" value="Generate new webhook URL for delivery receipts" /> \
                  <input type="text" id="flowapi_url" name="flowapi_url" autocomplete="false" /><br><br> \
                  Flowroute only supports sending/receiving SMS/MMS messages within USA and Canada and it doesn\'t support Alphanumeric Sender IDs.</div><br>');


		  $("#telapi_url_rec").val(settingsfromdb.telapi_url_rec);
		  $("#telapi_url").val(settingsfromdb.telapi_url);
		  $("#nexapi_url_rec").val(settingsfromdb.nexapi_url_rec);
		  $("#nexapi_url").val(settingsfromdb.nexapi_url);
		  $("#twilapi_url_rec").val(settingsfromdb.twilapi_url_rec);
		  $("#twilapi_url").val(settingsfromdb.twilapi_url);
		  $("#flowapi_url_rec").val(settingsfromdb.flowapi_url_rec);
		  $("#flowapi_url").val(settingsfromdb.flowapi_url);
		  $("#messagesperpage").val(settingsfromdb.messagesperpage);

		  if (settingsfromdb.get_notify == 1) {
		      $("#get_notify").attr('checked', true);
		  } else {
		      $("#get_notify").attr('checked', false);
		  }

		  $("#notification_email").val(settingsfromdb.notification_email);

		  if (settingsfromdb.getsmsinemail == 1) {
		      $("#includesmsinemail").attr('checked', true);
		  } else {
		      $("#includesmsinemail").attr('checked', false);
		  }

		  if (settingsfromdb.show_display_names == 1) {
		      $("#showdisplaynames").attr('checked', true);
		  } else {
		      $("#showdisplaynames").attr('checked', false);
		  }

		  if (settingsfromdb.add_display_names == 1) {
		      $("#adddisplaynames").attr('checked', true);
		  } else {
		      $("#adddisplaynames").attr('checked', false);
		  }

		  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);
		  });


         } else if (settingsfromdb.adminornot == 'admin') {

                  $("#appTitlePrg").append('<p id="settings-dscr"><h3>Enter your options in the fields from below:</h3></p><br>');
                  isadm = 'admin';

		  $("#messagesperpage").val(settingsfromdb.messagesperpage);

		  if (settingsfromdb.get_notify == 1) {
		      $("#get_notify").attr('checked', true);
		  } else {
		      $("#get_notify").attr('checked', false);
		  }

		  $("#notification_email").val(settingsfromdb.notification_email);

		  if (settingsfromdb.getsmsinemail == 1) {
		      $("#includesmsinemail").attr('checked', true);
		  } else {
		      $("#includesmsinemail").attr('checked', false);
		  }

		  if (settingsfromdb.show_display_names == 1) {
		      $("#showdisplaynames").attr('checked', true);
		  } else {
		      $("#showdisplaynames").attr('checked', false);
		  }

		  if (settingsfromdb.add_display_names == 1) {
		      $("#adddisplaynames").attr('checked', true);
		  } else {
		      $("#adddisplaynames").attr('checked', false);
		  }
         }


         // Auto-reply settings

         // Get the available phone numbers from all providers associated with the access keys entered on the Settings page (restrictions are applied to numbers for non-admins)
         $("#autoRplPhoneNb").addClass('icon-loading');
         var getnumbersUrl = OC.generateUrl("/apps/sms_relentless/user/getautoreplyconf");

	 $.ajax({
		  url: getnumbersUrl + '/' + userid,
		  type: "GET",
                  contentType: 'application/json',
		  success: function(autoreplydata) {

                                    $("#autoRplPhoneNb").removeClass('icon-loading');
                                    var cusrDisplayName = autoreplydata.userdisplayname;
                                    var availPhoneNmbrs = autoreplydata.phonenumbers;
                                    var autorpldata = autoreplydata.autoreplies;

				    if (autorpldata.length > 0) { 
				        var arplNmb = autorpldata.length;
				    } else { 
				        var arplNmb = 0; 
				    }

				    // List the auto-replies for the phone numbers available for the current user
				    if (arplNmb == 0) {

				        $("#autoReplyTbl").append("<tr><td><input type='text' class='arplAuthor' value='"+ cusrDisplayName +"' disabled></td><td><select id='arpphn-"+ arplNmb +"' class='arplPhoneNmbr'></select></td><td><div id='arplmode-"+ arplNmb +"' class='arplMode'><select id='modeselect-"+ arplNmb +"' class='selectArplMode'><option value='' selected>Select mode</option><option value='daily'>Daily mode</option><option value='vacation'>Vacation mode</option></select><div id='modecont-"+ arplNmb +"' class='modeContent'></div></div></td><td><textarea id='arpltxt-"+ arplNmb +"' class='arplText' rows='20' cols='40' placeholder='Enter the auto-reply message here.'></textarea></td><td><img id='rmRow-"+ arplNmb +"' class='removeRow' src='/apps/sms_relentless/img/closewnd.svg' title='Remove this row from the database' style='cursor:pointer;margin:9px 8px 0px 18px;'></td><td><input type='submit' id='arplsave-"+ arplNmb +"' class='saveAutoReply' value='Save' title='Save Row' /></td></tr>");
				        $("#autoReplyTbl").append("<div><img id='addArplRow' src='/apps/sms_relentless/img/add.svg' title='Add Row'></div>");

				    } else {

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

                                             if (autorpldata[k].days_of_week != '') {

                                                 var slctdMode = "<option value=''>Select mode</option><option value='daily' selected>Daily mode</option><option value='vacation'>Vacation mode</option>";
                                                 var dailyStartArr = autorpldata[k].daily_start.split(":");
                                                 var dailyEndArr = autorpldata[k].daily_end.split(":");

		                                 var dlHrStartOptions = "";
			                         for (var hr = 0; hr < 24; hr++) {
		                                      if (dailyStartArr[0] != hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false})) {
			                                  dlHrStartOptions += "<option value='"+ hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"'>"+ hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                                      } else {
			                                  dlHrStartOptions += "<option value='"+ hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"' selected>"+ hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                                      }
			                         }

		                                 var dlMnStartOptions = "";
			                         for (var mn = 0; mn < 60; mn++) {
		                                      if (dailyStartArr[1] != mn.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false})) {
			                                  dlMnStartOptions += "<option value='"+ mn.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"'>"+ mn.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                                      } else {
			                                  dlMnStartOptions += "<option value='"+ mn.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"' selected>"+ mn.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                                      }
			                         }

		                                 var dlHrEndOptions = "";
			                         for (var hr = 0; hr < 24; hr++) {
		                                      if (dailyEndArr[0] != hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false})) {
			                                  dlHrEndOptions += "<option value='"+ hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"'>"+ hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                                      } else {
			                                  dlHrEndOptions += "<option value='"+ hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"' selected>"+ hr.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                                      }
			                         }

		                                 var dlMnEndOptions = "";
			                         for (var mn = 0; mn < 60; mn++) {
		                                      if (dailyEndArr[1] != mn.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false})) {
			                                  dlMnEndOptions += "<option value='"+ mn.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"'>"+ mn.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                                      } else {
			                                  dlMnEndOptions += "<option value='"+ mn.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"' selected>"+ mn.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                                      }
			                         }

                                                 var modeContent = "<div class='daysOfWeek'>Days of the week:<div class='tooltipautoreply'><div id='infoautoreply'>i</div><div class='autorpltooltip'>Enter the order number of the days of the week in which the auto-reply will be sent. For example, to send the auto-reply every day from Monday to Friday outside the time interval specified below, enter 1,2,3,4,5 To send the auto-reply only Monday, Thursday and Friday enter 1,4,5 To send the auto-reply every day of the week enter 1,2,3,4,5,6,7 As an exception, if you want the auto-reply to be sent during an entire day, irrespective of the specified interval, add (full) after the number of that day. For example, if you want the auto-reply to be sent from Monday to Friday outside the interval specified below, and also during the entire days of Saturday and Sunday, enter 1,2,3,4,5,6(full),7(full)</div></div></div><input type='text' id='weekdays-"+ k +"' class='daysInWeek' value='"+ autorpldata[k].days_of_week +"'><div class='chooseTInterval'>Send auto-reply <span style='color:#ad0202'>outside</span> this interval:<div class='tooltipautoreplyst'><div id='infoautoreplyst'>i</div><div class='autorpltooltipst'>These fields specify the time of the server. If the server is located in a time zone that is different from that of the owner/company, the time interval entered here should be adjusted accordingly.</div></div></div><div class='selectArplHours'><select id='dmstarthr-"+ k +"' class='selectHrMin'>"+ dlHrStartOptions +"</select><select id='dmstartmn-"+ k +"' class='selectHrMin'>"+ dlMnStartOptions +"</select><span style='font-weight: 600'> — </span><select id='dmendhr-"+ k +"' class='selectHrMin'>"+ dlHrEndOptions +"</select><select id='dmendmn-"+ k +"' class='selectHrMin'>"+ dlMnEndOptions +"</select></div>";

                                             } else {

                                                 var vctnStart = autorpldata[k].vacation_start.split(" ")[0];
                                                 var vctnEnd = autorpldata[k].vacation_end.split(" ")[0];

                                                 var slctdMode = "<option value=''>Select mode</option><option value='daily'>Daily mode</option><option value='vacation' selected>Vacation mode</option>";
                                                 var modeContent = "<div class='chooseDateIntvl'>Send auto-reply <span style='color:#ad0202'>inside</span> this interval:</div><div class='arplstrtendDates'><div class='stdtTitle'>Start Date</div><input type='text' id='startDT-"+ k +"' class='startDate' placeholder='Pick a date' value='"+ vctnStart +"'><div class='enddtTitle'>End Date</div><input type='text' id='endDT-"+ k +"' class='endDate' placeholder='Pick a date' value='"+ vctnEnd +"'></div>"
                                             }

				             $("#autoReplyTbl").append("<tr><td><input type='text' class='arplAuthor' value='"+ autorpldata[k].saved_by_dsplname +"' disabled></td><td><select id='arpphn-"+ k +"' class='arplPhoneNmbr' style='pointer-events:none'><option selected>"+ autorpldata[k].phone_number +"</option></select></td><td><div id='arplmode-"+ k +"' class='arplMode'><select id='modeselect-"+ k +"' class='selectArplMode'>"+ slctdMode +"</select><div id='modecont-"+ k +"' class='modeContent'>"+ modeContent +"</div></div></td><td><textarea id='arpltxt-"+ k +"' class='arplText' rows='20' cols='40' placeholder='Enter the auto-reply message here.'>"+ autorpldata[k].message_text +"</textarea></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:9px 8px 0px 18px;'></td><td><input type='submit' id='arplsave-"+ k +"' class='saveAutoReply' value='Edit' title='Edit Row' /></td></tr>");
				        }
				        $("#autoReplyTbl").append("<div><img id='addArplRow' src='/apps/sms_relentless/img/add.svg' title='Add Row'></div>");
				    }


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

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

                                    if (arplNmb == 0) {
				        $("#arpphn-"+ arplNmb).append(numbersListItems);
                                    }

                                    // Initialize the date picker
			            $('[id^="endDT-"]').datepicker({ dateFormat: "yy-mm-dd" });
			            $('[id^="startDT-"]').datepicker({ dateFormat: "yy-mm-dd" });


                                    // Select the auto-reply mode
                                    function selectMode() {

		                            $('[id^="modeselect-"]').change(function() {

		                               var crtnmbr = $(this).attr("id").replace("modeselect-", "");

		                               var dailyHrStart = "";
		                               for (var h = 0; h < 24; h++) {
		                                    dailyHrStart += "<option value='"+ h.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"'>"+ h.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                               }

		                               var dailyMnStart = "";
		                               for (var m = 0; m < 60; m++) {
		                                    dailyMnStart += "<option value='"+ m.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"'>"+ m.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) +"</option>";
		                               }

		                               var dailyHrEnd = dailyHrStart;
		                               var dailyMnEnd = dailyMnStart;

		                               if ($(this).val() == 'daily') {
		                                   $("#modecont-"+ crtnmbr).empty();
		                                   $("#modecont-"+ crtnmbr).append("<div class='daysOfWeek'>Days of the week:<div class='tooltipautoreply'><div id='infoautoreply'>i</div><div class='autorpltooltip'>Enter the order number of the days of the week in which the auto-reply will be sent. For example, to send the auto-reply every day from Monday to Friday outside the time interval specified below, enter 1,2,3,4,5 To send the auto-reply only Monday, Thursday and Friday enter 1,4,5 To send the auto-reply every day of the week enter 1,2,3,4,5,6,7 As an exception, if you want the auto-reply to be sent during an entire day, irrespective of the specified interval, add (full) after the number of that day. For example, if you want the auto-reply to be sent from Monday to Friday outside the interval specified below, and also during the entire days of Saturday and Sunday, enter 1,2,3,4,5,6(full),7(full)</div></div></div><input type='text' id='weekdays-"+ crtnmbr +"' class='daysInWeek'><div class='chooseTInterval'>Send auto-reply <span style='color:#ad0202'>outside</span> this interval:<div class='tooltipautoreplyst'><div id='infoautoreplyst'>i</div><div class='autorpltooltipst'>These fields specify the time of the server. If the server is located in a time zone that is different from that of the owner/company, the time interval entered here should be adjusted accordingly.</div></div></div><div class='selectArplHours'><select id='dmstarthr-"+ crtnmbr +"' class='selectHrMin'>"+ dailyHrStart +"</select><select id='dmstartmn-"+ crtnmbr +"' class='selectHrMin'>"+ dailyMnStart +"</select><span style='font-weight: 600'> — </span><select id='dmendhr-"+ crtnmbr +"' class='selectHrMin'>"+ dailyHrEnd +"</select><select id='dmendmn-"+ crtnmbr +"' class='selectHrMin'>"+ dailyMnEnd +"</select></div>");
		                               } else if ($(this).val() == 'vacation') {
		                                   $("#modecont-"+ crtnmbr).empty();
		                                   $("#modecont-"+ crtnmbr).append("<div class='chooseDateIntvl'>Send auto-reply <span style='color:#ad0202'>inside</span> this interval:</div><div class='arplstrtendDates'><div class='stdtTitle'>Start Date</div><input type='text' id='startDT-"+ crtnmbr +"' class='startDate' placeholder='Pick a date'><div class='enddtTitle'>End Date</div><input type='text' id='endDT-"+ crtnmbr +"' class='endDate' placeholder='Pick a date' /></div>");
		                               }

					       $("#endDT-"+ crtnmbr +"").datepicker({ dateFormat: "yy-mm-dd" });
					       $("#startDT-"+ crtnmbr +"").datepicker({ dateFormat: "yy-mm-dd" });
		                          });
                                  }
                                  selectMode();

				  // Save the data
				  function saveArplRow() {

				     $('[id^="arplsave-"]').unbind("click");
				     $('[id^="arplsave-"]').click(function(event) {

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

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

				            var phoneNmbr = $("#arpphn-"+ crntrwnmbr).val();
				            var arplText = $("#arpltxt-"+ crntrwnmbr).val();
				            var slctdMode = $("#modeselect-"+ crntrwnmbr).val();

				            var slctddmDays = "";
				            var slctdHrStart = "";
				            var slctdMnStart = "";
				            var slctdHrEnd = "";
				            var slctdMnEnd = "";

				            var vcStartDate = null;
				            var vcEndDate = null;

				            if (slctdMode == 'daily') {

				                slctddmDays = $("#weekdays-"+ crntrwnmbr).val().trim();
				                slctdHrStart = $("#dmstarthr-"+ crntrwnmbr).val().trim();
				                slctdMnStart = $("#dmstartmn-"+ crntrwnmbr).val().trim();
				                slctdHrEnd = $("#dmendhr-"+ crntrwnmbr).val().trim();
				                slctdMnEnd = $("#dmendmn-"+ crntrwnmbr).val().trim();

                                                if (slctdHrStart != '' && slctdMnStart != '') {
                                                    var hrmnStartComp = slctdHrStart +":"+ slctdMnStart;
                                                } else { var hrmnStartComp = ""; }

                                                if (slctdHrEnd != '' && slctdMnEnd != '') {
                                                    var hrmnEndComp = slctdHrEnd +":"+ slctdMnEnd;
                                                } else { var hrmnEndComp = ""; }

                                                if (!(/^[1-7ful\,\(\)]+$/.test(slctddmDays))) {
				                    showAlert("The 'Days of the week' field can contain only digits from 1 to 7, the lowercase letters f, u and l, round brackets ()() and commas (,).");
				                    return;
                                                }

                                                if (!(/^[0-9]+$/.test(slctdHrStart + slctdMnStart + slctdHrEnd + slctdMnEnd))) {
				                    showAlert("The starting and ending values of the time interval for the 'Daily mode' can contain only digits from 0 to 9.");
				                    return;
                                                }

                                                if (slctddmDays.trim() == '' || (slctdHrStart == slctdHrEnd && slctdMnStart == slctdMnEnd)) {
				                    showAlert("For the 'Daily mode', you have to enter the order number of the days of the week for which you want the auto-reply to be sent, and you have to set a starting time that is different from the ending time!");
				                    return;
                                                }

				            } else if (slctdMode == 'vacation') {
		
                                                if ($("#startDT-"+ crntrwnmbr).val().trim() == '' || $("#endDT-"+ crntrwnmbr).val().trim() == '') {

				                    showAlert("For the 'Vacation mode', you have to enter both a start date and an end date.");
				                    return;

                                                } else {

                                                    if (!(/^[0-9\-]+$/.test($("#startDT-"+ crntrwnmbr).val().trim() + $("#endDT-"+ crntrwnmbr).val().trim()))) {
				                        showAlert("The start date and end date values for the 'Vacation mode' can contain only digits from 0 to 9 and hyphens (-).");
				                        return;
                                                    }

		                                    vcStartDate = $("#startDT-"+ crntrwnmbr).val().trim() +" 00:00:00";
				                    vcEndDate = $("#endDT-"+ crntrwnmbr).val().trim() +" 23:59:59";
				                    var strtDateCmp = new Date(vcStartDate).toJSON().slice(0, 10) +" 00:00:00";
				                    var endDateCmp = new Date(vcEndDate).toJSON().slice(0, 10) +" 23:59:59";
				                    var crntDate = new Date().toJSON().slice(0, 10) +" 23:59:59";

                                                    if (vcStartDate.trim() == "" || vcEndDate.trim() == "" || (strtDateCmp >= endDateCmp || ((strtDateCmp < crntDate) && (endDateCmp < crntDate)))) {
				                        showAlert("For 'Vacation mode', you have to enter both a start date and an end date, the start date must be before the end date and at least the ending of the time interval must be in the future.");
				                        return;
                                                    }
                                                }
				            }


				            if (phoneNmbr != '') {

				              if (arplText.trim() != '') {

				                if (slctdMode != '') {

				                    var saveArplUrl = OC.generateUrl('/apps/sms_relentless/user/updateautoreplies');
				                    var arpldata = {
				                         userId: userid,
				                         savedByDsplname: cusrDisplayName,
				                         phoneNumber: phoneNmbr,
				                         daysOfWeek: slctddmDays,
				                         dailyStart: hrmnStartComp,
				                         dailyEnd: hrmnEndComp,
				                         vacationStart: vcStartDate,
				                         vacationEnd: vcEndDate,
				                         messageText: arplText
				                    };

					            $.ajax({
					              method: 'PUT',
					              url: saveArplUrl + '/' + userid,
					              contentType: 'application/json',
					              data: JSON.stringify(arpldata),
				                      success: function(messagereceived) {

				                                   if (messagereceived == 'success') {
				                                       showAlert('The auto-reply has been successfully saved to the database!');
				                                   } else if (messagereceived == 'failure') {
				                                       showAlert('Error while trying to save the auto-reply!');
				                                   } else if (messagereceived == 'not allowed') {
                                                                       showAlert('You cannot change an auto-reply that was saved by a different user.');
                                                                   }
				                      },
					              error: function() {
						                   showAlert('Error while attempting to save the auto-reply! You can check the Nextcloud log to find more details about this issue.');
					              }
					            });


                                                } else { showAlert("Please select the auto-reply mode."); return; }

                                              } else { showAlert("Please enter the text of the auto-reply."); return; }

                                            } else { showAlert("Please select a phone number if at least one number is available in the 'Phone Number' drop-down list. Otherwise, you should contact the administrator."); return; }

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

                                        } else {
                                            $("#arplsave-"+ crntrwnmbr).attr("value", "Save");
                                        }

                                     });

				  }
                                  saveArplRow();


				  // Remove a row
				  function removeArplRow() {
				       $('[id^="rmRow-"]').click(function() {

					  var slctRowRm = $(this).attr("id").replace("rmRow-", "");
					  var crntPhnNmbr = $("#arpphn-"+ slctRowRm).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 rmvArplUrl = OC.generateUrl('/apps/sms_relentless/user/removeautoreplies');
					      $.ajax({
						   url: rmvArplUrl + '/' + userid,
						   method: "POST",
						   dataType: "text",
						   data: { phoneNumber: crntPhnNmbr },
						   success: function(delresult) {

						                     if (delresult.indexOf("success") > -1) {
						                         showAlert("The auto-reply has been removed successfully!");
						                         $("#arpphn-"+ slctRowRm).closest("tr").remove();
						                     } else if (delresult.indexOf("failure") > -1) {
						                         showAlert("Error while trying to remove auto-reply data!");
						                     } else if (delresult.indexOf("not allowed") > -1) {
                                                                         showAlert("You cannot remove the auto-reply saved by another user.");
                                                                     }
						   },
						   error: function() { showAlert("Error while attempting to remove auto-reply data! You can check the Nextcloud log to find more details about this issue."); }
					       });
					  });
				       });
				  }
				  removeArplRow();

                                  // Add a new row
                                  $("#addArplRow").click(function() {

                                     if ($("#autoReplyTbl").find("tr:last-child").find(".arplPhoneNmbr").length > 0) {
                                         var lastarpl = $("#autoReplyTbl").find("tr:last-child").find(".arplPhoneNmbr").attr("id").replace("arpphn-", "");
                                         var indArplAdd = parseInt(lastarpl + 1);
                                     } else { var indArplAdd = 0; }
			             $("#autoReplyTbl").append("<tr><td><input type='text' class='arplAuthor' value='"+ cusrDisplayName +"' disabled></td><td><select id='arpphn-"+ indArplAdd +"' class='arplPhoneNmbr'>"+ numbersListItems +"</select></td><td><div id='arplmode-"+ indArplAdd +"' class='arplMode'><select id='modeselect-"+ indArplAdd +"' class='selectArplMode'><option value='' selected>Select mode</option><option value='daily'>Daily mode</option><option value='vacation'>Vacation mode</option></select><div id='modecont-"+ indArplAdd +"' class='modeContent'></div></div></td><td><textarea id='arpltxt-"+ indArplAdd +"' class='arplText' rows='20' cols='40' placeholder='Enter the auto-reply message here.'></textarea></td><td><img id='rmRow-"+ indArplAdd +"' class='removeRow' src='/apps/sms_relentless/img/closewnd.svg' title='Remove this row from the database' style='cursor:pointer;margin:9px 8px 0px 18px;'></td><td><input type='submit' id='arplsave-"+ indArplAdd +"' class='saveAutoReply' value='Save' title='Save Row' /></td></tr>");

                                     selectMode();
                                     saveArplRow();
                                     removeArplRow();

			             // Check if there is an auto-reply set for the same phone number
				     $("#arpphn-"+ indArplAdd).change(function() {
					 var selectedPhNb = $("#arpphn-"+ indArplAdd).val();
					 var allArplPhNmbrs = $("#autoReplyTbl").find("tr").find(".arplPhoneNmbr");
					 var phNbChck = 0;
					 allArplPhNmbrs.each(function() {
					    var slctphnb = ($(this).val())? $(this).val() : $(this).text();
					    if (selectedPhNb == slctphnb) { phNbChck++; }
					 });

					 if (phNbChck == 2) {
					     showAlert("There is already an auto-reply set up for this phone number. Please edit its own row, or choose a different phone number.");
					     $(this).val('');
					     return;
					 }
				     });
                                  });

		  },
		  error: function() {
                                    $("#autoRplPhoneNb").removeClass('icon-loading'); 
                                    showAlert("Error while attempting to get the auto-reply settings! You can check the Nextcloud log to find more details about this issue.");
                  }
         });

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



  // Save personal settings for non-admin users
  $("#save_sms_settings").on("click", function(event) {

     if (isadm == 'reguser') {

	    event.preventDefault();
	    var baseUrlsave = OC.generateUrl('/apps/sms_relentless/user/updatesettings');

	    var messagesperpageinit = $("#messagesperpage").val();
	    var messagesperpagesec = messagesperpageinit.replace(/[^0-9]/g, '');

	    if (messagesperpagesec != '') {
		var messagesperpageproc = messagesperpagesec;
	    } else {
		var messagesperpageproc = 100;
	    }

	    var getnotify = 0;

	    if ($("#get_notify").is(':checked')) {
		getnotify = 1;
	    }

	    var emailaddressinit = $("#notification_email").val();

	    function validate_email($email) {
		var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		return email_reg.test($email);
	    }

	    if (validate_email(emailaddressinit)) {
		 var notifyemail = emailaddressinit;
	    } else {
		 var notifyemail = '';
	    }

	    var includesmsinemail = 0;
	    if ($("#includesmsinemail").is(':checked')) {
		includesmsinemail = 1;
                if ($("#notification_email").val().trim() == '') {
                    showAlert("Please enter an email address in the field: 'I want to receive a notification to the email address from below ...', or uncheck the checkbox: 'Include the SMS/MMS message in the email notification itself'.");
                    return;
                }
	    }

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

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

	    var datatosave = {
			      userId: userid,
		              telapiUrlRec: $("#telapi_url_rec").val(),
		              telapiUrl: $("#telapi_url").val(),
		              nexapiUrlRec: $("#nexapi_url_rec").val(),
		              nexapiUrl: $("#nexapi_url").val(),
		              twilapiUrlRec: $("#twilapi_url_rec").val(),
		              twilapiUrl: $("#twilapi_url").val(),
		              flowapiUrlRec: $("#flowapi_url_rec").val(),
		              flowapiUrl: $("#flowapi_url").val(),
			      messagesperpage: messagesperpageproc,
			      getNotify: getnotify,
			      notificationEmail: notifyemail,
			      getsmsinemail: includesmsinemail,
			      showDisplayNames: showdisplaynm,
                              addDisplayNames: adddisplaynm
	    };


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


     } else if (isadm == 'admin') {

	    // Save personal settings for admins
	    event.preventDefault();
	    var baseUrlsaveadm = OC.generateUrl('/apps/sms_relentless/user/updatepersadmnsettings');

	    var messagesperpageinit = $("#messagesperpage").val();
	    var messagesperpagesec = messagesperpageinit.replace(/[^0-9]/g, '');

	    if (messagesperpagesec != '') {
		var messagesperpageproc = messagesperpagesec;
	    } else {
		var messagesperpageproc = 100;
	    }

	    var getnotify = 0;

	    if ($("#get_notify").is(':checked')) {
		getnotify = 1;
	    }

	    var emailaddressinit = $("#notification_email").val();

	    function validate_email($email) {
		var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		return email_reg.test($email);
	    }

	    if (validate_email(emailaddressinit)) {
		 var notifyemail = emailaddressinit;
	    } else {
		 var notifyemail = '';
	    }

	    var includesmsinemail = 0;
	    if ($("#includesmsinemail").is(':checked')) {
		includesmsinemail = 1;
                if ($("#notification_email").val().trim() == '') {
                    showAlert("Please enter an email address in the field: 'I want to receive a notification to the email address from below ...', or uncheck the checkbox: 'Include the SMS/MMS message in the email notification itself'.");
                    return;
                }
	    }

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

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

	    var datatosave = {
			      userId: userid,
			      messagesperpage: messagesperpageproc,
			      getNotify: getnotify,
			      notificationEmail: notifyemail,
			      getsmsinemail: includesmsinemail,
			      showDisplayNames: showdisplaynm,
                              addDisplayNames: adddisplaynm
	    };


	    $.ajax({
	       method: 'PUT',
	       url: baseUrlsaveadm + '/' + userid,
	       contentType: 'application/json',
	       data: JSON.stringify(datatosave),
	       success: function() {
                               OC.msg.startAction('#smsr_save_msg', t('sms_relentless', 'Saved'));
	       },
	       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) {

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

     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(); });
  }

});
