<?php
/**
 * Created by PhpStorm.
 * User: UNTREF
 * Date: 7/12/2017
 * Time: 10:28 AM
 */

namespace App\Listeners;


use App\Events\CreateAttach;
use App\Notifications;
use App\Pipeline;
use App\Subtask;
use App\Task;
use App\Tasktag;
use Carbon\Carbon;
use Illuminate\Support\Facades\Notification;
use Laravelista\Comments\Events\CommentWasPosted;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Eventlog;
use Illuminate\Support\Facades\Auth;
use App\Unit;
use Illuminate\Support\Facades\DB;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use phpDocumentor\Reflection\Types\Null_;

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

    /**
     * Handle the event.
     * @param  Event $task
     * Crea un evento
     * @return void
     */

    public function handle(CreateAttach $event)
    {
        $attach = $event->attach;

        $typeTask = $event->arrayType;
        $user_array =array();

        foreach ($typeTask as $key=>$id) {

            //si el archivo se subió en una subtarea
            if ($key == 'id_subtask' && $id != "undefined") {



                $users = $this->subtaskUser( $id);

                foreach ($users as $user) {

                    array_push($user_array, $user);
                }

                /** buscar grupos de attach **/

                $menos5 =Carbon::now()->subMinutes(5);

                $eventlog_aux= Eventlog::where('relation_id',$id)->where('type', 'AttachSubtask')->where('user_id', Auth::user()->id)->where('created_at', '>', $menos5)->orderBy('created_at','desc')->first();

                if($eventlog_aux){

                    if($eventlog_aux->count == null) {

                        $eventlog_aux->count = 2;
                        $eventlog_aux->created_at = Carbon::now();
                        $eventlog_aux->save();


                    } else{
                        $eventlog_aux->count = $eventlog_aux->count + 1;
                        $eventlog_aux->created_at = Carbon::now();
                        $eventlog_aux->save();

                    }
                }else{


                    $eventlog_aux= new Eventlog();
                    $eventlog_aux->user_id = Auth::user()->id;
                    $eventlog_aux->type = 'AttachSubtask';
                    $eventlog_aux->relation_id = $id;//id de la tarea
                    $eventlog_aux->content = $attach->id; //id de attach
                    $eventlog_aux->save();

                }


            }

            //si el archivo que se subió en una tarea
            if ($key == 'id_task' && $id != "undefined") {

                $users = $this->taskUser($id);

                foreach ($users as $user) {

                    array_push($user_array, $user);
                }


                /** buscar grupos de attach **/

                $menos5 =Carbon::now()->subMinutes(5);

                $eventlog_aux= Eventlog::where('relation_id',$id)->where('type', 'AttachTask')->where('user_id', Auth::user()->id)->where('created_at', '>', $menos5)->orderBy('created_at','desc')->first();

                if($eventlog_aux){

                    if($eventlog_aux->count == null) {

                        $eventlog_aux->count = 2;
                        $eventlog_aux->created_at = Carbon::now();
                        $eventlog_aux->save();


                    } else{
                        $eventlog_aux->count = $eventlog_aux->count + 1;
                        $eventlog_aux->created_at = Carbon::now();
                        $eventlog_aux->save();

                        }
                }else{

                    $eventlog_aux= new Eventlog();
                    $eventlog_aux->user_id = Auth::user()->id;
                    $eventlog_aux->type = 'AttachTask';
                    $eventlog_aux->relation_id = $id;//id de la tarea
                    $eventlog_aux->content = $attach->id; //id de attach
                    $eventlog_aux->save();

                }


            }

        }
        $menos1=Carbon::now()->subMinutes(1);

//        $count =int($eventlog_aux->comment_id);

        if(($eventlog_aux->count == null) && ($eventlog_aux->create_at < $menos1 )){

            $array_unique =  array_unique($user_array,SORT_REGULAR);


            foreach ($array_unique as $user_id) {

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

        }else{

            Notifications::where('eventlogs_id',$eventlog_aux->id)->update(['created_at' => $eventlog_aux->created_at]);

        }

    }


    /**
     * @param $eventlog
     * @param $attach
     * @return array de id de usuarios que estan etiquetados en la tarea ,admin,supervisores,
     * teamleader de la misma unidad de la tarea y clientes de la tarea.
     */
    private function taskUser($id){

        $user_array= array();

        $task = Task::find($id);

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

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

        foreach ($adminOSupervisor as $user) {

            if ( $user->user_id != Auth::user()->id) {

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

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


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

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

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

        //trae los usuarios clientes
        $userClient = $task->profile->users;
        $unitFirst = $pipeline->unitsByRevision($task->pipelineRevision)->first()->id;

        foreach ($userClient as $index => $user) {
            switch ($pipeline->system) {
                // pipeline comun
                case 0:
                    if ($task->unit_id == $unitFirst && $user->id != Auth::user()->id){

                        array_push($user_array, $user->id);
                    }
                    
                    break;

                // pipeline de pre ingreso
                case 1:
                    // usuario no es exteno (cliente)
                    if (!$user->isApplicant()) {
                        if ($task->unit_id == $unitFirst && $user->id != Auth::user()->id){

                            array_push($user_array, $user->id);
                        }   
                    }
                    
                    break;
                
                default:
                    if ($task->unit_id == $unitFirst && $user->id != Auth::user()->id){

                        array_push($user_array, $user->id);
                    }
                    
                    break;
            }
        }

        //usuarios etiquetados
        $userTag = $this->tagUser($task->id, $task->unit_id, 'task');//busca (tasktag)etiquetas donde los usuarios estén etiquetados en la tarea

        foreach ($userTag as $user){

                array_push($user_array, $user);
        }

        return $user_array;

    }

    /**
     * @param $eventlog
     * @return array de id de usuarios donde estan eiquetados en la misma subtarea, teamleader que creo la subtarea y usario asignado a la tarea si es el         *caso que no sean igual al usuario logueado
     */

    private function SubtaskUser($id){

        if($id != null) {

            $user_array = array();

            $userTag = $this->tagUser($id, null, 'subtask');//busca (tasktag)etiquetas donde los usuarios estén etiquetados

            $subtask = Subtask::find($id);

            if ($subtask->assigned_id != Auth::user()->id) {//es usuario asignado?

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

            }
            if ($subtask->user_id != Auth::user()->id) { //es teamleader?

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

            foreach ($userTag as $user) {

                    array_push($user_array, $user);
            }

            return $user_array;
        }
    }


    /**
     * @param $relationId
     * @param $unit_id
     * @param $type
     * @return array ID USER busca (tasktag)etiquetas donde los usuarios estén etiquetados en la tarea comentada
     */

    private function  tagUser($relationId,$unit_id,$type){

        $user_tags = Tasktag::where('relation_id','=',$relationId)
            ->where('unit_id','=',$unit_id)
            ->where('type','=',$type)
            ->where('active','=',1)->get();
        $user_array= array();


            if (is_countable($user_tags)){

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

                if (Auth::user()->id != $user->user_id) {

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

        return $user_array;
    }

}