<?php

namespace App\Services\Support;

use App\Services\Email\EmailDispatchService;
use Illuminate\Support\Facades\Log;

class ContactMessageService
{
    public function __construct(private EmailDispatchService $emailService)
    {
    }

    public function send(array $payload): array
    {
        $name = (string) $payload['name'];
        $email = strtolower((string) $payload['email']);
        $subject = (string) $payload['subject'];
        $message = (string) $payload['message'];

        $formatted = "<p><strong>From:</strong> {$name} ({$email})</p>";
        $formatted .= "<p><strong>Subject:</strong> {$subject}</p>";
        $formatted .= '<p>' . nl2br($message) . '</p>';

        $recipient = (string) config('support.contact_email', 'support@alrahmaisgl.org');

        $emailSent = false;
        if (!app()->runningUnitTests()) {
            $emailSent = $this->emailService->send($recipient, $subject, $formatted, null, $email, $name);
        }

        if (!$emailSent) {
            Log::warning('Contact email failed for ' . $email);
        }

        return [
            'email_sent' => $emailSent,
            'recipient' => $recipient,
        ];
    }
}
