<?php
/**
 * Created by PhpStorm.
 * User: UNTREF
 * Date: 22/11/2017
 * Time: 4:36 PM
 */

namespace App\Listeners;

use App\Events\CreateUnTag;
use App\Events\Event;
use App\Eventlog;
use App\Subtask;
use Illuminate\Support\Facades\Auth;
use App\Notifications;
use Illuminate\Support\Facades\DB;
use App\Task;
use App\Tasktag;
use Carbon\Carbon;



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

    }

    /**
     * Handle the event.
     * @param  Event $event
     *pre: inserta un nuevo eventlogs y notifications en sus correspondientes tablas en BD ,
     */
    public function handle(CreateUnTag $event)
    {
//        dd($event->task_tag);

        $task_tag = $event->task_tag;
        $eventlog = new Eventlog();
        $eventlog->user_id = Auth::user()->id;
        $eventlog->type = 'unTasktag';
        $eventlog->relation_id = $task_tag->id;//id de la etiqueta
        $eventlog->content =$task_tag->user_id;
        $eventlog->save();

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

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

        }

        $user_array =array();

        if($task_tag->type == 'task'){ //si es una tarea

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

            foreach ($supervisor as $user) {

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

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

            //notifica a los teamleader de la misma unidad excepto si el teamleader creo el evento de cambio de estado

            $task = Task::find($task_tag->relation_id);

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

                if ($eventlog->user_id != $tl->id && $tl->id != $task_tag->user_id) {

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

                }
            }

            //busco los etiquetados en la tarea para notificar que hay un nuevo etiquetado

            $user_tags = Tasktag::where('relation_id','=',$task->id) //etiquetados
                ->where('type','=','task')
                ->where('unit_id','=',$task->unit_id)
                ->where('active','=',1)->get();


               if (is_countable($user_tags)){

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

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

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

                }
            }


        }elseif ($task_tag->type =='subtask'){ //si es type subtarea

            $subtag =Subtask::find($task_tag->relation_id);

            if($subtag->assigned_id != $eventlog->user_id && $subtag->assigned_id != $task_tag->user_id){

                array_push($user_array, $subtag->assigned_id);

            }
            if ($subtag->user_id != $eventlog->user_id && $subtag->user_id != $task_tag->user_id){//si usuario logueado es difernte a usurio que creò la subtarea

                array_push($user_array, $subtag->user_id);

            }

            //busco los etiquetados en la subtarea para notificar que hay un nuevo etiquetado

            $user_tags = Tasktag::where('relation_id','=',$subtag->id) //etiquetados
                ->where('type','=','subtask')
                ->where('active','=',1)->get();


            if (is_countable($user_tags)){

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

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

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

                }
            }

        }

        $array_unique =  array_unique($user_array,SORT_REGULAR);//unifico

        $menos24 = Carbon::now()->subHour(5);

        $tasktag_aux = Tasktag::where('relation_id', $task_tag->relation_id)->where('type',$task_tag->type)->where('created_at', '>', $menos24)->where('active',0)->where('unit_id',$task_tag->unit_id)->orderBy('created_at', 'desc')->get();

        $usersId = array();

        foreach ($tasktag_aux As $key=>$tasktag){

            array_push($usersId,$tasktag->user_id);

        }

        //-------------

        foreach ($array_unique as $user_id){

            if ($tasktag_aux) {

                if (count($tasktag_aux) > 1) {

                    $notif_aux = Notifications::where('type', 'InfoUntag')->where('created_at', '>', $menos24)->where('user_to', $user_id)->orderBy('created_at', 'desc')->first();

                    if($notif_aux ){

                        $notif_aux->is_read = 0;
                        $notif_aux->is_archived = 0;
                        $notif_aux->array_users = json_encode($usersId);
                        $notif_aux->created_at = Carbon::now();
                        $notif_aux->save();

                    }


                } else {

                    $notification = new Notifications();
                    $notification->eventlogs_id = $eventlog->id;
                    $notification->type = 'InfoUntag';
                    $notification->user_to = $user_id;
                    $notification->is_delivered = 0;
                    $notification->is_read = 0;
                    $notification->is_archived = 0;
                    $notification->save();
                }
            }
        }//falta crear evento para los que teamleader y supervisor q estan etiquetados


    }


}