<?php

namespace App\Helper;


use Exception;

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']);

    }

    /**
     * Uploads a local file to a remote FTP server.
     *
     * @param string $localFile The local file path to upload.
     * @param string $warehouse
     * @return void
     * @throws Exception If the upload fails or encounters an error.
     */
    public function uploadFile(string $localFile, string $warehouse): void
    {
        $ftp = ftp_ssl_connect($this->getHost(), $this->getPort());

        if (!$ftp) {
            throw new Exception("Failed to connect to FTP server");
        }

        $ftp_login = ftp_login($ftp, $this->getUser(), $this->getPassword());

        if (!$ftp_login) {
            throw new Exception("FTP login failed");
        }

        ftp_pasv($ftp, true);
        ftp_set_option($ftp, FTP_TIMEOUT_SEC, 120);

        $remoteFile = 'stock_' . $warehouse . '.csv';

        if (!file_exists($localFile)) {
            throw new Exception("Local file does not exist: $localFile");
        }

        $r = @ftp_nb_put($ftp, $this->getRemoteDir() . $remoteFile, $localFile, FTP_BINARY);

        while ($r == FTP_MOREDATA) {
            // Continue uploading...
            $r = @ftp_nb_continue($ftp);
        }

        if ($r != FTP_FINISHED) {
            throw new Exception("File upload failed");
        }

        ftp_close($ftp);

        if (!unlink($localFile)) {
            throw new Exception("Failed to delete local file: $localFile");
        }
    }

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

    /**
     * @param string $host
     * @return void
     */
    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;
    }
}