<?php

namespace App\Models;

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

class QuizAttempt extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id','subject_id','max_items','start_level','start_theta',
        'end_theta','se','total_correct','total_items','result_json', 'exam_id' ,
        'started_at','finished_at'
    ];

    protected $casts = [
        'max_items'   => 'integer',
        'start_level' => 'integer',
        'start_theta' => 'float',
        'end_theta'   => 'float',
        'se'          => 'float',
        'total_correct' => 'integer',
        'total_items'   => 'integer',
        'result_json' => 'array',
        'started_at'  => 'datetime',
        'finished_at' => 'datetime',
    ];

    public function user()    { return $this->belongsTo(User::class); }
    public function subject() { return $this->belongsTo(Subject::class); }
    public function items()   { return $this->hasMany(QuizAttemptItem::class, 'attempt_id'); }

    // Helper: map theta back to recommended level 1..9
    public function getRecommendedLevelAttribute(): int
    {
        $theta = $this->end_theta ?? $this->start_theta ?? 0.0;
        $lvl = (int) round(2 * $theta + 5);
        return max(1, min(9, $lvl));
    }

    public function getBandAttribute(): string
    {
        $theta = $this->end_theta ?? 0.0;
        if ($theta <= -0.5) return 'Below grade';
        if ($theta >= 0.5)  return 'Above grade';
        return 'At grade';
    }
}
