<?php

namespace App\Models;

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

class PengerjaanUjian extends Model
{
    use HasFactory;

    protected $table = 'pengerjaan_ujian';

    protected $fillable = [
        'ujian_id',
        'siswa_id',
        'waktu_mulai',
        'waktu_selesai',
        'status',
        'jumlah_pelanggaran',
        'is_locked',
        'catatan_reset',
    ];

    protected function casts(): array
    {
        return [
            'waktu_mulai'        => 'datetime',
            'waktu_selesai'      => 'datetime',
            'jumlah_pelanggaran' => 'integer',
            'is_locked'          => 'boolean',
        ];
    }

    public function ujian()
    {
        return $this->belongsTo(Ujian::class);
    }

    public function siswa()
    {
        return $this->belongsTo(Siswa::class);
    }

    public function pelanggaran()
    {
        return $this->hasMany(PelanggaranUjian::class);
    }

    public function scopeSedang($query)
    {
        return $query->where('status', 'sedang');
    }

    public function scopeSelesai($query)
    {
        return $query->where('status', 'selesai');
    }

    public function getDurasiAttribute(): ?int
    {
        if (!$this->waktu_mulai || !$this->waktu_selesai) return null;
        return $this->waktu_mulai->diffInMinutes($this->waktu_selesai);
    }
}
