<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Traits\HasRoles;
use App\Subtask;

class User extends Authenticatable
{
    use Notifiable;


    use HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];


    // deprecated en favor de units() -- para borrar cuando estemos seguros
    public function userUnit()
    {
        return $this->hasOne('App\UserUnit','user_id','id');
    }

    public function userUnits()
    {
        return $this->hasMany('App\UserUnit')->where('teamrole_id', 1)->where('unit_id','<>',2);
    }

    public function units(){
        return $this->belongsToMany('App\Unit','user_unit');
    }

    public function comments()
    {
        return $this->hasMany(\Laravelista\Comments\Comments\Comment::class);
    }

    public function isTeamLeaderAtAnyUnit()
    {

        $units = Unit::all();
        foreach ($units as $unit) {
            foreach ($unit->teamleaders as $tl) {
                if ($this->id == $tl->id) {
                    return true;
                }
            }

        }
        return false;

    }

    public function isTeamMemberAtAnyUnit()
    {

        $units = Unit::all();
        foreach ($units as $unit) {
            foreach ($unit->teammembers as $tl) {
                if ($this->id == $tl->id) {
                    return true;
                }
            }

        }
        return false;

    }


    public function isAdmin()
    {
        return $this->admin;

    }

    public function  tasktag(){

        return $this->hasOne('App\Tasktag','user_id','id');
    }

    /**
     * @param $task_id
     * @param $unit_id
     * @return tasktag ; donde el usuario está etiquetado en la tarea y unidad que se le pasa por parametro
     */
    public function  tasktagInTask($task_id,$unit_id){

        return $this->hasMany('App\Tasktag','user_id','id')->where('task_tag.type','task')->where('task_tag.relation_id',$task_id)->where('task_tag.unit_id',$unit_id)->get();

    }

    public function profiles()
    {

        return $this->belongsToMany('App\Profile','profile_user');

    }

    public function canTagOthers(){
     if($this->hasRole('administrator') ||$this->hasRole('supervisor')||  $this->hasRole('teamleader')){
         return true;
     }   else{

         return false;
     }
    }

    public function canViewAttach(){
        if($this->hasRole('administrator') ||$this->hasRole('supervisor')||  $this->hasRole('teamleader') ){
            return true;
        }   else{

            return false;
        }
    }

    public function isTeamLeaderInUnit($unitId)
    {

        $query = DB::table('user_unit')->where('user_id',Auth::user()->id)->where('teamrole_id',1)->where('unit_id',$unitId)->first();

        return $query ? true : false;

    }

    public function getRoleInUnit($userId,$unitId)
    {
        $rolesInUnit = array();
        $query = DB::table('user_unit')->join('teamroles','user_unit.teamrole_id','=','teamroles.id')->where('user_unit.user_id',$userId)->where('user_unit.unit_id',$unitId)->get();
        foreach ($query as $item) {
            array_push($rolesInUnit,$item->slug);
        }
        return $rolesInUnit;
    }

    /**
     * puede crear subtareas usuarios que son admin,supervisory temleaders de la unidad de la tarea
     * @param $unitId
     * @return true o false
     */
    public function canCreateSubtask($unitId){

        if($this->hasRole('administrator') ||$this->hasRole('supervisor') || $this->isTeamLeaderInUnit($unitId)){
            return true;
        }else{
            return false;
        }
    }
    public  function  canViewTasksSidebar(){

        if($this->hasRole('administrator') ||$this->hasRole('supervisor')||  $this->hasRole('teamleader') || $this->hasRole('teammember')){
            return true;
        }   else{

            return false;
        }
    }


    public function canViewTasks(){

        if($this->hasRole('administrator') ||  $this->hasRole('teamleader')){
            return true;
        }   else{

            return false;
        }
    }

    /**si el usuario es admin , está asignado a la subtarea  o es teamleader de la misma unidad de la tarea original => puede ver la tarea
     * @param $id de subtarea
     * @return bool
     */
    public  function  canViewSubtask($id){

        $subtask = Subtask::find($id); //subtarea

        if( $this->isAdmin() || ($this->id == $subtask->assigned_id )|| $this->isTeamLeaderInUnit( $subtask->task->unit_id)){
                return true;

        }else{

            return false;
        }
    }

    /**
     * si el usuario es admin , está asignado a la subtarea ,está etiquetado en la subtarea ó es teamleader de la misma unidad de la tarea original
     * entonces => puede ver la subtarea
     * @param $id de subtarea
     * @return bool
     */

    public  function  userCanViewSubtask($id){

        $subtask = Subtask::find($id); //subtarea


        if( $this->isAdmin() || ($this->id == $subtask->assigned_id )|| $this->isTeamLeaderInUnit( $subtask->task->unit_id) || $this->userTagInSubtask($id)){
            return true;

        }else{

            return false;
        }
    }


    /**
     * si el usuario está etiquetado en la subtarea
     * @param $id de subtarea
     * @return bool
     */
    public function userTagInSubtask($id){

        $tag = Tasktag::where('relation_id',$id)->where('type','subtask')->where('user_id',$this->id)->where('active',1)->first();

        if($tag){
            return true;
        }
        else{
            return false;
        }
    }

    public  function  canViewListSubtask(){


        if( !$this->hasRole('administrator') || !$this->hasRole('supervisor') || $this->isAdmin()){
            return true;

        }else{

            return false;
        }

    }


    public  function  canSearchSubtask(){

        if( $this->hasRole('administrator') || $this->hasRole('teammember') || $this->isTeamMemberAtAnyUnit()){
            return true;

        }else{

            return false;
        }
    }

    public function isApplicant(){
        if($this->hasRole('supervisor') || $this->hasRole('administrator') || $this->hasRole('teammember') || $this->hasRole('teamleader') || $this->isTeamMemberAtAnyUnit()){
            return false;
        } else {
            return true;
        }
    }

    public function permissionToTask(){

        if($this->hasRole('administrator') ||  $this->hasRole('teamleader') ||$this->hasRole('supervisor')){
            return true;
        }   else{

            return false;
        }
    }

    public function isTeamLeaderInUnitTest($unitId,$user_id)
    {

        $query = DB::table('user_unit')->where('user_id',$user_id)->where('teamrole_id',1)->where('unit_id',$unitId)->first();

        return $query ? true : false;

    }
    /**
     * @param $task_perfileId es el id del task->profile_id
     * @return bool  si el user se relaciona en la tabla user_profile con el id_profile del parametro
     */
//    public function userInProfiles_user($task_profileId){
//
////        $result =false;
//
//        foreach($this->profiles as $profile){
//
//            if($profile->id == $task_profileId){
////                $result =true;
//                return true;
//            }
//        }
//        return false;
//    }

}
