<?php
/**
 * Created by PhpStorm.
 * User: UNTREF
 * Date: 4/12/2017
 * Time: 3:42 PM
 */

namespace App\Listeners;

use App\Events\Event;
use App\Events\SubtaskStatusChange;
use App\Eventlog;
use Illuminate\Support\Facades\Auth;
use App\Unit;
use App\Notifications;
use App\Tasktag;


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

    /**
     * Handle the event.
     * @param  Event  $subtask
     * @Post: crea el evento y la notificación por el cambio de estado de la subtarea
     * @return
     */
    public function handle(SubtaskStatusChange $event)
    {


        $subtask = $event->subtask;
        $eventlog = new Eventlog();
        $eventlog->user_id = Auth::user()->id;
        $eventlog->type = 'SubtaskStatusChange';
        $eventlog->relation_id = $subtask->id;

        $user_array = array();

        if($event->content){
            $eventlog->content = $event->content;

            $user_tags = Tasktag::where('relation_id','=',$eventlog->relation_id)
                ->where('unit_id','=',$event->content)
                ->where('active','=',1)->get();//busca (tasktag)etiquetas donde los usuarios estén etiquetados en la tarea comentada


            if (is_countable($user_tags)){

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

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

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

        $eventlog->save();



        //assigned_id es usuario asignado a la subtarea que es teammember de la misma unidad

        if($eventlog->user_id != $subtask->assigned_id) { //el usuario que crea el evento de cambio de estado debe ser diferente al usuario asignado

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

        }

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

        foreach ($unit->teamleaders AS $tl) {  //notifica a los teamleader de la misma unidad excepto si el teamleader creo el evento de cambio de estado

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

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

            }
        }

        $array_unique =  array_unique($user_array,SORT_REGULAR);

        foreach ($array_unique as $user_id){

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

        }



    }
}
