<?php

namespace App\Listeners;

use App\Events\UpdateTask;
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;
use App\Tasktag;

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

    /**
     * Handle the event.
     *
     * @param  UpdateTask  $event
     *  @post: Crea un evento de la tarea editada y crea la notificación  para el usuario asignado y teamLeaders de la misma unidad
     * @return void
     */
    public function handle(UpdateTask $event)
    {
        $task = $event->task;
        $eventlog = new Eventlog();
        $eventlog->user_id = Auth::user()->id;
        $eventlog->type = 'UpdateTask';
        $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);
            }
        }

        if($task->unit_id){

            $user_tags = Tasktag::where('relation_id','=',$eventlog->relation_id)
                ->where('unit_id','=',$task->unit_id)
                ->where('active','=',1)->get();//busca (tasktag)etiquetas donde los usuarios estén etiquetados en la tarea comentada


            if (is_countable($user_tags)){

                foreach ($user_tags as $tag_index => $user) {

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

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


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

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

            if ($eventlog->user_id != $tl->id) {// SI EL USUARIO QUE CREA EL EVENTO ES DIFERENTE A TL(TEAMLEADER)

                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 = 'UpdateTask';
            $notification->user_to = $user_id;
            $notification->is_delivered = 0;
            $notification->is_read = 0;
            $notification->is_archived = 0;
            $notification->save();
        }
    }
}
