<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class Group extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'user_id',
        'name',
        'description',
        'is_join'
    ];

    protected static function booted()
    {
        static::creating(function(Group $group) {
            $group->user_id = auth()->user()->id;
        });
    }

    protected $appends = [
        'is_joined'
    ];

    public function getIsJoinedAttribute()
    {
       $is_joined = GroupUser::where([
        'group_id' => $this->id,
        'user_id' => auth()->user()->id,
       ])->first(); 

       return $is_joined == null ? 0 : 1;
    }

    public function user()
    {
        return $this->BelongsTo(User::class);
    }

    public function groupUser()
    {
        return $this->hasMany(GroupUser::class, 'group_id');
    }

    public function groupMessage()
    {
        return $this->hasMany(GroupMessage::class);
    }
}
