<?php

namespace App\Models;

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

class QuizAttempt extends Model
{
    use HasFactory;

    protected $fillable = [
        'quiz_id',
        'user_id',
        'mode',
        'score',
        'total_questions',
        'question_order',
        'correct_answers',
        'percentage',
        'started_at',
        'completed_at',
    ];

    protected $casts = [
        'score' => 'integer',
        'total_questions' => 'integer',
        'question_order' => 'array',
        'correct_answers' => 'integer',
        'percentage' => 'decimal:2',
        'started_at' => 'datetime',
        'completed_at' => 'datetime',
    ];

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

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

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

    // Helper methods
    public function isCompleted()
    {
        return $this->completed_at !== null;
    }

    public function getDurationAttribute()
    {
        if ($this->started_at && $this->completed_at) {
            return $this->started_at->diffInSeconds($this->completed_at);
        }
        return null;
    }

    public function getFormattedDurationAttribute()
    {
        $duration = $this->duration;
        if ($duration === null) {
            return 'N/A';
        }
        
        $minutes = floor($duration / 60);
        $seconds = $duration % 60;
        
        if ($minutes > 0) {
            return "{$minutes}m {$seconds}s";
        }
        return "{$seconds}s";
    }

    /**
     * Get answered question IDs
     */
    public function getAnsweredQuestionIds()
    {
        return $this->attemptAnswers()->pluck('question_id')->toArray();
    }

    /**
     * Get progress percentage
     */
    public function getProgressPercentage()
    {
        if ($this->total_questions == 0) {
            return 0;
        }
        $answered = $this->getAnsweredQuestionIds();
        return (count($answered) / $this->total_questions) * 100;
    }
}

