<?php
/**
 * Created by PhpStorm.
 * User: UNTREF
 * Date: 3/8/2017
 * Time: 3:41 PM
 */

namespace App\Http\Controllers;

use App\Attachment;
use App\Eventlog;
use App\Notifications;
use App\Profile;
use App\Subtask;
use App\Task;
use App\Taskdata;
use App\Tasktag;
use App\User;
use Illuminate\Support\Facades\Auth;
use Laravelista\Comments\Comments\Comment;
use phpDocumentor\Reflection\Types\Null_;
use PhpParser\Node\Arg;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Input;
use Carbon\Carbon;
//use App\Services\Pagination;


class NotificationsController extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->middleware('auth');


    }


    /**pre:consigue y muestra notificacion no leidas
     * post:muestra en vista las notificaciones no leídas;
     * @return notification.notifications, arreglo $args
     */
    public function index()
    {

        $notification = Notifications::where('user_to', '=', Auth::user()->id)
            ->where('is_read','=',0)
            ->where('is_archived','=',0)
            ->where('type','<>','TaskInactive')
            ->orderBy('created_at', 'DESC')->paginate(30);


        $notif_NoLeidas = array();
        $notif_noLeidasrender =array();

        if ($notification) //si existen notificaciones
        {
            $notif_NoLeidas = $this->notificationsNotRead($notification, $notif_NoLeidas);

            $notif_noLeidasrender = $notification;
        }

        $args = array(
            'notificaciones_noLeidas' => $notif_NoLeidas,
            'count_notif_noLeidas' => $this->countNotificationNotRead(),
            'countInactiveNoRead' => $this->countNotificationNotReadInactive(),
            'notif_noLeidasRender' => $notif_noLeidasrender,

        );

        return view('notification.notifications', $args);

    }


    /**
     *pre: consigue las notificaciones leidas/noArchivadas ,leídas/archivadas,
     * post: se muestra en vista las notificaciones encontradaas ;
     * @return vista notificacion_read, $args
     */

    public function getNotificationsRead()
    {
        $notification = Notifications::where('user_to', '=',Auth::user()->id)
                        ->where('is_read','=',1)
                        ->where('is_archived','=',0)
                        ->orderBy('created_at', 'DESC')->paginate(30);

        $notif_Leidas = array();
        $notif_Leidasrender =array();

        if (count($notification) >0) //si existen notificaciones
        {

            $notif_Leidas = $this->isRead($notification, $notif_Leidas);

            $notif_Leidasrender = $notification;
            // fin paginación


        }


        $args = array(
            'notificaciones_leidas' => $notif_Leidas,
            'count_notif_noLeidas' => $this->countNotificationNotRead(),
            'countInactiveNoRead' => $this->countNotificationNotReadInactive(),
            'notif_leidasRender' => $notif_Leidasrender,
        );

        return view('notification.notifications_read', $args);

    }


    /**
     *pre: consigue las notificaciones Archivadas ,
     * post: se muestra en vista las notificaciones encontradaas ;
     * @return vista notifications_arch, $args
     */
    public function getNotificationsArchivadas()
    {


        $notification = Notifications::where('user_to', '=', Auth::user()->id)
            ->where('is_archived','=',1)
            ->orderBy('created_at', 'DESC')->paginate(30);



        $notif_Archivadas= array();
        $notif_Archivadasrender =array();


        if ($notification) //si existen notificaciones
        {

            $notif_Archivadas= $this->isArchived($notification, $notif_Archivadas);
            $notif_Archivadasrender = $notification;

        }

        $args = array(
            'notificaciones_archivadas' => $notif_Archivadas  ,
            'count_notif_noLeidas' => $this->countNotificationNotRead(),
            'countInactiveNoRead' => $this->countNotificationNotReadInactive(),
            'notif_archivadasRender' => $notif_Archivadasrender,

        );

        return view('notification.notifications_arch', $args);
    }


    /**
     * @param $notificacion
     * @param $notif_Leidas
     * pre:recibe por parametro dos arreglos, un array de notificaciones y array en el guaradará las notificaciones con estado leído
     * post:retorna el arreglo con notificaciones en estado leído
     * @return notif_Leidas
     */
    private function isRead($notificacion, $notif_Leidas)
    {
        foreach ($notificacion as $n) {

                $notif_Leidas = $this->getArrayNotifications($n, $notif_Leidas);

           ;
        }

        return $notif_Leidas;
    }


    /**
     * @param $notification
     * @param $notif_Archivadas
     * pre: recibe por parametro arrays de notificaciones y variable array donde se guarda las notificaciones no leída
     * post: devuelve arreglo de notificaciones que están en estado archivadas
     * @return notif_Archivadas
     */

    private function isArchived($notification, $notif_Archivadas)
    {

        foreach ($notification as $n) {

                $notif_Archivadas = $this->getArrayNotifications($n, $notif_Archivadas);

        }

        return $notif_Archivadas;
    }


    /**
     * @return int devuelve la cantidad de notificaciones no leídas
     */
    public function countNotificationNotRead(){

        $notification = Notifications::where('user_to', '=', Auth::user()->id)
            ->where('is_read','=',0)
            ->where('is_archived','=',0)
            ->where('type','<>','TaskInactive')
            ->orderByDesc('id')->count();

        return $notification;
    }

    /**
     * @return int devuelve la cantidad de notificaciones no leídas de inactividad
     */
    public function countNotificationNotReadInactive(){

        $notification = Notifications::where('user_to', '=', Auth::user()->id)
            ->where('is_read','=',0)
            ->where('is_archived','=',0)
            ->where('type','=','TaskInactive')
            ->orderByDesc('id')->count();

        return $notification;
    }

    /**
     * @param $notification
     * @param $notif_NoLeidas
     * pre: recibe por parametro un array de notificaciones y variable array donde se guarda las notificaciones no leída
     * post: devuelve arreglo de notificaciones que están en estado archivadas
     * @return notif_NoLeidas
     */
    public function notificationsNotRead($notification, $notif_NoLeidas)
    {

        foreach ($notification as $n) {


                $notif_NoLeidas = $this->getArrayNotifications($n, $notif_NoLeidas);

        }

        return $notif_NoLeidas;
    }

    /**
     * @param $n
     * @param $getNotif
     * pre:consigue las notificaciones de comentarios,nuevas tareas creadas y editadas.
     * post:@return  un arreglo $getNotif , contiene lo conseguido  para mostrar en la vista que lo pida*

     */
    private function getArrayNotifications($n, $getNotif)
    {
        $evento = $n->eventlog->id;

        $evenLog = Eventlog:: where('id', '=', $evento)->get(['user_id',"relation_id","content","comment_id","count"]);

        $tipoTarea = $n->type;


        foreach ($evenLog as $e) {


//          usuario que creó el evento
            $user = User::where('id', '=', $e->user_id)->value('name');

            switch ($tipoTarea) {


                case 'App\Task': //es un comentario

                    $tarea = Task::where('id', '=', $e->relation_id)->get(["id", "title", "user_id", "unit_id", "taskdata_id", "status_id"])->first();//tarea donde el id = relation_id(evento)

                    if ($tarea != null) {
                        $isActive = $this->tagActive($tarea->id, 'task',$tarea->unit_id);

                        $comment = Comment::where('id', '=', $e->comment_id)->get(['comment', 'unit_id'])->first();

                        if ($e->comment_id != null) { //existe un comentario

                            $unitComment = array();

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

//                            if (count($units[0]) > 0) {
//                                $getNotif[$n->id] = $this->changeUnit($units, $user, $tarea, $n->id, 'changeToUnit', $isActive, $n->created_at->format('d-m-Y H:i'));
//                            } else {

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

                            if ($unitComment != null) {
                                if (strlen($unitComment[0]) >0) {  //es un comentario  que se agrego cuando se cambio de unidad

                                    $getNotif[$n->id] = $this->arrayNotification($n->id,$user, $unitComment[0], $tarea->title, $tarea->id, $comment->unit_id, 'tarea', $tarea->status->name, $isActive, null, $n->created_at->format('d-m-Y H:i'), $comment->unit->name, null, null,null);
                                }
                            } else { //es un comentario simple en una tarea
                                $taskdata_title = Taskdata::where('id', $tarea->taskdata_id)->value('title');

                                $getNotif[$n->id] = $this->arrayNotification($n->id,$user, $comment->comment, $taskdata_title, $tarea->id, $comment->unit_id, 'tarea', $tarea->status->name, $isActive, null, $n->created_at->format('d-m-Y H:i'), $comment->unit->name, null, null,null);

                            }

                        }
                    }

                    break;


                case 'Task':

                    $tarea = Task::find($e->relation_id);//tarea donde el id = relation_id(evento)

                    if ($tarea != null) {
                        $isActive = $this->tagActive($tarea->id, 'task',$tarea->unit_id);


                        //es tarea con titulo

                        if ($tarea->title) {

                            $getNotif[$n->id] = $this->arrayNotification($n->id,$user, null, $tarea->title, $tarea->id, $tarea->unit_id, 'tarea', null, $isActive, $tarea->pipeline->first()->name, $n->created_at->format('d-m-Y H:i'),null,null,null,$tarea->type);

                        } else {


                            $getNotif[$n->id] = $this->arrayNotification($n->id,$user, null, $tarea->taskdata->title, $tarea->id, $tarea->unit_id, 'tarea', null, $isActive, $tarea->pipeline->first()->name, $n->created_at->format('d-m-Y H:i'),null,null,null,$tarea->type);

                        }
                    }

                    break;


                case 'ChangeToUnit':

                    $tarea = Task::where('id', '=', $e->relation_id)->get(["id", "title", "user_id", "unit_id", "taskdata_id"])->first();//tarea donde el id = relation_id(evento)

                    if ($tarea != null) {

                        $isActive = $this->tagActive($tarea->id, 'task',$tarea->unit_id);


                        if ($e->comment_id != null) {

                            $comment = Comment::where('id', '=', $e->comment_id)->get(['comment','unit_id'])->first();

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

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

                                $getNotif[$n->id] = $this->changeUnit($units, $user, $tarea, $n->id, 'changeToUnit', $isActive, $n->created_at->format('d-m-Y H:i'));

                            }
                        }
                    }
//

                    break;

                case 'TaskStatusChange':

                    $tarea = Task::where('id', '=', $e->relation_id)->get(["id", "title", "user_id", "unit_id", "taskdata_id"])->first();//tarea donde el id = relation_id(evento)

                    if ($tarea != null) {


                        $isActive = $this->tagActive($tarea->id, 'task',$tarea->unit_id);

                        //es tarea con titulo y sin comentario

                        if ($tarea->title) {
                            $getNotif[$n->id] = $this->arrayNotification($n->id,$user, null, $tarea->title, $tarea->id, $tarea->unit_id, 'statustask', $e->content, $isActive, null, $n->created_at->format('d-m-Y H:i'),null,null,null,null);

                        } else {
                            //es tarea sin titulo y sin comentario
                            $taskdata_title = Taskdata::where('id', $tarea->taskdata_id)->value('title');

                            $getNotif[$n->id] = $this->arrayNotification($n->id,$user, null, $taskdata_title, $tarea->id, $tarea->unit_id, 'statustask', $e->content, $isActive, null, $n->created_at->format('d-m-Y H:i'),null,null,null,null);

                        }
                    }

                    break;

                case 'SubtaskStatusChange':


                    $subtarea = Subtask::where('id', '=', $e->relation_id)->get(["id", "title", "user_id", 'task_id'])->first();//tarea donde el id = relation_id(evento)

                    if ($subtarea != null) {

                        $isActive = $this->tagActive($subtarea->id, 'subtask',null);

                        //es tarea con titulo y sin comentario

                        if ($subtarea->title) {
                            $getNotif[$n->id] = $this->arrayNotification($n->id,$user, null, $subtarea->title, $subtarea->id, null, 'statuSubtask', $e->content, $isActive, null, $n->created_at->format('d-m-Y H:i'),null,null,null,null);

                        }
                    }


                    break;

                case 'UpdateTask':

                    $tarea = Task::where('id', '=', $e->relation_id)->get(["id", "title", "user_id", "unit_id", "taskdata_id"])->first();//tarea donde el id = relation_id(evento)

                    if ($tarea != null) {
                        $isActive = $this->tagActive($tarea->id, 'task',$tarea->unit_id);

                        //es uptarea con titulo y sin comentario
                        if ($tarea->title) {

                            $getNotif[$n->id] = $this->arrayNotification($n->id,$user, null, $tarea->title, $tarea->id, $tarea->unit_id, 'upTask', null, $isActive, null, $n->created_at->format('d-m-Y H:i'),null,null,null,null);

                        } else {
                            //es uptarea sin titulo y sin comentario
                            $taskdata_title = Taskdata::where('id', $tarea->taskdata_id)->value('title');

                            $getNotif[$n->id] = $this->arrayNotification($n->id,$user, null, $taskdata_title, $tarea->id, $tarea->unit_id, 'upTask', null, $isActive, null, $n->created_at->format('d-m-Y H:i'),null,null,null,null);

                        }
                    }


                    break;


                case 'App\Subtask': //es un comentario en subtarea

                    $subtarea = Subtask::where('id', '=', $e->relation_id)->get(["id", "title", "user_id"])->first();//tarea donde el id = relation_id(evento)

                    if ($subtarea != null) {
                        $isActive = $this->tagActive($subtarea->id, 'subtask',null);

                        if ($e->comment_id !== null && $subtarea->title) {

                            $comment = Comment::where('id', '=', $e->comment_id)->get(['comment','unit_id'])->first();

                            $getNotif[$n->id] = $this->arrayNotification($n->id,$user, $comment->comment, $subtarea->title, $subtarea->id, $comment->unit_id, 'subtarea', null, $isActive, null, $n->created_at->format('d-m-Y H:i'),$comment->unit->name,null,null,null);

                        } else {           //es subtarea sin comentario
                            $getNotif[$n->id] = $this->arrayNotification($n->id,$user, null, null, $subtarea->id, null, 'subtarea', null, $isActive, null, $n->created_at->format('d-m-Y H:i'),null,null,null,null);

                        }
                    }

                    break;


                case 'Subtask': //se crea subtarea

                    $subtarea = Subtask::where('id', '=', $e->relation_id)->get(["id", "title", "user_id","assigned_id"])->first();//tarea donde el id = relation_id(evento)

                    if ($subtarea != null) {

                        $isActive = $this->tagActive($subtarea->id, 'subtask',null);


                        if ($subtarea->title) {

                            $getNotif[$n->id] = $this->arrayNotification($n->id,$user, null, $subtarea->title, $subtarea->id, null, 'subtarea', null, $isActive, null, $n->created_at->format('d-m-Y H:i'),null,null,null,null); //subtarea  con titulo

                        }
                    }


                    break;

                case 'UpdateSubtask':

                    $subtarea = Subtask::where('id', '=', $e->relation_id)->get(["id", "title", "user_id"])->first();// id = relation_id(evento)

                    if ($subtarea != null) {

                        $isActive = $this->tagActive($subtarea->id, 'subtask',null);


                        if ($subtarea->title) {

                            $getNotif[$n->id] = $this->arrayNotification($n->id,$user, null, $subtarea->title, $subtarea->id, null, 'upSubtarea', null, $isActive, null, $n->created_at->format('d-m-Y H:i'),null,null,null,null);


                        }
                    }

                    break;


                case 'AttachTask':


                    $tarea = Task::where('id', '=', $e->relation_id)->get(["id", "title", "user_id", "unit_id", "taskdata_id"])->first();

                    if ($tarea != null) {
                        $isActive = $this->tagActive($tarea->id, 'task',$tarea->unit_id);

                        if ($tarea->title) {

                            $getNotif[$n->id] = $this->arrayNotification($n->id,$user, null, $tarea->title, $tarea->id, $tarea->unit_id, 'attach', null, $isActive, null, $n->created_at->format('d-m-Y H:i'),null,$e->count,null,null);

                        } else {

                            //es tarea sin titulo y sin comentario
                            $taskdata_title = Taskdata::where('id', $tarea->taskdata_id)->value('title');

                            $getNotif[$n->id] = $this->arrayNotification($n->id,$user, null, $taskdata_title, $tarea->id, $tarea->unit_id, 'attach', null, $isActive, null, $n->created_at->format('d-m-Y H:i'),null,$e->count,null,null);

                        }
                    }

                    break;

                case 'AttachSubtask':

                    $subtarea = Subtask::where('id', '=', $e->relation_id)->get(["id", "title", "user_id"])->first();//tarea donde el id = relation_id(evento)

                    if ($subtarea != null) {

                        $isActive = $this->tagActive($subtarea->id, 'subtask',null);

                        if ($subtarea->title) {

                            $getNotif[$n->id] = $this->arrayNotification($n->id,$user, null, $subtarea->title, $subtarea->id, null, 'attach', null, $isActive, null, $n->created_at->format('d-m-Y H:i'),null,$e->count,null,null);

                        }
                    }

                    break;


                case 'TaskInactive':

                    $tarea = Task::where('id',$e->relation_id)->get(['id','title','user_id','unit_id'])->first();

                    $isActive = $this->tagActive($tarea->id, 'task',$tarea->unit_id);

                    if($tarea != null){

                        $getNotif[$n->id] = $this->arrayNotification($n->id,null,null,$tarea->title,$tarea->id,$tarea->unit_id,'Inactive',null,$isActive,null,$n->created_at->format('d-m-Y H:i'),null,null,null,null);

                    }

                    break;
            }

            //Notificaciones para usuarios etiquetados

            switch ($tipoTarea) {

                case'Tasktag':

                    $getNotif = $this->getTagsNotification($e->relation_id, $user, $n, $getNotif, null);

                    break;

                case 'unTasktag':

                    $getNotif = $this->getTagsNotification($e->relation_id, $user, $n, $getNotif, null);

                    break;

                case 'InfoTaskTag':


                    if($n->array_users!= null){

                        $getNotif = $this->getTagsNotification($e->relation_id, $user, $n, $getNotif, null);//cuando es infoTastag se guarda en e->comemt el id del etiquetado


                    }else {

                        $userTag = User::where('id', '=', $e->content)->value('name');//cuando es infoTastag se guarda en e->content el id del etiquetado
                        $getNotif = $this->getTagsNotification($e->relation_id, $user, $n, $getNotif, $userTag);//cuando es infoTastag se guarda en e->comemt el id del etiquetado

                    }
                    break;

                case 'InfoUntag':

                    if($n->array_users!= null){

                        $getNotif = $this->getTagsNotification($e->relation_id, $user, $n, $getNotif, null);//cuando es infoTastag se guarda en e->comemt el id del etiquetado

                    }else {

                        $userTag = User::where('id', '=', $e->content)->value('name');//cuando es infoUntag se guarda en e->content el id del etiquetado
                        $getNotif = $this->getTagsNotification($e->relation_id, $user, $n, $getNotif, $userTag);
                    }
                    break;
            }

        }//fin de for

        return $getNotif;

    }


    /**
     * @param $id
     * @param $user
     * @param $n
     * @param $getNotif
     * @return devuelve un arreglo con las notificaciones del usuario etiquetado
     */
    private function getTagsNotification($id, $user, $n, $getNotif,$user_tag)
    {

        $etiqueta = Tasktag::where('id','=',$id)->get(['type','relation_id','unit_id','active'])->first();//trae la etiqueta donde el id = relation_id(evento)

        switch ($n->type) {

            case 'Tasktag':


                $type = $etiqueta->type;

                switch ($type) {

                    case 'task':

                        $tarea = Task::where('id','=',$etiqueta->relation_id)->get(["id", "title", "user_id","taskdata_id"])->first();//tarea donde el id = relation_id(evento)

                        if( $tarea != null ) {

                            if ($tarea->title) {

                                $getNotif[$n->id] = $this->arrayNotification($n->id,$user, null, $tarea->title, $tarea->id, $etiqueta->unit_id, 'tasktag', null, $etiqueta->active, null, $n->created_at->format('d-m-Y H:i'),null,null,null,null);

                            } else {

                                $taskdata_title=Taskdata::where('id',$tarea->taskdata_id)->value('title');

                                $getNotif[$n->id] = $this->arrayNotification($n->id,$user, null, $taskdata_title, $tarea->id, $etiqueta->unit_id, 'tasktag', null, $etiqueta->active, null, $n->created_at->format('d-m-Y H:i'),null,null,null,null);

                            }
                        }
                        break;

                    case 'subtask':

                        $subtarea = Subtask::where('id','=',$etiqueta->relation_id)->get(["id", "title", "user_id"])->first();//tarea donde el id = relation_id(evento)
                        if( $subtarea != null ) {

                            if ($subtarea->title) {

                                $getNotif[$n->id] = $this->arrayNotification($n->id,$user, null, $subtarea->title, $subtarea->id, null, 'subtag', null, $etiqueta->active, null, $n->created_at->format('d-m-Y H:i'),null,null,null,null);

                            }
                        }

                        break;
                }

                break;

            case "unTasktag" :

                $type = $etiqueta->type;

                switch ($type) {

                    case 'task':

                        $tarea = Task::where('id','=',$etiqueta->relation_id)->get(["id", "title", "user_id",'taskdata_id'])->first();//tarea donde el id = relation_id(evento)

                        if( $tarea != null ) {

                            if ($tarea->title) {

                                $getNotif[$n->id] = $this->arrayNotification($n->id,$user, null, $tarea->title, $tarea->id, $etiqueta->unit_id, 'untasktag', null, null, null, $n->created_at->format('d-m-Y H:i'),null,null,null,null);

                            } else {
                                $taskdata_title = Taskdata::where('id',$tarea->taskdata_id)->value('title');

                                $getNotif[$n->id] = $this->arrayNotification($n->id,$user, null, $taskdata_title, $tarea->id, $etiqueta->unit_id, 'untasktag', null, null, null, $n->created_at->format('d-m-Y H:i'),null,null,null,null);
                            }
                        }

                        break;

                    case 'subtask':

                        $subtarea = Subtask::where('id','=',$etiqueta->relation_id)->get(["id", "title", "user_id"])->first();//tarea donde el id = relation_id(evento)

                        if ($subtarea->title) {

                            $getNotif[$n->id] = $this->arrayNotification($n->id,$user, null, $subtarea->title, $subtarea->id, null, 'unsubtag', null, null,null,$n->created_at->format('d-m-Y H:i'),null,null,null,null);
                        }

                        break;
                }
                break;

            case "InfoTaskTag":

                $type = $etiqueta->type;



                switch ($type) {


                    case 'task':

                        $tarea = Task::where('id', '=', $etiqueta->relation_id)->get(["id", "title", "user_id", "unit_id", "taskdata_id"])->first();//tarea donde el id = relation_id(evento)

                        if ($tarea != null) {


                            $namesUsers =$this->namesUsers($n->array_users,$etiqueta->relation_id,$type,$etiqueta->unit_id);


                            $isActive = $this->tagActive($tarea->id, 'task',$tarea->unit_id);

                            if ($tarea->title) {

                                if ($n->array_users) {

                                    $getNotif[$n->id] = $this->arrayNotification($n->id,$namesUsers, null, $tarea->title, $etiqueta->relation_id, $etiqueta->unit_id, 'infotasktag', null, $isActive, null, $n->created_at->format('d-m-Y H:i'), null, null, $n->array_users,null);

                                } else {

                                    $getNotif[$n->id] = $this->arrayNotification($n->id,$user_tag, null, $tarea->title,$etiqueta->relation_id, $etiqueta->unit_id, 'infotasktag', null, $isActive, null, $n->created_at->format('d-m-Y H:i'), null, null, $n->array_users,null);

                                }

                            } else {

                                if ($n->array_users) {

                                    $taskdata_title = Taskdata::where('id', $tarea->taskdata_id)->value('title');

                                    $getNotif[$n->id] = $this->arrayNotification($n->id,$namesUsers, null, $taskdata_title,$etiqueta->relation_id, $etiqueta->unit_id, 'infotasktag', null, $isActive, null, $n->created_at->format('d-m-Y H:i'), null, null, $n->array_users,null);

                                } else {

                                    $taskdata_title = Taskdata::where('id', $tarea->taskdata_id)->value('title');

                                    $getNotif[$n->id] = $this->arrayNotification($n->id,$user_tag, null, $taskdata_title, $etiqueta->relation_id, $etiqueta->unit_id, 'infotasktag', null, $isActive, null, $n->created_at->format('d-m-Y H:i'), null, null, $n->array_users,null);

                                }
                            }
                        }

                        break;

                    case 'subtask':

                        $subtarea = Subtask::where('id', '=', $etiqueta->relation_id)->get(["id", "title", "user_id"])->first();//tarea donde el id = relation_id(evento)

                        if ($subtarea != null) {

                            $namesUsers = $this->namesUsers($n->array_users,$etiqueta->relation_id,$type,null);

                            $isActive = $this->tagActive($subtarea->id, 'subtask',null);

                            if ($subtarea->title) {

                                if ($n->array_users) {

                                    $getNotif[$n->id] = $this->arrayNotification($n->id,$namesUsers, null, $subtarea->title, $subtarea->id, null, 'infosubtag', null, $isActive, null, $n->created_at->format('d-m-Y H:i'), null, null, $n->array_users,null);
                                } else {
                                    $getNotif[$n->id] = $this->arrayNotification($n->id,$user_tag, null, $subtarea->title, $subtarea->id, null, 'infosubtag', null, $isActive, null, $n->created_at->format('d-m-Y H:i'), null, null, $n->array_users,null);
                                }

                            }
                        }
                }

                break;

            case "InfoUntag":


                $type = $etiqueta->type;

                switch ($type) {


                    case 'task':
                        $tarea = Task::where('id','=',$etiqueta->relation_id)->get(["id", "title", "user_id","taskdata_id"])->first();//trae la tarea donde id = relation_id(etiqueta)

                        if( $tarea != null ) {
                            $namesUsers =$this->namesUsers($n->array_users,$tarea->id,$type,$etiqueta->unit_id);

                            $isActive = $this->tagActive($tarea->id, 'subtask',null);

                            if ($tarea->title) {

                                if ($n->array_users) {

                                    $getNotif[$n->id] = $this->arrayNotification($n->id,$namesUsers , null, $tarea->title, $tarea->id, $etiqueta->unit_id, 'infoUntag', null, $isActive, null, $n->created_at->format('d-m-Y H:i'),null,null,$n->array_users,null);

                                }else {
                                    $getNotif[$n->id] = $this->arrayNotification($n->id,$user_tag, null, $tarea->title, $tarea->id, $etiqueta->unit_id, 'infoUntag', null, $isActive, null, $n->created_at->format('d-m-Y H:i'), null, null, $n->array_users,null);

                                }
                            } else {

                                if ($n->array_users) {

                                    $taskdata_title = Taskdata::where('id', $tarea->taskdata_id)->value('title');

                                    $getNotif[$n->id] = $this->arrayNotification($n->id,$namesUsers, null, $taskdata_title, $tarea->id, $etiqueta->unit_id, 'infoUntag', null, $isActive, null, $n->created_at->format('d-m-Y H:i'), null, null, $n->count,null);

                                }else {
                                    $taskdata_title = Taskdata::where('id', $tarea->taskdata_id)->value('title');

                                    $getNotif[$n->id] = $this->arrayNotification($n->id,$user_tag, null, $taskdata_title, $tarea->id, $etiqueta->unit_id, 'infoUntag', null, $isActive, null, $n->created_at->format('d-m-Y H:i'), null, null, $n->count,null);
                                }

                            }
                        }

                        break;


                    case 'subtask':

                        $subtarea = Subtask::where('id','=',$etiqueta->relation_id)->get(["id", "title", "user_id"])->first();//tarea donde el id = relation_id(evento)

                        if( $subtarea != null ) {
                            $namesUsers = $this->namesUsers($n->array_users,$subtarea->id,$type,null);
                            $isActive = $this->tagActive($subtarea->id, 'subtask',null);

                            if ($subtarea->title) {

                                if ($n->array_users) {
                                    $getNotif[$n->id] = $this->arrayNotification($n->id,$namesUsers, null, $subtarea->title, $subtarea->id, null, 'infoUnsubtag', null, $isActive, null, $n->created_at->format('d-m-Y H:i'), null, null, $n->count,null);

                                } else {

                                    $getNotif[$n->id] = $this->arrayNotification($n->id,$user_tag, null, $subtarea->title, $subtarea->id, null, 'infoUnsubtag', null, $isActive, null, $n->created_at->format('d-m-Y H:i'), null, null, $n->count,null);

                                }
                            }
                        }
                        break; //2 switch
                }

                break;//1 switch

        }

        return $getNotif;

    }

    /**
     * @param $user
     * @param $comment
     * @param $title
     * @param $idType
     * @param $unit
     * @param $type
     * @param $status
     * @param $active
     * @return array con los datos de los
     */
    private function arrayNotification($id,$user, $comment, $title, $idType, $unit, $type, $status, $active,$pipeline_first,$fecha,$nameUnit,$countAttach,$countNotif,$type_task)
    {

        $array = array(
            'id_notif' => $id,
            'user' => $user,
            'comment' => $comment,
            'title' => $title,
            'id_tipoNoti' => $idType,
            'tarea_unit' => $unit,
            'tipo_noti' => $type,
            'name_status' => $status,
            'tag_active' => $active,
            'first_pipeline'=>$pipeline_first,
            'notiFecha' => $fecha,
            'name_unit' => $nameUnit,
            'count_attach' => $countAttach,
            'count_notif' =>$countNotif,
            'type_task' => $type_task,

        );
        return $array;
    }


    /**
     * @param  $array ,$user,$tarea,$n,$tipo
     * comentario por cambio de unidad => envia notificación de cambio de unidad
     */
    private function changeUnit($array, $user, $tarea, $n, $tipo, $active,$fecha)
    {
        $date=$fecha;
//        $fechaNotif=date('d-m-Y h:i', strtotime( $date->toDateTimeString()));
        $notif = array(
            'user' => $user,
            'comment' => 'de unidad ' . $array[0][0] . ' a ' . $array[0][1],
            'title' => $tarea->title,
            'id_tipoNoti' => $tarea->id,
            'tarea_unit' => $tarea->unit_id,
            'tipo_noti' => $tipo,
            'id_notif' => $n,
            'tag_active' => $active,
            'notiFecha' => $fecha,
            'name_unit' => null,
            'name_status' => null,
            'first_pipeline'=>null,
        );

        return $notif;
    }

//"[41,7,38,33]"[\[,\]]
    private function namesUsers($array,$tarea_id,$type,$tarea_unit){
        $namesUsers = '';

        if ($array) {

            // $n->array_users se guarda una arreglo tipo string en la columna array_users (notifications)
            $array_users = preg_split('/[\[,\]]/', $array, null, PREG_SPLIT_DELIM_CAPTURE);

            foreach ($array_users as $id_users) {

                if ($id_users ) { //puede tener valores null

                    if($type == 'task'){

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

                            $usersTag = Tasktag::where('relation_id', $tarea_id)->where('user_id', (integer)$id_users)->where('unit_id', $tarea_unit)->where('type', $type)->first();

                            if ($usersTag) {

                                $namesUsers .= $usersTag->user->name . ', ';

                            }
                        }

                    }else{

                        $usersTag = Tasktag::where('relation_id', $tarea_id)->where('active', 1)->where('user_id',(integer)$id_users)->where('type', $type)->first();

                        if ($usersTag) {
                            $namesUsers .= $usersTag->user->name . ', ';
                        }
                    }

                }
            }
        }
        return $namesUsers;
    }

    /**
     * @param $tarea
     * @param $type
     * @return devuelve si el usuario etiquetado en la tarea o subtarea etiquetado está activo
     */
    private function tagActive( $id_type, $type,$unit_id)
    {
        $tag_active= null;
        if($unit_id!= null){

            $tag_active = Tasktag::where('relation_id', $id_type)
                ->where('type', '=', $type)
                ->where('unit_id', '=', $unit_id)
                ->where('user_id', Auth::user()->id)->latest()->first(['active']);

        }else{
            $tag_active = Tasktag::where('relation_id', $id_type)
                ->where('type', '=', $type)
                ->where('user_id', Auth::user()->id)->latest()->first(['active']);
        }



        if (count($tag_active) > 0) {                 // si hay algún tag => el usuario está etiquetado

            if ($tag_active->active == 1) {             // si esta activado es igual a 1

                return true;
            } elseif ($tag_active->active == 0) {   //si esta desactivado es igual a 0

                return false;
            }
        } else {                                        // si no hay ningún tag => no está etiquetado

            return true;
        }
    }


    /**
     * Este metodo cambia el estado en is_archived en la tabla notificación
     * post: coloca 1 en el campo is-archived de la tabla Notifications
     */
    public function notificationsArchived(Request $request)
    {

        $notification = Notifications::find($request->id);
        $notification->is_archived = 1;
        $notification->save();
        return response()->json(['success' => 'success', 200]);//mensaje que esta ok

    }


    /**
     * @post Este metodo coloca 1  en el campo  is_read de la tabla notification
     * @return eturn json con mensaje ok
     */
    public function marcarLeidos()
    {

        $notification = Notifications::where('user_to', '=', Auth::user()->id)->where('is_read', '=', '0')->where('is_archived', '=', '0')->get();

        if ($notification) {

            foreach ($notification as $n) {

                $n->is_read = 1;
                $n->save();
            }

        }

        return response()->json(['success' => 'success', 200]);//mensaje que esta ok
    }

    public function markRead(Request $request)
    {
        $notification = Notifications::find($request->id);
        $notification->is_read = 1;
        $notification->save();
        return response()->json(['success' => 'success', 200]);//mensaje que esta ok

    }

    /**
     * @param Request $request
     * pre:
     * post:
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function searchNotifications($evenlog_id)
    {
        //busco notificaciones no leídas
        $notiNoLeidas = array();


        $notification = Notifications::where('eventlogs_id', '=',$evenlog_id)
            ->where('is_read','=',0)
            ->where('is_archived','=',0)
            ->where('user_to',Auth::user()->id)
            ->orderByDesc('id')->get();

        if (count($notification) >0) //si existen notificaciones
        {
            $notiNoLeidas = $this->notificationsNotRead($notification, $notiNoLeidas);

        }

        //busco notificaciones leídas
        $notification_read = Notifications::where('eventlogs_id', '=',$evenlog_id)
            ->where('is_read','=',1)
            ->where('is_archived','=',0)
            ->where('user_to',Auth::user()->id)
            ->orderByDesc('id')->get();


        $notiLeidas = array();

        if (count($notification_read) >0) //si existen notificaciones
        {

            $notiLeidas = $this->isRead($notification_read, $notiLeidas);

        }


        $notification_arch = Notifications::where('eventlogs_id', '=', $evenlog_id)
            ->where('is_archived','=',1)
            ->where('user_to',Auth::user()->id)
            ->orderBy('id', 'desc')->get();

        $notiArchivadas = array();

        if (count($notification_arch) >0) //si existen notificaciones
        {
            $notiArchivadas = $this->isArchived($notification_arch, $notiArchivadas);

        }

        return  compact(['notiNoLeidas', 'notiLeidas', 'notiArchivadas']);
    }

    public function  attachment(){

    }


    /**Busca las notificaciones que contengan la palabra ingresada por el usuario
     * @param Request $request
     *  "string" => "subtarea"
    "_token" => "dI120JRaVbMG3gAWDsO8QUkRIwsbyi0WYQdlOLgk"
    "type" => "NoLeidas"
     */

    public  function search(Request $request)
    {

        $type_notification ='';
        $array_match_notifications = array();
        $notif_Leidasrender= array();


        switch ($request->type){


            case 'NoLeidas':

                $notification = Notifications::where('user_to', '=', Auth::user()->id)
                    ->where('is_read', '=', 0)
                    ->where('is_archived', '=', 0)
                    ->orderBy('created_at', 'DESC')
                    ->limit(1500)
                    ->get();

                $notif_NoLeidas = array();
                $notif_noLeidasrender = array();


                if (count($notification) >0) //si existen notificaciones
                {
                    $notif_NoLeidas = $this->notificationsNotRead($notification, $notif_NoLeidas);

                    if($notif_NoLeidas){

                        $array_match_notifications= $this->matchNotification($request->string,$notif_NoLeidas);
                    }

                    $notif_noLeidasrender = $notification;
                }
                $type_notification ='no leídas';


            break;

            case 'Leidas':

                $notification = Notifications::where('user_to', '=',Auth::user()->id)
                    ->where('is_read','=',1)
                    ->where('is_archived','=',0)
                    ->orderBy('created_at', 'DESC')
                    ->limit(1500)
                    ->get();

                $notif_Leidas = array();
                $notif_Leidasrender =array();

                if (count($notification) >0) //si existen notificaciones
                {

                    $notif_Leidas = $this->isRead($notification, $notif_Leidas);

                    $array_match_notifications= $this->matchNotification($request->string,$notif_Leidas);
                    $notif_Leidasrender = $notification;
                    // fin paginación

                }

                $type_notification ='leídas';

                break;

            case 'Archivadas':

                $notification = Notifications::where('user_to', '=', Auth::user()->id)
                    ->where('is_archived','=',1)
                    ->orderBy('created_at', 'DESC')
                    ->limit(1500)
                    ->get();

                $notif_Archivadasrender =array();
                $notif_Archivadas= array();

                if ($notification) //si existen notificaciones
                {

                    $notif_Archivadas= $this->isArchived($notification, $notif_Archivadas);
                    $array_match_notifications= $this->matchNotification($request->string,$notif_Archivadas);
                    $notif_Archivadasrender = $notification;

                }

                $type_notification ='archivadas';
            break;

            case 'Inactive':
                $notification = Notifications::where('user_to', '=', Auth::user()->id)
                    ->where('is_read','=',0)
                    ->where('is_archived','=',0)
                    ->where('type','TaskInactive')
                    ->orderBy('created_at', 'DESC')
                    ->limit(1500)
                    ->get();


                if ($notification) //si existen notificaciones
                {

                    $notif_NoLeidas = array();
                    $notif_noLeidasrender = array();

                    $notif_NoLeidas = $this->notificationsNotRead($notification, $notif_NoLeidas);
                    if($notif_NoLeidas){

                        $array_match_notifications= $this->matchNotification($request->string,$notif_NoLeidas);
                    }

                    $notif_noLeidasrender = $notification;
                }
                $type_notification ='no leídas';



        }

        $args = array(
            'notificaciones' => $array_match_notifications,
            'count_notif_noLeidas' => $this->countNotificationNotRead(),
            'countInactiveNoRead' => $this->countNotificationNotReadInactive(),
            'tipo' => $type_notification,
        );

        return view('notification.search', $args);



    }

    /**
     * Realiza un preg_match del $string se ingreso ,en las notificaciones del usuario
     * @param $request
     * @param $array_Notif
     **/
    private function matchNotification($string,$array_Notif){


//        $string = $request->string;
        $output_array = array();
        $notif_u = array();


        foreach ($array_Notif as $n){


            if($string == 'subtarea' ){


                if($n['tipo_noti'] == $string || $n['tipo_noti'] =='upSubtarea' || $n['tipo_noti'] =='subtag'||$n['tipo_noti'] =='unsubtag' || $n['tipo_noti'] == 'statuSubtask' ||$n['tipo_noti'] == 'infosubtag' ||$n['tipo_noti'] == 'infoUnsubtag'){
                    array_push($notif_u,$n);

                }
            }


            if( $string == 'etiquetados' || $string== 'etiquetado'){
                if(  $n['tipo_noti'] =='subtag'||$n['tipo_noti'] =='unsubtag' ||$n['tipo_noti'] == 'infosubtag' ||$n['tipo_noti'] == 'infoUnsubtag' ||$n['tipo_noti']== 'tasktag' ||$n['tipo_noti']== 'untasktag' ||$n['tipo_noti']== 'infotasktag'||$n['tipo_noti']== 'infoUntag'  ){
                    array_push($notif_u,$n);

                }
            }

            preg_match("/".$string."/", $n['user'], $output_array);

            if(count($output_array)>0) {
                array_push($notif_u,$n);
            }

            preg_match("/".$string."/", $n[ 'comment'], $output_array);

            if(count($output_array)>0) {
                array_push($notif_u,$n);
            }

            preg_match("/".$string."/", $n[ 'title'], $output_array);
            if(count($output_array)>0) {
                array_push($notif_u,$n);
            }

            preg_match("/".$string."/", $n[ 'notiFecha'], $output_array);
            if(count($output_array)>0) {
                array_push($notif_u,$n);
            }


            preg_match("/" . $string . "/", $n['name_unit'], $output_array);
            if (count($output_array) > 0) {
                array_push($notif_u, $n);
            }


            preg_match("/".$string."/", $n[ 'name_status'], $output_array);
            if(count($output_array)>0) {
                array_push($notif_u,$n);
            }

            preg_match("/".$string."/", $n['first_pipeline'], $output_array);
            if(count($output_array)>0) {
                array_push($notif_u,$n);
            }

        }

        /*
         Realiza un reguex al $string y busca por cada palabra
         */

        if(count($string)>2) { //devuelve 2 cuando busca una palabra

            $array_regex = preg_split("/\s/", $string);

            $query = "";

            $stopwords = ['yo', 'vos', 'tu', 'usted', 'Yo', 'me', ' mi', ' conmigo', 'Nosotros', 'nos', 'nosotras', 'Tú', 'te', 'ti', 'contigo', 'usted', 'vos', 'Vosotros', 'vosotras', 'os', 'ustedes', 'Él', 'lo', 'le', 'se', 'sí', 'consigo', 'ella', 'la', 'ello', ' lo', 'Ellos', 'ellas', 'los', 'las', 'les', 'se', 'sí', 'consigo', 'el', 'la', 'lo', 'los', 'la', 'las', 'un', 'una', 'uno', 'unos', 'al', 'del', 'día', 'ir', 'es', 'y', 'a', 'o', 'u', 'te'];


            foreach ($array_regex as $re) {

                $str = $re;

                //si $str está en $stopword entonces no busca el query
                foreach ($stopwords as $w) {

                    if ($str == $w) {

                        $str = null;
                    }
                }

                if ($str != null) {

                    foreach ($array_Notif as $n) {

                        if($n['tipo_noti'] == $string || $n['tipo_noti'] =='upSubtarea' || $n['tipo_noti'] =='subtag'||$n['tipo_noti'] =='unsubtag' || $n['tipo_noti'] == 'statuSubtask' ||$n['tipo_noti'] == 'infosubtag' ||$n['tipo_noti'] == 'infoUnsubtag'){

                            if($n['id_tipoNoti'] == $str){
                                array_push($notif_u,$n);

                            }
                        }

                        preg_match("/".$str."/", $n['user'], $output_array);
                        if(count($output_array)>0) {
                            array_push($notif_u,$n);
                        }

                        preg_match("/".$str."/", $n[ 'comment'], $output_array);
                        if(count($output_array)>0) {
                            array_push($notif_u,$n);
                        }

                        preg_match("/".$str."/", $n[ 'title'], $output_array);
                        if(count($output_array)>0) {
                            array_push($notif_u,$n);
                        }

                        preg_match("/".$str."/", $n[ 'notiFecha'], $output_array);
                        if(count($output_array)>0) {
                            array_push($notif_u,$n);
                        }


                        preg_match("/" . $str . "/", $n['name_unit'], $output_array);
                        if (count($output_array) > 0) {
                            array_push($notif_u, $n);
                        }


                        preg_match("/".$str."/", $n[ 'name_status'], $output_array);
                        if(count($output_array)>0) {
                            array_push($notif_u,$n);
                        }

                        preg_match("/".$str."/", $n['first_pipeline'], $output_array);
                        if(count($output_array)>0) {
                            array_push($notif_u,$n);
                        }
                    }

                }
            }

        }

        $array_match_notif = $this->unique_multidim_array($notif_u,'id_notif');



        return $array_match_notif;
    }



    /**
     * Create multidimensional array unique for any single key index.
     * @param $array
     * @param $key
     * @return array
     */
    private function unique_multidim_array($array, $key) {
        $temp_array = array();
        $i = 0;
        $key_array = array();

        foreach($array as $val) {

            if (!in_array($val[$key], $key_array)) {
                $key_array[$i] = $val[$key];
                $temp_array[$i] = $val;
            }
            $i++;
        }
        return $temp_array;
    }


    /**
     * @param Request $request
     * @pre $type_notif es el tipo de eleccion del select
     * @post devuelve a la vista un arreglo con los arreglos encontrados de acuerda a la elección del select
     */
    public function select(Request $request)
    {
        $notificaciones = array();
        $notifSelect = array();

        if ($request->all()) {
            $typeSelect ='';


            switch ($request->type_notif) {

                case 'Tareas' :


                    $notificaciones = $this->queryNotifications((integer)$request->isRead, ['Task'], $request->type);
                    $typeSelect = 'Task';

                    break;

                case 'Subtareas' :

                    $notificaciones = $this->queryNotifications((integer)$request->isRead, ['Subtask'], $request->type);

                    $typeSelect ='Subtask';

                    break;

                case 'Comentarios':

                    $notificaciones = $this->queryNotifications((integer)$request->isRead, ['App\\Task','App\\Subtask'], $request->type);

                    $typeSelect ='Comentarios';

                    break;

                case 'Etiquetas':

                    $notificaciones = $this->queryNotifications((integer)$request->isRead, ['TaskTag'], $request->type);

                    $typeSelect = 'TaskTag';

                    break;

                case 'Info de etiquetados':


                    $notificaciones = $this->queryNotifications((integer)$request->isRead, ['InfoTaskTag','unTasktag','InfoUntag'], $request->type);

                    $typeSelect= 'infoTag';

                    break;

                case 'Cambios de estado':

                    $notificaciones = $this->queryNotifications((integer)$request->isRead, ['TaskStatusChange','SubtaskStatusChange'], $request->type);
//                    $notificaciones = $this->saveArrayNotifications($this->queryNotifications((integer)$request->isRead, 'SubtaskStatusChange', $request->type), $notificaciones);
                    $typeSelect = 'status';


                    break;

                case 'Cambios de unidad':

                    $notificaciones = $this->queryNotifications((integer)$request->isRead, ['ChangeToUnit'], $request->type);

                    $typeSelect = 'ChangeToUnit';

                    break;

                case 'Archivos':


                    $notificaciones = $this->queryNotifications((integer)$request->isRead, ['AttachTask','AttachSubtask'],$request->type);


                    $typeSelect = 'attach';

                    break;


                case 'Inactividad':

                    $notificaciones =  $this->queryNotifications((integer)$request->isRead,['TaskInactive'], $request->type);

                    $typeSelect = 'Inactividad';

                break;

            }


            if ($notificaciones) {

                foreach ($notificaciones as $n) {

                    $notifSelect = $this->getArrayNotifications($n, $notifSelect);
                }
            }

        }

        return $this->redirectToView($notifSelect,$request->type, $typeSelect);



    }

    /**
     * función privada usada en el select
     * @pre recibe por parametro el arreglo de notificaciones del tipo del seleccionado
     * @post retorna la vista de acuerdo al type (notificación) que se pasa por parametro
     * @param $notificaciones
     * @param $type
     * @param $typeSelect
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    private  function  redirectToView($notificaciones,$type,$typeSelect){



        if($type == 'noLeido'){

            $args = array(
                'notificaciones_noLeidas' => $notificaciones,
                'count_notif_noLeidas' => $this->countNotificationNotRead(),
                'countInactiveNoRead' => $this->countNotificationNotReadInactive(),
                'notif_noLeidasRender' => 'select',
                'typeSelect' => $typeSelect,
            );


            return view('notification.notifications', $args) ;

        }elseif ($type == 'leidas'){

            $args = array(
                'notificaciones_leidas' => $notificaciones,
                'count_notif_noLeidas' => $this->countNotificationNotRead(),
                'countInactiveNoRead' => $this->countNotificationNotReadInactive(),
                'notif_leidasRender' => 'select',
            );

            return  view('notification.notifications_read', $args);
        }
        elseif ($type == 'archivadas'){

            $args = array(
                'notificaciones_archivadas' => $notificaciones  ,
                'count_notif_noLeidas' => $this->countNotificationNotRead(),
                'countInactiveNoRead' => $this->countNotificationNotReadInactive(),
                'notif_archivadasRender' => 'select',

            );
            return view('notification.notifications_arch', $args);
        }

    }


    /**
     * función privada usada en el select guarda en un arreglo (que se envía a la vista) las notificaciones de diferentes consultas realizadas en la función 'queryNotifications'
     * @pre recibe por parametro arreglo de notificaciones ($arrayNotif) y el arreglo donde guarda las notificaciones($notificaciones) que serán enviadas a la vista
     * @param $arrayNotif
     * @param $notificaciones
     * @return el arreglo ($notificaciones)  con las nuevas notificaciones agregadas
     */
//    private  function  saveArrayNotifications($arrayNotif,$notificaciones){
//
//        if(count($arrayNotif) >0) { //si encontro notificaciones
//
//            foreach ($arrayNotif as $aux) { //guarda en el arreglo principal '$notificaciones' las notificaciones encontradas
//
//                array_push($notificaciones, $aux);
//            }
//        }
//
//        return $notificaciones;
//    }


    /**
     * función privada usada en el select
     * @param $is_read
     * @param $type
     * * @pre recibe por parametro datos que servirán para realizar el query de las notificaciones de la selección elegida
     * si el type es != de archivadas => es una notificación leída o no leída ,ese dato le dice ($is_read )
     * si es == archivadas => es  notificaciones  archivadas
     * @post retorna una collection de las notificaciones encontradas
     * @return \Illuminate\Support\Collection
     */
    private function queryNotifications($is_read,$type,$typeNoti){


        $notificationes = array();

        if($typeNoti  != 'archivadas') {

            $notification = Notifications::where('user_to', '=', Auth::user()->id)
                ->where('is_read', '=', $is_read)
                ->where('is_archived', '=', 0)
                ->whereIn('type', $type)
                ->orderBy('created_at', 'DESC')->get();



            foreach ($notification as $n) {
                array_push($notificationes, $n);


            }

            return $notificationes;


        }elseif ($typeNoti  == 'archivadas'){

            $notification = Notifications::where('user_to', '=', Auth::user()->id)
                ->where('is_archived','=',1)
                ->where('type', '=', $type)
                ->orderBy('created_at', 'DESC')->get();

            foreach ($notification as $n) {

                array_push($notificationes, $n);

            }
            return $notificationes;
        }
    }

    /**
     * @param Request $request
     * @pre esta función cambia a leídas las notificaciones del usuario de acuerdo a la selección
     * @post cambia a leida las notificaciones y retorna 'success, 200' y recarga la página
     */
    public function setToReadSelect(Request $request){

       if($request->all()){

            if($request->type != 'Comentarios' || $request->type != 'infoTag' || $request->type != 'status' || $request->type != 'attach'){

                $notification = Notifications::where('user_to', '=', Auth::user()->id)
                    ->where('is_read', '=', 0)
                    ->where('is_archived', '=', 0)
                    ->where('type', '=',$request->type)
                    ->orderBy('created_at', 'DESC')->get();

                $this->updateNotifications($notification);

            }

            if ($request->type == 'Comentarios' || $request->type =='infoTag'|| $request->type =='status' || $request->type =='attach') {


                switch ($request->type) {

                    case 'Comentarios' :

                        $notification = Notifications::where('user_to', '=', Auth::user()->id)
                            ->where('is_read', '=', 0)
                            ->where('is_archived', '=', 0)
                            ->whereIn('type', ['App\\Task','App\\Subtask'])
                            ->orderBy('created_at', 'DESC')->get();



                        $this->updateNotifications($notification);

                        break;

                    case 'infoTag' :

                        $notification = Notifications::where('user_to', '=', Auth::user()->id)
                            ->where('is_read', '=', 0)
                            ->where('is_archived', '=', 0)
                            ->whereIn('type', ['InfoTaskTag','unTasktag','InfoUntag'])
                            ->orderBy('created_at', 'DESC')->get();


                        $this->updateNotifications($notification);

                        break;

                    case 'status' :

                        $notification = Notifications::where('user_to', '=', Auth::user()->id)
                            ->where('is_read', '=', 0)
                            ->where('is_archived', '=', 0)
                            ->whereIn('type', ['TaskStatusChange','SubtaskStatusChange'])
                            ->orderBy('created_at', 'DESC')->get();
                        $this->updateNotifications($notification);

                        break;

                    case 'attach' :

                        $notification = Notifications::where('user_to', '=', Auth::user()->id)
                            ->where('is_read', '=', 0)
                            ->where('is_archived', '=', 0)
                            ->whereIn('type', ['AttachTask','AttachSubtask'])
                            ->orderBy('created_at', 'DESC')->get();

                        $this->updateNotifications($notification);
                        break;

                }
            }
       }

        return response()->json(['success' => 'success', 200]);//mensaje que esta ok

    }


    /**
     * función privada  es llamada en la función 'setToReadSelect'
     * @param $notifications
     * @pre recibe por parametro las notificaciones que se cambiarán a leídas
     *
     */
    private function updateNotifications($notifications){

        if($notifications){

            foreach ($notifications as $n){

                $n->is_read = 1;
                $n->save();
            }
        }
    }



    public function getNotificationsInactivas(){


        $notification = Notifications::where('user_to', '=', Auth::user()->id)
            ->where('is_read','=',0)
            ->where('is_archived','=',0)
            ->where('type','TaskInactive')
            ->orderBy('created_at', 'DESC')->paginate(30);


        $notif_NoLeidas = array();
        $notif_noLeidasrender =array();

        if ($notification) //si existen notificaciones
        {
            $notif_NoLeidas = $this->notificationsNotRead($notification, $notif_NoLeidas);

            $notif_noLeidasrender = $notification;
        }

        $args = array(
            'notificaciones_noLeidas' => $notif_NoLeidas,
            'count_notif_noLeidas' => $this->countNotificationNotRead(),
            'countInactiveNoRead' => $this->countNotificationNotReadInactive(),
            'notif_noLeidasRender' => $notif_noLeidasrender,

        );

        return view('notification.notifications_inactive', $args);
    }






}//fin class


