<?php

namespace App\Models;

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

class SubscriptionMember extends Model
{
    use HasFactory, SoftDeletes;

    protected $primaryKey = 'member_id';

    protected $fillable = [
        'subscription_id',
        'customer_id',
        'member_type',
        'full_name',
        'dob',
        'gender',
        'cnic',
        'mobile',
        'age_in_months',
        'contribution_age_group',
        'premium',
        'premium_paisa',
        'is_active',
    ];

    protected $casts = [
        'dob'          => 'date',
        'premium'      => 'decimal:2',
        'premium_paisa'=> 'integer',
        'is_active'    => 'boolean',
        'created_at'   => 'datetime',
        'updated_at'   => 'datetime',
    ];

    // ── Member type constants ──────────────────────────────────────────────────
    const TYPE_SELF     = 'self';
    const TYPE_SPOUSE   = 'spouse';
    const TYPE_SON      = 'son';
    const TYPE_DAUGHTER = 'daughter';

    public function getRouteKeyName(): string
    {
        return 'member_id';
    }

    // ── Relationships ──────────────────────────────────────────────────────────
    public function subscription()
    {
        return $this->belongsTo(Subscription::class, 'subscription_id', 'subscription_id');
    }

    public function customer()
    {
        return $this->belongsTo(EasypaisaCustomer::class, 'customer_id', 'customer_id');
    }

    // ── Accessors ─────────────────────────────────────────────────────────────
    public function getAgeInYearsAttribute(): int
    {
        return (int) floor($this->age_in_months / 12);
    }

    public function getIsSelfAttribute(): bool
    {
        return $this->member_type === self::TYPE_SELF;
    }
}