<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class MembershipRenewalConfig extends Model
{
    protected $fillable = [
        'membership_category_id',
        'renewal_period_months',
        'is_default',
        'effective_from',
        'effective_until',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'renewal_period_months' => 'integer',
        'is_default' => 'boolean',
        'effective_from' => 'date',
        'effective_until' => 'date',
    ];

    public function membershipCategory(): BelongsTo
    {
        return $this->belongsTo(MembershipCategory::class);
    }

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

    public function updater(): BelongsTo
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    /**
     * Get the renewal period months for a given category.
     * Falls back to the default config, then to 12 months.
     */
    public static function getForCategory(?int $categoryId): self
    {
        // Try category-specific config first
        if ($categoryId) {
            $config = static::where('membership_category_id', $categoryId)->first();
            if ($config) {
                return $config;
            }
        }

        // Fall back to default config
        $default = static::where('is_default', true)->first();
        if ($default) {
            return $default;
        }

        // Hardcoded fallback
        $fallback = new static();
        $fallback->renewal_period_months = 12;

        return $fallback;
    }
}
