<?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\PaxFax\Service;

use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;
use OCP\Security\ICrypto;

use OCP\AppFramework\ApiController;
use OCP\IRequest;
use OCP\AppFramework\Controller;
use OCP\Files\IAppData;
use OCP\AppFramework\App;
use OCP\Files\NotPermittedException;
use OCP\Files\Folder;
use OC\Files\Filesystem;
use \ReflectionClass;

use Phaxio;
use Phaxio\OperationResult;
use Phaxio\Error\AuthenticationException;
use Phaxio\Error\NotFoundException;
use Phaxio\Error\InvalidRequestException;
use Phaxio\Error\RateLimitException;
use Phaxio\Error\APIConnectionException;
use Phaxio\Error\GeneralException;


class PaxfaxService {

      private $connection;

      private $crypto;

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

              $this->connection = $connection;

              $this->crypto = $crypto;
      }


      /**
       * @NoAdminRequired
       */
      public function object_to_array($obj) {
         if(is_object($obj)) $obj = (array)$this->dismount($obj);
         if(is_array($obj)) {
            $new = array();
            foreach($obj as $key => $val) {
                $new[$key] = $this->object_to_array($val);
            }
         }
         else $new = $obj;
         return $new;
      }


      /**
       * @NoAdminRequired
       */
      public function dismount($object) {
         $reflectionClass = new ReflectionClass(get_class($object));
         $array = array();
         foreach ($reflectionClass->getProperties() as $property) {
            $property->setAccessible(true);
            $array[$property->getName()] = $property->getValue($object);
            $property->setAccessible(false);
         }
         return $array;
      }


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

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

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

          $settingsfromdb = $res0->fetch();
          if ($settingsfromdb['api_key'] != '') {

              // Send a placeholder to the browser, instead of the real API key
              $settingsfromdb['api_key'] = "%20%20%20%20%20%20%20%20%20%20%20%20%20%20";
          }
          if ($settingsfromdb['api_secret'] != '') {
              $settingsfromdb['api_secret'] = "%20%20%20%20%20%20%20%20%20%20%20%20%20%20";
          }
          if ($settingsfromdb['webhook_token'] != '') {
              $settingsfromdb['webhook_token'] = "%20%20%20%20%20%20%20%20%20%20%20";
          }
          if ($settingsfromdb['receive_url'] != '') {
              $settingsfromdb['receive_url']= "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%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, $apiKey, $apiSecret, $webhookToken, $receiveUrl, $getNotification, $notificationEmail) {

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

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

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

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

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

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

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

              $sql2 = "INSERT INTO `*PREFIX*pax_fax` (`user_id`, `api_key`, `api_secret`, `webhook_token`, `receive_url`, `get_notification`, `notification_email`) VALUES ('$userId', '$apikeystrenc', '$apisecretstrenc', '$webhookTokenenc', '$receiveUrlenc', '$getNotification', '$notificationEmail')";
              $res2 = $this->connection->prepare($sql2);
              $res2->execute();

          } else {

              if ($apiKey != '' && $apiKey != "%20%20%20%20%20%20%20%20%20%20%20%20%20%20") {
                  $apikeystrenc = $this->crypto->encrypt($apiKey, $password = '');                
              } elseif ($apiKey == "%20%20%20%20%20%20%20%20%20%20%20%20%20%20") {
                  $apikeystrenc = $row['api_key'];
              } elseif ($apiKey == '') {
                  $apikeystrenc = '';
              }

              if ($apiSecret != '' && $apiSecret != "%20%20%20%20%20%20%20%20%20%20%20%20%20%20") {
                  $apisecretstrenc = $this->crypto->encrypt($apiSecret, $password = '');                
              } elseif ($apiSecret == "%20%20%20%20%20%20%20%20%20%20%20%20%20%20") {
                  $apisecretstrenc = $row['api_secret'];
              } elseif ($apiSecret == '') {
                  $apisecretstrenc = '';
              }

              if ($webhookToken != '' && $webhookToken != "%20%20%20%20%20%20%20%20%20%20%20") {
                  $webhookTokenenc = $this->crypto->encrypt($webhookToken, $password = '');                
              } elseif ($webhookToken == "%20%20%20%20%20%20%20%20%20%20%20") {
                  $webhookTokenenc = $row['webhook_token'];
              } elseif ($webhookToken == '') {
                  $webhookTokenenc = '';
              }

              if ($receiveUrl != '' && $receiveUrl != "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20") {
                  $receiveUrlenc = $this->crypto->encrypt($receiveUrl, $password = '');                
              } elseif ($receiveUrl == "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20") {
                  $receiveUrlenc = $row['receive_url'];
              } elseif ($receiveUrl == '') {
                  $receiveUrlenc = '';
              }

              $sql3 = "UPDATE `*PREFIX*pax_fax` SET `api_key` = '$apikeystrenc', `api_secret` = '$apisecretstrenc', `webhook_token` = '$webhookTokenenc', `receive_url` = '$receiveUrlenc', `get_notification` = '$getNotification', `notification_email` = '$notificationEmail' WHERE `user_id` = '$userId'";
              $res3 = $this->connection->prepare($sql3);
              $res3->execute();
          }
      }

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

              $sql7 = "SELECT * FROM `*PREFIX*pax_fax` WHERE `user_id` = '$userId'";
              $res7 = $this->connection->prepare($sql7);
              $res7->execute();
              $settingsfrdb = $res7->fetch();
              $res7->closeCursor();

              $apikeystr = $this->crypto->decrypt($settingsfrdb['api_key'], $password = '');
              $apisecretstr = $this->crypto->decrypt($settingsfrdb['api_secret'], $password = '');
              $webhookToken = $this->crypto->decrypt($settingsfrdb['webhook_token'], $password = '');
              $receiveUrl = $this->crypto->decrypt($settingsfrdb['receive_url'], $password = '');
              $getnotification = $settingsfrdb['get_notification'];
              $notifyemail = $settingsfrdb['notification_email'];

              return [$apikeystr, $apisecretstr, $webhookToken, $receiveUrl, $getnotification, $notifyemail];

      }

}