/**
 * @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/>.
 *
 */

  var userid = "<?php p($userId); ?>";
  var telenctype = 'GSM-7';
  var nexenctype = 'text';
  var charcolorthr = 160;
  var textread = '';
  var providerUsed = '';
  var receiversNumbers = [];
  var waittime = 1000;

  // Clean the temp_files directory
  var cleanflUrl = OC.generateUrl("/apps/sms_relentless/user/cleantempdir");

  $.ajax({
          url: cleanflUrl + '/' + userid,
          type: "POST",
          data: { userid: userid },
          cache: false,
          processData: false,
          contentType: false
  });
  
  // Check the available balance
  $("#smsprovider").on("change", function () {

     var provider = $('#smsprovider :selected').val();

     if (provider == "Telnyx") {

        var gettelbalance = function() {

          $('#currentbalance').addClass('icon-loading');

          var gettelbalanceUrl = OC.generateUrl("/apps/sms_relentless/user/getbalancetel");

          $.ajax({
              url: gettelbalanceUrl + '/' + userid,
              type: "POST",
              data: { userid: userid },
              cache: false,
              processData: false,
              contentType: false,
              success: function(currentbalancetel) {

                     $('#currentbalance').empty();
                     $('#currentbalance').text(currentbalancetel);
                     $('#currentbalance').removeClass('icon-loading');
              }
          });
        }

        gettelbalance();

     } else if (provider == "Plivo") {

          var getnexbalance = function() {

            $('#currentbalance').addClass('icon-loading');

            var getnexbalanceUrl = OC.generateUrl("/apps/sms_relentless/user/getbalancenex");

            $.ajax({
                url: getnexbalanceUrl + '/' + userid,
                type: "POST",
                data: { userid: userid },
                cache: false,
                processData: false,
                contentType: false,
                success: function(currentbalancenex) {

                     $('#currentbalance').empty();
                     $('#currentbalance').text(currentbalancenex);
                     $('#currentbalance').removeClass('icon-loading');
                }
            });
          }

          getnexbalance();

       } else if (provider == "") {
                $('#currentbalance').text("");
                $('#currentbalance').removeClass('icon-loading');
       }
  });

  // Select the Sender ID
  $("#selectcalleridbttn").on("click", function(event) {

     $('#selectcalleridbttn').addClass('icon-loading');

     var getsmsnumbersUrl = OC.generateUrl("/apps/sms_relentless/user/getsmsnumbers");

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

                     $('#currentsmsnmbrs').empty();
                     $('#currentsmsnmbrs').append("<option value='' selected='selected' disabled class='optselectsmsnb'>Choose an ID</option>");

                     $.each(currentnmbrs, function(key, indsmsnmb) {
                         var emptyinit = indsmsnmb.split(":");
                         var emptysec = emptyinit[1];
                         var emptycheck = emptysec.replace(" ", "").replace("+", "");

                         if (emptycheck != '') {
                             $('#currentsmsnmbrs').append("<option value='"+indsmsnmb+"' class='optselectsmsnb'>"+indsmsnmb+"</option>");
                         }
                     });

                     $('#selectcalleridbttn').removeClass('icon-loading');
          }
     });
  });

  // Check the checkbox to send SMS message to multiple recipients
  $('#tomultchckbx').change(function() {
      if ($(this).is(':checked')) {
          $("#multiplerecivers").css("display", "block");
          $("#smstodiv").css("visibility", "hidden");
          $("#smsto").val("");

          receiversNumbers.length = 0;

      } else {
          $("#multiplerecivers").css("display", "none");
          $("#smstodiv").css("visibility", "visible");

          // Remove the uploaded file if any
          $("#induploadfile").remove();

          receiversNumbers.length = 0;

          $.ajax({
             url: cleanflUrl + '/' + userid,
             type: "POST",
             data: {userid: userid},
             cache: false,
             processData: false,
             contentType: false
          });
      }
  });

  // Upload the file with the recipients' phone numbers
  $("#uploadfileforsms").change(function(e) {

     $("#fileuploadednm").empty();

     receiversNumbers.length = 0;

     OC.msg.startAction("#sms_upload_msg", t("sms_relentless", "Uploading ..."));

     var baseUrl = OC.generateUrl("/apps/sms_relentless/user/upload_numbers_file");

     var formData = new FormData();
     formData.append('uploadfileforsms', $('#uploadfileforsms')[0].files[0]);

     var fileup = $('#uploadfileforsms').val();
     var fileuptrim = fileup.split('\\').pop();

     $('#fileuploadednm').append("<div id='induploadfile' class='indgenflcls'><div id='indfilediv' class='indivflcls'>" + fileuptrim + "</div><div id='indivflremove' class='indupfldl'>X</div></div><br>");

     var extension = fileup.replace(/^.*\./, '');

     if (extension == fileup) {
         extension = "";
     } else {
         extension = extension.toLowerCase();
     }

     var validExtensions = ["txt", "csv"];

     if (jQuery.inArray(extension, validExtensions) != -1) {

	// Check if the Sender ID is set
	if ($("#currentsmsnmbrs option[value='']").length > 0) {
            var setId = $('#currentsmsnmbrs :selected').val();
	} else { var setId = ''; }

	if (setId != '') {

               $.ajax({
                 url: baseUrl + '/' + userid,
                 type: "POST",
                 data: formData,
                 cache: false,
                 processData: false,
                 contentType: false,
                 success: function(numberarray) {

		    if (numberarray.length > 0) {

		        // Get the array of the receivers' phone numbers
		        var setIdsplit = setId.split(":");
		        var smsProvider = setIdsplit[0];

		        if (smsProvider == "T") {

		             for(key in numberarray) {
		                 receiversNumbers.push("+"+numberarray[key]);
		             }

		        } else if (smsProvider == "P") {

		             for(key in numberarray) {
		                 receiversNumbers.push(numberarray[key]);
		             }
		          }

		    } else {
		          alert("The uploaded file doesn't seem to contain any valid phone numbers. Please upload a txt or csv file that contains phone numbers separated by commas, semicolons, vertical bars or new lines.");
		    }
                            
                    // Preview the uploaded file
                    var smsfilename = e.target.files[0].name;
                    var baseUrl = OC.generateUrl("/remote.php/webdav/SMS_Relentless/temp_files/"+smsfilename);

                    var reader = new FileReader();
                    reader.readAsText(e.target.files[0]);
                    reader.onload = function(e) {
                          $("#smstables").empty();
                          $("#smstables").append(e.target.result.replace(/(?:\r\n|\r|\n)/g, '<br>'));
                    };

                    $("#smstables").show();

                    $('#sms_upload_msg').hide();
                    $('#smstables').removeClass('icon-loading');

                  },
                  error: function(){
                     alert('Error!');
                  }
               });

        } else {
               alert("Please choose a Sender ID from the Set ID drop-down list!");
               $('#sms_upload_msg').hide();
               $('#smstables').removeClass('icon-loading');
        }

     } else {
          alert('The file type is not supported ! Supported formats are txt and csv.');
          $('#pf_upload_msg').hide();
          $('#faxdocpreview').removeClass('icon-loading');

          $("#induploadfile").remove();
          $("#sms_upload_msg").hide();
     }

     //Preview uploaded file when clicked
     $("#indfilediv").on("click", function() {

          var smsfilename = e.target.files[0].name;
          var baseUrl = OC.generateUrl("/remote.php/webdav/SMS_Relentless/temp_files/"+smsfilename);

          var reader = new FileReader();
          reader.readAsText(e.target.files[0]);
          reader.onload = function(e) {
                  $("#smstables").empty();
                  $("#smstables").append(e.target.result.replace(/(?:\r\n|\r|\n)/g, '<br>'));
          };

          $("#smstables").show();
          $('#sms_upload_msg').hide();
          $('#smstables').removeClass('icon-loading');
     });

     // Remove selected file
     $("#indivflremove").on("click", function() {

          $("#induploadfile").remove();
          $("#sms_upload_msg").hide();

          receiversNumbers.length = 0;

          $.ajax({
             url: cleanflUrl + '/' + userid,
             type: "POST",
             data: {userid: userid},
             cache: false,
             processData: false,
             contentType: false
         });
     });

  });

  // Get the SMS encoding type
  $('#unicodechckbx').change(function() {
     if ($(this).is(':checked')) {
           telenctype = 'UCS-2';
           nexenctype = 'UCS-2';
           charcolorthr = 70;
     } else {
           telenctype = 'GSM-7';
           nexenctype = 'GSM-7';
           charcolorthr = 160;
     }
  });

  // Count the characters in the SMS text area
  $("#smstext").on('input', function() {
     $("#char_count").css("display", "inline");
     $(".maxmessagelength").css("display", "inline-block");

     $("#countchnb").text($(this).val().length);

     if ($(this).val().length > charcolorthr) {
         $("#char_count").css("color", "#BB2E4B");
     } else {
         $("#char_count").css("color", "#4cbc86;");
     }
  });

  // Send the SMS message
  $("#submitsms").on("click", function(event) {

     OC.msg.startAction("#sms_submit_msg", t("sms_relentless", "Sending SMS ... Please wait !"));
     $('#smstables').addClass('icon-loading');

     // Check if the Sender ID is set
     if ($("#currentsmsnmbrs option[value='']").length > 0) {
            var selectedid = $('#currentsmsnmbrs :selected').val();
     } else { var selectedid = ''; }

     if (selectedid != '') { 

         var sendersplit = selectedid.split(":");
         var providercap = sendersplit[0];
         var provsec = sendersplit[1];

         if (/[a-zA-Z]/.test(provsec)) {
             var alphanumcheck = true;
         } else { var alphanumcheck = false; }

         if (providercap == 'T' && alphanumcheck == false) {  
             var senderproc = selectedid.replace(/[^0-9]/g, "");
             var selectedsender = "+" + senderproc;
             var providerUsed = "telnyx";
             var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstel");
             var enctype = telenctype;
         } else if (providercap == 'P' && alphanumcheck == false) {
             var selectedsender = selectedid.replace(/[^0-9]/g, "");
             var providerUsed = "plivo";
             var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsnex");
             var enctype = nexenctype;
         } else if (providercap == 'T' && alphanumcheck == true) {
             var selectedsender = provsec;
             var providerUsed = "telnyx";
             var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmstel");
             var enctype = telenctype;
         } else if (providercap == 'P' && alphanumcheck == true) {
             var selectedsender = provsec;
             var providerUsed = "plivo";
             var relbaseUrl = OC.generateUrl("/apps/sms_relentless/user/sendsmsnex");
             var enctype = nexenctype;
         }

         // Get the interval between SMS consecutive sending requests, if it's the case
         if ($('#tomultchckbx').is(':checked')) {

             var numbersfile = 1;
             var initinterval = $("#multsmsinterval").val();
             var secinterval = initinterval.replace(/[^0-9]/g, "");

             if (secinterval != '') {
                 var tertinterval = parseInt(secinterval);
                     waittime = tertinterval;
             }

         } else {

             var numbersfile = 0;
             var toNumberinit = $('#smsto').val();
             var toNumber = toNumberinit.replace(/[^0-9,]/g, "");
             var toNumbersec = toNumber.split(",");

                 for (var i = 0; i < toNumbersec.length; i++) {
                      toNumbersec[i] = "+" + toNumbersec[i];
                 }

                 receiversNumbers = toNumbersec.filter(function(v){return v!==""});
         }

         if (numbersfile == 0 && $('#smsto').val().trim() == '') { receiversNumbers.length = 0; }

         var smstext = $("#smstext").val();

         if (receiversNumbers.length != 0) {

              if (smstext != '') {
                  $.ajax({
                     url: relbaseUrl + '/' + userid,
                     type: "POST",
                     data: {
                           receiversPhoneNbs: receiversNumbers,
                           fromsender: selectedsender,
                           waitinterval: waittime,
                           encoding: enctype,
                           sentsmstext: smstext
                         },
                     success: function() {

                           if (receiversNumbers.length == 1) {
                               alert("The message has been sent ! You can press the 'Sent SMS Messages' button to check the actual status and the delivery receit for this message. Please note that the price and the delivery receipt for the message that has just been sent will not be available immediately. Wait about 30 seconds, then check again.");
                           } else { alert("The messages have been sent ! You can press the 'Sent SMS Messages' button to check the actual status and the delivery receit for each message. Please note that the price and the delivery receipt for each message will not be available immediately. Wait about 30 seconds, then check again."); }

                           $('#sms_submit_msg').hide();
                           $('#smstables').removeClass('icon-loading');
                     },
                     error: function(){
                           alert("An error occurred! Please check the recipient's phone number and your settings !");
                           $('#sms_submit_msg').hide();
                           $('#smstables').removeClass('icon-loading');
                     }
                  });
              } else {
                     alert("Please enter a message in the text box !");
                     $('#sms_submit_msg').hide();
                     $('#smstables').removeClass('icon-loading');
              }
         } else if (receiversNumbers.length == 0 && !($('#tomultchckbx').is(':checked'))) {
                 alert("Please enter the recipient's phone number !");
                 $('#sms_submit_msg').hide();
                 $('#smstables').removeClass('icon-loading');
         } else if (receiversNumbers.length == 0 && $('#tomultchckbx').is(':checked')) {
                 alert("Please upload a txt or csv file that contains phone numbers separated by commas, semicolons, vertical bars or new lines !");
                 $('#sms_submit_msg').hide();
                 $('#smstables').removeClass('icon-loading');
         }
     } else {
           alert("Please choose a Sender ID from the Set ID drop-down list !");
           $('#smstables').removeClass('icon-loading');
           $('#sms_submit_msg').hide();
     }
  });

  // Check the checkbox to delete old SMS messages from the database
  $('#deleteoldchckbox').change(function() {
     if ($(this).is(':checked')) {
         $("#deleteoldsms").css("display", "block");
     } else {
         $("#deleteoldsms").css("display", "none");
     }
  });
