<?php

namespace Ignite\Core\Listeners;

use Ignite\Core\Emails\Enrolled;
use Ignite\Core\Entities\User;
use Ignite\Core\Facades\Program;
use Illuminate\Auth\Events\Registered;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Mail\Mailer;

class SendWelcomeEmail
{
    /**
     * @var Mailer
     */
    private $mailer;

    /**
     * SendWelcomeEmail constructor.
     *
     * @param Mailer $mailer
     */
    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    /**
     * When a user enrolls event.
     *
     * @param Registered $event
     */
    public function handle(Registered $event)
    {
        if (!request()->routeIs('admin.participant.store') && !request()->routeIs('admin.import.store')) {
            $this->sendEnrolledEmail($event->user);
        }

        if (request()->routeIs('admin.participant.store') && config('core.participant.enrollment.email_on_backend')) {
            $this->sendEnrolledEmail($event->user);
        }

        if (request()->routeIs('admin.import.store') && config('core.participant.enrollment.email_on_import')) {
            $this->sendEnrolledEmail($event->user);
        }
    }

    /**
     * @param User $user
     */
    protected function sendEnrolledEmail(User $user)
    {
        $this->mailer->later(now()->addSeconds(30), new Enrolled($user));
    }
}
