<?php

namespace App\Listeners;

use App\Events\CreateTask;
use App\Events\Event;
use App\User;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Eventlog;
use Illuminate\Support\Facades\Auth;
use App\Unit;
use App\Notifications;
use Illuminate\Support\Facades\DB;


class CreateTaskListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     * @param  Event  $task
     * @post: Crea un evento de la tarea creada y crea la notificación  para el usuario asignado y teamLeaders de la misma unidad
     * @return void
     */
    public function handle(CreateTask $event)
    {

        $task = $event->task;
        $eventlog = new Eventlog();
        $eventlog->user_id = Auth::user()->id;
        $eventlog->type = 'Task';
        $eventlog->relation_id = $task->id;
        $eventlog->save();


        $user_array = array();

        $adminOSupervisor = DB::table('user_has_roles')
        ->whereIn('user_has_roles.role_id', [1, 4])->get();

        foreach ($adminOSupervisor as $user) {

            if ($eventlog->user_id != $user->user_id) {

                array_push($user_array, $user->user_id);
            }
        }

        $unit = Unit::find($task->unit_id);

        $pipeline =$task->pipeline()->first();

        $unitFirst = $pipeline->unitsByRevision($task->pipelineRevision)->first()->id;

        foreach ($unit->teamleaders as $tl) {

            if ($task->unit_id == $unitFirst && $tl->id != $eventlog->user_id){ //usuarios que se encuentran en la primera unidad (si la !era unidad es == a unidad actual)

                array_push($user_array, $tl->id);
            }
        }

        $array_unique = array_unique($user_array, SORT_REGULAR);

        foreach ($array_unique as $user_id) {

            $notification = new Notifications();
            $notification->eventlogs_id = $eventlog->id;
            $notification->type = 'Task';
            $notification->user_to = $user_id;
            $notification->is_delivered = 0;
            $notification->is_read = 0;
            $notification->is_archived = 0;
            $notification->save();

        }
    }


}
