/**
 * @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 strlength;

  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();
     alert("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();
     alert("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();
     alert("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();
     alert("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_sms_settings").on("click", function(event) {

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

    var baseUrl = 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 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 flowsenderinit = $("#flow_sender_name").val();
    //  var flowsenderproc = flowsenderinit.replace(/[^A-Za-z 0-9]/g, '');

    var includesmsinemail = 0;

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

    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,
                      //  flowSenderName: flowsenderproc,
                      messagesperpage: messagesperpageproc,
                      getNotify: getnotify,
                      notificationEmail: notifyemail,
                      getsmsinemail: includesmsinemail
    };


    $.ajax({
       method: 'PUT',
       url: baseUrl + '/' + userid,
       contentType: 'application/json',
       data: JSON.stringify(datatosave),
       error: function(resp) {
            alert('Error ! Please check your settings !');
       }
    });

  });


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

  $.ajax({
     method: 'GET',
     url: baseUrlget + '/' + userid,
     contentType: 'application/json',
     success: function(settingsfromdb) {
         $("#telapi_key").val(settingsfromdb.telapi_key);
         $("#tel_pub_key").val(settingsfromdb.tel_pub_key);
         $("#telapi_url_rec").val(settingsfromdb.telapi_url_rec);
         $("#telapi_url").val(settingsfromdb.telapi_url);
         $("#messaging_profile_id").val(settingsfromdb.messaging_profile_id);
         $("#nexapi_key").val(settingsfromdb.nexapi_key);
         $("#nexapi_secret").val(settingsfromdb.nexapi_secret);
         $("#nexapi_url_rec").val(settingsfromdb.nexapi_url_rec);
         $("#nexapi_url").val(settingsfromdb.nexapi_url);
         $("#twilapi_key").val(settingsfromdb.twilapi_key);
         $("#twilapi_secret").val(settingsfromdb.twilapi_secret);
         $("#twilapi_url_rec").val(settingsfromdb.twilapi_url_rec);
         $("#twilapi_url").val(settingsfromdb.twilapi_url);
         $("#flowapi_key").val(settingsfromdb.flowapi_key);
         $("#flowapi_secret").val(settingsfromdb.flowapi_secret);
         $("#flowapi_url_rec").val(settingsfromdb.flowapi_url_rec);
         $("#flowapi_url").val(settingsfromdb.flowapi_url);
         $("#tel_sender_name").val(settingsfromdb.tel_sender_name);
         $("#nex_sender_name").val(settingsfromdb.nex_sender_name);
         $("#twil_sender_name").val(settingsfromdb.twil_sender_name);
         //  $("#flow_sender_name").val(settingsfromdb.flow_sender_name);
         $("#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);
         }
     }
  });

});
