<?php

namespace App\Domains\Event\Controllers\MailCompose;

use App\Mail\ManualMails\ManualMailsCommonMail;
use App\Mail\ManualMails\ManualMailsReportMail;
use App\Mail\ParticipantCocMails\ParticipantCocCompleteMail;
use App\Scopes\CommonController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class SendController extends CommonController
{
    public function __invoke(string $eventIdentifier, Request $request) {
        $recipients = $request->input('recipients')
        |> function (string $value) : string { return str_replace(';', ',', $value); }
        |> function (string $value) : array { return explode( ',', $value); };

        $event = $this->events->getByIdentifier($eventIdentifier, true)->toResource()->toArray($request);
        $sentRecipients = [];
        $allOkay = true;
        $subject = $request->input('subject') ?? 'Neue Nachricht zu Veranstaltung "' . $event['name'] . '"';

        foreach ($recipients as $recipient) {
            if (in_array($recipient, $sentRecipients)) {
                continue;
            }

            $sentRecipients[] = $recipient;
            try {
                Mail::to(trim($recipient))->send(new ManualMailsCommonMail(
                    mailSubject: $subject,
                    message: $request->input('message'),
                    event: $event,
                ));
            } catch (\Exception $e) {
                $allOkay = false;
            }
        }

        $user = auth()->user();
        $reportSubject = sprintf('Sendebericht für Nachricht mit Betreff "%s"', $subject);

        Mail::to($user->email)->send(new ManualMailsReportMail(
            mailSubject: $reportSubject,
            message: $request->input('message'),
            event: $event,
            originalRecipients: $sentRecipients
        ));

        if ($allOkay) {
            return response()->json([
                'success' => true,
                'message' => sprintf(
                    'E-Mail wurde erfolgreich an %1$s Personen versendet. Du hast eine Kopie an deine Mail-Adresse erhalten.',
                    count($sentRecipients)
                ),
            ]);
        } else {
            return response()->json([
                'success' => false,
                'message' => 'Es gab einen Fehler beim Versenden der Nachrichten.'
            ]);
        }
    }
}
