<?php

namespace App\Models;

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

class AdmissionTest extends Model
{
    use HasFactory;

    protected $table = 'admission_tests';
    
    protected $fillable = [
        'application_id',
        'roll_number',
        'test_date',
        'test_time',
        'room_number',
        'written_marks',
        'mcq_marks',
        'viva_marks',
        'total_marks',
        'merit_position',
        'status', // scheduled, completed, absent
        'checked_by',
        'remarks'
    ];

    protected $casts = [
        'test_date' => 'date',
        'test_time' => 'datetime',
        'written_marks' => 'decimal:2',
        'mcq_marks' => 'decimal:2',
        'viva_marks' => 'decimal:2',
        'total_marks' => 'decimal:2',
        'merit_position' => 'integer'
    ];

    public function application()
    {
        return $this->belongsTo(AdmissionApplication::class);
    }

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

    // Generate roll number
    public static function generateRollNumber($classId)
    {
        $lastTest = self::whereHas('application', function($q) use ($classId) {
            $q->where('class_id', $classId);
        })->orderBy('id', 'desc')->first();
        
        if ($lastTest) {
            return $lastTest->roll_number + 1;
        }
        
        return 1001; // Starting roll number
    }
}