<?php

namespace App\Models;

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

class BatchStatistic extends Model
{
    use HasFactory;

    protected $fillable = [
        'session',
        'exam_id',
        'total_students',
        'appeared',
        'passed',
        'failed',
        'average_marks',
        'highest_marks',
        'lowest_marks',
        'pass_rate',
    ];

    protected $casts = [
        'total_students' => 'integer',
        'appeared' => 'integer',
        'passed' => 'integer',
        'failed' => 'integer',
        'average_marks' => 'decimal:2',
        'highest_marks' => 'integer',
        'lowest_marks' => 'integer',
        'pass_rate' => 'decimal:2',
    ];

    /**
     * Get the academic session
     */
    public function academicSession()
    {
        return $this->belongsTo(AcademicSession::class, 'session', 'session');
    }

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

    /**
     * Scope to filter by session
     */
    public function scopeForSession($query, $session)
    {
        return $query->where('session', $session);
    }

    /**
     * Scope to filter by exam
     */
    public function scopeForExam($query, $examId)
    {
        return $query->where('exam_id', $examId);
    }

    /**
     * Calculate pass rate
     */
    public function calculatePassRate()
    {
        if ($this->appeared > 0) {
            $this->pass_rate = ($this->passed / $this->appeared) * 100;
            $this->save();
        }
        
        return $this->pass_rate;
    }
}
