<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Exam extends Model
{
    /**
     * fillable
     *
     * @var array
     */
    protected $fillable = [
        'title',
        'lesson_id',
        'classroom_id',
        'duration',
        'description',
        'random_question',
        'random_answer',
        'show_answer',
        'question_weights',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'question_weights' => 'array',
    ];

    /**
     * Get question weights, falling back to equal distribution
     *
     * @return array
     */
    public function getWeights()
    {
        if (!empty($this->question_weights)) {
            return $this->question_weights;
        }

        return [
            'pg' => 20,
            'pg_kompleks' => 20,
            'menjodohkan' => 20,
            'isian' => 20,
            'uraian' => 20,
        ];
    }

    /**
     * lesson
     *
     * @return void
     */
    public function lesson()
    {
        return $this->belongsTo(Lesson::class);
    }

    /**
     * classroom
     *
     * @return void
     */
    public function classroom()
    {
        return $this->belongsTo(Classroom::class);
    }

    /**
     * questions
     *
     * @return void
     */
    public function questions()
    {
        return $this->belongsToMany(Question::class, 'exam_questions')
            ->withPivot('order_number')
            ->orderBy('id', 'DESC');
    }

    /**
     * grades
     *
     * @return void
     */
    public function grades()
    {
        return $this->hasMany(Grade::class);
    }

    /**
     * sessions
     *
     * @return void
     */
    public function sessions()
    {
        return $this->hasMany(ExamSession::class);
    }
}
