<?php

namespace App\Domains\Event\Actions\SendMissingPaymentMails;

use App\Mail\ParticipantPaymentMails\ParticipantPaymentMissingPaymentMail;
use Illuminate\Support\Facades\Mail;

class SendMissingPaymentMailsCommand {
    function __construct(public SendMissingPaymentMailsRequest $request) {}

    public function execute() : SendMissingPaymentMailsResponse {
      $response = new SendMissingPaymentMailsResponse();

        foreach ($this->request->eventParticipants->getParticipantsWithMissingPayments($this->request->event, $this->request->httpRequest) as $participant) {
            $participantResource = $participant->toResource()->toArray($this->request->httpRequest);
            if (!$participantResource['needs_payment']) {
                continue;
            }

            Mail::to($participant->email_1)->send(new ParticipantPaymentMissingPaymentMail(
                participant: $participant,
            ));

            if ($participant->email_2 !== null && $participant->email_2 !== $participant->email_1) {
                Mail::to($participant->email_2)->send(new ParticipantPaymentMissingPaymentMail(
                    participant: $participant,
                ));
            }

            $response->remindedParticipants++;
        }

        $response->success = true;

        return $response;
    }
}
