<?php

namespace App\Listeners;

use App\Notifications;
use App\Subtask;
use App\Task;
use App\Tasktag;
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 Spatie\Permission\Models\Role;

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

    /**
     * Handle the event.
     * @param  CommentWasPosted  $event
     * @return void
     */
    public function handle(CommentWasPosted $event)
    {

        $comment = $event->comment;
        $eventlog = new Eventlog();
        $eventlog->user_id = Auth::user()->id;
        $eventlog->type = $comment->content_type;
        $eventlog->relation_id = $comment->content_id;
        $eventlog->comment_id = $comment->id;
        $eventlog->save();

        $user_array = array();
        $userTag = array();

        $admin  = Role::where('name', 'supervisor')->first()->id;
        $supervisor =Role::where('name', 'administrator')->first()->id;


        if ($eventlog->type == "App\Task") {

            $changeUnit = null;

            preg_match_all("/(([A-Z]+\s+([A-Z]+)[a-zÑñáéíóúÁÉÍÓÚ]+)|([A-Z][a-zÑñáéíóúÁÉÍÓÚ]+))(?={.*})/", $comment->comment, $changeUnit);


            if (count($changeUnit[0]) > 0) {

                $unitUser = array();
                $newUnit = $comment->unit_id;


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

                foreach ($adminOSupervisor as $user) {

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

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

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

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


                $userClient = $task->profile->users; //trae los usuarios clientes

                foreach ($userClient as $index => $user) {

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

                        array_push($unitUser, $user->id);
                    }
                }

                $unit = Unit::where('id', $newUnit)->first();

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

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

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

                $array_uniqueUnit = array_unique($unitUser, SORT_REGULAR);


                foreach ($array_uniqueUnit as $user_id) {

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

                }

                $unitComment = array();
                preg_match("/([a-zÑñáéíóúÁÉÍÓÚA-Z0-9\s\.\(\)\*\?$\^\w\+\-\¿\'\<\>\#\%\/\=\¡\!\[\]\@\"\:\,\;]+$)/", $comment->comment, $unitComment);

                if (strlen($unitComment[0]) > 4) {

                    foreach ($array_uniqueUnit as $user_id) {

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

                    }
                }

            } else {
                //si es un comentario en tarea

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

                foreach ($userTag as $user) {

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

                        array_push($user_array, $user);
                    }

                }


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

                foreach ($adminOSupervisor as $user) {

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

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

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

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


                $userClient = $task->profile->users; //trae los usuarios clientes

                foreach ($userClient as $index => $user) {

                    switch ($pipeline->system) {
                        // pipeline comun
                        case 0:
//
                            if ($comment->unit_id == $unitFirst && $user->id != $eventlog->user_id) { //(si la !era unidad es == a unidad actual) => usuarios que se encuentran en la primera unidad

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

                        // pipeline de pre ingreso
                        case 1:
                            // usuario no es exteno (cliente)
                            if (!$user->isApplicant()) {
                                if ($comment->unit_id == $unitFirst && $user->id != $eventlog->user_id) { //(si la !era unidad es == a unidad actual) => usuarios que se encuentran en la primera unidad
                                    array_push($user_array, $user->id);
                                }
                            }
                            break;
                        
                        default:
                            if ($comment->unit_id == $unitFirst && $user->id != $eventlog->user_id) { //(si la !era unidad es == a unidad actual) => usuarios que se encuentran en la primera unidad
                                    array_push($user_array, $user->id);
                            }
                            break;
                    }

                }


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

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

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

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

            }

        }// fin  App\Task

            //si es un comentario en subtarea
        if ($eventlog->type =="App\Subtask") {


            $userTag = $this->tagUser($eventlog->relation_id, null, 'subtask');//busca (tasktag)etiquetas donde los usuarios estén etiquetados en la tarea comentada

            foreach ($userTag as $user) {

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

                    array_push($user_array, $user);
                }

            }

            $subtask = Subtask::find($eventlog->relation_id);

            if ($subtask->assigned_id != $eventlog->user_id) {//es usuario asignado

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

            }
            if ($subtask->user_id != $eventlog->user_id) { //es teamleader

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

        }//fin App\Subtask


        $array_unique = array_unique($user_array, SORT_REGULAR);


        foreach ($array_unique as $user_id) {

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

        }
    }



    //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) {

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

        return $user_array;
    }

}
