<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Family extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'slug',
        'description',
        'created_by',
        'ethnic_group_id',
        'clan_id',
        'head_person_id',
        'settings',
    ];

    protected $casts = [
        'settings' => 'array',
    ];

    public function members()
    {
        return $this->belongsToMany(Person::class, 'family_members')
            ->withPivot(['role', 'joined_at', 'can_post_announcements', 'can_create_events'])
            ->withTimestamps();
    }

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

    public function invitations()
    {
        return $this->hasMany(Invitation::class);
    }

    public function relationships()
    {
        return $this->hasMany(Relationship::class);
    }

    public function wallPosts()
    {
        return $this->hasMany(FamilyWallPost::class);
    }

    public function ethnicGroup()
    {
        return $this->belongsTo(EthnicGroup::class);
    }

    public function clan()
    {
        return $this->belongsTo(Clan::class);
    }

    public function head()
    {
        return $this->belongsTo(Person::class, 'head_person_id');
    }

    public function subscriptions()
    {
        return $this->morphMany(Subscription::class, 'subscriber');
    }

    public function currentSubscription()
    {
        return $this->morphOne(Subscription::class, 'subscriber')->latestOfMany('id');
    }

    public function paymentMethods()
    {
        return $this->morphMany(SubscriptionPaymentMethod::class, 'subscriber');
    }
}
