<?php

namespace App\Actions\Contact;

use App\Models\ContactSubmission;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;

/**
 * Send the internal "new enquiry" notification email for a stored contact
 * submission.
 *
 * Mirrors the legacy endpoint's behaviour of firing off a plain-text email
 * on every successful submission without ever failing the request: a mail
 * delivery failure is logged and swallowed, never re-thrown.
 */
class NotifyContactSubmission
{
    public function handle(ContactSubmission $submission): void
    {
        try {
            $body = $this->buildBody($submission);

            Mail::raw($body, function ($message) use ($submission): void {
                $message
                    ->from('no-reply@pushpvatikaflorist.com', 'Pushpvatika Website')
                    ->to(config('site.notify_email'))
                    ->subject('New enquiry: '.$submission->service->label());
            });
        } catch (Throwable $e) {
            Log::warning('Failed to send contact submission notification email', [
                'id' => $submission->id,
                'exception' => $e->getMessage(),
            ]);
        }
    }

    private function buildBody(ContactSubmission $submission): string
    {
        $lines = [
            'Name: '.$submission->name,
            'Phone: '.$submission->phone,
            'Email: '.$submission->email,
            'Service: '.$submission->service->label(),
            'Event date: '.($submission->event_date?->format('d M Y') ?? 'Not specified'),
            'Budget: '.($submission->budget?->label() ?? 'Not specified'),
            'Message: '.$submission->message,
            'Received: '.($submission->created_at?->format('d M Y, H:i') ?? now()->format('d M Y, H:i')),
            '',
            route('admin.contacts.show', $submission->id),
        ];

        return implode("\n", $lines);
    }
}
