<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Modules\Category\Models\Category;

class Group extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'description',
        'privacy',
        'cover_image',
        'category_id',
        'creator_id',
        'user_id',
        'active',
        'is_featured',
        'is_private',
        'allow_members_to_post',
        'slug',
        'members_count',
    ];

    protected $casts = [
        'active' => 'boolean',
        'is_featured' => 'boolean',
        'is_private' => 'boolean',
        'allow_members_to_post' => 'boolean',
        'members_count' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * Get the creator of the group.
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'creator_id');
    }

    /**
     * Get the owner of the group.
     */
    public function owner()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * Get the category of the group.
     */
    public function category()
    {
        return $this->belongsTo(GroupCategory::class);
    }

    /**
     * Get the members of the group.
     */
    public function members()
    {
        return $this->hasMany(GroupMember::class);
    }

    /**
     * Get the posts in the group.
     */
    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    /**
     * Get the reports for the group.
     */
    public function reports()
    {
        return $this->hasMany(GroupReport::class);
    }

    /**
     * Scope a query to only include active groups.
     */
    public function scopeActive($query)
    {
        return $query->where('active', true);
    }

    /**
     * Scope a query to only include featured groups.
     */
    public function scopeFeatured($query)
    {
        return $query->where('is_featured', true);
    }

    /**
     * Scope a query to only include public groups.
     */
    public function scopePublic($query)
    {
        return $query->where('privacy', 'public');
    }

    /**
     * Scope a query to only include private groups.
     */
    public function scopePrivate($query)
    {
        return $query->where('privacy', 'private');
    }
    public function deleteGroup($group_id)
    {
        GroupMember::where('group_id', $group_id)->delete();
        $postModel = new Post();
        $groupPosts = $postModel->where('group_id', $group_id)->pluck('id')->toArray();
        $postModel->deletePosts($groupPosts);
        $this->where('id', $group_id)->delete();
    }
}
