<?php

namespace App\Models;

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

class CambridgeGradeBoundary extends Model
{
    use HasFactory;

    protected $table = 'cambridge_grade_boundaries';

    protected $fillable = [
        'disciplina_id',
        'ano',
        'serie',
        'letra',
        'percent_min',
        'percent_max',
        'is_default',
    ];

    protected $casts = [
        'percent_min' => 'decimal:2',
        'percent_max' => 'decimal:2',
        'is_default' => 'boolean',
    ];

    public function disciplina()
    {
        return $this->belongsTo(Disciplina::class);
    }

    public static function getLetra($disciplinaId, $percent, $ano = null, $serie = null)
    {
        $query = self::where('disciplina_id', $disciplinaId)
            ->where('percent_min', '<=', $percent);

        if ($ano) {
            $query->where('ano', $ano);
        }

        if ($serie) {
            $query->where('serie', $serie);
        }

        $boundary = $query->orderBy('percent_min', 'desc')->first();

        if (!$boundary) {
            // Fallback para default
            $boundary = self::where('disciplina_id', $disciplinaId)
                ->where('is_default', true)
                ->where('percent_min', '<=', $percent)
                ->orderBy('percent_min', 'desc')
                ->first();
        }

        return $boundary ? $boundary->letra : null;
    }
}



