<?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
     */
    protected $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') && 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);
        }

        // if called from anywhere else
        if (!request()->routeIs('admin.participant.store') && !request()->routeIs('admin.import.store')) {
            $this->sendEnrolledEmail($event->user);
        }
    }

    /**
     * @param User $user
     */
    protected function sendEnrolledEmail(User $user)
    {
        if (true) {
            $delay = app()->environment('local') ? 3 : 10;
            $this->mailer->later(now()->addSeconds($delay), new Enrolled($user));
        } else {
            // -- send without queue --
            $this->mailer->send(new Enrolled($user));
        }
    }
}
