<?php
/**
 * Created by PhpStorm.
 * User: UNTREF
 * Date: 26/1/2018
 * Time: 1:14 PM
 */

namespace App\Http\Controllers;
use App\Attachment;
use App\Eventlog;
use App\Notifications;
use App\Pipeline;
use App\Profile;
use App\Subtask;
use App\Task;
use App\Status;
use App\Taskdata;
use App\Tasktag;
use App\Unit;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Laravelista\Comments\Comments\Comment;
use App\Http\Controllers\NotificationsController;
use Symfony\Component\VarDumper\Dumper\DataDumperInterface;


class SearchController extends  Controller {



    private $array_comment = array();
    private $array_taskAttachs = array();
    private $array_subtaskAttachs = array();
    private $array_task = array();
    private $array_subtask =array();

    public function __construct()
    {
        parent::__construct();

        $this->middleware('auth');




    }

    /**
     * @param Request $request
     * busca en el string buscado en las varias tablas
     * @return
     */
    public function search(Request $request)
    {


        $array_unique_attachA = null;
        $array_unique_attachS = null;
        $array_unique_comemt = null;
        $array_unique_tasks = null;
        $array_unique_subtasks = null;
        $string = null;


        if((!empty($request->string))||(!empty($request->line_prod_filter)) ||(!empty($request->select_status_filter)) ||(!empty($request->select_unit_filter)) ||(!empty($request->user_auth_filter)) ||(!empty($request->user_comment_filter)) ||(!empty($request->fecha_cre_filter)) ||(!empty($request->fecha_end_filter)) ){

       //   ||(!empty($request->fecha_cre_filter)) ||(!empty($request->fecha_end_filter)) 

        $string = $request->string;

        $user = Auth::user();


        $arraySearch =array();

        /*
         Busca con cotas las palabras del string
         */
        $array_canViewTasks =$this->searchTaskComentAttach($user,$string,$request);

        $this->saveArrays($array_canViewTasks); //Guarda en los arreglos globales

        $array_canViewSubtasks =$this->searchSubtaskComemtAttach($user,$string,$request);

        $this->saveArrays($array_canViewSubtasks); //Guarda en los arreglos globales

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

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

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

            $query = "";

            $array1 = array();
            $array2 = array();

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

                    $array1 = $this->searchTaskComentAttach($user, $str,$request);
                    $this->saveArrays($array1); //Guarda en los arreglos globales

                    $array2 = $this->searchSubtaskComemtAttach($user, $str,$request);
                    $this->saveArrays($array2); //Guarda en los arreglos globales
                }
            }
        }


        // unifica los arreglos por id por si están repetidos en cada caso

        $array_unique_tasks = $this->unique_multidim_array($this->array_task,'id');
        $array_unique_subtasks = $this->unique_multidim_array($this->array_subtask, 'id');
        $array_unique_attachA = $this->unique_multidim_array($this->array_taskAttachs, 'id');
        $array_unique_attachS=$this->unique_multidim_array($this->array_subtaskAttachs, 'id');
        $array_unique_comemt = $this->unique_multidim_array($this->array_comment, 'content_id');
//        $details = $this->unique_multidim_array($this->array_task,'id');
//        dd($details,$array_unique_tasks);

        }

        $pipelines = Pipeline::orderBy("name")->get(); 


        $arraySearch = array(
            'attach_task' =>$array_unique_attachA,
            'attach_subtask' => $array_unique_attachS,
            'array_comment' =>$array_unique_comemt,
            'task' =>$array_unique_tasks,
            'subtask' =>$array_unique_subtasks,
            'searched'=> $string,
            'pipelines' => $pipelines,
            'status'   => Status::where('status_type','task')->orderBy("name")->get(), 
            'users'   => User::where('active','1')->orderBy("name")->get(), 
            'units'    => Unit::orderBy("name")->get(),
            'line_prod_filter' => !empty($request->line_prod_filter)?$request->line_prod_filter:null, 
            'select_status_filter' => !empty($request->select_status_filter)?explode(",",$request->select_status_filter):null, 
            'select_unit_filter' => !empty($request->select_unit_filter)?explode(",",$request->select_unit_filter):null,
            'user_auth_filter' => !empty($request->user_auth_filter)?$request->user_auth_filter:null,   
            'user_comment_filter' => !empty($request->user_comment_filter)?$request->user_comment_filter:null,
            'fecha_cre_filter' => !empty($request->fecha_cre_filter)?$request->fecha_cre_filter:"",
            'fecha_end_filter' => !empty($request->fecha_end_filter)?$request->fecha_end_filter:"",   
        );
//        dd( $arraySearch);
        return view('search',$arraySearch);

    }

    /***
     * @pre     Busca en las tareas , comentarios, nombres de archivos relacionados al query pasado por parametro,
     *          si el usuario tiene permisos
     * @param $user
     * @param $query
     * @return array de ubicaciones de las palabras encontradas
     */

    private function  searchTaskComentAttach($user,$query,$request=null)
    {
        $array_task = array();
        $array_taskAttachs = array();
        $array_comment = array();
        $tasks = null;
        $files = null;
        $taskdata = null;
        $comment = null;
        $comment2 = null;

        if ($user->canViewTasks()) {


// dd($request->select_unit_filter);


            if( !empty($query) OR !empty($request->user_auth_filter) OR !empty($request->line_prod_filter) OR !empty($request->select_status_filter) OR !empty($request->select_unit_filter) ||(!empty($request->fecha_cre_filter)) ||(!empty($request->fecha_end_filter))     ) { //  if de si se ingresa alguna busqueda

    //   ||(!empty($request->fecha_cre_filter)) ||(!empty($request->fecha_end_filter)) 

            $tasks = Task::select(['tasks.title', 'tasks.id', 'tasks.unit_id', 'tasks.profile_id','tasks.created_at'])
               ->join('task_pipeline', 'task_pipeline.task_id', '=', 'tasks.id')   
                ->where('tasks.title', 'like', '%' . $query . '%')       
               ->where('tasks.unit_id', '<>', null)
                ->orderBy('tasks.created_at', 'DESC')

                ->when(!empty($request->fecha_cre_filter), function ($q) use ($request) {

                $q->whereDate('tasks.created_at', '>=', $request->fecha_cre_filter);

                })

                ->when(!empty($request->fecha_end_filter), function ($q) use ($request) {

                $q->whereDate('tasks.created_at', '<=', $request->fecha_end_filter);

                })

              ->when(!empty($request->line_prod_filter), function ($q) use ($request) {

                    $q->where('task_pipeline.pipeline_id', $request->line_prod_filter);

                })

              ->when(!empty($request->user_auth_filter), function ($q) use ($request) {

                    $q->where('tasks.user_id', $request->user_auth_filter);

                })


                ->when(!empty($request->select_status_filter), function ($q) use ($request) {

                     $q->whereIn('tasks.status_id', array($request->select_status_filter));

                })

                ->when(!empty($request->select_unit_filter), function ($q) use ($request) {


                     $q->whereIn('tasks.unit_id',array($request->select_unit_filter));

                })


              ->distinct()->get();



            if (count($tasks) > 0) {

                foreach ($tasks as $t) {


                    array_push($array_task, ['title' => $t->title,
                        'descripcion' => null,
                        'id' => $t->id,
                        'unit_id' => $t->unit_id,
                        'pipeline' => $t->pipeline->first()->name]);
                }

            }


            $taskdata = Taskdata::select(['taskdata.description', 'taskdata.id','taskdata.created_at'])
                ->join('tasks', 'taskdata.id', '=', 'tasks.taskdata_id')  
                ->join('task_pipeline', 'task_pipeline.task_id', '=', 'tasks.id')   
                ->where('taskdata.description', 'like', '%' . $query . '%')
                ->orderBy('taskdata.created_at', 'DESC')
        

             ->when(!empty($request->user_auth_filter), function ($q) use ($request) {

                    $q->where('tasks.user_id', $request->user_auth_filter);

                })



                ->when(!empty($request->fecha_cre_filter), function ($q) use ($request) {

                $q->whereDate('tasks.created_at', '>=', $request->fecha_cre_filter);

                })

                ->when(!empty($request->fecha_end_filter), function ($q) use ($request) {

                $q->whereDate('tasks.created_at', '<=', $request->fecha_end_filter);

                })


              ->when(!empty($request->line_prod_filter), function ($q) use ($request) {

                    $q->where('task_pipeline.pipeline_id', $request->line_prod_filter);

                })

                ->when(!empty($request->select_status_filter), function ($q) use ($request) {

                     $q->whereIn('tasks.status_id', array($request->select_status_filter));

                })

                ->when(!empty($request->select_unit_filter), function ($q) use ($request) {


                     $q->whereIn('tasks.unit_id', array($request->select_unit_filter));

                })

             ->distinct()->get();




            if (count($taskdata) > 0) {

                foreach ($taskdata as $td) {

                    foreach ($td->tasksRel as $t) {

                        if ($t->unit_id != null) {

                            array_push($array_task, ['title' => $t->title,
                                'descripcion' => $td->description,
                                'id' => $t->id,
                                'unit_id' => $t->unit_id,
                                'pipeline' => $t->pipeline->first()->name]);
                        }

                    }
                }
            }




            $files = DB::table('attachments')
                ->join('tasks', 'attachments.task_id', '=', 'tasks.id')  
                ->join('task_pipeline', 'task_pipeline.task_id', '=', 'tasks.id')   
                ->join('attach_task', 'attach_task.attachment_id', '=', 'attachments.id')
                ->select('attachments.original_name', 'attach_task.task_id', 'attach_task.attachment_id','attachments.created_at')
                ->where('attachments.original_name', 'like', '%' . $query . '%')
                ->where('attach_task.active', 1)
 

             ->when(!empty($request->user_auth_filter), function ($q) use ($request) {

          //          $q->where('tasks.user_id', $request->user_auth_filter);

                })

              ->when(!empty($request->line_prod_filter), function ($q) use ($request) {

                    $q->where('task_pipeline.pipeline_id', $request->line_prod_filter);

                })

                ->when(!empty($request->select_status_filter), function ($q) use ($request) {

                     $q->whereIn('tasks.status_id', array($request->select_status_filter));

                })

                ->when(!empty($request->select_unit_filter), function ($q) use ($request) {


                     $q->whereIn('tasks.unit_id', array($request->select_unit_filter));

                })

               ->orderBy('attachments.created_at', 'DESC')
               ->get();



            foreach ($files as $f) {

                $task_attach = Task::where('id', '=', $f->task_id)->get(['title', 'unit_id']);

                foreach ($task_attach as $task) {

                    if ($user->canViewAttach()) {
                        array_push($array_taskAttachs, [
                                'name_file' => $f->original_name,
                                'id' => $f->task_id,
                                'unit_id' => $task->unit_id]
                        );
                    }


                }
            }


            }  // endif  busqueda por task , taskdata ni archivos se hace si no se ingresa nada en busqueda


             if( !empty($query) OR !empty($request->user_comment_filter) OR !empty($request->line_prod_filter)  OR !empty($request->select_status_filter) OR !empty($request->select_unit_filter) ) {

            // solo subtareas

            $comment = Comment::select(['comments.comment', 'comments.id', 'comments.content_id', 'comments.content_type', 'comments.unit_id','comments.created_at'])
                ->join('subtasks', 'subtasks.id', '=', 'comments.content_id') 
                ->join('tasks', 'tasks.id', '=', 'subtasks.task_id') 
                ->join('task_pipeline', 'task_pipeline.task_id', '=', 'tasks.id')  
                ->where('comments.comment', 'like', '%' . $query . '%')
                ->where('comments.content_type', 'App\Subtask') 


             ->when(!empty($request->user_comment_filter), function ($q) use ($request) {

                    $q->where('comments.user_id', $request->user_comment_filter);

                })

                ->when(!empty($request->line_prod_filter), function ($q) use ($request) {

                    $q->where('task_pipeline.pipeline_id', $request->line_prod_filter);

                })

                ->when(!empty($request->select_status_filter), function ($q) use ($request) {

                     $q->whereIn('tasks.status_id', array($request->select_status_filter));

                })

                ->when(!empty($request->select_unit_filter), function ($q) use ($request) {


                     $q->whereIn('tasks.unit_id', array($request->select_unit_filter));

                })

                ->orderBy('comments.created_at', 'DESC')
                ->distinct()->get();



                // Solo tareas 

                $comment2 = Comment::select(['comments.comment', 'comments.id', 'comments.content_id', 'comments.content_type', 'comments.unit_id','comments.created_at'])
                ->join('tasks', 'tasks.id', '=', 'comments.content_id') 
                ->join('task_pipeline', 'task_pipeline.task_id', '=', 'tasks.id')  
                ->where('comments.content_type', 'App\Task') 
                ->where('comments.comment', 'like', '%' . $query . '%')


             ->when(!empty($request->user_comment_filter), function ($q) use ($request) {

                    $q->where('comments.user_id', $request->user_comment_filter);

                })

                ->when(!empty($request->line_prod_filter), function ($q) use ($request) {

                    $q->where('task_pipeline.pipeline_id', $request->line_prod_filter);

                })

                ->when(!empty($request->select_status_filter), function ($q) use ($request) {

                     $q->whereIn('tasks.status_id', array($request->select_status_filter));

                })

                ->when(!empty($request->select_unit_filter), function ($q) use ($request) {


                     $q->whereIn('tasks.unit_id', array($request->select_unit_filter));

                })

                ->orderBy('comments.created_at', 'DESC')
                ->distinct()->get();

                $comment = $comment->concat($comment2);



            $regex = null;

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

                if (count($regex[0]) == 0) {

                    array_push($array_comment, [
                            'comment' => $cm->comment,
                            'content_id' => $cm->content_id,
                            'content_type' => $cm->content_type,
                            'unit_id' => $cm->unit_id]
                    );

                }

            }

            }

        }


        if(!($user->canViewTasks()) && !($user->canSearchSubtask())){



              if( !empty($query) OR !empty($request->user_auth_filter) OR !empty($request->line_prod_filter) OR !empty($request->select_status_filter) OR !empty($request->select_unit_filter) ||(!empty($request->fecha_cre_filter)) ||(!empty($request->fecha_end_filter))    ) { //  if de si se ingresa alguna busqueda


   //   ||(!empty($request->fecha_cre_filter)) ||(!empty($request->fecha_end_filter)) 

            $tasks = Task::select(['tasks.title', 'tasks.id', 'tasks.unit_id', 'tasks.profile_id','tasks.created_at'])
                ->join('task_pipeline', 'task_pipeline.task_id', '=', 'tasks.id') 
                ->Where('tasks.title', 'like', '%'.$query.'%')
                ->where('tasks.unit_id', '<>', null)
                ->where('tasks.user_id',$user->id)
                ->orderBy('tasks.created_at', 'DESC')


                ->when(!empty($request->fecha_cre_filter), function ($q) use ($request) {

                $q->whereDate('tasks.created_at', '>=', $request->fecha_cre_filter);

                })

                ->when(!empty($request->fecha_end_filter), function ($q) use ($request) {

                $q->whereDate('tasks.created_at', '<=', $request->fecha_end_filter);

                })

                 ->when(!empty($request->user_auth_filter), function ($q) use ($request) {

                    $q->where('tasks.user_id', $request->user_auth_filter);

                })


                ->when(!empty($request->line_prod_filter), function ($q) use ($request) {

                    $q->where('task_pipeline.pipeline_id', $request->line_prod_filter);

                })

                ->when(!empty($request->select_status_filter), function ($q) use ($request) {

                     $q->whereIn('tasks.status_id', array($request->select_status_filter));

                })

                ->when(!empty($request->select_unit_filter), function ($q) use ($request) {


                     $q->whereIn('tasks.unit_id',array($request->select_unit_filter));

                })

                ->distinct()->get();


            if (!empty($tasks)) {
//                dd($tasks);
                foreach ($tasks as $t) {


                    array_push($array_task, ['title' => $t->title,
                        'descripcion' => null,
                        'id' => $t->id,
                        'unit_id' => $t->unit_id,
                        'pipeline' => $t->pipeline->first()->name]);
                }

            }



            $taskdata = Taskdata::select(['taskdata.description', 'taskdata.id','taskdata.created_at'])
                        ->join('tasks', 'taskdata.id', '=', 'tasks.taskdata_id')  
                        ->join('task_pipeline', 'task_pipeline.task_id', '=', 'tasks.id')  
                        ->where('taskdata.description', 'like', '%' . $query . '%')
                        ->orderBy('taskdata.created_at', 'DESC')



                        ->when(!empty($request->fecha_cre_filter), function ($q) use ($request) {

                        $q->whereDate('tasks.created_at', '>=', $request->fecha_cre_filter);

                        })

                        ->when(!empty($request->fecha_end_filter), function ($q) use ($request) {

                        $q->whereDate('tasks.created_at', '<=', $request->fecha_end_filter);

                        })

                         ->when(!empty($request->user_auth_filter), function ($q) use ($request) {

                                $q->where('tasks.user_id', $request->user_auth_filter);

                        })


                        ->when(!empty($request->line_prod_filter), function ($q) use ($request) {

                            $q->where('task_pipeline.pipeline_id', $request->line_prod_filter);

                        })

                        ->when(!empty($request->select_status_filter), function ($q) use ($request) {

                             $q->whereIn('tasks.status_id', array($request->select_status_filter));

                        })

                        ->when(!empty($request->select_unit_filter), function ($q) use ($request) {


                             $q->whereIn('tasks.unit_id', array($request->select_unit_filter));

                        })

                        ->distinct()->get();


            if(!empty($taskdata)) {

                foreach ($taskdata as $td) {

                    foreach ($td->tasksRel as $t) {

                        if ($t->user_id == $user->id) {

                            array_push($array_task, ['title' => $t->title,
                                'descripcion' => $td->description,
                                'id' => $t->id,
                                'unit_id' => $t->unit_id,
                                'pipeline' => $t->pipeline->first()->name]);
                        }

                    }
                }
            }




            $files = DB::table('attachments')
                ->join('tasks', 'attachments.task_id', '=', 'tasks.id')  
                ->join('task_pipeline', 'task_pipeline.task_id', '=', 'tasks.id')   
                ->join('attach_task', 'attach_task.attachment_id', '=', 'attachments.id')
                ->select('attachments.original_name', 'attach_task.task_id', 'attach_task.attachment_id','attachments.created_at')
                ->where('attachments.original_name', 'like', '%' .  $query  . '%')
                ->where('attach_task.active', 1)


             ->when(!empty($request->user_auth_filter), function ($q) use ($request) {

               //    $q->where('tasks.user_id', $request->user_auth_filter);

                })

               ->when(!empty($request->line_prod_filter), function ($q) use ($request) {

                    $q->where('task_pipeline.pipeline_id', $request->line_prod_filter);

                })

                ->when(!empty($request->select_status_filter), function ($q) use ($request) {

                     $q->whereIn('tasks.status_id', array($request->select_status_filter));

                })

                ->when(!empty($request->select_unit_filter), function ($q) use ($request) {


                     $q->whereIn('tasks.unit_id', array($request->select_unit_filter));

                })

                ->orderBy('created_at', 'DESC')
                ->get();


            foreach ($files as $f) {

                $task_attach = Task::where('id', '=', $f->task_id)
                    ->where('user_id',$user->id)
                    ->get(['title', 'unit_id']);

                foreach ($task_attach as $task) {

                    if ($user->canViewAttach()) {
                        array_push($array_taskAttachs, [
                                'name_file' => $f->original_name,
                                'id' => $f->task_id,
                                'unit_id' => $task->unit_id]
                        );
                    }


                }
            }


//  goo



            }  // end if busqueda en task




             if( !empty($query) OR !empty($request->user_comment_filter) OR !empty($request->line_prod_filter)  OR !empty($request->select_status_filter) OR !empty($request->select_unit_filter) ) {



            // solo subtareas

            $comment = Comment::select(['comments.comment', 'comments.id', 'comments.content_id', 'comments.content_type', 'comments.unit_id','comments.created_at'])
                ->join('subtasks', 'subtasks.id', '=', 'comments.content_id') 
                ->join('tasks', 'tasks.id', '=', 'subtasks.task_id') 
                ->join('task_pipeline', 'task_pipeline.task_id', '=', 'tasks.id')  
                ->where('comments.user_id',$user->id)
                ->where('comments.comment', 'like', '%' . $query . '%')
                ->where('comments.content_type', 'App\Subtask') 

             ->when(!empty($request->user_comment_filter), function ($q) use ($request) {

                    $q->where('comments.user_id', $request->user_comment_filter);

                })

                ->when(!empty($request->line_prod_filter), function ($q) use ($request) {

                    $q->where('task_pipeline.pipeline_id', $request->line_prod_filter);

                })

                ->when(!empty($request->select_status_filter), function ($q) use ($request) {

                     $q->whereIn('tasks.status_id', array($request->select_status_filter));

                })

                ->when(!empty($request->select_unit_filter), function ($q) use ($request) {


                     $q->whereIn('tasks.unit_id', array($request->select_unit_filter));

                })

                ->orderBy('comments.created_at', 'DESC')
                ->distinct()->get();




                $comment2 = Comment::select(['comments.comment', 'comments.id', 'comments.content_id', 'comments.content_type', 'comments.unit_id','comments.created_at'])
                ->join('tasks', 'tasks.id', '=', 'comments.content_id') 
                ->join('task_pipeline', 'task_pipeline.task_id', '=', 'tasks.id')  
                 ->where('comments.user_id',$user->id)
                ->where('comments.content_type', 'App\Task') 
                ->where('comments.comment', 'like', '%' . $query . '%')


             ->when(!empty($request->user_comment_filter), function ($q) use ($request) {

                    $q->where('comments.user_id', $request->user_comment_filter);

                })


                ->when(!empty($request->line_prod_filter), function ($q) use ($request) {

                    $q->where('task_pipeline.pipeline_id', $request->line_prod_filter);

                })

                ->when(!empty($request->select_status_filter), function ($q) use ($request) {

                     $q->whereIn('tasks.status_id', array($request->select_status_filter));

                })

                ->when(!empty($request->select_unit_filter), function ($q) use ($request) {


                     $q->whereIn('tasks.unit_id', array($request->select_unit_filter));

                })

                ->orderBy('comments.created_at', 'DESC')
                ->distinct()->get();

                $comment = $comment->concat($comment2);


            $regex = null;

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

                if (count($regex[0]) == 0) {

                    array_push($array_comment, [
                            'comment' => $cm->comment,
                            'content_id' => $cm->content_id,
                            'content_type' => $cm->content_type,
                            'unit_id' => $cm->unit_id]
                    );

                }

            }



        }



        }

        return  $arraySearch = array(
            'tasks' =>$array_task,
            'attach_tasks' =>$array_taskAttachs,
            'array_comments' =>$array_comment,
        );
    }


    /**
     *
     * @pre    Busca en las subtareas , comentarios, nombres de archivos relacionados al query pasado por parametro,
     *          si el usuario tiene permisos
     * @param $user
     * @param $query
     * @return array de ubicaciones de las palabras encontradas
     */
    private function  searchSubtaskComemtAttach($user,$query, $request=null)
    {
        $array_subtask = array();
        $array_comment =array();
        $array_subtaskAttachs = array();



        if ($user->canSearchSubtask()) {


           if( !empty($query) OR !empty($request->user_auth_filter) OR !empty($request->line_prod_filter) OR !empty($request->select_status_filter) OR !empty($request->select_unit_filter)) { //  if de si se ingresa alguna busqueda




            $subtask = Subtask::select(['subtasks.title', 'subtasks.description', 'subtasks.id', 'subtasks.assigned_id'])
                ->join('tasks', 'tasks.id', '=', 'subtasks.task_id') 
                ->join('task_pipeline', 'task_pipeline.task_id', '=', 'tasks.id') 
                ->where('subtasks.title', 'like', '"%' .  $query  . '%"')
                ->orWhere('subtasks.description', 'like', '"%' . $query . '%"')


             ->when(!empty($request->user_auth_filter), function ($q) use ($request) {

                    $q->where('tasks.user_id', $request->user_auth_filter);

                })

                ->when(!empty($request->line_prod_filter), function ($q) use ($request) {

                    $q->where('task_pipeline.pipeline_id', $request->line_prod_filter);

                })

                ->when(!empty($request->select_status_filter), function ($q) use ($request) {

                     $q->whereIn('tasks.status_id', array($request->select_status_filter));

                })

                ->when(!empty($request->select_unit_filter), function ($q) use ($request) {


                     $q->whereIn('tasks.unit_id', array($request->select_unit_filter));

                })


                ->orderBy('subtasks.created_at', 'DESC')
                ->get();


            if (!empty($subtask)) {

                foreach ($subtask as $sub) {

                    if ($user->canViewSubtask($sub->id)) {

                        array_push($array_subtask, ['title' => $sub->title,
                                'id' => $sub->id,
                                'description' => $sub->description
                            ]
                        );
                    }
                }

            }







            $files = DB::table('attachments')
                ->join('tasks', 'attachments.task_id', '=', 'tasks.id')  
                ->join('task_pipeline', 'task_pipeline.task_id', '=', 'tasks.id')   
                ->join('attach_subtask', 'attach_subtask.attachment_id', '=', 'attachments.id')
                ->select('attachments.original_name', 'attach_subtask.subtask_id')
                ->where('attachments.original_name', 'like', '%' .  $query  . '%')
                 ->where('attach_subtask.active', 1)

             ->when(!empty($request->user_auth_filter), function ($q) use ($request) {

               //     $q->where('tasks.user_id', $request->user_auth_filter);

                })

               ->when(!empty($request->line_prod_filter), function ($q) use ($request) {

                    $q->where('task_pipeline.pipeline_id', $request->line_prod_filter);

                })

                ->when(!empty($request->select_status_filter), function ($q) use ($request) {

                     $q->whereIn('tasks.status_id', array($request->select_status_filter));

                })

                ->when(!empty($request->select_unit_filter), function ($q) use ($request) {


                     $q->whereIn('tasks.unit_id', array($request->select_unit_filter));

                })

                ->orderBy('attachments.created_at', 'DESC')
                ->get();



            foreach ($files as $f) {

                if ($user->canViewSubtask($f->subtask_id)) {
                    array_push($array_subtaskAttachs, [
                            'name_file' => $f->original_name,
                            'id' => $f->subtask_id
                        ]
                    );
                }

            }


            } // endif




      if( !empty($query) OR !empty($request->user_comment_filter) OR !empty($request->line_prod_filter)  OR !empty($request->select_status_filter) OR !empty($request->select_unit_filter) ) {


            // solo subtareas

            $comment = Comment::select(['comments.comment', 'comments.id', 'comments.content_id', 'comments.content_type', 'comments.unit_id','comments.created_at'])
                ->join('subtasks', 'subtasks.id', '=', 'comments.content_id') 
                ->join('tasks', 'tasks.id', '=', 'subtasks.task_id') 
                ->join('task_pipeline', 'task_pipeline.task_id', '=', 'tasks.id')  
                ->where('comments.comment', 'like', '%' . $query . '%')
                ->where('comments.content_type', 'App\Subtask') 


             ->when(!empty($request->user_comment_filter), function ($q) use ($request) {

                    $q->where('comments.user_id', $request->user_comment_filter);

                })

                ->when(!empty($request->line_prod_filter), function ($q) use ($request) {

                    $q->where('task_pipeline.pipeline_id', $request->line_prod_filter);

                })

                ->when(!empty($request->select_status_filter), function ($q) use ($request) {

                     $q->whereIn('tasks.status_id', array($request->select_status_filter));

                })

                ->when(!empty($request->select_unit_filter), function ($q) use ($request) {


                     $q->whereIn('tasks.unit_id', array($request->select_unit_filter));

                })

                ->orderBy('comments.created_at', 'DESC')
                ->distinct()->get();



                // Solo tareas 

                $comment2 = Comment::select(['comments.comment', 'comments.id', 'comments.content_id', 'comments.content_type', 'comments.unit_id','comments.created_at'])
                ->join('tasks', 'tasks.id', '=', 'comments.content_id') 
                ->join('task_pipeline', 'task_pipeline.task_id', '=', 'tasks.id')  
                ->where('comments.content_type', 'App\Task') 
                ->where('comments.comment', 'like', '%' . $query . '%')


             ->when(!empty($request->user_comment_filter), function ($q) use ($request) {

                    $q->where('comments.user_id', $request->user_comment_filter);

                })

                ->when(!empty($request->line_prod_filter), function ($q) use ($request) {

                    $q->where('task_pipeline.pipeline_id', $request->line_prod_filter);

                })

                ->when(!empty($request->select_status_filter), function ($q) use ($request) {

                     $q->whereIn('tasks.status_id', array($request->select_status_filter));

                })

                ->when(!empty($request->select_unit_filter), function ($q) use ($request) {


                     $q->whereIn('tasks.unit_id', array($request->select_unit_filter));

                })

                ->orderBy('comments.created_at', 'DESC')
                ->distinct()->get();

                $comment = $comment->concat($comment2);




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

                if (count($regex[0]) == 0) {

                    array_push($array_comment, [
                            'comment' => $cm->comment,
                            'content_id' => $cm->content_id,
                            'content_type' => $cm->content_type,
                            'unit_id' => $cm->unit_id]
                    );

                }

            }




            }            





        }

        return $arraySearch = array(
            'subtasks' =>$array_subtask,
            'attach_subtasks' => $array_subtaskAttachs,
            'array_comments' =>$array_comment,
        );

    }

    /**
     * Guarda en los arreglos globales los array de ubicaciones de las palabras encontradas que devuelven
     * las funciones->( searchSubtaskComemtAttach,searchTaskComentAttach)
     * @param $array_type
     */

    private function saveArrays($array_type){


        foreach ($array_type as $key=> $array){

            foreach ($array as $str){

                switch($key){

                    case 'tasks':

                        array_push($this->array_task,$str);

                        break;
                    case 'subtasks':


                        array_push($this->array_subtask,$str);
                        break;

                    case 'attach_tasks':

                        array_push($this->array_taskAttachs,$str);
                        break;

                    case 'attach_subtasks':
                        array_push($this->array_subtaskAttachs,$str);
                        break;

                    case 'array_comments':
                        array_push($this->array_comment,$str);

                        break;

                }//fin switch

            }//fin 1er foreach

        }//fin 2do foreach


    }


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

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

}
