<?php

namespace App\Helper;
use phpseclib3\Net\SFTP;

class Ftp
{
    private string $host;
    private int $port;
    private string $user;
    private string $password;
    private string $remoteDir;


    public function __construct()
    {
        $this->setHost($_ENV['FTP_HOST']);
        $this->setPort((int)$_ENV['FTP_PORT']);
        $this->setUser($_ENV['FTP_USER']);
        $this->setPassword($_ENV['FTP_PASSWORD']);

        $this->setRemoteDir($_ENV['FTP_REMOTE_DIR']);

    }

    public function getHost(): string
    {
        return $this->host;
    }

    public function setHost(string $host): void
    {
        $this->host = $host;
    }
    public function getPort(): int
    {
        return $this->port;
    }

    public function setPort(int $port): void
    {
        $this->port = $port;
    }

    public function getUser(): string
    {
        return $this->user;
    }

    public function setUser(string $user): void
    {
        $this->user = $user;
    }

    public function getPassword(): string
    {
        return $this->password;
    }

    public function setPassword(string $password): void
    {
        $this->password = $password;
    }

    public function getRemoteDir(): string
    {
        return $this->remoteDir;
    }

    public function setRemoteDir(string $remoteDir): void
    {
        $this->remoteDir = $remoteDir;
    }

    /**
     * @param string $localFile
     * @return bool
     */
    public function uploadFile(string $localFile): bool
    {
        $ftp = ftp_ssl_connect($this->getHost(),$this->getPort());
        $ftp_login = ftp_login($ftp,$this->getUser(), $this->getPassword());
        ftp_pasv($ftp, true);

        $remoteFile = 'stock_hiltes.csv';

        if($ftp_login){
            $r = ftp_put($ftp,$this->getRemoteDir().$remoteFile, $localFile);
            ftp_close($ftp);
         //   dump(array('$r'=>$r,$this->getRemoteDir().$remoteFile, $localFile,'Line'=>__LINE__));
            if($r){
//                if(ftp_rename($ftp,$this->getRemoteDir().$remoteFile.'.tmp',$this->getRemoteDir().$remoteFile)){
//                    ftp_close($ftp);
                    return unlink($localFile); # löschen der datei
                //}
            }else
                return false;
        }

        return false;
    }
}