<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;

/**
 * Maps current level → next level so the promotion workflow does not
 * hard-code grade progression inside controller logic
 * (see plan section 10).
 */
class LevelProgression extends BaseModel
{
    protected $table = 'level_progressions';

    public $timestamps = true;

    protected $fillable = [
        'current_level_id',
        'current_level_name',
        'next_level_id',
        'next_level_name',
        'order_index',
        'is_terminal',
        'is_active',
        'notes',
    ];

    protected $casts = [
        'current_level_id' => 'integer',
        'next_level_id' => 'integer',
        'order_index' => 'integer',
        'is_terminal' => 'boolean',
        'is_active' => 'boolean',
    ];

    public function scopeActive(Builder $q): Builder
    {
        return $q->where('is_active', 1);
    }

    public function scopeOrdered(Builder $q): Builder
    {
        return $q->orderBy('order_index')->orderBy('current_level_name');
    }

    public static function findByCurrentLevelId(int $levelId): ?self
    {
        return static::query()
            ->where('current_level_id', $levelId)
            ->where('is_active', 1)
            ->first();
    }

    public static function findByCurrentLevelName(string $name): ?self
    {
        return static::query()
            ->whereRaw('LOWER(current_level_name) = ?', [strtolower(trim($name))])
            ->where('is_active', 1)
            ->first();
    }
}
