<?php

namespace App\Models\Courses;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class CourseAnswer extends Model
{
    protected $fillable = [
        'question_id', 'user_id', 'answer', 'is_best_answer'
    ];

    protected $casts = [
        'is_best_answer' => 'boolean',
    ];

    public function question()
    {
        return $this->belongsTo(CourseQuestion::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function markAsBestAnswer()
    {
        // Remove any existing best answer
        CourseAnswer::where('question_id', $this->question_id)
            ->where('id', '!=', $this->id)
            ->update(['is_best_answer' => false]);
        
        // Set this as best answer
        $this->is_best_answer = true;
        $this->save();
        
        // Mark question as resolved
        $this->question->markAsResolved();
    }
}