<?php

namespace App\Jobs;

use App\Mail\BulkEmail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;

class SendBulkEmailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * The name of the queue the job should be sent to.
     *
     * @var string|null
     */
    public $queue = 'emails';

    protected $users;
    protected $subject;
    protected $message;

    /**
     * Create a new job instance.
     */
    public function __construct($users, $subject, $message)
    {
        $this->users = $users;
        $this->subject = $subject;
        $this->message = $message;
    }

    /**
     * Execute the job.
     */
    public function handle()
    {
        foreach ($this->users as $user) {
            Mail::to($user->email)->send(new BulkEmail($this->subject, $this->message));
            // Add delay to prevent overwhelming the mail server
            sleep(1);
        }
    }
}
