<?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\DB\QueryBuilder\IQueryBuilder;
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) {

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

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


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

            $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`)
				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
			');
	    $sql->execute([$userId, $sentmessagearr[0], $sentmessagearr[1], $sentmessagearr[2], $sentmessagearr[3], $sentmessagearr[4], $sentmessagearr[5], $sentmessagearr[6], 
                           $sentmessagearr[7], $textwithnl]);
     }


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

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

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

            $recdatafromdb = $recdatatable;

            return $recdatafromdb;
     }


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

        $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;

        return $sentdatafromdb;
     }


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

     }


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

        $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`
		   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`)
				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]);

        } 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` = ?
	                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, $userId]);
	    $updateRes->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;
    }
}