<?php

namespace App\Models;

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

class MlmLevel extends Model
{
    use HasFactory;

    protected $fillable = [
        'level',
        'name',
        'commission_rate',
        'bonus_rate',
        'is_active',
    ];

    protected $casts = [
        'commission_rate' => 'decimal:2',
        'bonus_rate' => 'decimal:2',
        'is_active' => 'boolean',
    ];

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeOrdered($query)
    {
        return $query->orderBy('level', 'asc');
    }

    public static function getRate($level)
    {
        $mlmLevel = static::where('level', $level)->where('is_active', true)->first();
        return $mlmLevel ? $mlmLevel->commission_rate : 0;
    }

    public static function getMaxLevel()
    {
        return static::active()->max('level') ?? 10;
    }
}
