<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class PlanTier extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'description',
        'parent_tier_id',
        'sort_order',
        'metadata',
    ];

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

    public function plans(): HasMany
    {
        return $this->hasMany(Plan::class);
    }

    public function parentTier(): BelongsTo
    {
        return $this->belongsTo(PlanTier::class, 'parent_tier_id');
    }

    public function childTiers(): HasMany
    {
        return $this->hasMany(PlanTier::class, 'parent_tier_id');
    }

    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order')->orderBy('name');
    }

    public function getMetadata(?string $key = null, $default = null)
    {
        if ($key) {
            return data_get($this->metadata, $key, $default);
        }

        return $this->metadata;
    }
}
