<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ExamAttempt extends Model
{
    use HasFactory;

    protected $fillable = [
        'exam_id',
        'user_id',
        'status',
        'score',
        'passed',
        'questions_answered',
        'correct_answers',
        'incorrect_answers',
        'time_taken_seconds',
        'started_at',
        'submitted_at',
        'expires_at',
        'attempt_number',
    ];

    protected $casts = [
        'started_at' => 'datetime',
        'submitted_at' => 'datetime',
        'expires_at' => 'datetime',
        'passed' => 'boolean',
        'score' => 'integer',
    ];

    /**
     * Get the exam this attempt belongs to
     */
    public function exam(): BelongsTo
    {
        return $this->belongsTo(Exam::class);
    }

    /**
     * Get the user who made this attempt
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get all answers for this attempt
     */
    public function answers(): HasMany
    {
        return $this->hasMany(ExamAnswer::class, 'attempt_id');
    }

    /**
     * Get the certificate issued for this attempt (if passed)
     */
    public function certificate()
    {
        return $this->hasOne(Certificate::class, 'attempt_id');
    }

    /**
     * Check if attempt is expired
     */
    public function isExpired(): bool
    {
        return $this->expires_at < now() && $this->status === 'in_progress';
    }

    /**
     * Get time remaining in seconds
     */
    public function getTimeRemainingSecondsAttribute(): int
    {
        if ($this->status !== 'in_progress' || $this->expires_at < now()) {
            return 0;
        }
        
        return max(0, now()->diffInSeconds($this->expires_at, false));
    }

    /**
     * Scope for in-progress attempts
     */
    public function scopeInProgress($query)
    {
        return $query->where('status', 'in_progress')
            ->where('expires_at', '>', now());
    }

    /**
     * Scope for submitted attempts
     */
    public function scopeSubmitted($query)
    {
        return $query->where('status', 'submitted');
    }
}
