<?php

namespace App\Models;

use CodeIgniter\Model;

class ExamEventModel extends Model
{
    protected $table            = 'exam_events';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = true;
    protected $allowedFields    = [
        'academic_period_id', 'name', 'event_code', 'start_date', 'end_date', 'grade_levels', 'is_locked', 'created_by', 'pairing_plan',
        'proctor_rules', 'student_rules', 'chairman_name', 'chairman_nip', 'proctors_per_room'
    ];

    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    public function getAllEvents($periodId = null)
    {
        $builder = $this->select('exam_events.*, ap.semester, ay.name as academic_year, u.name as creator_name')
            ->join('academic_periods ap', 'ap.id = exam_events.academic_period_id')
            ->join('academic_years ay', 'ay.id = ap.academic_year_id')
            ->join('users u', 'u.id = exam_events.created_by');

        if ($periodId) {
            $builder->where('exam_events.academic_period_id', $periodId);
        }

        return $builder->orderBy('exam_events.created_at', 'DESC')->findAll();
    }
}
