<?php

declare(strict_types=1);

namespace External\HannahBundle\Maileon\Util;

use External\HannahBundle\Maileon\Exception\MaileonException;
use External\HannahBundle\Util\Configuration;

class FTPUtil
{
    private array $connection = [];

    private $configuration;

    private array $credentials = [];

    public function __construct(Configuration $configuration)
    {
        $this->configuration = $configuration;
    }

    public function setCredentials(string $user, string $password): void
    {
        $this->credentials = [
            'user' => $user,
            'password' => $password,
        ];
    }

    public function uploadFile(string $source, string $destination): bool
    {
        return ftp_put($this->getFTP(), $destination, $source);
    }

    public function getFTP()
    {
        if (empty($this->credentials['user']) || empty($this->credentials['password'])) {
            throw new MaileonException('Missing FTP credentials');
        }

        $connectionKey = md5(implode('-', array_values($this->credentials)));

        if ($this->connection[$connectionKey] ?? false) {
            return $this->connection[$connectionKey];
        }

        $config = $this->getFTPConfig();

        $connection = ftp_ssl_connect($config['host']);
        if (!ftp_login($connection, $this->credentials['user'], $this->credentials['password'])) {
            throw new MaileonException('Unable to connect to FTP server');
        }

        ftp_pasv($connection, true);

        return $this->connection[$connectionKey] = $connection;
    }

    private function getFTPConfig(): array
    {
        return $this->configuration->get('maileon')['ftp'] ?? [];
    }
}
