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

declare(strict_types=1);

namespace OCA\SMSRelentless\Service;

use OCP\IDBConnection;
use OCP\Security\ICrypto;
use OCP\AppFramework\ApiController;
use OCP\AppFramework\Controller;
use OCP\IRequest;
use OCP\IGroupManager;


class SmsrelentlessService {

     private $connection;
     private $crypto;
     private $groupManager;

     public function __construct(IDBConnection $connection, ICrypto $crypto, IGroupManager $groupManager) {

                $this->connection = $connection;
                $this->crypto = $crypto;
                $this->groupManager = $groupManager;
     }


     /**
      * @NoAdminRequired
      *
      */
     public function insertrecsms($userId, $recmessagearr) {

            $authorDisplayNm = '';
            $internalSender = 0;

            // Search for the sender's Display Name
            $getacdata = $this->connection->prepare('SELECT `uid`, `name`, `value` FROM `*PREFIX*accounts_data` WHERE `name` = ? AND `value` = ?');
            $getacdatares = $getacdata->execute(['phone', $recmessagearr[2]]);

            $acdatausers = [];
            while ($acusrfetched = $getacdatares->fetch()) {
                   $acdatausers[] = $acusrfetched['uid'];
            }
            $getacdatares->closeCursor();

            if ($acdatausers) {

                $acdatausrdn = [];
                foreach ($acdatausers as $dnkey => $dnvalue) {

                     $getacdatadn = $this->connection->prepare('SELECT `uid`, `name`, `value` FROM `*PREFIX*accounts_data` WHERE `uid` = ? AND `name` = ?');
	             $getacdatadnres = $getacdatadn->execute([$dnvalue, 'displayname']);

		     while ($acusrdnfetched = $getacdatadnres->fetch()) {
		            $acdatausrdn[] = $acusrdnfetched['value'];
		     }
		     $getacdatadnres->closeCursor();
                }

                if ($acdatausrdn) {

                    if (count($acdatausrdn) == 1) {

                        $authorDisplayNm = $acdatausrdn[0];
                        $internalSender = 1;

                    } elseif (count($acdatausrdn) > 1) {

                        $authorDisplayNm = implode("/", $acdatausrdn);
                        $internalSender = 1;
                    }

                } else { $authorDisplayNm = ''; $internalSender = 0; }

            } else {

                  // Search for the associated Display Name in the previous messages coming from the same number
                  $getdspnm = $this->connection->prepare('SELECT `from`, `author_displayname` FROM `*PREFIX*sms_relent_received` WHERE `from` = ? LIMIT 1');
	          $getdspnmres = $getdspnm->execute([$recmessagearr[2]]);
                  $dspnmfetched = $getdspnmres->fetch();
		  $authorDisplayNm = $dspnmfetched['author_displayname'];
		  $getdspnmres->closeCursor();
                  $internalSender = 0;
            }


            $escapedmessagepre = $recmessagearr[4];
            $escapedmessage = nl2br($escapedmessagepre);

            $sql = $this->connection->prepare('
				INSERT INTO `*PREFIX*sms_relent_received`
					(`user_id`, `message_id`, `date`, `from`, `to`, `message`, `author_displayname`, `internal_sender`)
				VALUES (?, ?, ?, ?, ?, ?, ?, ?)
			');
	    $sql->execute([$userId, $recmessagearr[0], $recmessagearr[1], $recmessagearr[2], $recmessagearr[3], $escapedmessage, $authorDisplayNm, $internalSender]);
     }


     /**
      * @NoAdminRequired
      *
      */
     public function insertsentsms($userId, $sentmessagearr) {

            $authorDisplayName = '';
            $msgsentfrompre = explode("+", $sentmessagearr[2]);
            $msgsentfrom = "+" . $msgsentfrompre[1];

            // Search for the sender's Display Name
            $getacdatast = $this->connection->prepare('SELECT `uid`, `name`, `value` FROM `*PREFIX*accounts_data` WHERE `name` = ? AND `value` = ?');
            $getacdatastres = $getacdatast->execute(['phone', $msgsentfrom]);

            $acdatausersst = [];
            while ($acusrstfetched = $getacdatastres->fetch()) {
                   $acdatausersst[] = $acusrstfetched['uid'];
            }
            $getacdatastres->closeCursor();

            if ($acdatausersst) {

                $acdatausrdnst = [];
                foreach ($acdatausersst as $dnstkey => $dnstvalue) {

                     $getacdatadnst = $this->connection->prepare('SELECT `uid`, `name`, `value` FROM `*PREFIX*accounts_data` WHERE `uid` = ? AND `name` = ?');
	             $getacdatadnstres = $getacdatadnst->execute([$dnstvalue, 'displayname']);

		     while ($acusrdnstfetched = $getacdatadnstres->fetch()) {
		            $acdatausrdnst[] = $acusrdnstfetched['value'];
		     }
		     $getacdatadnstres->closeCursor();
                }

                if ($acdatausrdnst) {

                    if (count($acdatausrdnst) == 1) {

                        $authorDisplayName = $acdatausrdnst[0];

                    } elseif (count($acdatausrdnst) > 1) {

                        $authorDisplayName = implode("/", $acdatausrdnst);
                    }

                } else { $authorDisplayName = ''; }

            } else { $authorDisplayName = ''; }


            $textwithnl = nl2br($sentmessagearr[8]);
            $sql = $this->connection->prepare('
				INSERT INTO `*PREFIX*sms_relent_sent`
					(`user_id`, `message_id`, `date`, `from`, `to`, `network`, `price`, `status`, `deliveryreceipt`, `message`, `author_displayname`)
				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
			');
	    $sql->execute([$userId, $sentmessagearr[0], $sentmessagearr[1], $sentmessagearr[2], $sentmessagearr[3], $sentmessagearr[4], $sentmessagearr[5], $sentmessagearr[6], 
                           $sentmessagearr[7], $textwithnl, $authorDisplayName]);
     }


     /**
      * @NoAdminRequired
      *
      */
     public function updatedeliverystatustel($ncuserfortelnyxdel, $messageid, $network, $messageprice, $messagestatus, $deliverystatus) {

	    $sqlupdateds = $this->connection->prepare('
			UPDATE `*PREFIX*sms_relent_sent`
			SET `price` = ?, `status` = ?, `deliveryreceipt` = ?, `network` = ?
                        WHERE `message_id` = ? AND `user_id` = ? ');
	    $updateRes = $sqlupdateds->execute([$messageprice, $messagestatus, $deliverystatus, $network, $messageid, $ncuserfortelnyxdel]);
	    $updateRes->closeCursor();
     }


     /**
      * @NoAdminRequired
      *
      */
     public function updatedeliverystatusnex($ncuserforplivodel, $messageid, $networkcode, $messageprice, $mStatus, $deliverystatus) {

	    $sqlupdatedspl = $this->connection->prepare('
			UPDATE `*PREFIX*sms_relent_sent`
			SET `price` = ?, `deliveryreceipt` = ?, `status` = ?, `network` = ?
                        WHERE `message_id` = ? AND `user_id` = ? ');
	    $updateResdspl = $sqlupdatedspl->execute([$messageprice, $deliverystatus, $mStatus, $networkcode, $messageid, $ncuserforplivodel]);
	    $updateResdspl->closeCursor();
     }


     /**
      * @NoAdminRequired
      *
      */
     public function updatedeliverystatustwil($ncuserfortwildel, $messageid, $networkcode, $messageprice, $mStatus, $deliverystatus) {

	    $sqlupdatedstw = $this->connection->prepare('
			UPDATE `*PREFIX*sms_relent_sent`
			SET `price` = ?, `deliveryreceipt` = ?, `status` = ?, `network` = ?
                        WHERE `message_id` = ? AND `user_id` = ? ');
	    $updateResdstw = $sqlupdatedstw->execute([$messageprice, $deliverystatus, $mStatus, $networkcode, $messageid, $ncuserfortwildel]);
	    $updateResdstw->closeCursor();
     }


     /**
      * @NoAdminRequired
      *
      */
     public function updatedeliverystatusflow($ncuserforflowdel, $messageid, $networkcode, $messageprice, $mStatus, $deliverystatus) {

	    $sqlupdatedsfl = $this->connection->prepare('
			UPDATE `*PREFIX*sms_relent_sent`
			SET `price` = ?, `deliveryreceipt` = ?, `status` = ?, `network` = ?
                        WHERE `message_id` = ? AND `user_id` = ? ');
	    $updateResdsfl = $sqlupdatedsfl->execute([$messageprice, $deliverystatus, $mStatus, $networkcode, $messageid, $ncuserforflowdel]);
	    $updateResdsfl->closeCursor();
     }


     /**
      * @NoAdminRequired
      */
     public function getreceivedtable($userId) {

        // Get the user's preferences from the settings
        $getgamcheckrc = $this->connection->prepare('
		       SELECT `user_id`, `show_all_messages`, `show_display_names`
		       FROM  `*PREFIX*sms_relent_settings` WHERE `user_id` = ?');
        $getgamcheckrcres = $getgamcheckrc->execute([$userId]);
        $getcrgamsrcpref = $getgamcheckrcres->fetch();
        $crgamsrcpref = $getcrgamsrcpref['show_all_messages'];
        $crdnmsrcpref = $getcrgamsrcpref['show_display_names'];
        $getgamcheckrcres->closeCursor();

        if ($crgamsrcpref == 1 && $this->groupManager->isAdmin($userId)) {

            if ($crdnmsrcpref == 1) {
	        $getrectable = $this->connection->prepare('
			SELECT `id`, `user_id`, `message_id`, `date`, `from`, `to`, `message`, `author_displayname`, `internal_sender`
			FROM  `*PREFIX*sms_relent_received`');
	        $rcresult = $getrectable->execute();
            } else {
	        $getrectable = $this->connection->prepare('
			SELECT `id`, `user_id`, `message_id`, `date`, `from`, `to`, `message`, `internal_sender`
			FROM  `*PREFIX*sms_relent_received`');
	        $rcresult = $getrectable->execute();
            }

        } else {

            if ($crdnmsrcpref == 1) {
	        $getrectable = $this->connection->prepare('
			SELECT `id`, `user_id`, `message_id`, `date`, `from`, `to`, `message`, `author_displayname`, `internal_sender`
			FROM  `*PREFIX*sms_relent_received`
			WHERE `user_id` = ?');
	        $rcresult = $getrectable->execute([$userId]);
            } else {
	        $getrectable = $this->connection->prepare('
			SELECT `id`, `user_id`, `message_id`, `date`, `from`, `to`, `message`, `internal_sender`
			FROM  `*PREFIX*sms_relent_received`
			WHERE `user_id` = ?');
	        $rcresult = $getrectable->execute([$userId]);
            }
        }

        $recdatatable = [];
        while ($rowfetched = $rcresult->fetch()) {
               $recdatatable[] = $rowfetched;
        }
	$rcresult->closeCursor();

        $recdatafromdb = $recdatatable;



        if ($this->groupManager->isAdmin($userId)) {

            return $recdatafromdb;

        } else {

            // Get the restrictions from the 'sms_relent_restrict' table
            $getrestr = $this->connection->prepare('
		       SELECT `phone_number`, `groups`, `users`
		       FROM  `*PREFIX*sms_relent_restrict`');
            $getrestrres = $getrestr->execute();

            $restrdata = [];
            while ($restrfetched = $getrestrres->fetch()) {
                   $restrdata[] = $restrfetched;
            }
            $getrestrres->closeCursor();

            if ($restrdata) {

                // Get the groups to which the current user belongs
                $getusrgrp = $this->connection->prepare('
		       SELECT `gid`, `uid`
		       FROM  `*PREFIX*group_user`
                       WHERE `uid` = ?');
                $getusrgrpres = $getusrgrp->execute([$userId]);

                $usergrps = [];
                while ($fetchedgrps = $getusrgrpres->fetch()) {
                       $usergrps[] = $fetchedgrps['gid'];
                }
                $getusrgrpres->closeCursor();

		// Get the Display Name of the current user
		$getacdatadn = $this->connection->prepare('SELECT `uid`, `name`, `value` FROM `*PREFIX*accounts_data` WHERE `uid` = ? AND `name` = ?');
		$getacdatadnres = $getacdatadn->execute([$userId, 'displayname']);
		$acdatausrdnadm = $getacdatadnres->fetch();
		$cruserdname = $acdatausrdnadm['value'];
		$getacdatadnres->closeCursor();

                // Get the phone numbers that are not allowed for the current user
                $restrPhoneNb = [];
                foreach ($restrdata as $rskey => $rsvalue) {

                       $restrgrparr = explode("|", $rsvalue['groups']);
                       $chck = 0;
                       foreach ($restrgrparr as $rkey => $rvalue) {
                                if (str_contains(implode("|", $usergrps), $rvalue)) { $chck++; }
                       }
                       if (str_contains($rsvalue['users'], $cruserdname)) { $chck++; }

                       if ($chck == 0) { $restrPhoneNb[] = $rsvalue['phone_number']; }
                }

                $restrPhoneNmbrs = array_unique($restrPhoneNb);

                // Clean the phone numbers from tags
                $restrPhfin = [];
                foreach ($restrPhoneNmbrs as $phkey => $phvalue) {

                    $restrpharr = explode(": ", $phvalue);
                    $restrPhfin[] = $restrpharr[1];
                }

                // Assemble the array of message rows that excludes the rows for the restricted phone numbers
                foreach ($recdatafromdb as $mdkey => $mdvalue) {

                    if (str_contains($mdvalue['to'], "+")) {
                        $fromnmbrarr = explode("+", $mdvalue['to']);
                        if (in_array("+" . $fromnmbrarr[1], $restrPhfin)) {
                            unset($recdatafromdb[$mdkey]);
                        }
                    } else {
                        $tonmbrarr = explode(": ", $mdvalue['to']);
                        if (count($tonmbrarr) == 2) {
                            $tonmbrtbcmprd = $tonmbrarr[1];
                        } else {
                            $tonmbrtbcmprd = $tonmbrarr[0];
                        }
                        if (in_array($tonmbrtbcmprd, $restrPhfin)) {
                            unset($recdatafromdb[$mdkey]);
                        }
                    }
                }

                $recdatafdbproc = array_values($recdatafromdb);

                return $recdatafdbproc;
            }
        }

     }


     /**
      * @NoAdminRequired
      */
     public function getreceivedtablefordel($userId) {

        if ($this->groupManager->isAdmin($userId)) {

            $getrecfordl = $this->connection->prepare('
			SELECT `id`, `user_id`, `message_id`, `date`, `from`, `to`, `message`
			FROM  `*PREFIX*sms_relent_received`
			WHERE `user_id` = ?');
	    $resultdl = $getrecfordl->execute([$userId]);

            $recdatatable = [];
            while ($rowfetched = $resultdl->fetch()) {
                   $recdatatable[] = $rowfetched;
            }
            $resultdl->closeCursor();

            $recdatafromdb = $recdatatable;

            return $recdatafromdb;

        } else { return "not permitted"; }
     }


     /**
      * @NoAdminRequired
      */
     public function removerecrows($userId, $recmessagedbIDs) {

        foreach ($recmessagedbIDs as $key => $rowtodel) {
		 $query = $this->connection->prepare('
		       DELETE FROM `*PREFIX*sms_relent_received`
		       WHERE `id` = ?');
		 $deleteResult = $query->execute([$rowtodel]);
		 $deleteResult->closeCursor();
        }

	$sqlupdate = $this->connection->prepare('
                  SET @resetrec = 0;
		  UPDATE `*PREFIX*sms_relent_received`
		  SET `id` = @resetrec := @resetrec + 1;
                  ALTER TABLE `*PREFIX*sms_relent_received` auto_increment=1;');
	$updateRes = $sqlupdate->execute();
	$updateRes->closeCursor();
     }


     /**
      * @NoAdminRequired
      */
     public function getsenttable($userId) {

        // Get the user's preferences from the settings
        $getgamcheck = $this->connection->prepare('
		       SELECT `user_id`, `show_all_messages`, `show_display_names`
		       FROM  `*PREFIX*sms_relent_settings` WHERE `user_id` = ?');
        $getgamcheckres = $getgamcheck->execute([$userId]);
        $getcrgamspref = $getgamcheckres->fetch();
        $crgamspref = $getcrgamspref['show_all_messages'];
        $crdnamespref = $getcrgamspref['show_display_names'];
        $getgamcheckres->closeCursor();

        if ($crgamspref == 1 && $this->groupManager->isAdmin($userId)) {

            if ($crdnamespref == 1) {
                $getsenttbl = $this->connection->prepare('
		       SELECT `id`, `user_id`, `message_id`, `date`, `from`, `to`, `network`, `price`, `status`, `deliveryreceipt`, `message`, `author_displayname`
		       FROM  `*PREFIX*sms_relent_sent`');
                $resultsent = $getsenttbl->execute();
            } else {
                $getsenttbl = $this->connection->prepare('
		       SELECT `id`, `user_id`, `message_id`, `date`, `from`, `to`, `network`, `price`, `status`, `deliveryreceipt`, `message`
		       FROM  `*PREFIX*sms_relent_sent`');
                $resultsent = $getsenttbl->execute();
            }

        } else {

            if ($crdnamespref == 1) {
                $getsenttbl = $this->connection->prepare('
		       SELECT `id`, `user_id`, `message_id`, `date`, `from`, `to`, `network`, `price`, `status`, `deliveryreceipt`, `message`, `author_displayname`
		       FROM  `*PREFIX*sms_relent_sent`
		       WHERE `user_id` = ?');
                $resultsent = $getsenttbl->execute([$userId]);
            } else {
                $getsenttbl = $this->connection->prepare('
		       SELECT `id`, `user_id`, `message_id`, `date`, `from`, `to`, `network`, `price`, `status`, `deliveryreceipt`, `message`
		       FROM  `*PREFIX*sms_relent_sent`
		       WHERE `user_id` = ?');
                $resultsent = $getsenttbl->execute([$userId]);
            }
        }

        $sentdatatable = [];
        while ($rowfetched = $resultsent->fetch()){
               $sentdatatable[] = $rowfetched;
        }
        $resultsent->closeCursor();

        $sentdatafromdb = $sentdatatable;


        if ($this->groupManager->isAdmin($userId)) {

            return $sentdatafromdb;

        } else {

            // Get the restrictions from the 'sms_relent_restrict' table
            $getrestr = $this->connection->prepare('
		       SELECT `phone_number`, `groups`, `users`
		       FROM  `*PREFIX*sms_relent_restrict`');
            $getrestrres = $getrestr->execute();

            $restrdata = [];
            while ($restrfetched = $getrestrres->fetch()) {
                   $restrdata[] = $restrfetched;
            }
            $getrestrres->closeCursor();

            if ($restrdata) {

                // Get the groups to which the current user belongs
                $getusrgrp = $this->connection->prepare('
		       SELECT `gid`, `uid`
		       FROM  `*PREFIX*group_user`
                       WHERE `uid` = ?');
                $getusrgrpres = $getusrgrp->execute([$userId]);

                $usergrps = [];
                while ($fetchedgrps = $getusrgrpres->fetch()) {
                       $usergrps[] = $fetchedgrps['gid'];
                }
                $getusrgrpres->closeCursor();

		// Get the Display Name of the current user
		$getacdatadn = $this->connection->prepare('SELECT `uid`, `name`, `value` FROM `*PREFIX*accounts_data` WHERE `uid` = ? AND `name` = ?');
		$getacdatadnres = $getacdatadn->execute([$userId, 'displayname']);
		$acdatausrdnadm = $getacdatadnres->fetch();
		$cruserdname = $acdatausrdnadm['value'];
		$getacdatadnres->closeCursor();

                // Get the phone numbers that are not allowed for the current user
                $restrPhoneNb = [];
                foreach ($restrdata as $rskey => $rsvalue) {

                       $restrgrparr = explode("|", $rsvalue['groups']);
                       $chck = 0;
                       foreach ($restrgrparr as $rkey => $rvalue) {
                                if (str_contains(implode("|", $usergrps), $rvalue)) { $chck++; }
                       }
                       if (str_contains($rsvalue['users'], $cruserdname)) { $chck++; }

                       if ($chck == 0) { $restrPhoneNb[] = $rsvalue['phone_number']; }
                }

                $restrPhoneNmbrs = array_unique($restrPhoneNb);

                // Clean the phone numbers from tags
                $restrPhfin = [];
                foreach ($restrPhoneNmbrs as $phkey => $phvalue) {

                    $restrpharr = explode(": ", $phvalue);
                    $restrPhfin[] = $restrpharr[1];
                }

                // Assemble the array of message rows that excludes the rows for the restricted phone numbers
                foreach ($sentdatafromdb as $smdkey => $smdvalue) {

                    if (str_contains($smdvalue['from'], "+")) {
                        $fromnmbrarr = explode("+", $smdvalue['from']);
                        if (in_array("+" . $fromnmbrarr[1], $restrPhfin)) {
                            unset($sentdatafromdb[$smdkey]);
                        }
                    } else {
                        $frmnmbrarr = explode(": ", $smdvalue['from']);
                        if (count($frmnmbrarr) == 2) {
                            $nmbtbcmprd = $frmnmbrarr[1];
                        } else { 
                            $nmbtbcmprd = $frmnmbrarr[0];
                        }

                        if (in_array($nmbtbcmprd, $restrPhfin)) {
                            unset($sentdatafromdb[$smdkey]);
                        }
                    }
                }

                $sentdatadbproc = array_values($sentdatafromdb);

                return $sentdatadbproc;
            }
        }
     }


     /**
      * @NoAdminRequired
      */
     public function getsenttablefordel($userId) {

        if ($this->groupManager->isAdmin($userId)) {

            $getsenttbldel = $this->connection->prepare('
		          SELECT `id`, `user_id`, `message_id`, `date`, `from`, `to`, `network`, `price`, `status`, `deliveryreceipt`, `message`
		          FROM  `*PREFIX*sms_relent_sent`
		          WHERE `user_id` = ?');
            $resultsentdl = $getsenttbldel->execute([$userId]);

            $sentdatatable = [];
            while ($rowfetched = $resultsentdl->fetch()){
                   $sentdatatable[] = $rowfetched;
            }
            $resultsentdl->closeCursor();

            $sentdatafromdb = $sentdatatable;

            return $sentdatafromdb;

        } else { return "not permitted"; }
     }


     /**
      * @NoAdminRequired
      */
     public function removesentrows($userId, $sentmessagedbIDs) {

        foreach ($sentmessagedbIDs as $key => $sentrowtodel) {
		 $query = $this->connection->prepare('
		       DELETE FROM `*PREFIX*sms_relent_sent`
		       WHERE `id` = ?');
		 $deleteResult = $query->execute([$sentrowtodel]);
		 $deleteResult->closeCursor();
        }

	$sqlupdate = $this->connection->prepare('
                  SET @resetsent = 0;
		  UPDATE `*PREFIX*sms_relent_sent`
		  SET `id` = @resetsent := @resetsent + 1;
                  ALTER TABLE `*PREFIX*sms_relent_sent` auto_increment=1;');
	$updateRes = $sqlupdate->execute();
	$updateRes->closeCursor();
     }


     /**
      * @NoAdminRequired
      */
     public function getgroupedtable($userId) {


        // Get the user's preferences from the settings
        $getpref = $this->connection->prepare('
		       SELECT `user_id`, `show_all_messages`
		       FROM  `*PREFIX*sms_relent_settings` WHERE `user_id` = ?');
        $getprefres = $getpref->execute([$userId]);
        $getprefresdata = $getprefres->fetch();
        $crsampref = $getprefresdata['show_all_messages'];
        $getprefres->closeCursor();


        // Get all the received messages
        if ($crsampref == 1 && $this->groupManager->isAdmin($userId)) {

            $getrecmsgs = $this->connection->prepare('
			SELECT `id`, `user_id`, `date`, `from`, `to`, `message`, `author_displayname`
			FROM  `*PREFIX*sms_relent_received`');
	    $getrecmsgsres = $getrecmsgs->execute();

        } else {

            $getrecmsgs = $this->connection->prepare('
			SELECT `id`, `user_id`, `date`, `from`, `to`, `message`, `author_displayname`
			FROM  `*PREFIX*sms_relent_received`
			WHERE `user_id` = ?');
	    $getrecmsgsres = $getrecmsgs->execute([$userId]);
        }

        $recmsgs = [];
        while ($rcrowsfetch = $getrecmsgsres->fetch()) {
               $rcrowsfetch['deliveryreceipt'] = '';
               $rcrowsfetch['table'] = 'received';
               $recmsgs[] = $rcrowsfetch;
        }
	$getrecmsgsres->closeCursor();


        // Get all the sent messages
        if ($crsampref == 1 && $this->groupManager->isAdmin($userId)) {

            $getsentmsgs = $this->connection->prepare('
		       SELECT `id`, `user_id`, `date`, `from`, `to`,`message`, `author_displayname`, `deliveryreceipt`
		       FROM  `*PREFIX*sms_relent_sent`');
            $getsentmsgsres = $getsentmsgs->execute();

        } else {

            $getsentmsgs = $this->connection->prepare('
		       SELECT `id`, `user_id`, `date`, `from`, `to`,`message`, `author_displayname`, `deliveryreceipt`
		       FROM  `*PREFIX*sms_relent_sent`
		       WHERE `user_id` = ?');
            $getsentmsgsres = $getsentmsgs->execute([$userId]);
        }

        $sentmsgs = [];
        while ($rowfetchedsmsg = $getsentmsgsres->fetch()) {
               $rowfetchedsmsg['table'] = 'sent';
               $sentmsgs[] = $rowfetchedsmsg;
        }
        $getsentmsgsres->closeCursor();

        $groupedfromdb = array_merge($recmsgs, $sentmsgs);

        if ($this->groupManager->isAdmin($userId)) {

            return $groupedfromdb;

        } else {

            // Get the restrictions from the 'sms_relent_restrict' table
            $getrestr = $this->connection->prepare('
		       SELECT `phone_number`, `groups`, `users`
		       FROM  `*PREFIX*sms_relent_restrict`');
            $getrestrres = $getrestr->execute();

            $restrdata = [];
            while ($restrfetched = $getrestrres->fetch()) {
                   $restrdata[] = $restrfetched;
            }
            $getrestrres->closeCursor();

            if ($restrdata) {

                // Get the groups to which the current user belongs
                $getusrgrp = $this->connection->prepare('
		       SELECT `gid`, `uid`
		       FROM  `*PREFIX*group_user`
                       WHERE `uid` = ?');
                $getusrgrpres = $getusrgrp->execute([$userId]);

                $usergrps = [];
                while ($fetchedgrps = $getusrgrpres->fetch()) {
                       $usergrps[] = $fetchedgrps['gid'];
                }
                $getusrgrpres->closeCursor();

		// Get the Display Name of the current user
		$getacdatadn = $this->connection->prepare('SELECT `uid`, `name`, `value` FROM `*PREFIX*accounts_data` WHERE `uid` = ? AND `name` = ?');
		$getacdatadnres = $getacdatadn->execute([$userId, 'displayname']);
		$acdatausrdnadm = $getacdatadnres->fetch();
		$cruserdname = $acdatausrdnadm['value'];
		$getacdatadnres->closeCursor();

                // Get the phone numbers that are not allowed for the current user
                $restrPhoneNb = [];
                foreach ($restrdata as $rskey => $rsvalue) {

                       $restrgrparr = explode("|", $rsvalue['groups']);
                       $chck = 0;
                       foreach ($restrgrparr as $rkey => $rvalue) {
                                if (str_contains(implode("|", $usergrps), $rvalue)) { $chck++; }
                       }
                       if (str_contains($rsvalue['users'], $cruserdname)) { $chck++; }

                       if ($chck == 0) { $restrPhoneNb[] = $rsvalue['phone_number']; }
                }

                $restrPhoneNmbrs = array_unique($restrPhoneNb);

                // Clean the phone numbers from tags
                $restrPhfin = [];
                foreach ($restrPhoneNmbrs as $phkey => $phvalue) {

                    $restrpharr = explode(": ", $phvalue);
                    $restrPhfin[] = $restrpharr[1];
                }

                // Assemble the array of message rows that excludes the rows for the restricted phone numbers
                foreach ($groupedfromdb as $gmdkey => $gmdvalue) {

                    if ($gmdvalue['user_id'] == $userId) {

                        if ($gmdvalue['table'] == 'sent') {

                            if (str_contains($gmdvalue['from'], "+")) {
                                $fromnmbrarr = explode("+", $gmdvalue['from']);
                                if (in_array("+" . $fromnmbrarr[1], $restrPhfin)) {
                                    unset($groupedfromdb[$gmdkey]);
                                }
                            } else {
                                $frmnmbrarr = explode(": ", $gmdvalue['from']);
                                if (count($frmnmbrarr) == 2) {
                                    $nmbtbcmprd = $frmnmbrarr[1];
                                } else { 
                                    $nmbtbcmprd = $frmnmbrarr[0];
                                }
                                if (in_array($nmbtbcmprd, $restrPhfin)) {
                                    unset($groupedfromdb[$gmdkey]);
                                }
                            }

                        } elseif ($gmdvalue['table'] == 'received') {

                            if (str_contains($gmdvalue['to'], "+")) {
                                $fromnmbrarr = explode("+", $gmdvalue['to']);
                                if (in_array("+" . $fromnmbrarr[1], $restrPhfin)) {
                                    unset($groupedfromdb[$gmdkey]);
                                }
                            } else {
                                $tonmbrarr = explode(": ", $gmdvalue['to']);
                                if (count($tonmbrarr) == 2) {
                                    $tonmbrtbcmprd = $tonmbrarr[1];
                                } else {
                                    $tonmbrtbcmprd = $tonmbrarr[0];
                                }
                                if (in_array($tonmbrtbcmprd, $restrPhfin)) {
                                    unset($groupedfromdb[$gmdkey]);
                                }
                            }
                        }

                    } else { unset($groupedfromdb[$gmdkey]); }

                }

                $groupedfdbproc = array_values($groupedfromdb);

                return $groupedfdbproc;
            }
        }
     }


     /**
      * @NoAdminRequired
      */
     public function getgroupedpernumber($userId, $phoneNumber) {

        $phoneNumberpr = "%" . $phoneNumber;

        // Get the user's preferences from the settings
        $getpref = $this->connection->prepare('
		       SELECT `user_id`, `show_all_messages`
		       FROM  `*PREFIX*sms_relent_settings` WHERE `user_id` = ?');
        $getprefres = $getpref->execute([$userId]);
        $getprefresdata = $getprefres->fetch();
        $crsampref = $getprefresdata['show_all_messages'];
        $getprefres->closeCursor();


        // Get all the received messages for the current number
        if ($crsampref == 1 && $this->groupManager->isAdmin($userId)) {

            $getrecmsgs = $this->connection->prepare('
			SELECT `id`, `user_id`, `date`, `from`, `to`, `message`, `author_displayname`
			FROM  `*PREFIX*sms_relent_received` WHERE `from` = ? OR `to` LIKE ?');
	    $getrecmsgsres = $getrecmsgs->execute([$phoneNumber, $phoneNumberpr]);

        } else {

            $getrecmsgs = $this->connection->prepare('
			SELECT `id`, `user_id`, `date`, `from`, `to`, `message`, `author_displayname`
			FROM  `*PREFIX*sms_relent_received`
			WHERE `user_id` = ? AND (`from` = ? OR `to` LIKE ?)');
	    $getrecmsgsres = $getrecmsgs->execute([$userId, $phoneNumber, $phoneNumberpr]);
        }

        $recmsgs = [];
        while ($rcrowsfetch = $getrecmsgsres->fetch()) {
               $rcrowsfetch['deliveryreceipt'] = '';
               $rcrowsfetch['table'] = 'received';
               $recmsgs[] = $rcrowsfetch;
        }
	$getrecmsgsres->closeCursor();


        // Get all the sent messages
        if ($crsampref == 1 && $this->groupManager->isAdmin($userId)) {

            $getsentmsgs = $this->connection->prepare('
		       SELECT `id`, `user_id`, `date`, `from`, `to`,`message`, `author_displayname`, `deliveryreceipt`
		       FROM  `*PREFIX*sms_relent_sent` WHERE `from` LIKE ? OR `to` = ?');
            $getsentmsgsres = $getsentmsgs->execute([$phoneNumberpr, $phoneNumber]);

        } else {

            $getsentmsgs = $this->connection->prepare('
		       SELECT `id`, `user_id`, `date`, `from`, `to`,`message`, `author_displayname`, `deliveryreceipt`
		       FROM  `*PREFIX*sms_relent_sent`
		       WHERE `user_id` = ? AND (`from` LIKE ? OR `to` = ?)');
            $getsentmsgsres = $getsentmsgs->execute([$userId, $phoneNumberpr, $phoneNumber]);
        }

        $sentmsgs = [];
        while ($rowfetchedsmsg = $getsentmsgsres->fetch()) {
               $rowfetchedsmsg['table'] = 'sent';
               $sentmsgs[] = $rowfetchedsmsg;
        }
        $getsentmsgsres->closeCursor();

        $groupedpernb = array_merge($recmsgs, $sentmsgs);

        if ($this->groupManager->isAdmin($userId)) {

            return $groupedpernb;

        } else {

            // Get the restrictions from the 'sms_relent_restrict' table
            $getrestr = $this->connection->prepare('
		       SELECT `phone_number`, `groups`, `users`
		       FROM  `*PREFIX*sms_relent_restrict`');
            $getrestrres = $getrestr->execute();

            $restrdata = [];
            while ($restrfetched = $getrestrres->fetch()) {
                   $restrdata[] = $restrfetched;
            }
            $getrestrres->closeCursor();

            if ($restrdata) {

                // Get the groups to which the current user belongs
                $getusrgrp = $this->connection->prepare('
		       SELECT `gid`, `uid`
		       FROM  `*PREFIX*group_user`
                       WHERE `uid` = ?');
                $getusrgrpres = $getusrgrp->execute([$userId]);

                $usergrps = [];
                while ($fetchedgrps = $getusrgrpres->fetch()) {
                       $usergrps[] = $fetchedgrps['gid'];
                }
                $getusrgrpres->closeCursor();

		// Get the Display Name of the current user
		$getacdatadn = $this->connection->prepare('SELECT `uid`, `name`, `value` FROM `*PREFIX*accounts_data` WHERE `uid` = ? AND `name` = ?');
		$getacdatadnres = $getacdatadn->execute([$userId, 'displayname']);
		$acdatausrdnadm = $getacdatadnres->fetch();
		$cruserdname = $acdatausrdnadm['value'];
		$getacdatadnres->closeCursor();

                // Get the phone numbers that are not allowed for the current user
                $restrPhoneNb = [];
                foreach ($restrdata as $rskey => $rsvalue) {

                       $restrgrparr = explode("|", $rsvalue['groups']);
                       $chck = 0;
                       foreach ($restrgrparr as $rkey => $rvalue) {
                                if (str_contains(implode("|", $usergrps), $rvalue)) { $chck++; }
                       }
                       if (str_contains($rsvalue['users'], $cruserdname)) { $chck++; }

                       if ($chck == 0) { $restrPhoneNb[] = $rsvalue['phone_number']; }
                }

                $restrPhoneNmbrs = array_unique($restrPhoneNb);

                // Clean the phone numbers from tags
                $restrPhfin = [];
                foreach ($restrPhoneNmbrs as $phkey => $phvalue) {

                    $restrpharr = explode(": ", $phvalue);
                    $restrPhfin[] = $restrpharr[1];
                }

                // Assemble the array of message rows that excludes the rows for the restricted phone numbers
                foreach ($groupedpernb as $gmdkey => $gmdvalue) {

                    if ($gmdvalue['user_id'] == $userId) {

                        if ($gmdvalue['table'] == 'sent') {

                            if (str_contains($gmdvalue['from'], "+")) {
                                $fromnmbrarr = explode("+", $gmdvalue['from']);
                                if (in_array("+" . $fromnmbrarr[1], $restrPhfin)) {
                                    unset($groupedpernb[$gmdkey]);
                                }
                            } else {
                                $frmnmbrarr = explode(": ", $gmdvalue['from']);
                                if (count($frmnmbrarr) == 2) {
                                    $nmbtbcmprd = $frmnmbrarr[1];
                                } else { 
                                    $nmbtbcmprd = $frmnmbrarr[0];
                                }
                                if (in_array($nmbtbcmprd, $restrPhfin)) {
                                    unset($groupedpernb[$gmdkey]);
                                }
                            }

                        } elseif ($gmdvalue['table'] == 'received') {

                            if (str_contains($gmdvalue['to'], "+")) {
                                $fromnmbrarr = explode("+", $gmdvalue['to']);
                                if (in_array("+" . $fromnmbrarr[1], $restrPhfin)) {
                                    unset($groupedpernb[$gmdkey]);
                                }
                            } else {
                                $tonmbrarr = explode(": ", $gmdvalue['to']);
                                if (count($tonmbrarr) == 2) {
                                    $tonmbrtbcmprd = $tonmbrarr[1];
                                } else {
                                    $tonmbrtbcmprd = $tonmbrarr[0];
                                }
                                if (in_array($tonmbrtbcmprd, $restrPhfin)) {
                                    unset($groupedpernb[$gmdkey]);
                                }
                            }
                        }

                    } else { unset($groupedpernb[$gmdkey]); }
                }

                $groupedpernb = array_values($groupedpernb);

                return $groupedpernb;
            }
        }
     }


     /**
      * @NoAdminRequired
      */
     public function savedisplayname($userId, $authorDisplayname, $from) {

        if ($this->groupManager->isAdmin($userId)) {

	    $updatedispnm = $this->connection->prepare('
			UPDATE `*PREFIX*sms_relent_received`
			SET `author_displayname` = ?
                        WHERE `from` = ?');
	    $updatedispnmres = $updatedispnm->execute([$authorDisplayname, $from]);

            if ($updatedispnmres) {
                return $respupdname = "The new Display Name has been saved. If on the Settings page the option 'Add the display name of the message author, before each message' is checked, when you refresh the page you will see the new Display Name before the messages.";
            } else {
                return $respupdname = "Error while trying to save the new Display Name to the database.";
            }
	    $updatedispnmres->closeCursor();

        } else { return $respupdname = "Only admins can save Display Names for phone numbers that are not associated with Nextcloud users."; }
     }

     /**
      * @NoAdminRequired
      */
     public function getmessagesperpage($userId) {

        $sqlmpp = $this->connection->prepare('
	       SELECT `user_id`, `messagesperpage` 
               FROM `*PREFIX*sms_relent_settings`
               WHERE `user_id` = ?');
	$result = $sqlmpp->execute([$userId]);
        $mesppdata = $result->fetch();
        $result->closeCursor();
        if ($mesppdata) {
            $mesperpagedb = $mesppdata['messagesperpage'];
            return $mesperpagedb;
        }
     }


     /**
      * @NoAdminRequired
      */
     public function getsettings($userId) {

        $getsettings = $this->connection->prepare('
                    SELECT `id`, `user_id`, `telapi_key`, `tel_pub_key`, `telapi_url_rec`, `telapi_url`, `messaging_profile_id`, `nexapi_key`, `nexapi_secret`, `nexapi_url_rec`,
                           `nexapi_url`, `tel_sender_name`, `nex_sender_name`, `messagesperpage`, `get_notify`, `notification_email`, `getsmsinemail`, `twilapi_key`, `twilapi_secret`, 
                           `twilapi_url_rec`, `twilapi_url`, `twil_sender_name`, `flowapi_key`, `flowapi_secret`, `flowapi_url_rec`, `flowapi_url`, `show_display_names`
		    FROM  `*PREFIX*sms_relent_settings`
		    WHERE `user_id` = ?');

        $resultsettings = $getsettings->execute([$userId]);

        $settingsfromdb = $resultsettings->fetch();

        $resultsettings->closeCursor();

        if ($settingsfromdb) {

            if ($settingsfromdb['telapi_key'] != '') {

                // Send a placeholder to the browser, instead of the real API key
                $settingsfromdb['telapi_key'] = "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20";
            }
            if ($settingsfromdb['tel_pub_key'] != '') {
                $settingsfromdb['tel_pub_key'] = "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20";
            }
            if ($settingsfromdb['messaging_profile_id'] != '') {
                $settingsfromdb['messaging_profile_id'] = "%20%20%20%20%20%20%20%20%20%20%20%20";
            }
            if ($settingsfromdb['nexapi_key'] != '') {
                $settingsfromdb['nexapi_key'] = "%20%20%20%20%20%20%20%20%20";
            }
            if ($settingsfromdb['nexapi_secret'] != '') {
                $settingsfromdb['nexapi_secret'] = "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20";
            }
            if ($settingsfromdb['twilapi_key'] != '') {
                $settingsfromdb['twilapi_key'] = "%20%20%20%20%20%20%20%20%20";
            }
            if ($settingsfromdb['twilapi_secret'] != '') {
                $settingsfromdb['twilapi_secret'] = "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20";
            }
            if ($settingsfromdb['flowapi_key'] != '') {
                $settingsfromdb['flowapi_key'] = "%20%20%20%20%20%20%20%20%20";
            }
            if ($settingsfromdb['flowapi_secret'] != '') {
                $settingsfromdb['flowapi_secret'] = "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20";
            }

            return $settingsfromdb;
        }

     }


     public function updatenumberrestrictions($userId, $savedByDsplname, $phoneNumber, $groups, $users) {

        if ($this->groupManager->isAdmin($userId)) {

            $groupsproc = implode("|", $groups);
            $usersproc = implode("|", $users);

            // Get the restrictions for the current number from the 'sms_relent_restrict' table
            $getrestr = $this->connection->prepare('SELECT `user_id`, `saved_by_dsplname`, `phone_number`, `groups`, `users` FROM `*PREFIX*sms_relent_restrict` WHERE
                                                   `phone_number` = ?');
            $getrestrresult = $getrestr->execute([$phoneNumber]);
            $crntrestr = $getrestrresult->fetch();
            $getrestrresult->closeCursor();

            if ($getrestrresult && !$crntrestr) {

	        $insertphrestr = $this->connection->prepare('INSERT INTO `*PREFIX*sms_relent_restrict` (`user_id`, `saved_by_dsplname`, `phone_number`, `groups`, `users`) VALUES
                                                             (?, ?, ?, ?, ?)');
	        if ($insertphrestr->execute([$userId, $savedByDsplname, $phoneNumber, $groupsproc, $usersproc])) { $messagetosend = 'success'; } else { $messagetosend = 'failure'; }  
         
            } elseif ($getrestrresult && $crntrestr) {

	        $updatephrestr = $this->connection->prepare('UPDATE `*PREFIX*sms_relent_restrict` SET `user_id` = ?, `saved_by_dsplname` = ?, `groups` = ?, `users` = ? WHERE 
                                                            `phone_number` = ?');
	        if ($admupdatephonerestr = $updatephrestr->execute([$userId, $savedByDsplname, $groupsproc, $usersproc, $phoneNumber])) { 
                    $messagetosend = 'success';
                } else { 
                    $messagetosend = 'failure'; 
                }

	        $admupdatephonerestr->closeCursor();
            }
            return $messagetosend;
        }
     }


     public function removenumberrestrictions($userId, $phoneNumber) {

        if ($this->groupManager->isAdmin($userId)) {

                // Remove the restrictions for the given phone number
		$delrstr = $this->connection->prepare('
		       DELETE FROM `*PREFIX*sms_relent_restrict`
		       WHERE `phone_number` = ?');
                if ($delrstrres = $delrstr->execute([$phoneNumber])) { $delresult = "success"; } else { $delresult = "failure"; }
		$delrstrres->closeCursor();

	        $updateind = $this->connection->prepare('
                       SET @resetrec = 0;
		       UPDATE `*PREFIX*sms_relent_restrict`
		       SET `id` = @resetrec := @resetrec + 1;
                       ALTER TABLE `*PREFIX*sms_relent_restrict` auto_increment=1;');
	        $updateindres = $updateind->execute();
	        $updateindres->closeCursor();

                return $delresult;
        }
     }


    /**
     * @NoAdminRequired
     */
    public function updateautoreplies($userId, $savedByDsplname, $phoneNumber, $daysOfWeek, $dailyStart, $dailyEnd, $vacationStart, $vacationEnd, $messageText) {

        // Get the auto-reply for the current number from the 'sms_relent_autorply' table
        $getarpl = $this->connection->prepare('SELECT `user_id`, `saved_by_dsplname`, `phone_number`, `days_of_week`, `daily_start`, `daily_end`, `vacation_start`,
                                              `vacation_end`, `message_text` FROM `*PREFIX*sms_relent_autorply` WHERE `phone_number` = ?');
        $getarplresult = $getarpl->execute([$phoneNumber]);
        $crntarpl = $getarplresult->fetch();
        $getarplresult->closeCursor();

        if ($getarplresult && !$crntarpl) {

	    $insertpharpl = $this->connection->prepare('INSERT INTO `*PREFIX*sms_relent_autorply` (`user_id`, `saved_by_dsplname`, `phone_number`, `days_of_week`, 
                                                       `daily_start`, `daily_end`, `vacation_start`, `vacation_end`, `message_text`) VALUES
                                                        (?, ?, ?, ?, ?, ?, ?, ?, ?)');
	    if ($insertpharpl->execute([$userId, $savedByDsplname, $phoneNumber, $daysOfWeek, $dailyStart, $dailyEnd, $vacationStart, $vacationEnd, $messageText])) { 
                $messagetosend = 'success'; 
            } else { 
                $messagetosend = 'failure'; 
            }
         
        } elseif ($getarplresult && $crntarpl) {

            if ($this->groupManager->isAdmin($userId)) {

                $updatepharpl = $this->connection->prepare('UPDATE `*PREFIX*sms_relent_autorply` SET `user_id` = ?, `saved_by_dsplname` = ?, `days_of_week` = ?, `daily_start` = ?,
                                                           `daily_end` = ?, `vacation_start` = ?, `vacation_end` = ?, `message_text` = ?  WHERE `phone_number` = ?');
	        if ($updatephnmbrarpl = $updatepharpl->execute([$userId, $savedByDsplname, $daysOfWeek, $dailyStart, $dailyEnd, $vacationStart, $vacationEnd, $messageText,
                                                                $phoneNumber])) { 
                    $messagetosend = 'success';
                } else { 
                    $messagetosend = 'failure'; 
                }
	        $updatephnmbrarpl->closeCursor();

            } else {

                // Check if the current user is the author of the existing version of the auto-reply
                if ($userId == $crntarpl['user_id']) {

                    $updatepharpl = $this->connection->prepare('UPDATE `*PREFIX*sms_relent_autorply` SET `user_id` = ?, `saved_by_dsplname` = ?, `days_of_week` = ?, `daily_start` = ?,
                                                               `daily_end` = ?, `vacation_start` = ?, `vacation_end` = ?, `message_text` = ?  WHERE `phone_number` = ?');
	            if ($updatephnmbrarpl = $updatepharpl->execute([$userId, $savedByDsplname, $daysOfWeek, $dailyStart, $dailyEnd, $vacationStart, $vacationEnd, $messageText,
                                                                    $phoneNumber])) { 
                        $messagetosend = 'success';
                    } else { 
                        $messagetosend = 'failure'; 
                    }
	            $updatephnmbrarpl->closeCursor();

                } else { $messagetosend = 'not allowed'; }
            }
        }

        return $messagetosend;
    }


    /**
     * @NoAdminRequired
     */
    public function removeautoreplies($userId, $phoneNumber) {

        if ($this->groupManager->isAdmin($userId)) {

                // Remove the auto-reply for the given phone number
		$delarpl = $this->connection->prepare('
		       DELETE FROM `*PREFIX*sms_relent_autorply`
		       WHERE `phone_number` = ?');
                if ($delarplres = $delarpl->execute([$phoneNumber])) { $delarplresult = "success"; } else { $delarplresult = "failure"; }
		$delarplres->closeCursor();

	        $updateindarpl = $this->connection->prepare('
                       SET @resetarpl = 0;
		       UPDATE `*PREFIX*sms_relent_autorply`
		       SET `id` = @resetarpl := @resetarpl + 1;
                       ALTER TABLE `*PREFIX*sms_relent_autorply` auto_increment=1;');
	        $updateindarplres = $updateindarpl->execute();
	        $updateindarplres->closeCursor();

                return $delarplresult;

        } else {
                // Get the author of the auto-reply for the given phone number
		$getarplusr = $this->connection->prepare('SELECT `user_id`, `phone_number` FROM `*PREFIX*sms_relent_autorply` WHERE `phone_number` = ?');
		$getarplusrres = $getarplusr->execute([$phoneNumber]);
		$crntarpldata = $getarplusrres->fetch();
                $crntarpluser = $crntarpldata['user_id'];
		$getarplusrres->closeCursor();

                // If the author of the auto-reply is the current user, allow the removal
                if ($crntarpluser == $userId) {

                    // Remove the auto-reply for the given phone number
		    $delarpl = $this->connection->prepare('
		           DELETE FROM `*PREFIX*sms_relent_autorply`
		           WHERE `phone_number` = ?');
                    if ($delarplres = $delarpl->execute([$phoneNumber])) { $delarplresult = "success"; } else { $delarplresult = "failure"; }
		    $delarplres->closeCursor();

	            $updateindarpl = $this->connection->prepare('
                           SET @resetarpl = 0;
		           UPDATE `*PREFIX*sms_relent_autorply`
		           SET `id` = @resetarpl := @resetarpl + 1;
                           ALTER TABLE `*PREFIX*sms_relent_autorply` auto_increment=1;');
	            $updateindarplres = $updateindarpl->execute();
	            $updateindarplres->closeCursor();

                    return $delarplresult;

                } else { 
                    return $delarplresult = 'not allowed';
                }
        }
    }


     public function getadminsettings($userId) {

        if ($this->groupManager->isAdmin($userId)) {

	    // Get the 'show_all_messages' option for the current admin
	    $getsettingsadm = $this->connection->prepare('SELECT `user_id`, `show_all_messages` FROM `*PREFIX*sms_relent_settings` WHERE `user_id` = ?');
	    $getadmsetresult = $getsettingsadm->execute([$userId]);
	    $settingsfdbadm = $getadmsetresult->fetch();
	    $getadmsetresult->closeCursor();

	    if ($settingsfdbadm) {

		    // Get the Display Name of the current admin
		    $getacdatadn = $this->connection->prepare('SELECT `uid`, `name`, `value` FROM `*PREFIX*accounts_data` WHERE `uid` = ? AND `name` = ?');
		    $getacdatadnres = $getacdatadn->execute([$userId, 'displayname']);
		    $acdatausrdnadm = $getacdatadnres->fetch();
		    $cruserdname = $acdatausrdnadm['value'];
		    $getacdatadnres->closeCursor();

		    // Get all the restrictions on phone numbers
		    $getrestr = $this->connection->prepare('SELECT `saved_by_dsplname`, `phone_number`, `groups`, `users` FROM `*PREFIX*sms_relent_restrict`');
		    $getrestres = $getrestr->execute();

		    $restrictedArr = [];
		    while ($restrfetched = $getrestres->fetch()) {
		           $restrictedArr[] = $restrfetched;
		    }
		    $getrestres->closeCursor();

		    if ($restrictedArr) { $restrictedUsers = $restrictedArr; } else { $restrictedUsers = ''; }

		    // Get the name of all groups
		    $getgroups = $this->connection->prepare('SELECT `gid`, `displayname` FROM `*PREFIX*groups`');
		    $getgroupsres = $getgroups->execute();

		    $groupsArr = [];
		    while ($groupsfetched = $getgroupsres->fetch()) {
		           $groupsArr[] = $groupsfetched;
		    }
		    $getgroupsres->closeCursor();

		    if ($groupsArr) { $allgroups = $groupsArr; } else { $allgroups = ''; }


		    // Get the name of all users
		    $getusers = $this->connection->prepare('SELECT `uid`, `name`, `value` FROM `*PREFIX*accounts_data` WHERE `name` = ?');
		    $getusersres = $getusers->execute(['displayname']);

		    $usersArr = [];
		    while ($usersfetched = $getusersres->fetch()) {
		           $usersArr[] = $usersfetched;
		    }
		    $getusersres->closeCursor();

		    if ($usersArr) { $allusers = $usersArr; } else { $allusers = ''; }


		    $settingsadm = ['show_all_messages' => $settingsfdbadm['show_all_messages'], 'admdisplayname' => $cruserdname, 'restrictions' => $restrictedUsers, 
		                    'allgroups' => $allgroups, 'allusers' => $allusers];

		    return $settingsadm;
	    }
        }
     }


     /**
      * @NoAdminRequired
      *
      */
     public function updatesettings($userId, $telapiKey, $telPubKey, $telapiUrlRec, $telapiUrl, $messagingProfileId, $nexapiKey, $nexapiSecret, $nexapiUrlRec, $nexapiUrl,
                                    $telSenderName, $nexSenderName, $messagesperpage, $getNotify, $notificationEmail, $getsmsinemail, $twilapiKey, $twilapiSecret, 
                                    $twilapiUrlRec, $twilapiUrl, $twilSenderName, $flowapiKey, $flowapiSecret, $flowapiUrlRec, $flowapiUrl, $showDisplayNames) {

        $upsettings = $this->connection->prepare('
                   SELECT `id`, `user_id`, `telapi_key`, `tel_pub_key`, `telapi_url_rec`, `telapi_url`, `messaging_profile_id`, `nexapi_key`, `nexapi_secret`, `nexapi_url_rec`,
                          `nexapi_url`, `tel_sender_name`, `nex_sender_name`, `messagesperpage`, `get_notify`, `notification_email`, `getsmsinemail`, `twilapi_key`, `twilapi_secret`,
                          `twilapi_url_rec`, `twilapi_url`, `twil_sender_name`, `flowapi_key`, `flowapi_secret`, `flowapi_url_rec`, `flowapi_url`, `show_display_names`
		   FROM  `*PREFIX*sms_relent_settings`
		   WHERE `user_id` = ?');

        $resultstng = $upsettings->execute([$userId]);

        $rowup = $resultstng->fetch();

        $resultstng->closeCursor();

        if ($resultstng && !$rowup) {

	    if ($telapiKey != '') {
	        $telapikeystrenc = $this->crypto->encrypt($telapiKey);             
	    } else { $telapikeystrenc = ''; }

	    if ($telPubKey != '') {
	        $telpubkeystrenc =  $this->crypto->encrypt($telPubKey);             
	    } else { $telpubkeystrenc = ''; }

	    if ($messagingProfileId != '') {
	        $messagingprofenc = $this->crypto->encrypt($messagingProfileId);             
	    } else { $messagingprofenc = ''; }

	    if ($nexapiKey != '') {
	        $nexapikeystrenc = $this->crypto->encrypt($nexapiKey);             
	    } else { $nexapikeystrenc = ''; }

	    if ($nexapiSecret != '') {
	        $nexapisecretstrenc = $this->crypto->encrypt($nexapiSecret);             
	    } else { $nexapisecretstrenc = ''; }

	    if ($twilapiKey != '') {
	        $twilapikeystrenc = $this->crypto->encrypt($twilapiKey);             
	    } else { $twilapikeystrenc = ''; }

	    if ($twilapiSecret != '') {
	        $twilapisecretstrenc = $this->crypto->encrypt($twilapiSecret);             
	    } else { $twilapisecretstrenc = ''; }

	    if ($flowapiKey != '') {
	        $flowapikeystrenc = $this->crypto->encrypt($flowapiKey);             
	    } else { $flowapikeystrenc = ''; }

	    if ($flowapiSecret != '') {
	        $flowapisecretstrenc = $this->crypto->encrypt($flowapiSecret);             
	    } else { $flowapisecretstrenc = ''; }

	    $sql = $this->connection->prepare('
				INSERT INTO `*PREFIX*sms_relent_settings`
					(`user_id`, `telapi_key`, `tel_pub_key`, `telapi_url_rec`, `telapi_url`, `messaging_profile_id`, `nexapi_key`, `nexapi_secret`, `nexapi_url_rec`, 
	                                 `nexapi_url`, `tel_sender_name`, `nex_sender_name`, `messagesperpage`, `get_notify`, `notification_email`, `getsmsinemail`, `twilapi_key`, 
	                                 `twilapi_secret`, `twilapi_url_rec`, `twilapi_url`, `twil_sender_name`, `flowapi_key`, `flowapi_secret`, `flowapi_url_rec`, `flowapi_url`,
                                         `show_display_names`)
				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
			');
	    $sql->execute([$userId, $telapikeystrenc, $telpubkeystrenc, $telapiUrlRec, $telapiUrl, $messagingprofenc, $nexapikeystrenc, $nexapisecretstrenc, $nexapiUrlRec, $nexapiUrl, 
	                   $telSenderName, $nexSenderName, $messagesperpage, $getNotify, $notificationEmail, $getsmsinemail, $twilapikeystrenc, $twilapisecretstrenc, $twilapiUrlRec, 
	                   $twilapiUrl, $twilSenderName, $flowapikeystrenc, $flowapisecretstrenc, $flowapiUrlRec, $flowapiUrl, $showDisplayNames]);

        } elseif ($resultstng && $rowup) {

	    // Check if the value of the field is the placeholder or an empty string
	    if ($telapiKey != '' && $telapiKey != "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20") {
	        $telapikeystrenc = $this->crypto->encrypt($telapiKey);                
	    } elseif ($telapiKey == "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20") {
	        $telapikeystrenc = $rowup['telapi_key'];
	    } elseif ($telapiKey == '') {
	        $telapikeystrenc = '';
	    }

	    if ($telPubKey != '' && $telPubKey != "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20") {
	        $telpubkeystrenc = $this->crypto->encrypt($telPubKey);                
	    } elseif ($telPubKey == "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20") {
	        $telpubkeystrenc = $rowup['tel_pub_key'];
	    } elseif ($telPubKey == '') {
	        $telpubkeystrenc = '';
	    }

	    if ($messagingProfileId != '' && $messagingProfileId != "%20%20%20%20%20%20%20%20%20%20%20%20") {
	        $messagingprofenc = $this->crypto->encrypt($messagingProfileId);                
	    } elseif ($messagingProfileId == "%20%20%20%20%20%20%20%20%20%20%20%20") {
	        $messagingprofenc = $rowup['messaging_profile_id'];
	    } elseif ($messagingProfileId == '') {
	        $messagingprofenc = '';
	    }

	    if ($nexapiKey != '' && $nexapiKey != "%20%20%20%20%20%20%20%20%20") {
	        $nexapikeystrenc = $this->crypto->encrypt($nexapiKey);                
	    } elseif ($nexapiKey == "%20%20%20%20%20%20%20%20%20") {
	        $nexapikeystrenc = $rowup['nexapi_key'];
	    } elseif ($nexapiKey == '') {
	        $nexapikeystrenc = '';
	    }

	    if ($twilapiKey != '' && $twilapiKey != "%20%20%20%20%20%20%20%20%20") {
	        $twilapikeystrenc = $this->crypto->encrypt($twilapiKey);                
	    } elseif ($twilapiKey == "%20%20%20%20%20%20%20%20%20") {
	        $twilapikeystrenc = $rowup['twilapi_key'];
	    } elseif ($twilapiKey == '') {
	        $twilapikeystrenc = '';
	    }

	    if ($flowapiKey != '' && $flowapiKey != "%20%20%20%20%20%20%20%20%20") {
	        $flowapikeystrenc = $this->crypto->encrypt($flowapiKey);                
	    } elseif ($flowapiKey == "%20%20%20%20%20%20%20%20%20") {
	        $flowapikeystrenc = $rowup['flowapi_key'];
	    } elseif ($flowapiKey == '') {
	        $flowapikeystrenc = '';
	    }

	    if ($nexapiSecret != '' && $nexapiSecret != "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20") {
	        $nexapisecretstrenc = $this->crypto->encrypt($nexapiSecret);                
	    } elseif ($nexapiSecret == "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20") {
	        $nexapisecretstrenc = $rowup['nexapi_secret'];
	    } elseif ($nexapiSecret == '') {
	        $nexapisecretstrenc = '';
	    }

	    if ($twilapiSecret != '' && $twilapiSecret != "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20") {
	        $twilapisecretstrenc = $this->crypto->encrypt($twilapiSecret);                
	    } elseif ($twilapiSecret == "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20") {
	        $twilapisecretstrenc = $rowup['twilapi_secret'];
	    } elseif ($twilapiSecret == '') {
	        $twilapisecretstrenc = '';
	    }

	    if ($flowapiSecret != '' && $flowapiSecret != "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20") {
	        $flowapisecretstrenc = $this->crypto->encrypt($flowapiSecret);                
	    } elseif ($flowapiSecret == "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20") {
	        $flowapisecretstrenc = $rowup['flowapi_secret'];
	    } elseif ($flowapiSecret == '') {
	        $flowapisecretstrenc = '';
	    }

	    $sqlupdatedb = $this->connection->prepare('
			UPDATE `*PREFIX*sms_relent_settings`
			SET `telapi_key` = ?, `tel_pub_key` = ?, `telapi_url_rec` = ?, `telapi_url` = ?, `messaging_profile_id` = ?, `nexapi_key` = ?, `nexapi_secret` = ?,
	                    `nexapi_url_rec` = ?, `nexapi_url` = ?, `tel_sender_name` = ?, `nex_sender_name` = ?, `messagesperpage` = ?, `get_notify` = ?, `notification_email` = ?,
	                    `getsmsinemail` = ?, `twilapi_key` = ?, `twilapi_secret` = ?, `twilapi_url_rec` = ?, `twilapi_url` = ?, `twil_sender_name` = ?, `flowapi_key` = ?, 
	                    `flowapi_secret` = ?, `flowapi_url_rec` = ?, `flowapi_url` = ?, `show_display_names` = ?
	                WHERE `user_id` = ?');
	    $updateRes = $sqlupdatedb->execute([$telapikeystrenc, $telpubkeystrenc, $telapiUrlRec, $telapiUrl, $messagingprofenc, $nexapikeystrenc, $nexapisecretstrenc, $nexapiUrlRec,
	                                        $nexapiUrl, $telSenderName, $nexSenderName, $messagesperpage, $getNotify, $notificationEmail, $getsmsinemail, $twilapikeystrenc, 
	                                        $twilapisecretstrenc, $twilapiUrlRec, $twilapiUrl, $twilSenderName, $flowapikeystrenc, $flowapisecretstrenc, $flowapiUrlRec, 
	                                        $flowapiUrl, $showDisplayNames, $userId]);
	    $updateRes->closeCursor();

	}
     }


    public function updateadminsettings($userId, $showAllMessages) {

        if ($this->groupManager->isAdmin($userId)) {

            $upsettingsadm = $this->connection->prepare('SELECT `id`, `user_id`, `show_all_messages` FROM `*PREFIX*sms_relent_settings` WHERE `user_id` = ?');

            $resultstngadm = $upsettingsadm->execute([$userId]);

            $rowupadm = $resultstngadm->fetch();

            $resultstngadm->closeCursor();

            if ($resultstngadm && !$rowupadm) {

	        $sqladm = $this->connection->prepare('INSERT INTO `*PREFIX*sms_relent_settings` (`user_id`, `show_all_messages`) VALUES (?, ?)');
	        $sqladm->execute([$userId, $showAllMessages]);

            } elseif ($resultstngadm && $rowupadm) {

	        $sqlupdatedbadm = $this->connection->prepare('UPDATE `*PREFIX*sms_relent_settings` SET `show_all_messages` = ? WHERE `user_id` = ?');
	        $updateResadm = $sqlupdatedbadm->execute([$showAllMessages, $userId]);
	        $updateResadm->closeCursor();
            }
        }
    }

    /**
     * @NoAdminRequired
     */
    public function getapicredentials($userId) {

        $sqlcr = $this->connection->prepare('
              SELECT `id`, `user_id`, `telapi_key`, `tel_pub_key`, `telapi_url_rec`, `telapi_url`, `messaging_profile_id`, `nexapi_key`, `nexapi_secret`, `nexapi_url_rec`, `nexapi_url`,
                     `tel_sender_name`, `nex_sender_name`, `messagesperpage`, `get_notify`, `notification_email`, `getsmsinemail`, `twilapi_key`, `twilapi_secret`, `twilapi_url_rec`, 
                     `twilapi_url`, `twil_sender_name`, `flowapi_key`, `flowapi_secret`, `flowapi_url_rec`, `flowapi_url` FROM `*PREFIX*sms_relent_settings`
	      WHERE `user_id` = ?');
	$resultcr = $sqlcr->execute([$userId]);
        $settingsfrdb = $resultcr->fetch();
        $resultcr->closeCursor();

        if (($settingsfrdb['telapi_key'] != '') && ($settingsfrdb['telapi_key'] != 'undefined') && ($settingsfrdb['telapi_key'] != null)) { 
             $telapikeystrdec = $this->crypto->decrypt($settingsfrdb['telapi_key']); 
        } else { $telapikeystrdec = ''; }

        if (($settingsfrdb['tel_pub_key'] != '') && ($settingsfrdb['tel_pub_key'] != 'undefined') && ($settingsfrdb['tel_pub_key'] != null)) {
             $telpubkeystrdec = $this->crypto->decrypt($settingsfrdb['tel_pub_key']); 
        } else { $telpubkeystrdec = ''; }

        $telapiurlrec = $settingsfrdb['telapi_url_rec'];
        $telapiurlstr = $settingsfrdb['telapi_url'];

        if (($settingsfrdb['messaging_profile_id'] != '') && ($settingsfrdb['messaging_profile_id'] != 'undefined') && ($settingsfrdb['messaging_profile_id'] != null)) {
             $messagingprofid = $this->crypto->decrypt($settingsfrdb['messaging_profile_id']); 
        } else { $messagingprofid = ''; }

        if (($settingsfrdb['nexapi_key'] != '') && ($settingsfrdb['nexapi_key'] != 'undefined') && ($settingsfrdb['nexapi_key'] != null)) { 
             $nexapikeystr = $this->crypto->decrypt($settingsfrdb['nexapi_key']); 
        } else { $nexapikeystr = ''; }

        if (($settingsfrdb['nexapi_secret'] != '') && ($settingsfrdb['nexapi_secret'] != 'undefined') && ($settingsfrdb['nexapi_secret'] != null)) { 
             $nexapisecretstr = $this->crypto->decrypt($settingsfrdb['nexapi_secret']); 
        } else { $nexapisecretstr = ''; }

        if (($settingsfrdb['twilapi_key'] != '') && ($settingsfrdb['twilapi_key'] != 'undefined') && ($settingsfrdb['twilapi_key'] != null)) { 
             $twilapikeystr = $this->crypto->decrypt($settingsfrdb['twilapi_key']); 
        } else { $twilapikeystr = ''; }

        if (($settingsfrdb['twilapi_secret'] != '') && ($settingsfrdb['twilapi_secret'] != 'undefined') && ($settingsfrdb['twilapi_secret'] != null)) { 
             $twilapisecretstr = $this->crypto->decrypt($settingsfrdb['twilapi_secret']); 
        } else { $twilapisecretstr = ''; }

        if (($settingsfrdb['flowapi_key'] != '') && ($settingsfrdb['flowapi_key'] != 'undefined') && ($settingsfrdb['flowapi_key'] != null)) { 
             $flowapikeystr = $this->crypto->decrypt($settingsfrdb['flowapi_key']); 
        } else { $flowapikeystr = ''; }

        if (($settingsfrdb['flowapi_secret'] != '') && ($settingsfrdb['flowapi_secret'] != 'undefined') && ($settingsfrdb['flowapi_secret'] != null)) { 
             $flowapisecretstr = $this->crypto->decrypt($settingsfrdb['flowapi_secret']); 
        } else { $flowapisecretstr = ''; }

        $nexapiurlrecsms = $settingsfrdb['nexapi_url_rec'];
        $nexapiurldelrcpt = $settingsfrdb['nexapi_url'];
        $twilapiurlrecsms = $settingsfrdb['twilapi_url_rec'];
        $twilapiurldelrcpt = $settingsfrdb['twilapi_url'];
        $flowapiurlrecsms = $settingsfrdb['flowapi_url_rec'];
        $flowapiurldelrcpt = $settingsfrdb['flowapi_url'];
        $gettelsendername = $settingsfrdb['tel_sender_name'];
        $getnexsendername = $settingsfrdb['nex_sender_name'];
        $gettwilsendername = $settingsfrdb['twil_sender_name'];
        $getmessagesperpage = $settingsfrdb['messagesperpage'];
        $getnotification = $settingsfrdb['get_notify'];
        $notifyemail = $settingsfrdb['notification_email'];
        $includesmsinemail = $settingsfrdb['getsmsinemail'];

        return [$telapikeystrdec, $telpubkeystrdec, $telapiurlrec, $telapiurlstr, $messagingprofid, $nexapikeystr, $nexapisecretstr, $nexapiurlrecsms, $nexapiurldelrcpt,
                $gettelsendername, $getnexsendername, $getmessagesperpage, $getnotification, $notifyemail, $includesmsinemail, $twilapikeystr, $twilapisecretstr, $twilapiurlrecsms, 
                $twilapiurldelrcpt, $gettwilsendername,  $flowapikeystr, $flowapisecretstr, $flowapiurlrecsms, $flowapiurldelrcpt];
    }

    /**
     * @NoAdminRequired
     */
    public function getuserbytelrecwhurl($recsmswebhookurl) {

        $sqlrec = $this->connection->prepare('SELECT `user_id`, `telapi_url_rec` FROM `*PREFIX*sms_relent_settings` WHERE `telapi_url_rec` = ?');
	$result = $sqlrec->execute([$recsmswebhookurl]);
        $datafromdb = $result->fetch();
        $result->closeCursor();
        $ncusertelrec = $datafromdb['user_id'];

        return $ncusertelrec;
    }

    /**
     * @NoAdminRequired
     */
    public function getuserbyteldelrwhurl($delsmswebhookurl) {

        $sqldel = $this->connection->prepare('SELECT `user_id`, `telapi_url` FROM `*PREFIX*sms_relent_settings` WHERE `telapi_url` = ?');
	$ressqldel = $sqldel->execute([$delsmswebhookurl]);
        $datafromdbdel = $ressqldel->fetch();
        $ressqldel->closeCursor();
        $ncuserteldel = $datafromdbdel['user_id'];

        return $ncuserteldel;
    }

    /**
     * @NoAdminRequired
     */
    public function getuserbyplivorecwhurl($plivorecurl) {

        $sqlrecpl = $this->connection->prepare('SELECT `user_id`, `nexapi_url_rec` FROM `*PREFIX*sms_relent_settings` WHERE `nexapi_url_rec` = ?');
	$plresrecsql = $sqlrecpl->execute([$plivorecurl]);
        $pldatafromdb = $plresrecsql->fetch();
        $plresrecsql->closeCursor();
        $ncuserplrec = $pldatafromdb['user_id'];

        return $ncuserplrec;
    }

    /**
     * @NoAdminRequired
     */
    public function getuserbyplivodelrwhurl($plivodrurl) {

        $sqldrpl = $this->connection->prepare('SELECT `user_id`, `nexapi_url` FROM `*PREFIX*sms_relent_settings` WHERE `nexapi_url` = ?');
	$ressqldelrec = $sqldrpl->execute([$plivodrurl]);
        $datafromdbdr = $ressqldelrec->fetch();
        $ressqldelrec->closeCursor();
        $ncuserplivodel = $datafromdbdr['user_id'];

        return $ncuserplivodel;
    }

    /**
     * @NoAdminRequired
     */
    public function getuserbytwilrecwhurl($twilrecurl) {

        $sqlrectw = $this->connection->prepare('SELECT `user_id`, `twilapi_url_rec` FROM `*PREFIX*sms_relent_settings` WHERE `twilapi_url_rec` = ?');
	$twresrecsql = $sqlrectw->execute([$twilrecurl]);
        $twdatafromdb = $twresrecsql->fetch();
        $twresrecsql->closeCursor();
        $ncusertwrec = $twdatafromdb['user_id'];

        return $ncusertwrec;
    }

    /**
     * @NoAdminRequired
     */
    public function getuserbytwildelrwhurl($twildrurl) {

        $sqldrtw = $this->connection->prepare('SELECT `user_id`, `twilapi_url` FROM `*PREFIX*sms_relent_settings` WHERE `twilapi_url` = ?');
	$ressqldelrectw = $sqldrtw->execute([$twildrurl]);
        $datafromdbdrtw = $ressqldelrectw->fetch();
        $ressqldelrectw->closeCursor();
        $ncusertwildel = $datafromdbdrtw['user_id'];

        return $ncusertwildel;
    }

    /**
     * @NoAdminRequired
     */
    public function getuserbyflowrecwhurl($flowrecurl) {

        $sqlrecfl = $this->connection->prepare('SELECT `user_id`, `flowapi_url_rec` FROM `*PREFIX*sms_relent_settings` WHERE `flowapi_url_rec` = ?');
	$flresrecsql = $sqlrecfl->execute([$flowrecurl]);
        $fldatafromdb = $flresrecsql->fetch();
        $flresrecsql->closeCursor();
        $ncuserflrec = $fldatafromdb['user_id'];

        return $ncuserflrec;
    }

    /**
     * @NoAdminRequired
     */
    public function getuserbyflowdelrwhurl($flowdrurl) {

        $sqldrfl = $this->connection->prepare('SELECT `user_id`, `flowapi_url` FROM `*PREFIX*sms_relent_settings` WHERE `flowapi_url` = ?');
	$ressqldelrecfl = $sqldrfl->execute([$flowdrurl]);
        $datafromdbdrfl = $ressqldelrecfl->fetch();
        $ressqldelrecfl->closeCursor();
        $ncuserflowdel = $datafromdbdrfl['user_id'];

        return $ncuserflowdel;
    }
}
