<?php

namespace App\Domains\Admin\Actions\RemovePaymentMethodUsage;

use App\Mail\EventReportMails\PaymentMethodsExhaustedMail;
use App\Models\AvailablePaymentMethod;
use Illuminate\Support\Facades\Mail;

class RemovePaymentMethodUsageAction
{
    public function execute(AvailablePaymentMethod $availablePaymentMethod): void
    {
        foreach ($availablePaymentMethod->events()->get() as $event) {
            $event->paymentMethods()->detach($availablePaymentMethod->slug);

            $remainingActive = $event->paymentMethods()->where('active', true)->count();
            if ($remainingActive === 0 && $event->registration_allowed) {
                $event->registration_allowed = false;
                $event->save();

                $recipients = $event->eventManagers;
                if ($event->costUnit !== null) {
                    $recipients = $recipients->merge($event->costUnit->treasurers);
                }

                foreach ($recipients->unique('id') as $recipient) {
                    Mail::to($recipient->email)->send(new PaymentMethodsExhaustedMail($event));
                }
            }
        }
    }
}
