<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class StudyGroup extends Model
{
    protected $fillable = [
        'owner_id',
        'name',
        'slug',
        'description',
        'visibility',
        'is_active',
    ];

    protected $casts = [
        'is_active' => 'boolean',
    ];

    protected static function booted(): void
    {
        static::creating(function ($group) {
            if (blank($group->slug)) {
                $group->slug = Str::slug($group->name) . '-' . Str::lower(Str::random(6));
            }
        });
    }

    public function owner()
    {
        return $this->belongsTo(User::class, 'owner_id');
    }

    public function members()
    {
        return $this->hasMany(StudyGroupMember::class);
    }

    public function activeMembers()
    {
        return $this->hasMany(StudyGroupMember::class)->where('status', 'active');
    }

    public function logs()
    {
        return $this->hasMany(StudyLog::class);
    }
}