<?php

namespace App\Jobs;

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\DB;
use Illuminate\Support\Facades\Mail;
use App\Mail\SendMailable;

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

    protected $users_ids;
    protected $users_emails;
    protected $notification_id;
    protected $notif_data;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($users_ids,$users_emails,$notification_id,$notif_data)
    {
        $this->users_ids = $users_ids;
        $this->users_emails = $users_emails;
        $this->notification_id = $notification_id;
        $this->notif_data = $notif_data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //Prendre les ids des users qui n'ont pas encore lu la notification
        $ids = DB::connection('tenant')
            ->table('user_notifications')
            ->whereIn('user_id',$this->users_ids)
            ->where('notification_id',$this->notification_id)
            ->where('statut','UNREAD')
            ->get()->pluck('user_id')->toArray();

        //Mail::to('latipiitech@gmail.com')->send(new SendMailable());

        foreach ($ids as $id) {
            Mail::to($this->users_emails["$id"])->send(new SendMailable($this->notif_data));
        }

    }
}
