<?php

namespace App\Listeners\Applications;

use App\Events\Applications\ApplicationExpertChanged;
use App\Mail\Applications\NotifyApplicationExpertChanged;
use App\Models\Applications\Application;
use App\Models\Companies\CompanyMember;
use App\Models\User;
use Illuminate\Support\Facades\Mail;

class SendApplicationExpertChangedNotifications {

    public function __construct() {
    }

    public function handle(ApplicationExpertChanged $event) {
        if ($v = $event->application->submitter) $this->notify($v, $event->application);
        if ($v = $event->application->expert()->first()) $this->notify($v->user, $event->application);
        if ($v = $event->previousExpert) $this->notify($v->user, $event->application);
        $this->notifyApplicationManagers($event->application);
    }

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

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


}
