<?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) {

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


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

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


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

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


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

            $sql8 = "UPDATE `*PREFIX*sms_relent_sent` SET `price` = '$messageprice', `deliveryreceipt` = '$deliverystatus' , `status` = '$mStatus', `network` = '$networkcode' WHERE `message_id` = '$messageid' AND `user_id` = '$ncuserforplivodel'";
            $res8 = $this->connection->prepare($sql8);
            $res8->execute();
     }


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

        $sql9 = "SELECT * FROM `*PREFIX*sms_relent_received` WHERE `user_id` = '$userId'";
        $res9 = $this->connection->prepare($sql9);
        $res9->execute();

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

        $recdatafromdb = $recdatatable;

        $res9->closeCursor();

        return $recdatafromdb;
     }


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

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

            $sql9 = "SELECT * FROM `*PREFIX*sms_relent_received` WHERE `user_id` = '$userId'";
            $res9 = $this->connection->prepare($sql9);
            $res9->execute();

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

            $recdatafromdb = $recdatatable;

            $res9->closeCursor();

            return $recdatafromdb;

        } else { return "not permitted"; }
     }


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

        $finalrecmessagesIDs = implode(",", $recmessagedbIDs);
        $rowstobedeleted = "(" . $finalrecmessagesIDs . ")";

        $sql10 = "DELETE FROM `*PREFIX*sms_relent_received` WHERE `id` IN ".$rowstobedeleted.";";
        $res10 = $this->connection->prepare($sql10);
        $res10->execute();
        $res10->closeCursor();

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


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

        $sql10 = "SELECT * FROM `*PREFIX*sms_relent_sent` WHERE `user_id` = '$userId'";

        $res10 = $this->connection->prepare($sql10);
        $res10->execute();

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

        $sentdatafromdb = $sentdatatable;

        $res10->closeCursor();

        return $sentdatafromdb;

     }


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

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

            $sql10 = "SELECT * FROM `*PREFIX*sms_relent_sent` WHERE `user_id` = '$userId'";

            $res10 = $this->connection->prepare($sql10);
            $res10->execute();

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

            $sentdatafromdb = $sentdatatable;

            $res10->closeCursor();

            return $sentdatafromdb;

        } else { return "not permitted"; }

     }


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

        $finalsentDbIDs = implode(",", $sentmessagedbIDs);
        $sentrowsfordelete = "(" . $finalsentDbIDs . ")";

        $sql11 = "DELETE FROM `*PREFIX*sms_relent_sent` WHERE `id` IN ".$sentrowsfordelete.";";
        $res11 = $this->connection->prepare($sql11);
        $res11->execute();
        $res11->closeCursor();

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


     /**
      * @NoAdminRequired
      */
     public function getmessagesperpage($userId) {
        $sqlmpp = "SELECT `user_id`, `messagesperpage` FROM `*PREFIX*sms_relent_settings` WHERE `user_id` = '$userId'";

        $resmpp = $this->connection->prepare($sqlmpp);
        $resmpp->execute();

        $getmesperpage = $resmpp->fetch();
        $mesperpagedb = $getmesperpage['messagesperpage'];

        $resmpp->closeCursor();

        return $mesperpagedb;
     }


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

        $sql0 = "SELECT * FROM `*PREFIX*sms_relent_settings` WHERE `user_id` = '$userId'";

        $res0 = $this->connection->prepare($sql0);
        $res0->execute();

        $settingsfromdb = $res0->fetch();
        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";
        }

        $res0->closeCursor();

        return $settingsfromdb;
     }


     /**
      * @NoAdminRequired
      *
      */
     public function updatesettings($userId, $telapiKey, $telPubKey, $telapiUrlRec, $telapiUrl, $messagingProfileId, $nexapiKey, $nexapiSecret, $nexapiUrlRec, $nexapiUrl, $telSenderName, $nexSenderName, $messagesperpage, $getNotify, $notificationEmail, $getsmsinemail) {

        $sql1 = "SELECT * FROM `*PREFIX*sms_relent_settings` WHERE `user_id` = '$userId'";
        $res1 = $this->connection->prepare($sql1);
        $res1->execute();

        $rowup = $res1->fetch();
        $res1->closeCursor();

        if ($rowup['user_id'] == '' || $rowup['user_id'] == 'undefined' || $rowup['user_id'] == null) {

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

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

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

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

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

            $sql2 = "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`) VALUES ('$userId', '$telapikeystrenc', '$telpubkeystrenc', '$telapiUrlRec', '$telapiUrl', '$messagingprofenc', '$nexapikeystrenc', '$nexapisecretstrenc', '$nexapiUrlRec', '$nexapiUrl', '$telSenderName', '$nexSenderName', '$messagesperpage', '$getNotify', '$notificationEmail', '$getsmsinemail')";
            $res2 = $this->connection->prepare($sql2);
            $res2->execute();

        } else {

            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, $password = '');                
            } 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, $password = '');                
            } 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, $password = '');                
            } 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, $password = '');                
            } elseif ($nexapiKey == "%20%20%20%20%20%20%20%20%20") {
                $nexapikeystrenc = $rowup['nexapi_key'];
            } elseif ($nexapiKey == '') {
                $nexapikeystrenc = '';
            }

            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, $password = '');                
            } 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 = '';
            }

            $sql3 = "UPDATE `*PREFIX*sms_relent_settings` SET `telapi_key` = '$telapikeystrenc', `tel_pub_key` = '$telpubkeystrenc', `telapi_url_rec` = '$telapiUrlRec', `telapi_url` = '$telapiUrl', `messaging_profile_id` = '$messagingprofenc', `nexapi_key` = '$nexapikeystrenc', `nexapi_secret` = '$nexapisecretstrenc', `nexapi_url_rec` = '$nexapiUrlRec', `nexapi_url` = '$nexapiUrl', `tel_sender_name` = '$telSenderName', `nex_sender_name` = '$nexSenderName', `messagesperpage` = '$messagesperpage', `get_notify` = '$getNotify', `notification_email` = '$notificationEmail', `getsmsinemail` = '$getsmsinemail' WHERE `user_id` = '$userId'";
            $res3 = $this->connection->prepare($sql3);
            $res3->execute();
        }
     }

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

        $sql7 = "SELECT * FROM `*PREFIX*sms_relent_settings` WHERE `user_id` = '$userId'";
        $res7 = $this->connection->prepare($sql7);
        $res7->execute();
        $settingsfrdb = $res7->fetch();
        $telapikeystrdec = $this->crypto->decrypt($settingsfrdb['telapi_key'], $password = '');
        $telpubkeystrdec = $this->crypto->decrypt($settingsfrdb['tel_pub_key'], $password = '');
        $telapiurlrec = $settingsfrdb['telapi_url_rec'];
        $telapiurlstr = $settingsfrdb['telapi_url'];
        $messagingprofid = $this->crypto->decrypt($settingsfrdb['messaging_profile_id'], $password = '');
        $nexapikeystr = $this->crypto->decrypt($settingsfrdb['nexapi_key'], $password = '');
        $nexapisecretstr = $this->crypto->decrypt($settingsfrdb['nexapi_secret'], $password = '');
        $nexapiurlrecsms = $settingsfrdb['nexapi_url_rec'];
        $nexapiurldelrcpt = $settingsfrdb['nexapi_url'];
        $gettelsendername = $settingsfrdb['tel_sender_name'];
        $getnexsendername = $settingsfrdb['nex_sender_name'];
        $getmessagesperpage = $settingsfrdb['messagesperpage'];
        $getnotification = $settingsfrdb['get_notify'];
        $notifyemail = $settingsfrdb['notification_email'];
        $includesmsinemail = $settingsfrdb['getsmsinemail'];
        $res7->closeCursor();

        return [$telapikeystrdec, $telpubkeystrdec, $telapiurlrec, $telapiurlstr, $messagingprofid, $nexapikeystr, $nexapisecretstr, $nexapiurlrecsms, $nexapiurldelrcpt, $gettelsendername, $getnexsendername, $getmessagesperpage, $getnotification, $notifyemail, $includesmsinemail];

    }

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

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

        return $ncusertelrec;
    }

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

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

        return $ncuserteldel;
    }

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

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

        return $ncuserplrec;
    }

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

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

        return $ncuserplivodel;
    }

}
