<?php

namespace App\Models;

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

class Exam extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'academic_year_id',
        'class_id',
        'subject_id',
        'name',
        'exam_type',
        'description',
        'total_marks',
        'passing_marks',
        'exam_date',
        'start_time',
        'end_time',
        'duration_minutes',
        'is_published',
    ];

    protected $casts = [
        'exam_date' => 'date',
        'start_time' => 'datetime',
        'end_time' => 'datetime',
        'total_marks' => 'decimal:2',
        'passing_marks' => 'decimal:2',
        'duration_minutes' => 'integer',
        'is_published' => 'boolean',
    ];

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

    public function class()
    {
        return $this->belongsTo(SchoolClass::class, 'class_id');
    }

    public function subject()
    {
        return $this->belongsTo(Subject::class);
    }

    public function marks()
    {
        return $this->hasMany(Mark::class);
    }

    public function schedules()
    {
        return $this->hasMany(ExamSchedule::class);
    }

    // Scopes
    public function scopePublished($query)
    {
        return $query->where('is_published', true);
    }

    public function scopeByType($query, $type)
    {
        return $query->where('exam_type', $type);
    }

    public function scopeForClass($query, $classId)
    {
        return $query->where('class_id', $classId);
    }

    public function scopeForSubject($query, $subjectId)
    {
        return $query->where('subject_id', $subjectId);
    }

    public function scopeUpcoming($query)
    {
        return $query->where('exam_date', '>=', now()->toDateString());
    }

    public function scopeCompleted($query)
    {
        return $query->where('exam_date', '<', now()->toDateString());
    }

    // Accessors
    public function getPassingPercentageAttribute()
    {
        return $this->total_marks > 0 ? round(($this->passing_marks / $this->total_marks) * 100, 2) : 0;
    }

    // Methods
    public function calculateClassAverage()
    {
        return $this->marks()->avg('marks_obtained');
    }

    public function getPassedStudentsCount()
    {
        return $this->marks()->where('marks_obtained', '>=', $this->passing_marks)->count();
    }

    public function getFailedStudentsCount()
    {
        return $this->marks()->where('marks_obtained', '<', $this->passing_marks)->count();
    }
}
