<?php

namespace App\Console\Commands;

use App\Services\UserService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
use App\Mail\CourseNotificationMail;
use App\Services\CourseNotificationService;

class SendProductEmailNotifications extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'send:lp-notifications';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command that checks scheduled learning product notifications, sending emails to users specified.';

    private $userService;

    private $courseNotificationService;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(
        UserService $userService,
        CourseNotificationService $courseNotificationService
    ) {
        parent::__construct();
        $this->userService = $userService;
        $this->courseNotificationService = $courseNotificationService;
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $course_notifications = $this->courseNotificationService->getExpiredToSendWithProducts();

        // No notifications? Exit
        if ($course_notifications->count() <= 0) return 0;

        foreach ($course_notifications as $notification) {

            $users = json_decode($notification->users);
            $emails = json_decode($notification->emails);

            // Send emails to not registered users 
            if (count($emails) > 0) {

                foreach ($emails as $email) {
                    Mail::to($email)->queue(new CourseNotificationMail($notification));
                }
            }

            // Send emails to specified registered users 
            foreach ($users as $userId) {

                $user = $this->userService->get($userId);
                Mail::to($user)->queue(new CourseNotificationMail($notification));
            }

            // Mark as sent
            $notification->sent = true;
            $notification->save();
        }

        return 0;
    }
}
