<?php

namespace App\Models;

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

class Quiz extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'description',
        'course_id',
        'book_id',
        'level',
        'is_active',
        'time_limit_minutes',
        'created_by',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'level' => 'integer',
    ];

    // Relationships
    public function course()
    {
        return $this->belongsTo(Course::class, 'course_id');
    }

    public function book()
    {
        return $this->belongsTo(Book::class, 'book_id');
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function questions()
    {
        return $this->hasMany(QuizQuestion::class, 'quiz_id')->orderBy('order');
    }

    public function attempts()
    {
        return $this->hasMany(QuizAttempt::class, 'quiz_id');
    }

    // Helper methods
    public function getLevelNameAttribute()
    {
        return match($this->level) {
            1 => 'Beginner',
            2 => 'Intermediate',
            3 => 'Advanced',
            default => 'Unknown'
        };
    }

    public function getTotalQuestionsAttribute()
    {
        // Use relationship count to avoid N+1 queries
        if ($this->relationLoaded('questions')) {
            return $this->questions->count();
        }
        return $this->questions()->count();
    }

    public function getUserAttempts($userId)
    {
        return $this->attempts()->where('user_id', $userId)->orderBy('completed_at', 'desc');
    }

    public function getUserBestScore($userId)
    {
        $bestAttempt = $this->attempts()
            ->where('user_id', $userId)
            ->whereNotNull('completed_at')
            ->orderBy('percentage', 'desc')
            ->first();
        
        return $bestAttempt ? $bestAttempt->percentage : null;
    }
}

