<?php

namespace App\Http\Controllers;

use App\Attachment;
use App\Events\Event;
use App\Http\Requests\StoreFormEvento;
use App\Notifications;
use App\Eventlog;
use App\Pipeline;
use App\Profile;
use App\ProfileUser;
use App\Project;
use App\Status;
use App\Subtask;
use App\Taskdata;
use App\Tasktag;
use App\TeamRole;
use App\User;
use App\UserUnit;
use App\TaskForm;
use function Couchbase\defaultDecoder;
use Illuminate\Routing\Controller as BaseController;
use Kris\LaravelFormBuilder\FormBuilder;
use App\Task;
use App\Unit;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
use App\Http\Requests\StoreFormWeb;
use App\Http\Requests\StoreFormEmail;
use App\Http\Requests\StoreFormEvent;
use App\Http\Requests\StoreFormCoverage;
use App\Http\Requests\UpdateFormWeb;
use App\Http\Requests\UpdateFormEmail;
use App\Http\Requests\UpdateFormEvent;
use Laravelista\Comments\Comments\Comment;
use App\Http\Requests\StoreFormOther;
use App\Http\Requests\UpdateFormOther;
use App\Http\Requests\StoreFormTeamLeader;
use App\Listeners\CreateTaskListener;
use App\Events\CreateTask;
use App\Events\UpdateTask;
use App\Events\TaskStatusChange;
use DateTime;
use Laravelista\Comments\Events\CommentWasPosted;
use Laravelista\Comments\Events\CommentWasUpdated;
use Laravelista\Comments\Events\CommentWasDeleted;
use ZipArchive;
use App\Events\CreateAttach;
use App\Events\CreateTags;
use Illuminate\Routing\Route;
use Carbon\Carbon;
use App\Events\TaskInactive;
use App\SettingUser;
use Illuminate\Pagination\LengthAwarePaginator;

use App\Services\Pagination;




class TaskController extends Controller
{


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

        $this->middleware('auth');


    }

    /**
     * @return
     */
    public function index()
    {

        $units = Unit::orderBy('order', 'asc')->get();
        $openUnit = $units->first()->id;

        $tasks = Task::whereNotIn('status_id', [3, 6])->with('pipeline', 'taskdata', 'unit', 'status')->get();
        $status = Status::where('status_type', 'task')->get();


        $args = array(

            'units' => $units,
            'filtertasks' => 'opentasks',
            'openunit' => $openUnit,
            'alltasks' => $tasks,
            'status' => $status,

        );

        return view('task.collection', $args);


    }

    public function indexInProgress()
    {
//        $this->objUnit->set_status = $status;


        $units = Unit::orderBy('order', 'asc')->get();
        $openUnit = $units->first()->id;

        $tasks = Task::whereNotIn('status_id', [3, 6])->with('pipeline', 'taskdata', 'unit', 'status')->get();
        $status = Status::where('status_type', 'task')->get();


        $args = array(

            'units' => $units,
            'filtertasks' => 'opentasksFilterProgress',
            'openunit' => $openUnit,
            'alltasks' => $tasks,
            'status' => $status,
        );

        return view('task.collection', $args);
    }


    public function indexUninitiated()
    {

//------- 1* ver el panel de tareas a una de las unidades al que pertenece el usuario
        $user = Auth::user();

        $settingUser = SettingUser::where('user_id',$user->id)->first();
        $openUnit = 0;

        if(count($settingUser) >0)
        {
            $openUnit = $settingUser->unit_id;
        }
        elseif (count($settingUser) == 0)
        {
            $user_unit = $user->userUnits->first()->unit_id;
            $openUnit = $user_unit;
        }

        //fin 1*

        // busca las unidades excepto la unidad 'aprobación'
        $units = Unit::orderBy('order', 'asc')->where('slug', '<>', 'aprobacion')->get(['id', 'name', 'slug', 'color', 'order', 'approve_unit', 'unitType_id', 'created_at', 'updated_at']);

        $tasks = Task::whereNotIn('status_id', [3, 6])->with('pipeline', 'taskdata', 'unit', 'status')->get(['id', 'created_at', 'updated_at', 'draft', 'type', 'title', 'description', 'deadline', 'profile_id', 'status_id', 'user_id', 'taskdata_id', 'unit_id', 'pipelineRevision']);

        $status = Status::where('status_type', 'task')->get();

//dd($tasks);
        $args = array(

            'units' => $units,
            'filtertasks' => 'opentasksFilterUninitiated',
            'openunit' => $openUnit,
            'alltasks' => $tasks,
            'status' => $status,
        );

        return view('task.collection', $args);


    }


    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function clientHome($st)
    {


        $arrayTaskData = array();
        $arrayDraft = array();
//        define('LIMIT', 10);
//        define('OFFSET', (($page * LIMIT) - LIMIT));

        if (Auth::user()->hasRole('supervisor') || Auth::user()->hasRole('administrador') || Auth::user()->hasRole('teamleader')) {
            //$taskdata = Taskdata::all();
            $tasks = DB::table('tasks')->where('status_id', '=', $st)->get();

            foreach ($tasks as $t) {
                array_push($arrayTaskData, $t->taskdata_id);
                if ($t->unit_id == null) {
                    array_push($arrayDraft, $t->id);
                }
            }
//            $taskdata = Taskdata::whereIn('id', $arrayTaskData)->offset(OFFSET)->limit(LIMIT)->get();
            $taskdata = Taskdata::whereIn('id', $arrayTaskData)->get();
        } else {
            $arrayProfile = array();
            $profile = ProfileUser::where('user_id', '=', Auth::user()->id)->get();
            foreach ($profile as $p) {
                array_push($arrayProfile, $p->profile_id);
            }

            //$tasks = DB::table('tasks')->whereIn('profile_id', $arrayProfile)->where('status_id','!=',3)->where('status_id','!=',6)->get();
            $tasks = DB::table('tasks')->whereIn('profile_id', $arrayProfile)->where('status_id', '=', $st)->get();

            foreach ($tasks as $t) {
                array_push($arrayTaskData, $t->taskdata_id);
                if ($t->unit_id == null) {
                    array_push($arrayDraft, $t->id);
                }
            }
//            $taskdata = Taskdata::whereIn('id', $arrayTaskData)->offset(OFFSET)->limit(LIMIT)->get();
            $taskdata = Taskdata::whereIn('id', $arrayTaskData)->get();
        }

//        $cantidad = Taskdata::whereIn('id', $arrayTaskData)->count('id');
//        $pages = ceil($cantidad / LIMIT);

        $units_query = Unit::where('slug', '<>', 'aprobacion')->get();
        $status = Status::where('status_type', '=', 'task')->get();


        $units = array();
        //$status = array();


        foreach ($units_query as $u) {
            $units[$u->id] = $u->name;
        }

//        foreach ($status_query as $s) {
//            $status[$s->id] = $s->name;
//
//        }
        $profiles = DB::select('SELECT DISTINCT(profiles.id),profiles.area FROM profiles,tasks where profiles.status = 1 and profiles.id =tasks.profile_id');


        return view('task.client.home', array(
            'units' => $units,
            'status' => $status,
            'taskdata' => $taskdata,
            'active' => $st,
            'draft' => $arrayDraft,
            'profiles' => $profiles,
//            'cantidad' => $cantidad,
//            'pages' => $pages,
//            'page' => $page,
//            'limit' => LIMIT
        ));
    }

    public function clientIndex()
    {

    }

    public function taskRelatedToUnit()
    {

    }


    /**
     * @param $openunit
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getUnit($openunit)
    {
//        $this->objUnit->set_status = $status;


//        $units = \App\Unit::all();
        $units = Unit::where('slug', '<>', 'aprobacion')->orderBy('order', 'asc')->get();

        $tasks = Task::whereNotIn('status_id', [3, 6])->get();
        $status = Status::where('status_type', 'task')->get();
        $args = array(

            'units' => $units,
            'filtertasks' => 'opentasks',
            'openunit' => $openunit,
            'cons' => $tasks,
            'alltasks' => $tasks,
            'status' => $status,


        );
        return view('task.collection', $args);


    }

    /**
     * @param $status
     * @param $openUnit
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getStatus($status, $openUnit)
    {

        $units = Unit::where('slug', '<>', 'aprobacion')->orderBy('order', 'asc')->get();

//        $tasks = Task::whereNotIn('status_id', [3,6])->get();

        switch ($status) {
            case 1:
                $tasks = Task::whereNotIn('status_id', [3, 6])->get();
                $filtertasks = 'opentasks';
                break;
            case 3:
                $tasks = Task::whereIn('status_id', [3, 6])->get();
                $filtertasks = 'closedtasks';
                break;
            default:
                $tasks = Task::whereIn('status_id', [3, 6])->get();
                $filtertasks = 'opentasks';


        }

        $filtertasks =

//        $status =Status::where('status_type','task')->get();

        $args = array(

            'units' => $units,
            'filtertasks' => $filtertasks,
            'openunit' => $openUnit,
            'alltasks' => $tasks,
            'status' => $status,

        );
        return view('task.collection', $args);

    }


    /**
     * @return envia a la vista task.myTask los datos que se utilizan para que muestre las tareas,subtareas y etiquetas de las tareas  del usuario logeado
     */
    public function getMyTasks(Request $request)
    {

        $statusId = $request->input('status');
        $tipo = $request->input('type');

        $arrayTasks = array();

        $countTas = Task::where('user_id', '=', Auth::user()->id)
            ->where('unit_id', '<>', 'null')->count();
        $countSub = Subtask::where('assigned_id', '=', Auth::user()->id)->count();
        $countTags = Tasktag::where('user_id', '=', Auth::user()->id)
            ->where('active', '=', 1)->count();


        if ($statusId != null && $tipo != null) {

            switch ($tipo) {

                case "task":
                    $typeTasks = Task::where('user_id', '=', Auth::user()->id)
                        ->where('unit_id', '<>', 'null')->get();
                    $statusArray = $this->typeStatus($statusId, $tipo);
                    $status = $statusArray['status'];
                    $statuName = $statusArray['statuName'];
                    $arrayTasks = $this->getTaKs($typeTasks, $tipo, $arrayTasks);//inserta elementos al arreglo

                    break;

                case "subtask":
                    $typeTasks = Subtask::where('assigned_id', '=', Auth::user()->id)->get();
                    $statusArray = $this->typeStatus($statusId, $tipo);
                    $status = $statusArray['status'];
                    $statuName = $statusArray['statuName'];
                    $arrayTasks = $this->getTaKs($typeTasks, $tipo, $arrayTasks);//inserta elementos al arreglo

                    break;

                case "tags":
                    $tags = Tasktag::where('user_id', '=', Auth::user()->id)
                        ->where('active', '=', 1)->get();

                    $tagAux = array();

                    //busca tarea o subtarea donde está etiquetado el usuario
                    foreach ($tags as $t) {
                        if ($t->type == 'task') {
                            $tagAux = Task::where('id', '=', $t->relation_id)
                                ->where('unit_id', '<>', 'null')->get();
                            $arrayTasks = $this->getTaks($tagAux, $t->type, $arrayTasks);//inserta elementos al arreglo


                        }
                        if ($t->type == 'subtask') {
                            $tagAux = Subtask::where('id', '=', $t->relation_id)->get();
                            $arrayTasks = $this->getTaks($tagAux, $t->type, $arrayTasks);//inserta elementos al arreglo

                        }
                    }
                    $statuName = "tags";
                    $status = "";

                    break;

            }

            return view('task.myTask', compact(['countSub', 'countTags', 'status', 'statuName', 'arrayTasks', 'countTas']));

        } else {
            $statusArray = $this->typeStatus('1', 'task');
            $status = $statusArray['status'];
            $statuName = $statusArray['statuName'];
            $typeTasks = Task::where('user_id', '=', Auth::user()->id)
                ->where('unit_id', '<>', 'null')->get();

            $arrayTasks = $this->getTaks($typeTasks, "task", $arrayTasks);//inserta elementos al arreglo

            return view('task.myTask', compact(['countSub', 'status', 'statuName', 'arrayTasks', 'countTags', 'countTas']));
        }
    }


    /**
     * @param $tagsAux
     * @param $tipo
     * @param $arrayTasks
     * @return retorna un arreglo con contenido  necesario para mostrar en la tabla
     */
    private function getTaks($taskAux, $tipo, $arrayTasks)
    {
        foreach ($taskAux as $aux) {

            if ($tipo == 'task') {

                $title = $aux->title;
                if ($aux->title == null) { //si el campo título de la tarea es vacío, busca el título en taskdata
                    $title = $aux->taskdata->title;
                }

                if ($aux->type == 'event') {
                    array_push($arrayTasks, array(
                        'title' => $title,
                        'statu' => $aux->status->name,
                        'id' => $aux->id,
                        'deadline' => $aux->taskdata->deadline,
                        'tipo' => 'tasks',
                    ));
                } else {
                    array_push($arrayTasks, array(
                        'title' => $title,
                        'statu' => $aux->status->name,
                        'id' => $aux->id,
                        'deadline' => $aux->taskdata->deadline,
                        'tipo' => 'tasks',
                    ));
                }

            } else {
                array_push($arrayTasks, array(
                    'title' => $aux->title,
                    'statu' => $aux->status->name,
                    'id' => $aux->id,
                    'deadline' => $aux->deadline,
                    'tipo' => 'subtasks',
                ));
            }
        }
        return $arrayTasks;
    }


    /**
     * @param $statusId , id del statu, ejm abierta
     * @param $type , tipo de tarea, ejm task
     * Funcion que recibe dos parametros
     * @return devuelve un array busca el status por tipo(status_type,ejm task)
     */
    private function typeStatus($statusId, $type)
    {
        $status = Status::where('status_type', '=', $type)->get();
        $statuName = " ";

        foreach ($status as $s) {

            if ($s->id == $statusId) {
                $statuName = $s->name;
            }
        }

        $args = array('status' => $status,
            'statuName' => $statuName);
        return $args;

    }


    /**
     * @param $taskId
     * @param null $unitId
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function clientShow($taskId, $unitId = null)
    {

        $this->notificationsRead($taskId); // marca como leído las notificaciones de la tarea
        $task = Task::find($taskId);

        if (isset($unitId)) {
            $unit = Unit::find($unitId);
        } else {
            $unit = Unit::find($task->unit_id);

        }

        $pipeline = Pipeline::find($task->pipeline()->first()->id);

        $args = array(
            'task' => $task,
            'active_unit' => $pipeline->unitsByRevision($task->pipelineRevision)->first(),

        );

        return view('task.client.show', $args);
    }


    /**
     * @param $task_id ,$unitId(condicional, puede ser nulo)
     * pre:busca notificaciones por id de tarea,
     * post:cambia el estado (a leido) la notificacion de tarea encontrada
     **/
    private function notificationsRead($taskId)
    {

        $notificaciones = Notifications::select('notifications.id as id')->join('eventlogs as  e', 'e.id', '=', 'notifications.eventlogs_id')
            ->where('notifications.user_to', Auth::user()->id)
            ->where('e.relation_id', $taskId)
            ->where('is_read', 0)
            ->whereIn('notifications.type', ['task', 'app\task', 'updatetask', 'taskstatuschange', 'attachtask', 'changetounit', 'TaskInactive'])
            ->get();


        $tasktags = Tasktag::select('id')->where('type', 'task')->where('relation_id', $taskId)->get();

        $tasktag_ids = array();
        foreach ($tasktags as $tasktag) {

            array_push($tasktag_ids, $tasktag->id);

        }

        $notifTags = Notifications::select('notifications.id')->join('eventlogs as  e', 'e.id', '=', 'notifications.eventlogs_id')
            ->where('notifications.user_to', Auth::user()->id)
            ->where('is_read', 0)
            ->whereIn('e.relation_id', $tasktag_ids)
            ->whereIn('e.type', ['tasktag', 'untasktag'])->get();
//            ->whereIn('notifications.type',['tasktag','untasktag','InfoTaskTag','infoUntag'])->get();

        if (count($notificaciones) > 0) {

            foreach ($notificaciones as $n) {

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

            }
        }

        if (count($notifTags) > 0) {

            foreach ($notifTags as $n) {

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

            }
        }

    }


    /**
     * @param $taskId
     * @param null $unitId
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function show($taskId, $unitId = null)
    {


        //cambia estado en tabla Notifications is_Read
        $this->notificationsRead($taskId);



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


        $tr_query = TeamRole::all();

        $teamroles = array();

        foreach ($tr_query as $tm) {
            $teamroles[$tm->id] = $tm->name;
        }

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

        if (isset($unitId)) {
            $unit = Unit::find($unitId);
        } else {
            $unit = Unit::find($task->unit_id);

        }

        $pipeline = Pipeline::find($active_pipeline->id);


        $initialUnit = Unit::where('approve_unit', '1')->first();
        $relatedTasks = $task->where('taskdata_id', $task->taskdata_id)->where('unit_id', '!=', $initialUnit->id)->get();


        $generatedPipelines = [];
        foreach ($relatedTasks as $rTask) {
            array_push($generatedPipelines, $rTask->pipeline->first()->id);
        }


        $pipelines_query = Pipeline::All();

        $allPipelines = array();
        foreach ($pipelines_query as $p) {
            $allPipelines[$p->id] = $p->name;

        }

        $status = Status::where('status_type', '=', 'task')->get();


        //Busco usuarios para seleccionar y etiquetar

        $userTasktag = Tasktag::where('relation_id', '=', $taskId)//busco usuarios que ya estan etiquetados en la esta tarea
        ->where('type', '=', 'task')
            ->where('unit_id', '=',$unitId )
            ->where('active', '=', 1)->get();

        $usersEtiq = array();               //usuarios etiquetados
        $usersEtiq_id = array();            //usuarios etiquetados

        foreach ($userTasktag as $tg) {                     //$userTaskTag el query está mas arriba usado para otros fines ...

            if ($tg->user->active == 1) {                   // usuario está activo de la (tabla users)?

            $usersEtiq[$tg->id] = array("name" => $tg->user->name, "unit" => $tg->unit_id);
            array_push($usersEtiq_id,$tg->user_id);

            }
        }



        //unifico los arreglos de usuarios buscados por role
        $auxUserForRole = array_merge($this->userForRole(2, 'teamleader'), $this->userForRole(1, 'supervisor'));
        $auxUserForRole2 = array_merge($auxUserForRole, $this->userForRole(4, 'administrador'));

        $allUserAux = array_unique($auxUserForRole2);

        //busco usuarios de la unidad con role 'tag' que no estén etiquetados(task_tag) y que esten activos
        foreach ($task->unit->autotags as $ua){

            if($ua->active == 1 ) {                 //usuario activo

                //si el usuario no está etiquetado en la tarea
                if (empty($ua->tasktagInTask($taskId, $unitId)->first())) {

                    array_push($allUserAux, $ua->id);
                }
            }

        }


        if ($task->unit->type->slug == 'interna'){

            foreach ($task->unit->usersUnitInternal() as $ui){

                $user = User::find($ui->user_id)->active;

                if($user == 1 ) {   //usuario activo
                    array_push($allUserAux, $ui->user_id);
                }
            }
        }

//        $user = new User();

        if ($task->unit->type->slug == 'externa'){
//            if ($user->isTeamLeaderInUnit($task->unit_id)){

            foreach ($task->unit->usersUnitExtern() as $ui){

                $user = User::find($ui->user_id)->active;

                if($user == 1 ) {  //usuario activo
                    array_push($allUserAux, $ui->user_id);
                }
            }
        }

       // Busco que User id = 31(carlos Barrientos)no esté etiquetado
        $aux = Tasktag::where('id',31)->where('type','task')->where('relation_id',$taskId)->where('unit_id',$unitId)->first();

        if($aux == null){

            array_push($allUserAux,31);
        }
        //fin

        $allusers = array_unique($allUserAux,SORT_REGULAR);


        $users = DB::table('users')
            ->select('name','surname','users.id as userID')
//            ->where('id', '<>', Auth::user()->id)
//            ->whereIn('id', $allusers)
            ->leftJoin('user_unit', 'users.id', '=', 'user_unit.user_id')
            ->where('user_unit.teamrole_id', '=', 1)
            ->whereNotIn('users.id', $usersEtiq_id)
            ->orderBy('name', 'asc')->distinct()->get();


        $profiles = Profile::all();

        //-----------------fin ------------------



        // Archivos Propios de la tarea, esos podran activarse  //  usados por AJAX  en otro metodo

        $AttachnativeTask = DB::table('attach_task')
            ->select('attach_task.*')
            ->where('attach_task.task_id', '=', $taskId)
            ->join('attach_subtask', 'attach_task.attachment_id', '=', 'attach_subtask.attachment_id')->get();

        $notActive = array();

        if ($AttachnativeTask) {

            foreach ($AttachnativeTask as $key3 => $value3) {

                array_push($notActive, $value3->attachment_id);

            }
        }


        $pipelines = Pipeline::orderBy('hidden')->get();



        // se usa para cambiar línea de producción

        $pipelines = Pipeline::where('deprecated', '=', null)
            ->where('system', '=', 0)
            ->where('slug', '<>', 'pre-ingreso')->get();

        $pipeline_unit = array();

        foreach ($pipelines as $key => $p) {

            if ($p->deprecated == '') {
                $pipeline_unit[$p->id] = $p->name;

            }
        }

        //----------------------------------------------
        //busca tiempo que la tarea estuvo en la unidad

        $difftime = $this->countTimeInUnit($taskId,$unitId);


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

        //  Busca archivos compartidos 


        $taskdataIdc = Task::select('taskdata_id')->where('id',$taskId)->get()->pluck('taskdata_id')->first();


        $taskComp = Task::select('id')->where('taskdata_id',$taskdataIdc)->get()->pluck('id')->toArray();

        $acumpAttach = array();

        foreach ($taskComp as $key9 => $value9) {
           
             $tasktemp = Task::find($value9);

             $acumpAttach[$value9] = $tasktemp->attachments->toArray();

        }





        $taskCompUnique = array();

        foreach ($acumpAttach as $key8 => $value8) {

 

            if(!empty($value8)){

                foreach ($value8 as $key3 => $value3) {

                    if(empty($taskCompUnique[$value3['id']])){

                        $taskCompUnique[$value3['id']] = $value3;
                    }

                }
            }
               
        }


        //  Elimino los del archivo actual, esos no se combinan

        foreach ($taskCompUnique as $key4 => $value4) {


         
                foreach ($task->attachments as $key5 => $value5) {
    
                    if($value4['id']==$value5->id){
                        unset($taskCompUnique[$key4]);
                    }
               }  


               if($value4['pivot']['active']==0){

                    unset($taskCompUnique[$key4]);

                }

        }


//exit;

// dd($taskCompUnique); exit; 


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


        $args = array(
            'task' => $task,
            'pipeline' => $pipeline,
            'active_unit' => $unit,
            'teamroles' => $teamroles,
            'allPipelines' => $allPipelines,
            'pipelines_query' => $pipelines_query,
            'statuses' => $status,
            'users' => $users,
//            'userUnit' => $userUnit,
            'usersEtiq' => $usersEtiq,
            'notActive' => $notActive,
            'pipelines' => $pipelines,
            'relatedTasks' => $relatedTasks,
            'generatedPipelines' => $generatedPipelines,
            'profiles' => $profiles,
            'pipeline_unit' => $pipeline_unit,
            'difftime' =>$difftime,
            'unicos' =>$taskCompUnique, 
        );

        $user_permition = Auth::user();
        if(!$user_permition->isApplicant())
        {
            return view('task.show', $args);
        }
        else{
            return \redirect('/otask/' . $task->id . '/show');
        }

    }


    /**
     * busca tiempo que la tarea en la unidad
     * @param $taskId
     * @param $unitId
     * @return string
     */
    private function  countTimeInUnit($taskId,$unitId){


        $coment =Comment::where('content_id',$taskId)->where('content_type','App\\Task')->get();
        $task = Task::find($taskId);

        //variables auxiliares
        $date_created = '';//fecha en que se crea la tarea en la unidad
        $date_post = ''; //fecha posterior en que se crea la tarea en la unidad
        $unit_actual = '';
        $unit_anterior ='';
//        $date_unitAnterior ='';


        if($unitId != null){
            $task_unit = $unitId;
        }
        else{

            $task_unit = $task->unit_id;
        }


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

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

                $unit_aux=Unit::where('name',$changeUnit[0][1])->first();
//var_dump($unit_aux);
                if(!empty($unit_aux)) {
                    if ($unit_aux->id == (integer)$task_unit) {

                        $date_created = $cmt->created_at;
                        $unit_actual = $changeUnit[0][1];
                        $unit_anterior = $changeUnit[0][0];

                    }
                }


            }

        }

            //verifico la unidad anterior
        foreach ($coment as $cmt) {

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

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

                $unit_aux = Unit::where('name', $changeUnit[0][1])->first(); //busco si hubo un cambio de unidad de la unidad anterior
                if(!empty($unit_aux)) {
                    if ($unit_anterior == '') { //si no tiene unidad anterior => la tarea está en la 1era unidad ,guardo la fecha de la creación de la tarea

                        $date_created = $task->created_at; //fecha en que se creo la tarea
                    } else {

                        if ($unit_aux->name == $unit_anterior) {

                            $date_created = $cmt->created_at; //fecha en que cambia a otra unidad

                        }
                    }
                }
            }
        }

        //verifico la unidad siguiente
        foreach ($coment as $cmt) {

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

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

                $unit_aux = Unit::where('name', $changeUnit[0][0])->first(); //busco si hay un cambio de unidad de esta unidad a otra ,si hay guardo la fecha
                if(!empty($unit_aux)) {

                    if ($unit_actual == '') { //si es vacio es porque la tarea está en la 1era unidad no se guardó la unidad actual

                        if ($unit_aux->id == $task_unit) {

                            $date_post = $cmt->created_at; //fecha en que cambia a otra unidad
                        }

                    } else {

                        if ($unit_aux->name == $unit_actual) {


                            $date_post = $cmt->created_at; //fecha en que cambia a otra unidad
                        }
                    }
                }

            }

        }


        if($date_post == null){

            $date_post = Carbon::now();
        }

        $createdDate=Carbon::parse($date_created);
        $postDate =Carbon::parse($date_post);
        $difftime='';


        if($unit_actual!= null && $unit_anterior != null) {


            $diffDaysAux = $createdDate->diffInDays($postDate);

            if ($diffDaysAux < 2) {



                if ($createdDate->diffInHours($date_post) < 2) {

                    if($diffDaysAux == 0){
                        $difftime = '1 minutos';
                    }else{
                        $difftime = $createdDate->diffInHours($date_post) . ' hora';
                    }


                } else {
                    $difftime = $createdDate->diffInHours($date_post) . ' horas';
                }

            } elseif ($diffDaysAux > 1 && $diffDaysAux < 31) {

                $difftime = $date_created->diffInDays($date_post) . ' días';

            } else {
                $difftime = $date_created->diffInMonths($date_post) . ' meses';//aca se rompe porq no existe comentario
            }
        }else{
            $difftime = ',"No hay actividad en esta unidad."';
        }

        return $difftime;

    }


    /**
     * @param $valor
     * @param $name
     * @return array de usuarios de acuerso al role_id y el nombre del role
     */
    private function userForRole($role_id, $name)
    {

        $userTeamleaders = array();
        $userForRole = DB::table('user_has_roles')
            ->select('user_id')
            ->where('user_has_roles.user_id', '<>', Auth::user()->id)
            ->whereIn('user_has_roles.role_id', (DB::table('roles')->select('id')->where('id', '=', $role_id)->where('name', '=', $name)))->get();

        foreach ($userForRole as $key => $value) {

            array_push($userTeamleaders, $value->user_id);
        }

        return $userTeamleaders;
    }


    public function showInPipeline($taskId, $pipelineId)
    {


    }


    /**
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function assignPipeline(Request $request)
    {
//  todo event notificar
        $task = Task::find($request->taskId);
        $pipeline = Pipeline::find($request->pipeline_assign);

        $unit_id = $pipeline->unitsByRevision($pipeline->latestRevision)->first()->id;

        $task->unit_id = $unit_id;
        $task->pipelineRevision = $pipeline->latestRevision;
        $task->type = $pipeline->slug;

        DB::table('task_pipeline')->where('task_id', $task->id)->update(['pipeline_id' => $pipeline->id]);

        $task->save();

        return redirect()->back()->with('message', 'Tarea Publicada!');
    }


    /**
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function publishDraft(Request $request)
    {


        $task = Task::find($request->id);


        $pipeline = Pipeline::find($task->pipeline->first()->id);
        $unit_id = $pipeline->unitsByRevision($pipeline->latestRevision)->first()->id;

        $task->unit_id = $unit_id;
        $task->pipelineRevision = $pipeline->latestRevision;
        $task->type = $pipeline->slug;
        $task->save();
        return redirect()->back()->with('message', 'Tarea Publicada!');
    }


    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateStatus(Request $request)
    {

        $task = Task::find($request->id);

        if ($task->status_id != $request->status_id) {

            $task->status_id = $request->status_id;
            $task->save();

            event(new TaskStatusChange($task, $request->status_id));

            return response()->json(['success' => 'success', 200]);
        }
    }


    /**
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function moveTaskToUnit(Request $request)
    {
        // todo event notificar


        $task = Task::find($request->task_id);
        $task->unit_id = $request->to_unit;

        $toUnit = Unit::find($task->unit_id);
        $fromUnit = Unit::find($request->from_unit);


        $task->save();


        $comment = new Comment();

        $comment->user_id = Auth::user()->id;

        $comment->content_type = 'App\\Task';
        $comment->content_id = $request->task_id;
        $comment->unit_id = $request->to_unit;
//@formater:off
        $comment->comment = $fromUnit->name . '{' . $fromUnit->slug . ' unit-element}  

to{unit-comment unit-element}

' . $toUnit->name . '{' . $toUnit->slug . ' unit-element}

' . $request->add_content;


//@formater:on

        $comment->save();

        $comment = new Comment();

        $comment->user_id = Auth::user()->id;

        $comment->content_type = 'App\\Task';
        $comment->content_id = $request->task_id;
        $comment->unit_id = $request->from_unit;
//@formater:off
        $comment->comment = $fromUnit->name . '{' . $fromUnit->slug . ' unit-element}  

to{unit-comment unit-element}

' . $toUnit->name . '{' . $toUnit->slug . ' unit-element}

';


//@formater:on

        $comment->save();
        event(new CommentWasPosted($comment));

        $this->userAutotagInTask((int)$task->unit_id, $task->pipeline->first()->id, $task->profile_id,$task->id);

        return \redirect('/tasks/' . $request->task_id . '/unit/' . $request->unit_id . '/show')->with('status', 'Tarea enviada a la unidad ' . $toUnit->name . '!');;
    }


    /**
     * @param FormBuilder $formBuilder
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create(FormBuilder $formBuilder)
    {
        $form = $formBuilder->create(\App\Forms\TaskForm::class, [
            'method' => 'POST',
            'url' => route('task.store')
        ]);

        return view('task.create', compact('form'));
    }


    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function createSelector()
    {


        $pipelines = Pipeline::all();

//        $forms = TaskForm::all(['id', 'name', 'slug', 'description', 'public', 'order', 'created_at', 'updated_at']);
        $forms = TaskForm::orderBy('order', 'asc')->get();

        return view('task.client.createtaskselector', array(
            'pipelines' => $pipelines,
            'forms' => $forms,
        ));
    }


    /**
     * @param FormBuilder $formBuilder
     * @return $this
     */
    public function store(FormBuilder $formBuilder)
    {
        $form = $formBuilder->create(\App\Forms\TaskForm::class);

        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }

    }


    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function createFormWeb()
    {


//        $profiles = Profile::where('user_id', '=', Auth::user()->id)
//            ->where('status', '=', '1')->get();

        if (Auth::user()->hasRole('supervisor') || Auth::user()->hasRole('administrador') || Auth::user()->hasRole('teamleader')) {
            $profiles = Profile::all();
        } else {
            $profiles = Auth::user()->profiles;
        }

        if (count(Auth::user()->profiles) == 0) {
            return Redirect::to(URL::to('/profile/create/web_create'));
        }
        return view('task.create', array(
                'type' => 'web_create',
                'profiles' => $profiles,

            )
        );


    }


    /**
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function editFormWeb($id)
    {


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

//        $profiles = Profile::where('user_id', '=', Auth::user()->id)
//            ->where('status', '=', '1')->get();

        if (Auth::user()->hasRole('supervisor') || Auth::user()->hasRole('administrador') || Auth::user()->hasRole('teamleader')) {
            $profiles = Profile::all();
        } else {
            $profiles = Auth::user()->profiles;
        }

        if (count(Auth::user()->profiles) == 0) {
            return Redirect::to(URL::to('/profile/create/web'));
        }


        return view('task.create', array(
                'task' => $task,
                'type' => 'web_edit',
                'profiles' => $profiles,
            )
        );


    }


//    private function createTaskdata($request, $pipeline)
//    {
//
//        $taskdata = new Taskdata();
//        $taskdata->title = $request->title; //agrega titulo a la tarea en tabla taskdata ***
//        $taskdata->description = $request->description;
//        $taskdata->web_link = $request->web_link;
//
////        if ($request->event_deadline) {
////            $deadline = DateTime::createFromFormat('d/m/Y', $request->web_deadline)->format('Y-m-d');
////            $taskdata->deadline = $deadline;
////        }
//        $taskdata->save();
//
//        $status = Status::where('slug', '=', 'open')->where('status_type', '=', 'task')->get();
//        $task = new Task();
//        $task->profile_id = $request->profile_id;
//        $task->title = $request->title;    //agrega titulo a la tarea ***
//        $task->user_id = Auth::user()->id;
//        $task->status_id = $status->first()->id;
//        $task->type = 'web';
//
////        if ($taskdata->deadline != null) {
////            $task->deadline = $taskdata->deadline; //***
////        }
//        $task->taskdata_id = $taskdata->id;
//
//
//        if ($request->draft == null) {
//
//            $task->unit_id = $pipeline->unitsByRevision($pipeline->latestRevision)->first()->id;
//            $task->pipelineRevision = $pipeline->latestRevision;
//        }
//
//
//        $task->save();
//
//        return $task;
//
//    }

    /**
     * @param StoreFormWeb $request
     * @return \Illuminate\Http\RedirectResponse
     **/
    public function storeFormWeb(StoreFormWeb $request)
    {


        $pipelines = Pipeline::where('slug', '=', 'web')->get();


        foreach ($pipelines as $pipeline) {

            $profile = Profile::find($request->profile_id);
            $area = $profile->area;


            $taskdata = new Taskdata();
            $taskdata->title = $request->title; //agrega titulo a la tarea en tabla taskdata ***
            $taskdata->description = $request->description;
            $taskdata->web_link = $request->web_link;

//            if ($request->web_deadline) {
//                $deadline = DateTime::createFromFormat('d/m/Y', $request->web_deadline)->format('Y-m-d');
//
//                $taskdata->deadline = $deadline;
//            }
            $taskdata->save();

            $status = Status::where('slug', '=', 'open')->where('status_type', '=', 'task')->get();
            $task = new Task();
            $task->profile_id = $request->profile_id;
            $task->title = $request->title;    //agrega titulo a la tarea ***

//            if ($taskdata->deadline != null) {
//                $task->deadline = $taskdata->deadline; //***
//            }
            $task->user_id = Auth::user()->id;
            $task->status_id = $status->first()->id;
            $task->type = 'web';
            $task->taskdata_id = $taskdata->id;


            if ($request->draft == null) {

                $task->unit_id = $pipeline->unitsByRevision($pipeline->latestRevision)->first()->id;
                $task->pipelineRevision = $pipeline->latestRevision;
            }


            $task->save();


            $query = DB::table('task_pipeline')->insert(
                ['task_id' => $task->id, 'pipeline_id' => $pipeline->id]
            );


            $this->setJsonAttach($task->id, $request->jsonIdAttachments);

            if ($request->draft == null) {

                event(new CreateTask($task));

                $this->userAutotagInTask($task->unit_id, $pipeline->id, $profile->id, $task->id);
            }
        }

//        return redirect()->route('redirectHome');
        return redirect()->route('redirectHome',['t'=>$task->id,'u'=>$task->unit_id])->with('task', 'Tarea Creada!!');



    }

    /**
     * @param $unit_id
     * @param $pipeline_id
     * @param $task_id
     * etiqueta a usuarios que estan en la unidad y pipeline de la tarea
     */
    public function userAutotagInTask($unit_id, $pipeline_id,$profile_id, $task_id)
    {

        $user_autoTag = DB::table('user_autotag')->select('user_id')->where('unit_id', '=', $unit_id)->where('pipeline_id', '=', $pipeline_id)->orWhere('profile_id', $profile_id)->get();

//        dd($user_autoTag);
        foreach ($user_autoTag as $key => $value) {

            $exists = Tasktag::where('user_id', $value->user_id)->where('relation_id', $task_id)->where('type', 'task')->where('unit_id', $unit_id)->get();

            if (count($exists) == 0) {

                $tasktag = new Tasktag(); //creo un nuevo Tasktag
                $tasktag->relation_id = $task_id; //id de tarea
                $tasktag->user_id = $value->user_id; //id usuario etiquetado
                $tasktag->unit_id = $unit_id;
                $tasktag->type = 'task';
                $tasktag->save();

                event(new CreateTags($tasktag));

            }
        }

    }


    /**
     * @param UpdateFormWeb $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function updateFormWeb(UpdateFormWeb $request)
    {


        $pipelines = Pipeline::where('slug', '=', 'web')->get();

        foreach ($pipelines as $pipeline) {


            $profile = Profile::find($request->profile_id);
            $area = $profile->area;

            $task = Task::find($request->id);
            $taskdata = Taskdata::find($task->taskdata_id);

            $task->profile_id = $request->profile_id;
            $task->title = $request->title;//agrega titulo a la tarea ***
            $task->type = 'web';

            $taskdata->title = $request->title; //agrega titulo a la tarea en la tabla taskdata  ***
            $taskdata->description = $request->description;
            $taskdata->web_link = $request->web_link;

//            if ($request->web_deadline) {
//
//
//                //   si viene en - cambiar /
//
//                $pos = strpos($request->web_deadline, "-");
//
//                if ($pos === false) {
//
//                    $requestDeadline = $request->web_deadline;
//
//                } else {
//
//                    $requestDeadline = str_replace("-", "/", $request->web_deadline);
//
//                }
//
//
//                $deadline = DateTime::createFromFormat('d/m/Y', $requestDeadline)->format('Y-m-d');
//                $taskdata->deadline = $deadline;
//                $task->deadline = $taskdata->deadline; //***
//            }

            if ($request->draft == null) {

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

            }


            $task->save();
            $taskdata->save();


            $this->setJsonAttach($task->id, $request->jsonIdAttachments);

        }

        if ($request->draft == null) {

            event(new CreateTask($task));

            $this->userAutotagInTask($task->unit->id, $pipeline->id,$profile->id, $task->id);
        }


        if ($request->draft != null) {

            return redirect()->back()->with('message', 'Tarea Actualizada!');
        } else {
            //return redirect()->action('TaskController@clientHome');
            return redirect()->route('redirectHome');

        }
    }


    /**
     * post: elimina tarea guardada como borrador del formulario Web
     */
    public function deleteFormWeb(Request $request)
    {

        $task = Task::find($request->id);
        $web = Taskdata::destroy($task->taskdata_id);

        $task_pipeline = DB::table('task_pipeline')->where('task_id', '=', $task->id)->delete();


        //return redirect()->action('TaskController@clientHome')->with('message', 'Tarea eliminada');
        return redirect()->route('redirectHome')->with('message', 'Tarea eliminada');


    }


    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function createFormEvent()
    {

//        $profiles = Profile::where('user_id', '=', Auth::user()->id)
//            ->where('status', '=', '1')->get();

        if (Auth::user()->hasRole('supervisor') || Auth::user()->hasRole('administrador') || Auth::user()->hasRole('teamleader')) {
            $profiles = Profile::all();
        } else {
            $profiles = Auth::user()->profiles;
        }

        $pipelines = Pipeline::orderBy('hidden')->get();

        if (count(Auth::user()->profiles) == 0) {
            return Redirect::to(URL::to('/profile/create/event_create'));
        }

        return view('task.create', array(
                'type' => 'event_create',
                'profiles' => $profiles,
                'pipelines' => $pipelines,

            )
        );
    }


    /**
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function editFormEvent($id)
    {
        $task = Task::find($id);

//        $profiles = Profile::where('user_id', '=', Auth::user()->id)
//            ->where('status', '=', '1')->get();

        if (Auth::user()->hasRole('supervisor') || Auth::user()->hasRole('administrador') || Auth::user()->hasRole('teamleader')) {
            $profiles = Profile::all();
        } else {
            $profiles = Auth::user()->profiles;
        }
        $pipelines = Pipeline::all();


        if (count(Auth::user()->profiles) == 0) {
            return Redirect::to(URL::to('/profile/create/event'));
        }


        return view('task.create', array(
                'task' => $task,
                'type' => 'event_edit',
                'profiles' => $profiles,
                'pipelines' => $pipelines,

            )
        );

    }

    /**
     * @param $request
     * @param $task
     * @return devuelve tasKdata creada
     */
    private function saveTaskdata($request)
    {


        $taskdata = new Taskdata();

        $taskdata->title = $request->title;

        $taskdata->description = $request->description;

        if ($request->type == 'evento' || $request->type == 'event') {
            if ($request->event_date_check == null) {
                $event_date = explode('/', $request->event_date);
                $taskdata->event_date_format = $event_date[2] . '-' . $event_date[1] . '-' . $event_date[0] . ' 00:00:00';
            }
        }

        $taskdata->event_time = $request->event_time;
        $taskdata->event_venue = $request->event_venue;
        $taskdata->event_is_paid = $request->event_is_paid;
        $taskdata->event_cost = $request->event_cost;
        $taskdata->event_contact_name = $request->event_contact_name;
        $taskdata->event_foundation = $request->event_foundation;
        $taskdata->event_contact_email = $request->event_contact_email;
        $taskdata->event_contact_tel = $request->event_contact_tel;
        $taskdata->event_web = $request->event_web;
        $taskdata->event_twitter = $request->event_twitter;
        $taskdata->event_facebook = $request->event_facebook;
        $taskdata->event_other = $request->event_other;
        $taskdata->event_is_paid = $request->event_is_paid;
        $taskdata->event_cost = $request->event_cost;
        $taskdata->event_disexp = $request->event_disexp;
        $taskdata->event_participants = $request->event_participants;
        $taskdata->event_coverage = $request->event_coverage;
        $taskdata->event_interest = $request->event_interest;
        $taskdata->event_interviewed = $request->event_interviewed;
        $taskdata->event_applicant = $request->event_applicant;
        $taskdata->name_activity = $request->name_activity;
        $taskdata->type_activity = $request->type_activity;
        $taskdata->event_language = $request->event_language;
        $taskdata->event_type_activity = $request->event_type_activity;

//        if ($request->event_deadline) {
//            $deadline = DateTime::createFromFormat('d/m/Y', $request->event_deadline)->format('Y-m-d');
//            $taskdata->deadline = $deadline;
//        }

        $taskdata->save();


        return $taskdata;

    }


    /**
     * @param $request
     * @param $task
     * @return devuelve tasKdata editada
     */

    private function editTaskdata($request, $task)
    {


        $taskdata = Taskdata::find($task->taskdata_id);
        //$taskdata->title = '(Borrador) Solicitud Novedades | ' . $area . '';
        $taskdata->title = $request->title;

        $taskdata->description = $request->description;
        $taskdata->event_date = $request->event_date;
        $taskdata->event_time = $request->event_time;
        $taskdata->event_venue = $request->event_venue;
        $taskdata->event_is_paid = $request->event_is_paid;
        $taskdata->event_cost = $request->event_cost;
        $taskdata->event_contact_name = $request->event_contact_name;
        $taskdata->event_foundation = $request->event_foundation;
        $taskdata->event_contact_email = $request->event_contact_email;
        $taskdata->event_contact_tel = $request->event_contact_tel;
        $taskdata->event_web = $request->event_web;
        $taskdata->event_twitter = $request->event_twitter;
        $taskdata->event_facebook = $request->event_facebook;
        $taskdata->event_other = $request->event_other;
        $taskdata->event_is_paid = $request->event_is_paid;
        $taskdata->event_cost = $request->event_cost;
        $taskdata->event_disexp = $request->event_disexp;
        $taskdata->event_participants = $request->event_participants;
        $taskdata->event_coverage = $request->event_coverage;
        $taskdata->event_interest = $request->event_interest;
        $taskdata->event_interviewed = $request->event_interviewed;
        $taskdata->event_applicant = $request->event_applicant;
        $taskdata->name_activity = $request->name_activity;
        $taskdata->type_activity = $request->type_activity;
        $taskdata->event_language = $request->event_language;
        $taskdata->event_type_activity = $request->event_type_activity;

//        if ($request->event_deadline) {
//
//            //   si viene en - cambiar /
//
//            $pos = strpos($request->event_deadline, "-");
//
//            if ($pos === false) {
//
//                $requestDeadline = $request->event_deadline;
//
//            } else {
//
//                $requestDeadline = str_replace("-", "/", $request->event_deadline);
//
//            }
//
//
//            $deadline = DateTime::createFromFormat('d/m/Y', $requestDeadline)->format('Y-m-d');
//            $taskdata->deadline = $deadline;
//        }

        $taskdata->save();

        return $taskdata;
    }

    /**
     * @param StoreFormEvent $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function storeFormEvent(StoreFormEvent $request)
    {

        if ($request->draft != null) {


            $status = Status::where('slug', '=', 'open')->where('status_type', '=', 'task')->get();


            $profile = Profile::find($request->profile_id);
            $area = $profile->area;

            $taskdata = $this->saveTaskdata($request);//guarda y crea y nuevo taskdata, devuelve el taskdata creado

            $task = new Task();
            $task->profile_id = $request->profile_id;
            $task->user_id = Auth::user()->id;
            $task->status_id = $status->first()->id;
            $task->taskdata_id = $taskdata->id;
            $task->type = 'event';
            $task->title = $request->title;

//            if ($taskdata->deadline != null) {
//                $task->deadline = $taskdata->deadline; //***
//            }
            $task->draft = true;//el usuario marca en borrador la tarea => draft =1 (guarda en la tabla tasks)

            $task->save();

            $this->setJsonAttach($task->id, $request->jsonIdAttachments);


        } else {


            $profile = Profile::find($request->profile_id);
            $area = $profile->area;

            $status = Status::where('slug', '=', 'open')->where('status_type', '=', 'task')->get();


//

            $taskdata = $this->saveTaskdata($request);//guarda y crea y nuevo taskdata, devuelve el taskdata creado


            if ($request->event_coverage != null) {

                foreach ($request->event_coverage as $c) {

                    $pipeline = Pipeline::find($c);


                    $task = new Task();
                    $task->profile_id = $request->profile_id;
                    $task->user_id = Auth::user()->id;
                    $task->title = $request->title; //****
                    $task->status_id = $status->first()->id;
                    $task->draft = null;
                    $task->type = 'event';
//
//                    if ($taskdata->deadline != null) {
//                        $task->deadline = $taskdata->deadline; //***
//                    }

                    $task->taskdata_id = $taskdata->id;

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

                    $task->title = $request->title;


                    $task->save();


                    $this->setJsonAttach($task->id, $request->jsonIdAttachments);


                    $query = DB::table('task_pipeline')->insert(
                        ['task_id' => $task->id, 'pipeline_id' => $pipeline->id]
                    );

                    $this->setJsonAttach($task->id, $request->jsonIdAttachments);


                    event(new CreateTask($task));
                    $this->userAutotagInTask($task->unit->id, $pipeline->id,$profile->id, $task->id);


                }
            }


        }


        if ($request->draft != null) {

            //return redirect()->action('TaskController@clientHome');
            return redirect()->route('redirectHome');
        } else {

            //return redirect()->action('TaskController@clientHome');
            return redirect()->route('redirectHome',['t'=>$task->id,'u'=>$task->unit_id])->with('task', 'Tarea Creada!!');


        }

    }


    /**
     * @param UpdateFormEvent $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function updateFormEvent(UpdateFormEvent $request)
    {

        if ($request->draft != null) {


            $status = Status::where('slug', '=', 'open')->where('status_type', '=', 'task')->get();


            $profile = Profile::find($request->profile_id);
            $area = $profile->area;

            $task = Task::find($request->id);


            $taskdata = $this->editTaskdata($request, $task);//edita el taskdata, devuelve el taskdata creado


            $task->profile_id = $request->profile_id;
            $task->user_id = Auth::user()->id;
            $task->status_id = $status->first()->id;
            $task->taskdata_id = $taskdata->id;
            $task->type = 'event';
            $task->title = $request->title;

//            if ($taskdata->deadline != null) {
//                $task->deadline = $taskdata->deadline; //***
//            }

            $task->draft = true;


            $task->save();


        } else {

            $profile = Profile::find($request->profile_id);
            $area = $profile->area;

            $status = Status::where('slug', '=', 'open')->where('status_type', '=', 'task')->get();
            $oldtask = Task::find($request->id);

            $taskdata = $this->editTaskdata($request, $oldtask); //edita el taskdata, devuelve el taskdata creado


            $attachTaske = DB::table('attach_task')
                ->select('attachment_id as id')
                ->where('task_id', '=', $request->id)
                ->where('active', '=', 1)
                ->get()->toArray();


            $attachTaskeelement = array();
            $jsonIdAttachments = null;

            if ($attachTaske) {

                foreach ($attachTaske as $key6 => $value6) {

                    array_push($attachTaskeelement, $value6);
                }

                $jsonIdAttachments = json_encode($attachTaskeelement);

            }


            foreach ($request->event_coverage as $c) {


                $pipeline = Pipeline::find($c);


                $task = new Task();
                $task->profile_id = $request->profile_id;
                $task->user_id = Auth::user()->id;
                $task->status_id = $status->first()->id;
                $task->draft = null;
                $task->type = 'event';

                $task->taskdata_id = $taskdata->id;

//                if ($taskdata->deadline != null) {
//                    $task->deadline = $taskdata->deadline; //***
//                }
                $task->unit_id = $pipeline->unitsByRevision($pipeline->latestRevision)->first()->id;
                $task->pipelineRevision = $pipeline->latestRevision;

                $task->title = $request->title;
//                $task->deadline = $taskdata->deadline;
                $task->draft = false;

                $task->save();


                $query = DB::table('task_pipeline')->insert(
                    ['task_id' => $task->id, 'pipeline_id' => $pipeline->id]
                );
                // event(new UpdateTask($task));

                $this->setJsonAttach($task->id, $jsonIdAttachments);


                event(new CreateTask($task));

                $this->userAutotagInTask($task->unit->id, $pipeline->id,$profile->id, $task->id);


            }

            $delete = Task::destroy($oldtask->id);


        }

        if ($request->draft != null) {

            return redirect()->back()->with('message', 'Tarea Actualizada!');
        } else {
            //return redirect()->action('TaskController@clientHome');
            return redirect()->route('redirectHome');

        }

    }


    /**
     * post: Elimina tarea guardada como borrador del formulario Other
     */
    public function deleteFormEvent(Request $request)
    {


        $task = Task::find($request->id);
        $event = Taskdata::destroy($task->taskdata_id);

        $task_pipeline = DB::table('task_pipeline')->where('task_id', '=', $task->id)->delete();


        //return redirect()->action('TaskController@clientHome')->with('message', 'Tarea eliminada');
        return redirect()->route('redirectHome')->with('message', 'Tarea eliminada');

    }


    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function createFormEmail()
    {

//        $profiles = Profile::where('user_id', '=', Auth::user()->id)
//            ->where('status', '=', '1')->get();

        if (Auth::user()->hasRole('supervisor') || Auth::user()->hasRole('administrador') || Auth::user()->hasRole('teamleader')) {
            $profiles = Profile::all();
        } else {
            $profiles = Auth::user()->profiles;
        }

        if (count(Auth::user()->profiles) == 0) {
            return Redirect::to(URL::to('/profile/create/email_create'));
        }

        return view('task.create', array(
                'profiles' => $profiles,
                'type' => 'email_create'
            )
        );


    }


    /**
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function editFormEmail($id)
    {
        $task = Task::find($id);

//        $profiles = Profile::where('user_id', '=', Auth::user()->id)
//            ->where('status', '=', '1')->get();

        if (Auth::user()->hasRole('supervisor') || Auth::user()->hasRole('administrador') || Auth::user()->hasRole('teamleader')) {
            $profiles = Profile::all();
        } else {
            $profiles = Auth::user()->profiles;
        }

        if (count(Auth::user()->profiles) == 0) {
            return Redirect::to(URL::to('/profile/create/email'));
        }


        return view('task.create', array(
                'task' => $task,
                'type' => 'email_edit',
                'profiles' => $profiles,
            )
        );

    }


    /**
     * @param StoreFormEmail $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function storeFormEmail(StoreFormEmail $request)
    {
        $pipeline = Pipeline::where('slug', '=', 'email')->first();
//        foreach ($pipelines as $pipeline) {

            $profile = Profile::find($request->profile_id);
            $area = $profile->area;
            $taskdata = new Taskdata();
            $taskdata->title = 'Solicitud Email Institucional | ' . $area . '';
            if ($request->email_request == 'registration'){
                $taskdata->email_name = $request->name;
                $taskdata->email_surname = $request->surname;
                $taskdata->email_personalemail = $request->personalemail;
                $taskdata->email_observation = $request->observation;
            } elseif ($request->email_request == 'laundering'){
                $taskdata->email_name_clean = $request->name_clean;
                $taskdata->email_personalemail = $request->personalemail;
            } else {
                $taskdata->email_deleteemail = $request->deleteemail;
                $taskdata->email_description = $request->description;
            }

            $taskdata->email_request = $request->email_request;
            $taskdata->save();

            $status = Status::where('slug', '=', 'open')->where('status_type', '=', 'task')->get();
            $task = new Task();
            $task->profile_id = $request->profile_id;
            $task->user_id = Auth::user()->id;
            $task->status_id = $status->first()->id;
            $task->title = 'Solicitud Email Institucional | ' . $area . ''; //****
            $task->type = 'email';
            $task->taskdata_id = $taskdata->id;

            if ($request->draft == null) {

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

            }

            $task->save();
            $query = DB::table('task_pipeline')->insert(
                ['task_id' => $task->id, 'pipeline_id' => $pipeline->id]
            );

            if ($request->draft == null) {
                event(new CreateTask($task));
                $this->userAutotagInTask($task->unit_id, $pipeline->id,$profile->id, $task->id);
            }

//        }
        return redirect()->route('redirectHome');
//        return redirect()->route('redirectHome',['t'=>$task->id,'u'=>$task->unit_id])->with('task', 'Tarea Creada!!');
    }


    /**
     * @param UpdateFormEmail $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function updateFormEmail(UpdateFormEmail $request)
    {
        $pipelines = Pipeline::where('slug', '=', 'email')->get();

        foreach ($pipelines as $pipeline) {


            $profile = Profile::find($request->profile_id);
            $area = $profile->area;

            $task = Task::find($request->id);
            $taskdata = Taskdata::find($task->taskdata_id);

            $task->profile_id = $request->profile_id;
            $task->type = 'email';

            $taskdata->title = 'Solicitud Email Institucional| ' . $area . '';
            $taskdata->email_name = $request->email_name;
            $taskdata->email_surname = $request->email_surname;
            $taskdata->email_personalemail = $request->email_personalemail;
            $taskdata->description = $request->description;
            $taskdata->email_request = $request->email_request;


//            if ($request->email_deadline) {
//
//
//                $pos = strpos($request->email_deadline, "-");
//
//                if ($pos === false) {
//
//                    $requestDeadline = $request->email_deadline;
//
//                } else {
//
//                    $requestDeadline = str_replace("-", "/", $request->email_deadline);
//
//                }
//
//
//                $deadline = DateTime::createFromFormat('d/m/Y', $requestDeadline)->format('Y-m-d');
//                $taskdata->deadline = $deadline;
//
//                $task->deadline = $taskdata->deadline; //***
//
//            }


            if ($request->draft == null) {

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

            }


            $task->save();
            $taskdata->save();

            $this->setJsonAttach($task->id, $request->jsonIdAttachments);

            /*
            $attachmentsIds = json_decode($request->jsonIdAttachments);
            if ($attachmentsIds) {
                foreach ($attachmentsIds as $attachment) {
                    $attach = Attachment::find($attachment->id);
                    $attach->task_id = $task->id;
                    $attach->save();
                }
            }
            */


        }

        if ($request->draft == null) {

            event(new CreateTask($task));

            $this->userAutotagInTask($task->unit->id, $pipeline->id, $profile->id, $task->id);
        }

        if ($request->draft != null) {

            return redirect()->back()->with('message', 'Tarea Actualizada!');
        } else {
            //return redirect()->action('TaskController@clientHome');
            return redirect()->route('redirectHome');

        }

    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     *
     */
    public function deleteFormEmail(Request $request)
    {


        $task = Task::find($request->id);
        $email = Taskdata::destroy($task->taskdata_id);

        $task_pipeline = DB::table('task_pipeline')->where('task_id', '=', $task->id)->delete();


        //return redirect()->action('TaskController@clientHome')->with('message', 'Email eliminado');
        return redirect()->route('redirectHome')->with('message', 'Email eliminado');

    }


    /**
     *  CODIGO OTHER
     *
     */
    public function createFormOther()
    {
//        $profiles = Profile::where('user_id', '=', Auth::user()->id)
//            ->where('status', '=', '1')->get();

        if (Auth::user()->hasRole('supervisor') || Auth::user()->hasRole('administrador') || Auth::user()->hasRole('teamleader')) {
            $profiles = Profile::all();
        } else {
            $profiles = Auth::user()->profiles;
        }

        if (count(Auth::user()->profiles) == 0) {
            return Redirect::to(URL::to('/profile/create/other_create'));
        }

        return view('task.create', array(
                'profiles' => $profiles,
                'type' => 'other_create'
            )
        );

    }


    /**
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function editFormOther($id)
    {
        $task = Task::find($id);

//        $profiles = Profile::where('user_id', '=', Auth::user()->id)
//            ->where('status', '=', '1')->get();

        if (Auth::user()->hasRole('supervisor') || Auth::user()->hasRole('administrador') || Auth::user()->hasRole('teamleader')) {
            $profiles = Profile::all();
        } else {
            $profiles = Auth::user()->profiles;
        }

        if (count(Auth::user()->profiles) == 0) {
            return Redirect::to(URL::to('/profile/create/web'));
        }


        return view('task.create', array(
                'task' => $task,
                'type' => 'other_edit',
                'profiles' => $profiles,
            )
        );

    }


    /**
     * @param StoreFormOther $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function storeFormOther(StoreFormOther $request)
    {


        $pipelines = Pipeline::where('slug', '=', 'otros')->get();


        foreach ($pipelines as $pipeline) {


            $profile = Profile::find($request->profile_id);
            $area = $profile->area;


            $taskdata = new Taskdata();
            $taskdata->title = $request->title;
            $taskdata->description = $request->description;
            $taskdata->web_link = $request->web_link;

//            if ($request->other_deadline) {
//                $deadline = DateTime::createFromFormat('d/m/Y', $request->other_deadline)->format('Y-m-d');
//                $taskdata->deadline = $deadline;
//            }
            $taskdata->save();

            $status = Status::where('slug', '=', 'open')->where('status_type', '=', 'task')->get();
            $task = new Task();
            $task->profile_id = $request->profile_id;
            $task->user_id = Auth::user()->id;
            $task->status_id = $status->first()->id;
            $task->type = 'other';
            $task->title = $request->title;
            $task->taskdata_id = $taskdata->id;
//
//            if ($taskdata->deadline != null) {
//                $task->deadline = $taskdata->deadline; //***
//            }


            if ($request->draft == null) {

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

            }


            $task->save();


            /*
            $attachmentsIds = json_decode($request->jsonIdAttachments);

            if ($attachmentsIds) {
                foreach ($attachmentsIds as $attachment) {

                $query = DB::table('attach_task')->insert(
                            ['attachment_id' => $attachment->id, 'task_id' => $task->id]);

                }
            }
            */
            $query = DB::table('task_pipeline')->insert(
                ['task_id' => $task->id, 'pipeline_id' => $pipeline->id]
            );


            $this->setJsonAttach($task->id, $request->jsonIdAttachments);


            if (!$request->draft) {

                //Create event
                event(new CreateTask($task));

                $this->userAutotagInTask($task->unit_id, $pipeline->id, $profile->id, $task->id);
            }
//

        }

        //return redirect()->action('TaskController@clientHome');
//        return redirect()->route('redirectHome');
        return redirect()->route('redirectHome',['t'=>$task->id,'u'=>$task->unit_id])->with('task', 'Tarea Creada!!');



    }


    /**
     * @param UpdateFormOther $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function updateFormOther(UpdateFormOther $request)
    {

        $pipelines = Pipeline::where('slug', '=', 'otros')->get();

        foreach ($pipelines as $pipeline) {


            $profile = Profile::find($request->profile_id);
            $area = $profile->area;

            $task = Task::find($request->id);
            $taskdata = Taskdata::find($task->taskdata_id);

            $task->profile_id = $request->profile_id;
            $task->type = 'other';

            $taskdata->title = $request->title;
            $taskdata->description = $request->description;

//            if ($request->other_deadline) {
//
//
//                $pos = strpos($request->other_deadline, "-");
//
//                if ($pos === false) {
//
//                    $requestDeadline = $request->other_deadline;
//
//                } else {
//
//                    $requestDeadline = str_replace("-", "/", $request->other_deadline);
//
//                }
//
//
//                $deadline = DateTime::createFromFormat('d/m/Y', $requestDeadline)->format('Y-m-d');
//                $taskdata->deadline = $deadline;
//                $task->deadline = $taskdata->deadline; //***
//            }

            if ($request->draft == null) {

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

            }

            $task->save();
            $taskdata->save();


            $this->setJsonAttach($task->id, $request->jsonIdAttachments);


            /*
            $attachmentsIds = json_decode($request->jsonIdAttachments);
            if ($attachmentsIds) {

                foreach ($attachmentsIds as $attachment) {
                    $attach = Attachment::find($attachment->id);
                    $attach->task_id = $task->id;
                    $attach->save();
                }

            }
            */
        }
        if ($request->draft == null) {

            event(new CreateTask($task));

            $this->userAutotagInTask($task->unit->id, $pipeline->id,$profile->id, $task->id);
        }


        if ($request->draft != null) {

            return redirect()->back()->with('message', 'Tarea Actualizada!');
        } else {
//            return redirect()->action('TaskController@clientHome');
            return redirect()->route('redirectHome');

        }
    }


    /**
     * post: Elimina tarea guardada como borrador del formulario Other
     */
    public function deleteFormOther(Request $request)
    {


        $task = Task::find($request->id);
        $other = Taskdata::destroy($task->taskdata_id);

        $task_pipeline = DB::table('task_pipeline')->where('task_id', '=', $task->id)->delete();


        //return redirect()->action('TaskController@clientHome')->with('message', 'Tarea eliminada');
        return redirect()->route('redirectHome')->with('message', 'Tarea eliminada');

    }


    /**
     * *post:si exite perfil ->retorna un arreglo con pipelines,unit, profiles,
     * si los valores de las variables que se pasan por parametro tienen valor diferente a NUll
     * crea una tarea relacionada a la tarea original cuyos id y unit_id  se pasan por parametro
     * @param null $profile_id
     * @param null $taskdata_id
     * @param null $task_id
     * @param null $unit_id
     * @return si la tarea es creada desde panel de control => retorna al panel de control
     * si es creada desde la tarea => retorna a la tarea padre
     *
     */
    public function createTaskTL($profile_id = null, $taskdata_id = null, $task_id = null, $unit_id = null)
    {

//        $profiles = Profile::where('status', '<>', '0')->get();//perfiles donde estatus != 0 (inactivo)

        if (Auth::user()->hasRole('supervisor') || Auth::user()->hasRole('administrador') || Auth::user()->hasRole('teamleader')) {
            $profiles = Profile::all();
        } else {
            $profiles = Auth::user()->profiles;
        }

        $pipelines = Pipeline::all();
        $units = Unit::all();

        $data = array(
            'pipelines' => $pipelines,
            'units' => $units,
            'profiles' => $profiles,
            'profile' => null,
            'taskdata' => null,
            'taskId' => null,
            'unitId' => null
        );

        if ($profile_id != null) {

            $data['profile'] = Profile::find($profile_id);
            $data['taskdata'] = Taskdata::find($taskdata_id);
            $data['taskId'] = $task_id;
            $data['unitId'] = $unit_id;
        }

        if (count(Auth::user()->profiles) == 0) {
//            return Redirect::to(URL::to('/profile/create/other'));
        }
        return view('task.createTaskTeamLeader', $data);

    }


    /**
     *pre: recibe datos del formulario crear tarea(cliente)
     *post:crea una nueva taskdata y tarea relacionada a la tarea original
     * return: a panel de tareas ,si la tarea es creada desde otra tarea => retorna a la tarea original
     */
    public function storeFormTeamLeader(StoreFormTeamLeader $request)
    {


        $pipeline = Pipeline::where('id', '=', $request->pipeline)->first();
        $profile = Profile::find($request->profile_id);

        if ($request->taskdataid && $request->taskdataid == 999999) {

            $taskdata = new Taskdata();

            $taskdata->description = $request->description;
//            $deadline = DateTime::createFromFormat('d/m/Y', $request->deadline)->format('Y-m-d');
//            $taskdata->deadline = $deadline;

            if ($request->title) {
                $taskdata->title = $request->title;
            }
            $taskdata->save();
            $storeTaskdata = $taskdata->id;

        } else {
            $taskdata = Taskdata::find($request->taskdataid);
            $storeTaskdata = $request->taskdataid;
        }

        $status = Status::where('slug', '=', 'open')->where('status_type', '=', 'task')->get();

        $task = new Task();
        $task->profile_id = $request->profile_id;
        $task->user_id = Auth::user()->id;
        $task->status_id = $status->first()->id;
        $task->type = $pipeline->unitsByRevision($pipeline->latestRevision)->first()->slug;
        $task->title = $request->title;//****

//        if ($taskdata->deadline != null) {
//            $task->deadline = $taskdata->deadline; //***
//        }

        $task->taskdata_id = $taskdata->id;


        $task->unit_id = $pipeline->unitsByRevision($pipeline->latestRevision)->first()->id;
        $task->pipelineRevision = $pipeline->latestRevision;
        $task->save();

        $query = DB::table('task_pipeline')->insert(
            ['task_id' => $task->id, 'pipeline_id' => $request->pipeline]);

        $this->setJsonAttach($task->id, $request->jsonIdAttachments);

        event(new CreateTask($task));

        $this->userAutotagInTask($task->unit_id, $request->pipeline,$profile->id, $task->id);


        if ($request->related_task != null) { //si la 'tarea relacionada' es creada desde la tarea ,regresa a la tarea

            return \redirect('/tasks/' . $request->related_task . '/unit/' . $request->related_unit . '/show')->with('message', 'Tarea relaciona creada');

        } else { //si no es así ,regresa al panel de tareas

            return redirect()->action('TaskController@index')->with('message', 'Tarea creada');
        }
    }


    /**
     * pre:recibe por parametro datos de la tarea editada
     * post: se realizan los cambios en la tarea,
     * return: mesaje y muestra panel de tareas.
     */

    public function editTaskTL(Request $request)
    {

        $task = Task::find($request->id);
        $task->title = $request->title;
        $task->description = $request->description;

        if ($request->edit_deadline) {
            $dat = str_replace('/', '-', $request->edit_deadline);
            $taskdata = Taskdata::find($task->taskdata_id);

            $taskdata->deadline = date('Y-m-d', strtotime($dat));
            $task->deadline = $taskdata->deadline; //***
            $taskdata->save();
        }

        $task->save();

        $comment = new Comment();
        $comment->user_id = Auth::user()->id;
        $comment->content_type = 'App\\Task';
        $comment->content_id = $request->id;
        $comment->unit_id = $task->unit_id;
        $comment->comment =
            'Fecha: '.date('d-m-Y').
            ' Hora: '.date('H:i').
            ' El usuario '.Auth::user()->name. ' editó la información de la tarea';
        $comment->save();

        event(new CreateTask($task));
//        $this->userAutotagInTask($task->unit_id,$pipelines->id,$task->id);

        return redirect()->back()->with('message', 'Tarea Editada.');

    }


    /**
     * pre:recibe por parametro id de tarea y json de ids
     * post: se insertan en tabla pivot attach_task
     * return: void
     */
    public function setJsonAttach($id, $data)
    {


        $attachmentsIds = json_decode($data);


        if ($attachmentsIds) {

            foreach ($attachmentsIds as $attachment) {

                $query = DB::table('attach_task')->insert(['attachment_id' => $attachment->id, 'task_id' => $id]);


            }

        }

    }


    public function getAttachTask(Request $request)
    {


        if ($request->subtask_id) {

            $AttachbyTask = DB::table('attach_task')
                ->join('attachments', 'attach_task.attachment_id', '=', 'attachments.id')
                ->select('attachments.id', 'attachments.original_name', 'attachments.filename', 'attachments.created_at')
                ->where('attach_task.task_id', '=', $request->task_id)
                ->where('attach_task.active', '=', "1")
                ->whereNotIn('attach_task.attachment_id', (DB::table('attach_subtask')->select('attachment_id')->where('subtask_id', '=', $request->subtask_id)->
                where('active', '=', '1')))
                ->get()->toArray();


            $return = $AttachbyTask ? $AttachbyTask : null;

        } else {

            $AttachbyTask = DB::table('attach_task')
                ->join('attachments', 'attach_task.attachment_id', '=', 'attachments.id')
                ->select('attachments.id', 'attachments.original_name', 'attachments.filename', 'attachments.created_at')
                ->where('attach_task.task_id', '=', $request->task_id)
                ->where('attach_task.active', '=', "1")
                ->get()->toArray();

            $return = $AttachbyTask ? $AttachbyTask : null;

        }


        $delivered = null;


        if ((!empty($request->getdelivered)) AND ($request->getdelivered == 'true')) {

            $Attachdelivered = DB::table('attach_task')
                ->join('attachments', 'attach_task.attachment_id', '=', 'attachments.id')
                ->select('attachments.*')
                ->where('attach_task.task_id', '=', $request->task_id)
                ->where('attach_task.active', '=', "1")
                ->where('attachments.delivered', '=', "1")
                ->get()->toArray();

            $delivered = $Attachdelivered ? $Attachdelivered : null;

        }

        echo json_encode(array("attachs" => $return, "delivered" => $delivered));

    }


    /**
     * pre:recibe el id de la tarea para buscar archivos adjuntados
     * return: zip de archivos
     */
    public function taskDownload($id)
    {


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

        $public_dir = public_path();


        if ($task->attachments) {

            foreach ($task->attachments as $key => $value) {

                if ($value->pivot->active == "0" || $value->pivot->delivered_final == 0) {

                    unset($task->attachments[$key]);

                }

            }


        } else {

            return redirect()->back()->with('message', 'Sin archivos para descargar.');

        }


        // $task->attachments = array_keys($task->attachments->toArray());

        if (count($task->attachments) == 1) {

            $headers = array(
                'Content-Type' => 'application/octet-stream',
            );


            foreach ($task->attachments as $p) {

                return response()->download(public_path('/uploads/' . $p->filename), $p->original_name, $headers);

            }


        } elseif (count($task->attachments) > 1) {

            $zipFileName = 'Task' . $id . 'Attach' . time() . '.zip';

            $zip = new ZipArchive();


            if ($zip->open($public_dir . '/' . $zipFileName, ZipArchive::CREATE) === TRUE) {
                // Add File in ZipArchive

                foreach ($task->attachments as $g) {

                    $zip->addFile(public_path('/uploads/' . $g->filename), $g->original_name);

                }

                // Close ZipArchive
                $zip->close();
            }

            $headers = array(
                'Content-Type' => 'application/octet-stream',
            );
            $filetopath = $public_dir . '/' . $zipFileName;
            // Create Download Response
            if (file_exists($filetopath)) {

                //  return response()->download($filetopath,$zipFileName,$headers);

                $response = response()->download($filetopath, $zipFileName, $headers);
                $response->deleteFileAfterSend(true);

                return $response;

            }


        } else {

            return redirect()->back()->with('message', 'Sin archivos para descargar.');

        }


    }


    /**
     * @param Request $request
     * cambia el deadline de la tarea creada  vista (task.show)
     */
    public function changeDeadline(Request $request)
    {
        if ($request->all()) {

            $task = Task::find($request->taskid);
            $dat = str_replace('/', '-', $request->deadline);
            $taskdata = Taskdata::find($task->taskdata->id);


            $taskdata->deadline = date('Y-m-d', strtotime($dat));
            if ($taskdata->deadline != null) {
                $task->deadline = $taskdata->deadline; //***
            }

            $taskdata->save();
            $task->save();
        }

        return response()->json([
            'deadline' => $dat,
        ]);
    }


    public function getOldAttach(Request $request)
    {


        if ($request->attachid) {

            $idAttach = array();

            foreach ($request->attachid as $key => $value) {

                array_push($idAttach, $value['id']);

            }

            $getOld = Attachment::whereIn('id', $idAttach)->get();

            echo json_encode(array("status" => "ok", "data" => $getOld));

        }

    }


    public function deleteAttachtask(Request $request)
    {

        //  Inserto el comentario

        $comment                = new Comment();
        $comment->user_id       = Auth::user()->id;
        $comment->content_type  = 'App\\Task';
        $comment->content_id    = $request->task_id;
        $comment->unit_id       = $request->unit_id;
        $message                = ($request->activate=="true")?" ACTIVADO ":" ELIMINADO ";
        $rc                     = !empty($request->comment)?$request->comment:" -";
        $comment->comment       = 'El archivo "'.$request->name.'" fue '.$message.' - Motivo: '.$rc; 

        $comment->save();

        event(new CommentWasPosted($comment));

        //   archivo eliminado y que fue entregado, si se libero no tiene relacion,

        //  Activo el attachment

        if ($request['activate'] == "true") {

            DB::table('attach_task')->where('task_id', '=', $request['task'])->where('attachment_id', '=', $request['attachitem'])->update(['active' => 1]);

            DB::table('attach_subtask')->where('attachment_id', '=', $request['attachitem'])->update(['active' => 1]);

            echo json_encode(array("status" => "ok"));
            exit;
        }


        //  si es herededo   activate "true"

        if (DB::table('attach_task')->where('task_id', '=', $request['task'])->where('attachment_id', '=', $request['attachitem'])->update(['active' => 0])) {


            if (!$request->deleteall) { // si fue asignado en alguna subtarea fue habilitado de vuelta

                DB::table('attach_subtask')->where('attachment_id', '=', $request['attachitem'])->update(['active' => 0]);

            } else { // borro un archivo que fue entregado

                DB::table('attachments')->where('id', '=', $request['attachitem'])->update(['delivered' => 0]);
            }

            echo json_encode(array("status" => "ok"));

        }


    }

    public function deliverAttachtask(Request $request)
    {



            DB::table('attach_task')->where('task_id', '=', $request['task'])->where('attachment_id', '=', $request['attachitem'])->update(['delivered_final' => 1]);

            echo json_encode(array("status" => "ok"));
            exit;


    }


    public function downloadFile($id)
    {
        $attachment = Attachment::find($id);
        $headers = array(
            'Content-Type' => 'application/octet-stream',
        );
        return response()->download(public_path('/uploads/' . $attachment->filename), $attachment->original_name, $headers);
    }


    public function storeFormCoverage(StoreFormCoverage $request) // $request viene desde tarea pre-ingreso
    {


        $profile = Profile::find($request->profile_id);
        $area = $profile->area;
        $status = Status::where('slug', '=', 'open')->where('status_type', '=', 'task')->get();
        $pipelinesCreated = [];
        if ($request->event_coverage != null) {

            foreach ($request->event_coverage as $c) {

                $pipeline = Pipeline::find($c);

                array_push($pipelinesCreated, 'Tarea creada con el pipeline ' . $pipeline->name . '<br />');
                $task = new Task();
                $task->profile_id = $request->profile_id;
                $task->user_id = Auth::user()->id;
                $task->title = $request->title; //****
                $task->status_id = $status->first()->id;
                $task->draft = null;
                $task->type = 'event';

                if ($request->deadline != null) {

                    $task->deadline = $request->deadline; //***
                }

                $task->taskdata_id = $request->taskdata_id;

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

                $task->title = $request->title;
                $task->description = $request->description;
//                $task->prevision = 1;

                $task->save();


                $initialTask = Task::find($request->id);

                $attachs = $initialTask->attachments;

                foreach ($attachs as $attach) {

                    if ($attach->pivot->active == 1) {
                        $query = DB::table('attach_task')->insert(['attachment_id' => $attach->id, 'task_id' => $task->id]);
                    }
                }


                $query = DB::table('task_pipeline')->insert(
                    ['task_id' => $task->id, 'pipeline_id' => $pipeline->id]
                );


                event(new CreateTask($task));
                $this->userAutotagInTask($task->unit->id, $pipeline->id, $profile->id,$task->id);


                //---------Replica comentarios de unidad Pre-ingreso a Ingreso-------------

                if($task->unit_id == 1){

                    $coment_aux = Comment::where('content_type','App\Task')
                        ->where('content_id',$request->id)
                        ->where('unit_id',13)
                        ->get();


                    foreach ($coment_aux as $c){

                        $newComent = $c->replicate();
                        $newComent->unit_id = $task->unit_id;
                        $newComent->content_id = $task->id;
                        $newComent->created_at = $c->created_at;
                        $newComent->updated_at = $c->updated_at;
                        $newComent->save();
                    }

                }

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

            }
        }

        $succesmessage = '';
        if (count($pipelinesCreated) > 0) {
            foreach ($pipelinesCreated as $pc) {
                $succesmessage = $succesmessage . $pc;
            }
        } else {
            $succesmessage = 'Debe seleccionar al menos una línea de producción';
        }


        return redirect()->back()->with('message', $succesmessage);
    }


    // Cambiar perfil de una tarea
    public function changeProfileTask(Request $request)
    {
        $this->validate($request, [
            'tarea' => 'required',
            'cambiarPerfilTarea' => 'required',
        ]);

        $tarea = Task::where('id', $request->tarea)->first();

        $tarea->profile_id = $request->cambiarPerfilTarea;
        $tarea->save();

        return back()->with('perfilCambiado', 'Perfil cambiado correctamente');
    }

    /**
     * Función que es llamada desde testerController para verificar las tareas inactivas ,para luego crear notificaciones a sus respectivos usuarios ,se usa en cron
     */
    public function searchTaskInactive()
    {

        $user_ids = DB::select('SELECT DISTINCT(user_id) FROM `user_has_roles`where role_id in (1,2,4)');

        $array_aux = array();
        foreach ($user_ids as $us) {
            array_push($array_aux, $us->user_id);
        }


        $users = User::select('*')->where('active', '<>', 0)->whereIn('id', $array_aux)->get();


        foreach ($users as $user) {

            $this->taskInactive($user);
        }
    }
    /**
     *busca tareas que se encuentran inactivas
     * //Busca tareas inactivas y notifica al teamleader (si el usuario logueado es teamleader)

    //------------------------------
     */
    public function taskInactive($user)
    {

            $tasks = Task::whereIn('status_id', [1, 5])->get();

            if ($tasks) {
                $menos1dia = $this->dayNotWeekend(1);

                foreach ($tasks as $task) {

                    $userTag = Tasktag::where('user_id',$user->id)
                        ->where('unit_id' ,$task->unit_id)
                        ->where('active',1)
                        ->where('relation_id',$task->id)
                        ->where('type','task')->latest()->first();

                    // es team-leader de la unidad de la tarea y verifica si el usuario está activo o si está etiquetado en la tarea

                    if(($user->isTeamLeaderInUnitTest($task->unit_id,$user->id)  && $user->active == 1) || ($userTag!= null && count($userTag) >0))
                    {
                        //busco si se crearon eventos para el usuario en menos de 24 horas
                        $event_aux = Eventlog::where('relation_id', $task->id)->where('type', 'TaskInactive')->where('created_at', '>', $menos1dia)->where('user_id', $user->id)->orderBy('created_at', 'desc')->get();

                        if (count($event_aux) == 0) {  //si existen eventos => cambio el estado de $date_isWeekend para que no cree nuevos eventos

                            $this->revisionInactiveTask($task,$user);
                        }
                    }
                }

            }

//        }//fin del else

    }

    /**
     * función es llamada desde la función clientHome,
     * verifica que la tarea que se pasa por parametro tenga inactividad ,
     * si tiene inactividad =>crea un evento y notifica al usuario loqueado (si es  teamleader) la inactividad de la tarea
     * @param $task
     */
    private function revisionInactiveTask($task,$user)
    {

        //   datos de fechas que necesito

        $date_menos3 = $this->dayNotWeekend(3); //fecha de hace 3 dias


        $event = Eventlog::where('relation_id', $task->id)
            ->whereIn('type', ['Task', 'TaskStatusChange', 'App\Task', 'ChangeToUnit', 'UpdateTask', 'AttachTask'])->latest()->first(); //busca el último evento relacionado a la tarea


        $eventag = Tasktag::where('relation_id', $task->id)->where('type', 'task')->where('unit_id', $task->unit_id)->latest()->first();//busca el último tasktag relacionado a la tarea


        if ($event != null && $eventag != null) { //existen los dos

            //busco la fecha mas aproximada a $date_menos3


            if ($event->created_at->toDateTimeString() > $eventag->created_at->toDateTimeString()) {

                if ($event->created_at->toDateTimeString() < $date_menos3) {

                    event(new TaskInactive($task,$user)); //crea el evento

                }

            } else {

                if ($eventag->created_at->toDateTimeString() < $date_menos3) {

                    event(new TaskInactive($task,$user)); //crea el evento

                }
            }



        } else { //=> solo existe una de las dos

            if ($event) {                      //existe event

                if ($event->created_at->toDateTimeString() < $date_menos3) {

                    event(new TaskInactive($task,$user)); //crea el evento
                }

            } elseif ($eventag) {               //existe eventag

                if ($eventag->created_at->toDateTimeString() < $date_menos3) {

                    event(new TaskInactive($task,$user)); //crea el evento
                }

            }

        }

    }


    /**
     * devuelve fecha de hace 'count' de días hábiles anteriores a la fecha actual
     * @param $count cantidad de días
     * @return fecha de hace 'cantidad'(count) días sin contar los findes
     */
    private function dayNotWeekend($count)
    {

        $aux1 = 0;
        $aux = 0;
        $countAux = 0;

        while ($aux < $count) {

            $aux1 += 1;
            $diaNew = Carbon::now()->subDay($aux1);

            if ($diaNew->isWeekend()) {
                $countAux += 1;

            } else {

                $aux += 1;

            }

        }

        $dia = Carbon::now()->subDay($aux + $countAux);

        return $dia;

    }


    /**
     * @param Request $request
     */
    public function updatePipeline(Request $request)
    {

        if ($request->all()) {

                $task = Task::find($request->id);

                $pipeline = Pipeline::find($request->pipeline_id);

                $newTask = $task->replicate();
                $newTask->unit_id = $pipeline->unitsByRevision($pipeline->latestRevision)->first()->id;
                $newTask->pipelineRevision = $pipeline->latestRevision;
                $newTask->status_id = 1;
                $newTask->save();

                //esto va siempre antes de crear el evento

                $query = DB::table('task_pipeline')->insert(
                    ['task_id' => $newTask->id, 'pipeline_id' => $pipeline->id]
                );
                //fin

                event(new CreateTask($newTask)); //crea nuevo evento de la tarea creada
                $this->userAutotagInTask($newTask->unit_id, $pipeline->id,$newTask->profile_id, $newTask->id); // Autoetiquetado

                $task->status_id = 6; //se cambia el status de la tarea a cancelada
                $task->reassignTask = $newTask->id; //guarda el id de la tarea clon con diferente pipeline

                return redirect()->route('redirectHome');

        }

    }


    /**
     * @param $id es el estado de las tareas a mostrar
     * @return las tareas por cada perfil
     */
    public function viewTaskByProfile($id=null)
    {

//        dd($id);
        $profiles = DB::select('SELECT DISTINCT(profiles.id) FROM profiles,tasks where profiles.status = 1 and profiles.id =tasks.profile_id');

        $allTaskByProfile = array();


        if ($id == 1 || $id == 5){

            foreach ($profiles as $pf) {
                $task = Task::where('profile_id', $pf->id)->where('status_id',$id)->orderBy('created_at', 'DESC')->get();


                if (count($task) > 0) {
                    array_push($allTaskByProfile, $task);
                }

            }

        }else{

            foreach ($profiles as $pf) {
                $task = Task::where('profile_id', $pf->id)->orderBy('created_at', 'DESC')->get();


                if (count($task) > 0) {
                    array_push($allTaskByProfile, $task);
                }

            }
        }

        $alltasks = array(
            'allTaskByProfile' => $allTaskByProfile,
        );
        return view('task.taskProfile', $alltasks);
    }


    /**
     * @param Request $request id de perfil seleccionado
     * @return array con perfiles a seleccionar y las tareas del perfil seleccionado (en el caso que se selecciona algún perfil)
     */
    public function selectTaskByProfile(Request $request)
    {

        if (count($request->all()) == 0) {

            $profiles = DB::select('SELECT DISTINCT(profiles.id),profiles.area FROM profiles,tasks where profiles.status = 1 and profiles.id =tasks.profile_id');

            $allprofiles = array(
                'allProfile' => $profiles,
            );
            return view('task.selectTaskProfile', $allprofiles);
        }else{

            $profiles = DB::select('SELECT DISTINCT(profiles.id),profiles.area FROM profiles,tasks where profiles.status = 1 and profiles.id =tasks.profile_id');


            if($request->profile_id) {
                $profile = Profile::find($request->profile_id);

                $allTaskByProfile = array();

                $tasks = Task::where('profile_id', $request->profile_id)->orderBy('created_at', 'DESC')->get();


                if (count($tasks) > 0) {

                    array_push($allTaskByProfile, $tasks);

                }
                $allprofiles = array(
                    'allProfile' => $profiles,
                    'allTasksbyProfile' => $tasks,
                    'profileSl' => $profile
                );

                return view('task.selectTaskProfile',$allprofiles );

            }else{

                return redirect()->back()->with('message', 'Debes seleccionar un perfil.');

            }
        }


    }



    public function combinateAttachtask(Request $request){


        if(DB::table('attach_task')->insert(['attachment_id' => $request['attachitem'],'task_id' => $request['task']]))
            echo json_encode(array("status"=>"ok"));


    }


    public function getAttachByTask(Request $request){




        $taskId = $request['task'];


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


        $AttachnativeTask = DB::table('attach_task')
            ->select('attach_task.*')
            ->where('attach_task.task_id', '=', $taskId)
            ->join('attach_subtask', 'attach_task.attachment_id', '=', 'attach_subtask.attachment_id')->get();

        $notActive = array();

        if ($AttachnativeTask) {

            foreach ($AttachnativeTask as $key3 => $value3) {

                array_push($notActive, $value3->attachment_id);

            }
        }


        return json_encode(array("todo"=>(String) view('task.ajaxTask', array('task' => $task,'notActive'=>$notActive))));



    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     *  "view" => "home"
     */
    public function selectTaskdata(Request $request)
    {
//        dd(count($request->all()),$request->all());
        $tasks = DB::table('tasks')->get();
        $profiles = DB::select('SELECT DISTINCT(profiles.id),profiles.area FROM profiles,tasks where profiles.status = 1 and profiles.id =tasks.profile_id');
        $status = Status::where('status_type', '=', 'task')->get();
        $arrayTasks = array();

        foreach ($tasks as $t) {
            array_push($arrayTasks, $t->taskdata_id);

        }

        $alltaskdata = Taskdata::whereIn('id', $arrayTasks)->get(['id', 'title']);

        if(count($request->all()) > 4)
        {

            $arrayTaskData = $this->advancedSearchTaskdata($request->taskdata_id,$request->id_profile,$request->id_statu);


            if(is_string($arrayTaskData) ){ //$alltaskdata es un msj
//                dd($arrayTaskData);
                if ($request->view == 'home') {

                    return redirect()->back()->with('error',  $arrayTaskData);//mensaje porq no ingreso el perfil y el estado de  la tarea.
                }else {
                    return view('task.client.selectTaskdata', array(
                        'alltaskdata' => $alltaskdata,
                        'profiles' => $profiles,
                        'status' => $status,
                        'error' => $arrayTaskData));
//                return redirect()->back()->with('error', $alltaskdata);//mensaje porq no ingreso el perfil y el estado de  la tarea.
                }

            }else{

                return view('task.client.selectTaskdata', array(
                    'arraytaskdata' => $arrayTaskData,
                    'alltaskdata' => $alltaskdata,
                    'profiles' => $profiles,
                    'status' => $status
                ));
            }

        }else {

            if ($request->taskdata_id != null) {
                $taskdata = Taskdata::where('id', $request->taskdata_id)->first();


                return view('task.client.selectTaskdata', array(
                    'taskdatas' => $taskdata,
                    'alltaskdata' => $alltaskdata,
                    'profiles' => $profiles,
                    'status' => $status,
                ));
            } else {

                if ($request->view == 'select') {
                    return view('task.client.selectTaskdata', array(
                        'alltaskdata' => $alltaskdata,
                        'profiles' => $profiles,
                        'status' => $status,
                        'error' => 'Debe seleccionar una tarea.'));

                } elseif ($request->view == 'home') {

                    return redirect()->back()->with('error', 'Debe seleccionar una tarea.');
                }
            }
        }

    }


    /**
     * @param $tasdata_id
     * @param $profile_id
     * @param $statu_id
     * @return  arreglo de taskdata
     */
    private function advancedSearchTaskdata($tasdata_id,$profile_id,$statu_id)
    {

//        dd($tasdata_id,$profile_id);
        if ($profile_id != null && $statu_id != null) {

//                $tasks = '';
            $arrayTaskData = array();

            if ($tasdata_id != null) {

                $tasks = Task::where('taskdata_id', $tasdata_id)
                    ->where('profile_id', $profile_id)
                    ->where('status_id', $statu_id)->get();

            } else {

                $tasks = Task::where('profile_id', $profile_id)
                    ->where('status_id', $statu_id)->get();

            }

            foreach ($tasks as $t) {
                array_push($arrayTaskData, $t->taskdata_id);

            }

            $alltaskdata = Taskdata::whereIn('id', $arrayTaskData)->get();

            return $alltaskdata;

        } else {

            return 'Debe seleccionar un perfi y un estado.';
        }
    }

    public function createFormEvento()
    {

//        $profiles = Profile::where('user_id', '=', Auth::user()->id)
//            ->where('status', '=', '1')->get();

        if (Auth::user()->hasRole('supervisor') || Auth::user()->hasRole('administrador') || Auth::user()->hasRole('teamleader')) {
            $profiles = Profile::all();
        } else {
            $profiles = Auth::user()->profiles;
        }

        $pipelines = Pipeline::orderBy('hidden')->get();

        if (count(Auth::user()->profiles) == 0) {
            return Redirect::to(URL::to('/profile/create/evento_create'));
        }

        return view('task.create', array(
                'type' => 'evento_create',
                'profiles' => $profiles,
                'pipelines' => $pipelines,

            )
        );
    }

    public function editFormEvento($id)
    {
        $task = Task::find($id);

//        $profiles = Profile::where('user_id', '=', Auth::user()->id)
//            ->where('status', '=', '1')->get();

        if (Auth::user()->hasRole('supervisor') || Auth::user()->hasRole('administrador') || Auth::user()->hasRole('teamleader')) {
            $profiles = Profile::all();
        } else {
            $profiles = Auth::user()->profiles;
        }
        $pipelines = Pipeline::all();


        if (count(Auth::user()->profiles) == 0) {
            return Redirect::to(URL::to('/profile/create/event'));
        }


        return view('task.create', array(
                'task' => $task,
                'type' => 'evento_edit',
                'profiles' => $profiles,
                'pipelines' => $pipelines,

            )
        );

    }

    public function storeFormEvento(StoreFormEvento $request)
    {

        if ($request->draft != null) {


            $status = Status::where('slug', '=', 'open')->where('status_type', '=', 'task')->get();


            $profile = Profile::find($request->profile_id);
            $area = $profile->area;

            $taskdata = $this->saveTaskdata($request);//guarda y crea y nuevo taskdata, devuelve el taskdata creado

            $task = new Task();
            $task->profile_id = $request->profile_id;
            $task->user_id = Auth::user()->id;
            $task->status_id = $status->first()->id;
            $task->taskdata_id = $taskdata->id;
            $task->type = 'evento';
            $task->title = $request->title;

//            if ($taskdata->deadline != null) {
//                $task->deadline = $taskdata->deadline; //***
//            }
            $task->draft = true;//el usuario marca en borrador la tarea => draft =1 (guarda en la tabla tasks)

            $task->save();

            $this->setJsonAttach($task->id, $request->jsonIdAttachments);


        } else {


            $profile = Profile::find($request->profile_id);
            $area = $profile->area;

            $status = Status::where('slug', '=', 'open')->where('status_type', '=', 'task')->get();


//

            $taskdata = $this->saveTaskdata($request);//guarda y crea y nuevo taskdata, devuelve el taskdata creado


            if ($request->event_coverage != null) {

                foreach ($request->event_coverage as $c) {

                    $pipeline = Pipeline::find($c);


                    $task = new Task();
                    $task->profile_id = $request->profile_id;
                    $task->user_id = Auth::user()->id;
                    $task->title = $request->title; //****
                    $task->status_id = $status->first()->id;
                    $task->draft = null;
                    $task->type = 'evento';
//
//                    if ($taskdata->deadline != null) {
//                        $task->deadline = $taskdata->deadline; //***
//                    }

                    $task->taskdata_id = $taskdata->id;

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

                    $task->title = $request->title;


                    $task->save();


                    $this->setJsonAttach($task->id, $request->jsonIdAttachments);


                    $query = DB::table('task_pipeline')->insert(
                        ['task_id' => $task->id, 'pipeline_id' => $pipeline->id]
                    );

                    $this->setJsonAttach($task->id, $request->jsonIdAttachments);


                    event(new CreateTask($task));
                    $this->userAutotagInTask($task->unit->id, $pipeline->id,$profile->id, $task->id);


                }
            }


        }


        if ($request->draft != null) {

            //return redirect()->action('TaskController@clientHome');
            return redirect()->route('redirectHome');
        } else {

            //return redirect()->action('TaskController@clientHome');
            return redirect()->route('redirectHome',['t'=>$task->id,'u'=>$task->unit_id])->with('task', 'Tarea Creada!!');


        }

    }

    public function updateFormEvento(UpdateFormEvento $request)
    {

        if ($request->draft != null) {


            $status = Status::where('slug', '=', 'open')->where('status_type', '=', 'task')->get();


            $profile = Profile::find($request->profile_id);
            $area = $profile->area;

            $task = Task::find($request->id);


            $taskdata = $this->editTaskdata($request, $task);//edita el taskdata, devuelve el taskdata creado


            $task->profile_id = $request->profile_id;
            $task->user_id = Auth::user()->id;
            $task->status_id = $status->first()->id;
            $task->taskdata_id = $taskdata->id;
            $task->type = 'evento';
            $task->title = $request->title;

//            if ($taskdata->deadline != null) {
//                $task->deadline = $taskdata->deadline; //***
//            }

            $task->draft = true;


            $task->save();


        } else {

            $profile = Profile::find($request->profile_id);
            $area = $profile->area;

            $status = Status::where('slug', '=', 'open')->where('status_type', '=', 'task')->get();
            $oldtask = Task::find($request->id);

            $taskdata = $this->editTaskdata($request, $oldtask); //edita el taskdata, devuelve el taskdata creado


            $attachTaske = DB::table('attach_task')
                ->select('attachment_id as id')
                ->where('task_id', '=', $request->id)
                ->where('active', '=', 1)
                ->get()->toArray();


            $attachTaskeelement = array();
            $jsonIdAttachments = null;

            if ($attachTaske) {

                foreach ($attachTaske as $key6 => $value6) {

                    array_push($attachTaskeelement, $value6);
                }

                $jsonIdAttachments = json_encode($attachTaskeelement);

            }


            foreach ($request->event_coverage as $c) {


                $pipeline = Pipeline::find($c);


                $task = new Task();
                $task->profile_id = $request->profile_id;
                $task->user_id = Auth::user()->id;
                $task->status_id = $status->first()->id;
                $task->draft = null;
                $task->type = 'evento';

                $task->taskdata_id = $taskdata->id;

//                if ($taskdata->deadline != null) {
//                    $task->deadline = $taskdata->deadline; //***
//                }
                $task->unit_id = $pipeline->unitsByRevision($pipeline->latestRevision)->first()->id;
                $task->pipelineRevision = $pipeline->latestRevision;

                $task->title = $request->title;
//                $task->deadline = $taskdata->deadline;
                $task->draft = false;

                $task->save();


                $query = DB::table('task_pipeline')->insert(
                    ['task_id' => $task->id, 'pipeline_id' => $pipeline->id]
                );
                // event(new UpdateTask($task));

                $this->setJsonAttach($task->id, $jsonIdAttachments);


                event(new CreateTask($task));

                $this->userAutotagInTask($task->unit->id, $pipeline->id,$profile->id, $task->id);


            }

            $delete = Task::destroy($oldtask->id);


        }

        if ($request->draft != null) {

            return redirect()->back()->with('message', 'Tarea Actualizada!');
        } else {
            //return redirect()->action('TaskController@clientHome');
            return redirect()->route('redirectHome');

        }

    }

    public function deleteFormEvento(Request $request)
    {


        $task = Task::find($request->id);
        $event = Taskdata::destroy($task->taskdata_id);

        $task_pipeline = DB::table('task_pipeline')->where('task_id', '=', $task->id)->delete();


        //return redirect()->action('TaskController@clientHome')->with('message', 'Tarea eliminada');
        return redirect()->route('redirectHome')->with('message', 'Tarea eliminada');

    }
}