<?php

declare(strict_types=1);

namespace App\Services;

final class MailerService
{
    public function send(string $to, string $subject, string $html): array
    {
        $messageId = sprintf(
            '<civigo-%s-%s@%s>',
            bin2hex(random_bytes(8)),
            time(),
            parse_url((string) config('app.url'), PHP_URL_HOST) ?: 'civigo.eu'
        );

        if (class_exists(\PHPMailer\PHPMailer\PHPMailer::class)) {
            try {
                $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
                $mail->isSMTP();
                $mail->Host = (string) config('mail.host');
                $mail->Port = (int) config('mail.port');
                $mail->SMTPAuth = true;
                $mail->Username = (string) config('mail.username');
                $mail->Password = (string) config('mail.password');
                $mail->CharSet = 'UTF-8';
                $mail->setFrom((string) config('mail.from_address'), (string) config('mail.from_name'));
                $mail->Sender = (string) config('mail.return_path');
                $mail->addAddress($to);
                $mail->Subject = $subject;
                $mail->isHTML(true);
                $mail->Body = $html;
                $mail->MessageID = $messageId;
                $mail->ConfirmReadingTo = (string) config('mail.from_address');
                $mail->addCustomHeader('Disposition-Notification-To', (string) config('mail.from_address'));
                $mail->addCustomHeader('Return-Receipt-To', (string) config('mail.from_address'));
                $mail->send();

                return [
                    'ok' => true,
                    'status' => 'smtp_accepted',
                    'message_id' => $messageId,
                    'sent_at' => date('Y-m-d H:i:s'),
                    'error' => null,
                ];
            } catch (\Throwable $exception) {
                return [
                    'ok' => false,
                    'status' => 'smtp_failed',
                    'message_id' => $messageId,
                    'sent_at' => null,
                    'error' => $exception->getMessage(),
                ];
            }
        }

        file_put_contents(
            config('storage.logs') . '/mail.log',
            '[' . date('c') . "] {$to} | {$subject} | {$messageId}\n",
            FILE_APPEND
        );

        return [
            'ok' => true,
            'status' => 'logged_demo_delivery',
            'message_id' => $messageId,
            'sent_at' => date('Y-m-d H:i:s'),
            'error' => null,
        ];
    }
}
