<?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\Controller;

use OCA\PaxFax\Service\PaxfaxService;
use OCP\IRequest;
use OCP\AppFramework\Controller;
use OCP\Files\File;
use OCP\Files\Folder;
use OCP\Files\IRootFolder;
use OCP\AppFramework\App;
use OCP\Files\NotPermittedException;
use OCP\IConfig;
use OCP\IUserSession;
use OC\Files\Filesystem;
use OC\Files\View;
use OC\URLGenerator;
use \ReflectionClass;
use \FilesystemIterator;
use Psr\Log\LoggerInterface;

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 PaxfaxController extends Controller {

    private $service;
    private $config;
    private $userId;
    private $folder;
    private $filesystem;
    private $view;
    private $userSession;
    private $urlGenerator;
    private $logger;
    private $rootFolder;

    public function __construct($appName, IRequest $request, PaxfaxService $service, IConfig $config, $userId, Folder $folder, Filesystem $filesystem, View $view, IUserSession $userSession, URLGenerator $urlGenerator, LoggerInterface $logger, IRootFolder $rootFolder) {

           parent::__construct($appName, $request);

           $this->service = $service;
           $this->config = $config;
           $this->userId = $userId;
           $this->folder = $folder;
           $this->filesystem = $filesystem;
           $this->view = $view;
           $this->userSession = $userSession;
           $this->urlGenerator = $urlGenerator;
           $this->logger = $logger;
           $this->rootFolder = $rootFolder;
    }

    /**
     * @NoAdminRequired
     */
    public function cleantempdir() {

           // If the 'temp_files' folder doesn't exist create it
           if ($this->folder->nodeExists('Pax_Fax/temp_files') == false) {
               $this->folder->newFolder('Pax_Fax/temp_files');
           }

           $gettempdir = $this->folder->get("/Pax_Fax/temp_files");
           $fileSystemIterator = $gettempdir->getDirectoryListing();

           $dirfiles = [];
           foreach ($fileSystemIterator as $fileInfo){
                    $dirfiles[] = $fileInfo->getName();
           }

           foreach ($dirfiles as $key => $indfile) {
                    $tempfile = "/Pax_Fax/temp_files/" . $indfile;
                    $userFolder = $this->rootFolder->getUserFolder($this->userSession->getUser()->getUID());
                    $removetmpfile = $userFolder->get($tempfile)->delete();
           }
    }


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

           $thisapicred = $this->service->getapicredentials($this->userSession->getUser()->getUID());

           $sinchKeyId = $thisapicred[5];
           $sinchKeySecret = $thisapicred[6];

           if ($sinchKeyId && $sinchKeySecret) {

               // Use Sinch
               return "n/a";

           } else {

               // Use Phaxio
               $apiMode = 'live';
               $apiKeys[$apiMode] = $thisapicred[0];
               $apiSecrets[$apiMode] = $thisapicred[1];

               $apiHost = 'https://api.phaxio.com/v2.1/';

               $phaxio = new Phaxio($apiKeys[$apiMode], $apiSecrets[$apiMode], $apiHost);

               try {
                    // Get Phaxio account balance
                    $phaxioresulttert = $phaxio->doRequest("GET", 'account/status');

                    $balancetoarr = $this->object_to_array($phaxioresulttert);

                    $phaxiobalance = $balancetoarr['data']['balance'];

               } catch (InvalidRequestException $e) {
                    $phaxiobalance = 'unknown';
                    $phaxiosuccess = 'false';
                    $errortype = 'invalid request error';
               } catch (AuthenticationException $e) {
                    $phaxiobalance = 'unknown';
                    $phaxiosuccess = 'false';
                    $errortype = 'authentication error';
               } catch (APIConnectionException $e) {
                    $phaxiobalance = 'unknown';
                    $phaxiosuccess = 'false';
                    $errortype = 'API connection error';
               } catch (RateLimitException $e) {
                    $phaxiobalance = 'unknown';
                    $phaxiosuccess = 'false';
                    $errortype = 'rate limit error';
               } catch (NotFoundException $e) {
                    $phaxiobalance = 'unknown';
                    $phaxiosuccess = 'false';
                    $errortype = 'not found error';
               } catch (GeneralException $e) {
                    $phaxiobalance = 'unknown';
                    $phaxiosuccess = 'false';
                    $errortype = 'undefined error';
               }

               return $phaxiobalance;
           }
    }


    /**
     * @NoAdminRequired
     */
    public function getfaxnumbers() {

           $thisapicred = $this->service->getapicredentials($this->userSession->getUser()->getUID());

           $sinchKeyId = $thisapicred[5];
           $sinchKeySecret = $thisapicred[6];

           if ($sinchKeyId && $sinchKeySecret) {

               // Use Sinch
	       $sinchProjectId = $thisapicred[4];
	       $sinchServiceId = $thisapicred[7];

	       $nbquery = [ "pageSize" => "100", "page" => "string" ];

	       $curl = curl_init();

	       curl_setopt_array($curl, [
		    CURLOPT_HTTPHEADER => [ "Authorization: Basic " . base64_encode("" . $sinchKeyId . ":" . $sinchKeySecret ."") ],
                    CURLOPT_PORT => "",
		    CURLOPT_URL => "https://fax.api.sinch.com/v3/projects/" . $sinchProjectId . "/services/" . $sinchServiceId . "/numbers?" . http_build_query($nbquery),
		    CURLOPT_RETURNTRANSFER => true,
		    CURLOPT_CUSTOMREQUEST => "GET",
		]);

		$responsesnb = curl_exec($curl);
		$errorsnb = curl_error($curl);

		curl_close($curl);

		if ($errorsnb) { $this->logger->error('cURL Error #: '. $errorsnb . '.'); }

                $sincharr = [];
                $sinchnmbrs = json_decode($responsesnb, true);

	        foreach ($sinchnmbrs['numbers'] as $snkey => $snvalue) {
	                 if (is_array($snvalue)) {
	                        foreach ($snvalue as $snkeysec => $snvaluesec) {
	                               if ($snkeysec == 'phoneNumber') {
	                                   $sincharr[] = $snvaluesec;
	                               }
	                        }
	                 }
	        }

                $sinchnbdata = ["nblist" => $sincharr, "provider" => "sinch"];

		return $sinchnbdata;

           } else {

                // Use Phaxio
		$apiMode = 'live';
		$apiKeys[$apiMode] = $thisapicred[0];
		$apiSecrets[$apiMode] = $thisapicred[1];

		$apiHost = 'https://api.phaxio.com/v2.1/';

		$phaxio = new Phaxio($apiKeys[$apiMode], $apiSecrets[$apiMode], $apiHost);

		try {
	            // Get all Phaxio fax numbers
	            $phaxioresultfour = $phaxio->doRequest("GET", 'phone_numbers');

	            $phaxionbstoarr = $this->object_to_array($phaxioresultfour);

	            $phaxioarr = [];

	            foreach ($phaxionbstoarr['data'] as $phkey => $phvalue) {
	                   if (is_array($phvalue)) {
	                         foreach ($phvalue as $phkeysec => $phvaluesec) {
	                               if ($phkeysec == 'phone_number') {
	                                   $phaxioarr[] = $phvaluesec;
	                               }
	                         }
	                   }
	            }

		} catch (InvalidRequestException $e) {
	            $phaxiobalance = 'unknown';
	            $phaxiosuccess = 'false';
	            $errortype = 'invalid request error';
		} catch (AuthenticationException $e) {
	            $phaxiobalance = 'unknown';
	            $phaxiosuccess = 'false';
	            $errortype = 'authentication error';
		} catch (APIConnectionException $e) {
	            $phaxiobalance = 'unknown';
	            $phaxiosuccess = 'false';
	            $errortype = 'API connection error';
		} catch (RateLimitException $e) {
	            $phaxiobalance = 'unknown';
	            $phaxiosuccess = 'false';
	            $errortype = 'rate limit error';
		} catch (NotFoundException $e) {
	            $phaxiobalance = 'unknown';
	            $phaxiosuccess = 'false';
	            $errortype = 'not found error';
		} catch (GeneralException $e) {
	            $phaxiobalance = 'unknown';
	            $phaxiosuccess = 'false';
	            $errortype = 'undefined error';
		}

                $phaxionbdata = ["nblist" => $phaxioarr, "provider" => "phaxio"];

		return $phaxionbdata;
           }
    }


    /**
     * @NoAdminRequired
     */
    public function uploadfile($uploadfileforfax) {

           $fileContent = file_get_contents($_FILES['uploadfileforfax']['tmp_name']);
           $fileName = $_FILES['uploadfileforfax']['name'];
           $fileSizeinit = $_FILES['uploadfileforfax']['size'];
           $fileSize = $fileSizeinit / 1048576;

           if ($this->folder->nodeExists('Pax_Fax/faxes_sent') == false) {
               $this->folder->newFolder('Pax_Fax/faxes_sent');
           }
           if ($this->folder->nodeExists('Pax_Fax/faxes_received') == false) {
               $this->folder->newFolder('Pax_Fax/faxes_received');
           }
           if ($this->folder->nodeExists('Pax_Fax/faxes_sent_failed') == false) {
               $this->folder->newFolder('Pax_Fax/faxes_sent_failed');
           }
           if ($this->folder->nodeExists('Pax_Fax/faxes_received_failed') == false) {
               $this->folder->newFolder('Pax_Fax/faxes_received_failed');
           }
           if ($this->folder->nodeExists('Pax_Fax/temp_files') == false) {
               $this->folder->newFolder('Pax_Fax/temp_files');
           }

           $targetfile = "/Pax_Fax/temp_files/" . $fileName;

           $target = $this->folder->newFile($targetfile);
           $target->putContent($fileContent);

           // Get the cumulative files size of the uploaded files
           $gettmpdir = $this->folder->get("/Pax_Fax/temp_files");
           $fliterator = $gettmpdir->getDirectoryListing();


           $dirfiles = [];
           foreach ($fliterator as $fileInfo){
                    $dirfiles[] = $fileInfo->getName();
           }

           $totalflsizeinit = 0;
           foreach ($dirfiles as $key => $indfile) {
                    $flsize = $this->folder->get("/Pax_Fax/temp_files/" . $indfile);
                    $fileSizeinit = $flsize->getSize();
                    $mbSize = $fileSizeinit / 1048576;
                    $totalflsizeinit += $mbSize;
           }

           $totalflsize = number_format($totalflsizeinit, 2) . ' MB';

           return $totalflsize;

    }

    /**
     * @NoAdminRequired
     */
    public function pickfile($path) {

           if ($this->folder->nodeExists('Pax_Fax/faxes_sent') == false) {
               $this->folder->newFolder('Pax_Fax/faxes_sent');
           }
           if ($this->folder->nodeExists('Pax_Fax/faxes_received') == false) {
               $this->folder->newFolder('Pax_Fax/faxes_received');
           }
           if ($this->folder->nodeExists('Pax_Fax/faxes_sent_failed') == false) {
               $this->folder->newFolder('Pax_Fax/faxes_sent_failed');
           }
           if ($this->folder->nodeExists('Pax_Fax/faxes_received_failed') == false) {
               $this->folder->newFolder('Pax_Fax/faxes_received_failed');
           }
           if ($this->folder->nodeExists('Pax_Fax/temp_files') == false) {
               $this->folder->newFolder('Pax_Fax/temp_files');
           }

           $getfl = $this->folder->get($path);

           $fileContentpk = $getfl->getContent();

           $patharr = explode("/", $path);

           $revarr = array_reverse($patharr);

           $relflpath = "/Pax_Fax/temp_files/" . $revarr[0]; 

           $target = $this->folder->newFile($relflpath);

           $target->putContent($fileContentpk);

           $gettmpdir = $this->folder->get("/Pax_Fax/temp_files");

           $fileitrt = $gettmpdir->getDirectoryListing();

           $dirfls = [];
           foreach ($fileitrt as $fileInfo) {
                    $dirfls[] = $fileInfo->getName();
           }

           $totalflsizeinitp = 0;

           foreach ($dirfls as $keyp => $indfilep) {

                    $flsizep = $this->folder->get("/Pax_Fax/temp_files/" . $indfilep);
                    $fileSizeinitp = $flsizep->getSize();
                    $mbSizep = $fileSizeinitp / 1048576;
                    $totalflsizeinitp += $mbSizep;
           }

           $totalflsizep = number_format($totalflsizeinitp, 2) . ' MB';

           return $totalflsizep;
    }

    /**
     * @NoAdminRequired
     */
    public function removeupfile($removedfilename) {

           $upfile = "/Pax_Fax/temp_files/" . $removedfilename;
           $userFolder = $this->rootFolder->getUserFolder($this->userSession->getUser()->getUID());
           $removetmpfile = $userFolder->get($upfile)->delete();

           $gettmpdir = $this->folder->get("/Pax_Fax/temp_files");
           $fliterator = $gettmpdir->getDirectoryListing();

           $dirfiles = [];
           foreach ($fliterator as $fileInfo){
                    $dirfiles[] = $fileInfo->getName();
           }

           $totalflsizeinit = 0;
           foreach ($dirfiles as $key => $indfile) {
                    $flsize = $this->folder->get("/Pax_Fax/temp_files/" . $indfile);
                    $fileSizeinit = $flsize->getSize();
                    $mbSize = $fileSizeinit / 1048576;
                    $totalflsizeinit += $mbSize;
           }

           $totalflsize = number_format($totalflsizeinit, 2) . ' MB';

           return $totalflsize;
    }

    /**
     * @NoAdminRequired
     */
    public function prevpickedfile($pickedfilename) {

           $getfl = $this->folder->get("/Pax_Fax/temp_files/" . $pickedfilename);
           $getfilecontent = $getfl->getContent();

           $namesplit = explode(".", $pickedfilename);
           $extension = end($namesplit);

           if ($extension == "txt" || $extension == "html") {
               $getpickedfile = $getfilecontent;
           } elseif ($extension == "jpg") {
               $getpickedfile = 'data:image/jpeg;base64,' . base64_encode($getfilecontent);
           } elseif ($extension == "png") {
               $getpickedfile = 'data:image/png;base64,' . base64_encode($getfilecontent);
           } else { $getpickedfile = ""; }

           return $getpickedfile;
    }

    /**
     * @NoAdminRequired
     */
    public function sendfax($uploadedtofax, $selectedcid, $toNumber) {

           $tonumbertr = str_replace("+", "", $toNumber[0]);
           $fldate = date("Y-m-d_H-i-s_").gettimeofday()["usec"];
           $fromnumberdigits = str_replace("+", "", $selectedcid);

           if ($selectedcid != '' && $selectedcid != 'click refresh button') { $fromnumber = $selectedcid; } else { $fromnumber = ''; }

           $thisapicred = $this->service->getapicredentials($this->userSession->getUser()->getUID());

           $sinchKeyId = $thisapicred[5];
           $sinchKeySecret = $thisapicred[6];

           if ($sinchKeyId && $sinchKeySecret) {

               // Use Sinch
	       $sinchProjectId = $thisapicred[4];

               $countfaxfiles = count($uploadedtofax);

               $openedfiles = [];
               $crtuser = $this->userSession->getUser()->getUID();
               $userFolder = $this->rootFolder->getUserFolder($this->userSession->getUser()->getUID());

               foreach ($uploadedtofax as $key => $flname) {

                    if ($key == 0) { $firstflname = $flname; }

                    $fileNamesec = array_reverse(explode(".", $flname));
                    $filenameext = $fileNamesec[0];

                    array_shift($fileNamesec);

                    $fileName = implode("", $fileNamesec);

                    if ($countfaxfiles == 1) {

                        $targetfile = "/Pax_Fax/faxes_sent/" . $fileName . "_" . $fromnumber . "_"  . $tonumbertr . "_" . $fldate . "." . $filenameext;

                    } else {

                         if ($this->folder->nodeExists("Pax_Fax/faxes_sent/" . $firstflname . "_et_al_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate) == false) {
                             $this->folder->newFolder("Pax_Fax/faxes_sent/" . $firstflname . "_et_al_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate);
                         }

                         $targetfile = "/Pax_Fax/faxes_sent/" . $firstflname . "_et_al_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "/" . $fileName . "_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "." . $filenameext;
                    }

		    $getfl = $this->folder->get("/Pax_Fax/temp_files/" . $flname);
		    $fileContentsnd = $getfl->getContent();

		    $target = $this->folder->newFile($targetfile);
		    $target->putContent($fileContentsnd);

		    $upfilefx = "/Pax_Fax/temp_files/" . $flname;
		    $removetmpfile = $userFolder->get($upfilefx)->delete();

                    if ($countfaxfiles == 1) {
                        $gtflfx = $this->folder->get("/Pax_Fax/faxes_sent/" . $fileName . "_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "." . $filenameext);
                        $openedfiles[] = [ "file" => base64_encode($gtflfx->getContent()), "fileType" => $filenameext ];
                    } else {
                        $gtflfx = $this->folder->get("/Pax_Fax/faxes_sent/" . $firstflname . "_et_al_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "/" . $fileName . "_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "." . $filenameext);
                        $openedfiles[] = [ "file" => base64_encode($gtflfx->getContent()), "fileType" => $filenameext ];
                    }
               }

               $toNumbersnfin = implode(",", $toNumber);

	       $datatosendsn = ["to" => $toNumbersnfin, "files" => $openedfiles];

	       $postedparamsn = json_encode($datatosendsn);

	       $chsn = curl_init();
               curl_setopt($chsn, CURLOPT_URL, "https://" . $sinchKeyId . ":" . $sinchKeySecret . "@fax.api.sinch.com/v3/projects/" . $sinchProjectId . "/faxes");
	       curl_setopt($chsn, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
	       curl_setopt($chsn, CURLOPT_TIMEOUT, 300);
	       curl_setopt($chsn, CURLOPT_RETURNTRANSFER, 1);
	       curl_setopt($chsn, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	       curl_setopt($chsn, CURLOPT_POST, 1);
	       curl_setopt($chsn, CURLOPT_POSTFIELDS, $postedparamsn);
	       $resultsn = curl_exec($chsn);
	       $statusCodesn = curl_getinfo($chsn, CURLINFO_HTTP_CODE);
	       curl_close($chsn);

	       $decresultsn = json_decode($resultsn, true);

	       if (in_array($statusCodesn, [400, 401, 402, 404, 422, 429, 500, 800])) {
                   $sinchsuccess = false;
                   $sincherrortype = "Error: " . $decresultsn['code'] . " . Message: " . $decresultsn['message'];
               } else { $sinchsuccess = true; $sincherrortype = ''; }

               $sendingresult = [ 'success' => $sinchsuccess, 'errortype' => $sincherrortype ];

               if ($sinchsuccess != true) {

                    foreach ($uploadedtofax as $key => $flname) {

                        $fileNamesec = array_reverse(explode(".", $flname));
                        $filenameext = $fileNamesec[0];
                        array_shift($fileNamesec);

                        $fileName = implode("", $fileNamesec);

                        if ($countfaxfiles == 1) {
                            $failedfl = "/Pax_Fax/faxes_sent/" . $fileName . "_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "." . $filenameext;
                            $newtargetfl =  "/Pax_Fax/faxes_sent_failed/" . $fileName . "_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "." . $filenameext;
                        } else {

                            $failedfl = "/Pax_Fax/faxes_sent/" . $firstflname . "_et_al_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "/" . $fileName . "_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "." . $filenameext;
                            $this->folder->newFolder("Pax_Fax/faxes_sent_failed/" . $firstflname . "_et_al_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate);
                            $newtargetfl = "/Pax_Fax/faxes_sent_failed/" . $firstflname . "_et_al_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "/" . $fileName . "_" . $tonumbertr . "_" . $fldate . "." . $filenameext;
                        }

		        $getflsc = $this->folder->get($failedfl);
		        $fileContentfld = $getflsc->getContent();

		        $targetact = $this->folder->newFile($newtargetfl);
		        $targetact->putContent($fileContentfld);

		        $removetmpfile = $userFolder->get($failedfl)->delete();
                    }

                }

                return $sendingresult;

           } else {

               // Use Phaxio
               if ($selectedcid != '' && $selectedcid != 'click refresh button') { $fromnumber = $fromnumberdigits; } else { $fromnumber = 'nocallerid'; }

               $countfaxfiles = count($uploadedtofax);

               $openedfiles = [];
               $crtuser = $this->userSession->getUser()->getUID();
               $userFolder = $this->rootFolder->getUserFolder($this->userSession->getUser()->getUID());

               foreach ($uploadedtofax as $key => $flname) {

                    if ($key == 0) { $firstflname = $flname; }

                    $fileNamesec = array_reverse(explode(".", $flname));
                    $filenameext = $fileNamesec[0];
                    array_shift($fileNamesec);

                    $fileName = implode("", $fileNamesec);

                    if ($countfaxfiles == 1) {
                        $targetfile = "/Pax_Fax/faxes_sent/" . $fileName . "_" . $fromnumber . "_"  . $tonumbertr . "_" . $fldate . "." . $filenameext;
                    } else {
                         if ($this->folder->nodeExists("Pax_Fax/faxes_sent/" . $firstflname . "_et_al_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate) == false) {
                             $this->folder->newFolder("Pax_Fax/faxes_sent/" . $firstflname . "_et_al_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate);
                         }

                         $targetfile = "/Pax_Fax/faxes_sent/" . $firstflname . "_et_al_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "/" . $fileName . "_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "." . $filenameext;
                    }

		    $getflsc = $this->folder->get("/Pax_Fax/temp_files/" . $flname);
		    $fileContentsnd = $getflsc->getContent();

                    $target = $this->folder->newFile($targetfile);
                    $target->putContent($fileContentsnd);

                    $fltodel = "/Pax_Fax/temp_files/" . $flname;
		    $removetmpfile = $userFolder->get($fltodel)->delete();

                    if ($countfaxfiles == 1) {
                        $getflopen = $userFolder->get("/Pax_Fax/faxes_sent/" . $fileName . "_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "." . $filenameext);
                        $openedfiles[] = $getflopen->fopen('r');
                    } else {
                        $getflopen = $userFolder->get("/Pax_Fax/faxes_sent/" . $firstflname . "_et_al_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "/" . $fileName . "_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "." . $filenameext);
                        $openedfiles[] = $getflopen->fopen('r');
                    }
               }

               $params = array(
                           'to' => $toNumber,
                           'file' => $openedfiles,
                           'caller_id' => $selectedcid
                         );

               $apiMode = 'live';

               $apiKeys[$apiMode] = $thisapicred[0];
               $apiSecrets[$apiMode] = $thisapicred[1];

               $apiHost = 'https://api.phaxio.com/v2.1/';

               $phaxio = new Phaxio($apiKeys[$apiMode], $apiSecrets[$apiMode], $apiHost);

               try {
                    $phaxioresultinit = $phaxio->sendFax($params);

                    $phaxioresultsec = $phaxio->doRequest("GET", 'faxes/' . urlencode((string)$phaxioresultinit['id']));

                    $statustoarr = $this->object_to_array($phaxioresultsec);

                    $phaxiosuccess = $statustoarr['success'];

                    $errortype = 'there are no errors';

               } catch (InvalidRequestException $e) {
                    $phaxiosuccess = 'false';
                    $errortype = 'invalid request error';
               } catch (AuthenticationException $e) {
                    $phaxiosuccess = 'false';
                    $errortype = 'authentication error';
               } catch (APIConnectionException $e) {
                    $phaxiosuccess = 'false';
                    $errortype = 'API connection error';
               } catch (RateLimitException $e) {
                    $phaxiosuccess = 'false';
                    $errortype = 'rate limit error';
               } catch (NotFoundException $e) {
                    $phaxiosuccess = 'false';
                    $errortype = 'not found error';
               } catch (GeneralException $e) {
                    $phaxiosuccess = 'false';
                    $errortype = 'undefined error';
               }

               $sendingresult = ['success' => $phaxiosuccess, 'errortype' => $errortype];

               if ($phaxiosuccess != 'true') {

                    foreach ($uploadedtofax as $key => $flname) {

                        $fileNamesec = array_reverse(explode(".", $flname));
                        $filenameext = $fileNamesec[0];
                        array_shift($fileNamesec);

                        $fileName = implode("", $fileNamesec);

                        if ($countfaxfiles == 1) {
                            $failedfl = "/Pax_Fax/faxes_sent/" . $fileName . "_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "." . $filenameext;
                            $newtargetfl =  "/Pax_Fax/faxes_sent_failed/" . $fileName . "_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "." . $filenameext;
                        } else {

                            $failedfl = "/Pax_Fax/faxes_sent/" . $firstflname . "_et_al_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "/" . $fileName . "_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "." . $filenameext;
                            $this->folder->newFolder("Pax_Fax/faxes_sent_failed/" . $firstflname . "_et_al_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate);
                            $newtargetfl = "/Pax_Fax/faxes_sent_failed/" . $firstflname . "_et_al_" . $fromnumber . "_" . $tonumbertr . "_" . $fldate . "/" . $fileName . "_" . $tonumbertr . "_" . $fldate . "." . $filenameext;
                        }

		        $getflthrd = $this->folder->get($failedfl);
		        $fileContentfld = $getflthrd->getContent();

                        $targetact = $this->folder->newFile($targetfile);
                        $targetact->putContent($fileContentfld);

		        $removefailed = $userFolder->get($failedfl)->delete();
                    }
               }

               return $sendingresult;
           }
    }


    /**
     * @NoAdminRequired
     */
    public function getsettings() {
           return $this->service->getsettings($this->userSession->getUser()->getUID());
    }


    /**
     * @NoAdminRequired
     */
    public function updatesettings($apiKey, $apiSecret, $webhookToken, $receiveUrl, $sinchProjectId, $sinchKeyId, $sinchKeySecret, $sinchServiceId, $sinchCallbackUrl, $getNotification, $notificationEmail) {
           return $this->service->updatesettings($this->userSession->getUser()->getUID(), $apiKey, $apiSecret, $webhookToken, $receiveUrl, $sinchProjectId, $sinchKeyId, $sinchKeySecret, $sinchServiceId, $sinchCallbackUrl, $getNotification, $notificationEmail);
    }

}
