<?php

namespace App\Models;

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

class Mark extends Model
{
    use HasFactory;

    protected $fillable = [
        'exam_id',
        'student_id',
        'subject_id',
        'marks_obtained',
        'remarks',
        'grade',
        'is_absent',
        'entered_by',
    ];

    protected $casts = [
        'marks_obtained' => 'decimal:2',
        'is_absent' => 'boolean',
    ];

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

    public function student()
    {
        return $this->belongsTo(Student::class);
    }

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

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

    // Scopes
    public function scopeForExam($query, $examId)
    {
        return $query->where('exam_id', $examId);
    }

    public function scopeForStudent($query, $studentId)
    {
        return $query->where('student_id', $studentId);
    }

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

    public function scopePresent($query)
    {
        return $query->where('is_absent', false);
    }

    public function scopeAbsent($query)
    {
        return $query->where('is_absent', true);
    }

    public function scopePassed($query)
    {
        return $query->whereHas('exam', function($q) {
            $q->whereRaw('marks_obtained >= passing_marks');
        });
    }

    // Accessors
    public function getPercentageAttribute()
    {
        $totalMarks = $this->exam?->total_marks ?? 0;
        return $totalMarks > 0 ? round(($this->marks_obtained / $totalMarks) * 100, 2) : 0;
    }

    public function getIsPassedAttribute()
    {
        $passingMarks = $this->exam?->passing_marks ?? 0;
        return $this->marks_obtained >= $passingMarks;
    }
}
