<?php

/**
 * Class CfMailSettings
 * Is used for retrieving mail settings
 */
class CfMailSettings
{
    public static function getSettings()
    {
        $connection =  new PDO(
            "pgsql:host=" . OAUTH_DATABASE_HOST . "; dbname=" . CFMP_DATABASE_NAME . ";port=" . OAUTH_DATABASE_PORT,
            OAUTH_DATABASE_USER,
            OAUTH_DATABASE_PASS
        );
        return $connection->query('SELECT * FROM mail_settings')->fetchAll(PDO::FETCH_KEY_PAIR);
    }
}

readonly class MailSettingsDTO
{
    public function __construct(
        public ?string $protocol = null,
        public ?string $defaultFromEmail = null,
        public ?string $maxAttachSize = null,
        public ?string $mailPath = null,
        public ?string $smtpHost = null, // plain text for non-HTML mail clients
        public ?string $smtpUser = null,
        public ?string $smtpPassword = null,
        public ?int $smtpPort = null,
        public ?string $smtpCrypto = null,
        public ?string $linksDomain = null,
    ) {
    }

    public function isSmtpEnabled(): bool
    {
        return $this->protocol === 'smtp';
    }

    public static function fromArray(array $data): self
    {
        return new self(
            protocol: $data['protocol'] ?? null,
            defaultFromEmail: $data['default_from_email'] ?? $data['smtp_user'] ?? 'root@localhost.loc',
            maxAttachSize: $data['max_email_attach_size'] ?? null,
            mailPath: $data['mailpath'] ?? null,
            smtpHost: $data['smtp_host'] ?? null,
            smtpUser: $data['smtp_user'] ?? null,
            smtpPassword: $data['smtp_pass'] ?? null,
            smtpPort:  empty($data['smtp_port']) ? null : intval($data['smtp_port']),
            smtpCrypto: $data['smtp_crypto'] ?? null,
            linksDomain: $data['email_link_domain'] ?? null,
        );
    }
}
