<?php

namespace App\Models;

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

class QuizQuestion extends Model
{
    use HasFactory;

    protected $fillable = [
        'quiz_id',
        'question',
        'question_type',
        'explanation',
        'order',
    ];

    protected $casts = [
        'order' => 'integer',
    ];

    // Relationships
    public function quiz()
    {
        return $this->belongsTo(Quiz::class);
    }

    public function answers()
    {
        return $this->hasMany(QuizAnswer::class, 'question_id')->orderBy('order');
    }

    public function attemptAnswers()
    {
        return $this->hasMany(QuizAttemptAnswer::class);
    }

    // Helper methods
    public function getCorrectAnswer()
    {
        return $this->answers()->where('is_correct', true)->first();
    }

    public function hasCorrectAnswer()
    {
        return $this->answers()->where('is_correct', true)->exists();
    }

    public function bookmarks()
    {
        return $this->hasMany(QuestionBookmark::class, 'question_id');
    }

    public function isBookmarkedBy($userId)
    {
        return $this->bookmarks()->where('user_id', $userId)->exists();
    }
}

