<?php

namespace App\Listeners\Applications;

use App\Events\Applications\ApplicationStatusChanged;
use App\Mail\Applications\NotifyApplicationStatusChanged;
use App\Models\Applications\Application;
use App\Models\Applications\ApplicationStatus;
use App\Models\Companies\CompanyMember;
use App\Models\User;
use Illuminate\Support\Facades\Mail;

class SendApplicationStatusChangedNotifications {
    public array $notifiableStatuses = [
        'applicant' => [ApplicationStatus::COMPLETED],
        'addresses' => [ApplicationStatus::PROCESSING]
    ];

    public function __construct() {
    }

    public function handle(ApplicationStatusChanged $event) {
        if (in_array($event->status, $this->notifiableStatuses['addresses'])) $this->notifyAddressees($event->application, $event->status);
        if (in_array($event->status, $this->notifiableStatuses['applicant'])) $this->notifyApplicant($event->application, $event->status);
    }

    public function notifyAddressees(Application $application, $status) {
        $application->addressees->each(function(CompanyMember $member) use($application, $status) {
            $this->notify($member->user, $application, $status);
        });
    }

    public function notifyApplicant(Application $application, $status) {
        $this->notify($application->submitter, $application, $status);
    }

    public function notify(User $recipient, Application $application, $status) {
        try {
            Mail::to($recipient->email)->send(new NotifyApplicationStatusChanged($application, $recipient, $status));
        } catch (\Exception $exception) {}
    }


}
