/**
 * @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); ?>";

    // Delete from the database all the received messages older than the specified period
    $("#delOldrecSMS").on("click", function() {

      var oldrecInterval = $("#oldrecSmsInterval").val();
      var procoldrecint = oldrecInterval.replace(/[^0-9]/g, "");
      var finaloldrecint = parseInt(procoldrecint);

      if (finaloldrecint == "" || !$.isNumeric(finaloldrecint)) {
          alert("Please enter the number of days in the box from above !");
      } else {

         var getRecUrl = OC.generateUrl("/apps/sms_relentless/user/getreceivedtablefordel");
         $('#smstables').addClass('icon-loading');

         $.ajax({
             url: getRecUrl + '/' + userid,
             method: "GET",
             dataType:'text',
             success: function(recinfoFromDB) {

                var parsedinfo = $.parseJSON(recinfoFromDB);

                if (parsedinfo == "not permitted") {

                    alert("Only admins can remove old messages using this option!");
                    $('#smstables').removeClass('icon-loading');
                    return;

                } else {

                    var recmessagedbIDs = [];
                    var oldrecRows = [];
                    oldrecRows.push("id,user_id,message_id,date,from,to,message\r\n");

                    var targetdate = new Date(new Date().setDate(new Date().getDate() - finaloldrecint));

                    for (var j = 0; j < parsedinfo.length; j++) {
                         var firstdate = parsedinfo[j].date;
                         var secdate = firstdate.split(" ");
                         var thirddate = secdate[0].split("-");
                         var fourthdate = secdate[1].split(":");
                         var pastdate = new Date(thirddate[0],(thirddate[1]-1),thirddate[2],fourthdate[0],fourthdate[1],fourthdate[2]);

                         if (pastdate < targetdate) {
                             recmessagedbIDs.push(parsedinfo[j].id);
                             oldrecRows.push(parsedinfo[j].id + "," + parsedinfo[j].user_id + "," + parsedinfo[j].message_id + "," + parsedinfo[j].date + "," + parsedinfo[j].from + "," + parsedinfo[j].to + "," + parsedinfo[j].message + "\r\n");
                         }
                    }


                    if (oldrecRows.length == 1) {

                        alert("No messages will be deleted since there are no messages older than " + finaloldrecint + " days.");

                    // Save in a '.csv' file all the received messages that will be deleted from the database, then delete them
                    } else {

                        if (confirm("Are you sure you want to delete all the received messages older than " + finaloldrecint + " days ?")) {

                            var deloldrecRowsUrl = OC.generateUrl("/apps/sms_relentless/user/saveoldrecrows");

                            $.ajax({
                                url: deloldrecRowsUrl + '/' + userid,
                                method: "POST",
                                dataType:'text',
                                data: { oldrecRows: oldrecRows },
                                success: function(savecheck) {

                                            // Delete received messages from the database
                                            var delrecDbSmsUrl = OC.generateUrl("/apps/sms_relentless/user/removerecrows");

                                            if (savecheck == 1) {

                                                $.ajax({
                                                       url: delrecDbSmsUrl + '/' + userid,
                                                       method: "POST",
                                                       dataType:'text',
                                                       data: {recmessagedbIDs: recmessagedbIDs},
                                                       success: function() {
                                                            alert((oldrecRows.length - 1)+" rows have been successfully saved in the 'SMS_relentless/removed_received_messages' directory and then deleted from the database !");
                                                            $('#smstables').removeClass('icon-loading');
                                                       },
                                                       error: function() {
                                                            alert("There was an error while deleting the messages older than the specified period!");
                                                            $('#smstables').removeClass('icon-loading');
                                                       }
                                                });

                                            } else { alert("There was an error while saving the messages older than the specified period!"); }

                                            $('#smstables').removeClass('icon-loading');
                                },
                                error: function() {
                                     alert("There was an error while saving and/or deleting the messages older than the specified period!");
                                     $('#smstables').removeClass('icon-loading');
                                }
                            });
                        }
                    }
                }
             },
             error: function() {
                alert("An error occurred while getting data from the database!");
                $('#smstables').removeClass('icon-loading');
             }
         });

      }

    });


    // Delete from the database all the sent messages older than the specified period
    $("#delOldsentSMS").on("click", function() {

      var oldsentInterval = $("#oldsentSmsInterval").val();
      var procoldsentint = oldsentInterval.replace(/[^0-9]/g, "");
      var finaloldsentint = parseInt(procoldsentint);

      if (finaloldsentint == "" || !$.isNumeric(finaloldsentint)) {
          alert("Please enter the number of days in the box above !");
      } else {

         var getSentUrl = OC.generateUrl("/apps/sms_relentless/user/getsenttablefordel");
         $('#smstables').addClass('icon-loading');

         $.ajax({
             url: getSentUrl + '/' + userid,
             method: "GET",
             dataType:'text',
             success: function(sentinfoFromDB) {

                var parsedsentinfo = $.parseJSON(sentinfoFromDB);

                if (parsedsentinfo == "not permitted") {

                    alert("Only admins can remove old messages using this option!");
                    $('#smstables').removeClass('icon-loading');
                    return;

                } else {

                    var sentmessagedbIDs = [];
                    var oldsentRows = [];
                    oldsentRows.push("id,user_id,message_id,date,from,to,network,price,status,deliveryreceipt,message\r\n");

                    var senttargetdate = new Date(new Date().setDate(new Date().getDate() - finaloldsentint));

                    for (var j = 0; j < parsedsentinfo.length; j++) {
                         var firstdate = parsedsentinfo[j].date;
                         var secdate = firstdate.split(" ");
                         var thirddate = secdate[0].split("-");
                         var fourthdate = secdate[1].split(":");
                         var sentpastdate = new Date(thirddate[0],(thirddate[1]-1),thirddate[2],fourthdate[0],fourthdate[1],fourthdate[2]);

                         if (sentpastdate < senttargetdate) {
                             sentmessagedbIDs.push(parsedsentinfo[j].id);
                             oldsentRows.push(parsedsentinfo[j].id + "," + parsedsentinfo[j].user_id + "," + parsedsentinfo[j].message_id + "," + parsedsentinfo[j].date + "," + parsedsentinfo[j].from + "," + parsedsentinfo[j].to + "," + parsedsentinfo[j].network + "," + parsedsentinfo[j].price + "," + parsedsentinfo[j].status + "," + parsedsentinfo[j].deliveryreceipt + "," + parsedsentinfo[j].message + "\r\n");
                         }
                    }


                    if (oldsentRows.length == 1) {

                        alert("No messages will be deleted since there are no messages older than " + finaloldsentint + " days.");

                    // Save in a '.csv' file all the sent messages that will be deleted from the database, then delete them
                    } else {

                          if (confirm("Are you sure you want to delete all the sent messages older than " + finaloldsentint + " days ?")) {

                              var deloldsentRowsUrl = OC.generateUrl("/apps/sms_relentless/user/saveoldsentrows");

                              $.ajax({
                                  url: deloldsentRowsUrl + '/' + userid,
                                  method: "POST",
                                  dataType:'text',
                                  data: { oldsentRows: oldsentRows },
                                  success: function(savesentcheck) {

                                            // Delete sent messages from the database
                                            var delsentDbSmsUrl = OC.generateUrl("/apps/sms_relentless/user/removesentrows");

                                            if (savesentcheck == 1) {

                                                $.ajax({
                                                       url: delsentDbSmsUrl + '/' + userid,
                                                       method: "POST",
                                                       dataType:'text',
                                                       data: { sentmessagedbIDs: sentmessagedbIDs },
                                                       success: function() {
                                                            alert((oldsentRows.length - 1) + " rows have been successfully saved in the 'SMS_relentless/removed_sent_messages' directory and then deleted from the database !");
                                                            $('#smstables').removeClass('icon-loading');
                                                       },
                                                       error: function() {
                                                            alert("There was an error while deleting the messages older than the specified period!");
                                                            $('#smstables').removeClass('icon-loading');
                                                       }
                                                });

                                            } else { alert("There was an error while saving the messages older than the specified period!"); }

                                            $('#smstables').removeClass('icon-loading');
                                  },
                                  error: function() {
                                     alert("There was an error while saving and/or deleting the messages older than the specified period!");
                                     $('#smstables').removeClass('icon-loading');
                                  }
                              });
                          }
                    }

                }  

             },
             error: function() {
                alert("An error occurred while getting data from the database!");
                $('#smstables').removeClass('icon-loading');
             }
         });
      }

    });
});