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

namespace App\Listeners;

use App\Events\CreateSubtask;
use App\Events\Event;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Eventlog;
use Illuminate\Support\Facades\Auth;
use App\Unit;
use App\Notifications;


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

   /**
     * Handle the event.
     *
     * @param  Event  $task
    * Crea un evento de la subtarea creada y crea notificación  al usuario asignado y teamLeader de la misma unidad
     * @return void
     */

    public function handle(CreateSubtask $event)
    {
        $subtask = $event->subtask;
        $eventlog = new Eventlog();
        $eventlog->user_id = Auth::user()->id;
        $eventlog->type = 'Subtask';
        $eventlog->relation_id = $subtask->id;
        $eventlog->save();

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

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

            if( $eventlog->user_id !=  $tl->id && $tl->id != $subtask->assigned_id){// SI EL USUARIO QUE CREA EL EVENTO ES DIFERENTE A TL(TEAMLEADERS) y tl es diferente a usuario asignado
                $notification = new Notifications();
                $notification->eventlogs_id = $eventlog->id;
                $notification->type = 'Subtask';
                $notification->user_to = $tl->id;
                $notification->is_delivered = 0;
                $notification->is_read = 0;
                $notification->is_archived = 0;
                $notification->save();

            }

        }

        if($eventlog->user_id != $subtask->assigned_id) { //el usuario que crea el evento es diferente a usuario asignado

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

            }


    }
}
