<?php

namespace App\Models;

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

class Exam extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'description',
        'instructions',
        'duration_minutes',
        'passing_score',
        'max_attempts',
        'category',
        'available_from',
        'available_until',
        'is_active',
    ];

    protected $casts = [
        'available_from' => 'datetime',
        'available_until' => 'datetime',
        'is_active' => 'boolean',
    ];

    /**
     * Get all questions for this exam
     */
    public function questions(): HasMany
    {
        return $this->hasMany(ExamQuestion::class)->orderBy('order');
    }

    /**
     * Get all attempts for this exam
     */
    public function attempts(): HasMany
    {
        return $this->hasMany(ExamAttempt::class);
    }

    /**
     * Get study materials for this exam
     */
    public function studyMaterials(): HasMany
    {
        return $this->hasMany(ExamStudyMaterial::class)->orderBy('order');
    }

    /**
     * Get bookings for this exam
     */
    public function bookings(): HasMany
    {
        return $this->hasMany(ExamBooking::class);
    }

    /**
     * Get certificates issued for this exam
     */
    public function certificates(): HasMany
    {
        return $this->hasMany(Certificate::class);
    }

    /**
     * Scope to get available exams
     */
    public function scopeAvailable($query)
    {
        return $query->where('is_active', true)
            ->where(function ($q) {
                $q->whereNull('available_from')
                  ->orWhere('available_from', '<=', now());
            })
            ->where(function ($q) {
                $q->whereNull('available_until')
                  ->orWhere('available_until', '>=', now());
            });
    }

    /**
     * Get user's attempts for this exam
     */
    public function userAttempts($userId)
    {
        return $this->attempts()->where('user_id', $userId);
    }

    /**
     * Check if user can take this exam
     */
    public function canTake($userId): array
    {
        $userAttempts = $this->userAttempts($userId)->count();
        $attemptsRemaining = max(0, $this->max_attempts - $userAttempts);
        
        $canTake = $this->is_active 
            && $attemptsRemaining > 0
            && (is_null($this->available_from) || $this->available_from <= now())
            && (is_null($this->available_until) || $this->available_until >= now());

        return [
            'can_take' => $canTake,
            'attempts_remaining' => $attemptsRemaining,
            'attempts_used' => $userAttempts,
        ];
    }
}
