<?php

declare(strict_types=1);

namespace MailerPress\Core\EmailManager\services;

\defined('ABSPATH') || exit;

use Exception;
use MailerPress\Core\EmailManager\AbstractEmailService;
use Symfony\Component\Mailer\Envelope;
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;

class SmtpService extends AbstractEmailService
{
    public function sendEmail(array $emailData): bool
    {
        try {
            $host = $this->config['conf']['host'] ?? '';
            $port = $this->config['conf']['port'] ?? 587;
            $encryption = $this->config['conf']['encryption'] ?? 'tls';
            $username = $this->config['conf']['auth_id'] ?? '';
            $password = $this->config['conf']['auth_password'] ?? '';

            $dsn = sprintf(
                '%s://%s:%s@%s:%s',
                $encryption === 'ssl' ? 'smtps' : 'smtp',
                urlencode($username),
                urlencode($password),
                $host,
                $port
            );

            $transport = Transport::fromDsn($dsn);
            $mailer = new Mailer($transport);

            $email = (new Email())
                ->from(new Address($emailData['sender_to'], $emailData['sender_name'] ?? ''))
                ->to($emailData['to'])
                ->subject($emailData['subject'] ?? '')
                ->html($emailData['body'] ?? '');

            // Ajouter Reply-To si fourni (utiliser From si Reply-To est vide)
            $replyToName = $emailData['reply_to_name'] ?? $emailData['sender_name'] ?? '';
            $replyToAddress = $emailData['reply_to_address'] ?? $emailData['sender_to'] ?? '';

            if (!empty($replyToAddress)) {
                $email->replyTo(new Address($replyToAddress, $replyToName));
            }

            $bounceConfig = get_option('mailerpress_bounce_config');
            if ($bounceConfig) {
                if (is_string($bounceConfig)) {
                    $bounceConfig = json_decode($bounceConfig, true);
                }
                $envelopeSender = $emailData['return_path'] ?? $bounceConfig['email'];
                $envelope = new Envelope(new Address($envelopeSender), [new Address($emailData['to'])]);
                $mailer->send($email, $envelope);
            } else {
                $mailer->send($email);
            }


            return true;
        } catch (TransportExceptionInterface | Exception $e) {
            return false;
        }
    }

    public function testConnection(): bool
    {
        // Optional: You can implement a test email send or SMTP handshake check here
        return true;
    }

    public function config(): array
    {
        return [
            'key' => 'smtp',
            'name' => 'Custom SMTP',
            'icon' => '<svg xmlns="http://www.w3.org/2000/svg" width="44" height="44" fill="none" viewBox="0 0 92 92"><rect width="92" height="92" fill="#FF4F00" rx="46"></rect><path fill="#fff" d="M51.012 65.526c-.312.748-.857 1.216-1.636 1.405-.779.186-1.449-.002-2.01-.563l-6.637-6.642c-.343-.343-.544-.78-.606-1.31-.063-.53.06-1.012.372-1.449l8.507-14.03-13.975 8.652c-.436.249-.911.35-1.425.303a2.098 2.098 0 0 1-1.333-.63l-6.637-6.642c-.56-.561-.748-1.232-.563-2.011.189-.78.657-1.325 1.404-1.637l36.411-14.826c.935-.312 1.745-.125 2.43.561.686.686.857 1.481.515 2.386L51.012 65.526Z"></path></svg>',
            'link' => 'https://www.brevo.com/fr/pricing/',
            'createAccountLink' => 'https://onboarding.brevo.com/account/register',
            'linkApiKey' => 'https://app.brevo.com/settings/keys/api',
            'description' => __(
                'Connect to any SMTP server using our Custom SMTP feature. For setup instructions, see our documentation.',
                'mailerpress'
            ),
            'recommended' => false,
            'sending_frequency' => [
                "numberEmail" => 75,
                "frequency" => [
                    'value' => 2,
                    'unit' => 'minutes',
                ]
            ]
        ];
    }
}
