<?php

namespace App\Jobs;

use App\Activity;
use App\Mail\NotifyUser;
use App\Project;
use App\Task;
use DateTime;
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 CheckTaskDelayJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $tasks = Task::all();
        foreach ($tasks as $task)
        {
            // dd($task);
            if ($task->statut != 'ended' && $task->start_date->diffInDays($task->end_date) > 2)
            {
                // dd($task);
                if (now()->lt($task->end_date) && now()->diffInDays($task->end_date) == 2)
                {
                    // dd($task);
                    $users = $task->users;
                    if($users)
                    {
                        // dd($users);
                        $activity = Activity::find($task->activity_id);
                        $project = Project::find($activity->projet_id);
                        foreach($users as $user)
                        {
                            // dd($user);
                            Mail::to($user->email)->send(new NotifyUser($user, $task, $activity, $project));
                        }
                    }
                }
            }
        }
    }
}
