<?php

namespace App\Models;

use CodeIgniter\Model;

class SchoolYearModel extends Model
{
    protected $table = 'school_years';
    protected $primaryKey = 'id';
    protected $returnType = 'array';
    protected $useTimestamps = true;

    protected $allowedFields = [
        'name',
        'status',
        'starts_on',
        'ends_on',
        'description',
        'registration_starts_on',
        'registration_ends_on',
        'previous_school_year_id',
        'next_school_year_id',
        'activated_at',
        'closing_started_at',
        'closed_at',
        'archived_at',
        'created_by',
        'updated_by',
    ];

    protected $validationRules = [
        'name' => 'required|regex_match[/^\d{4}-\d{4}$/]|max_length[9]',
        'status' => 'required|in_list[draft,active,closing,closed,archived]',
        'starts_on' => 'permit_empty|valid_date[Y-m-d]',
        'ends_on' => 'permit_empty|valid_date[Y-m-d]',
        'registration_starts_on' => 'permit_empty|valid_date[Y-m-d]',
        'registration_ends_on' => 'permit_empty|valid_date[Y-m-d]',
    ];

    public function active(): ?array
    {
        $rows = $this->where('status', 'active')
            ->orderBy('id', 'DESC')
            ->findAll(2);

        if (count($rows) !== 1) {
            return null;
        }

        return $rows[0];
    }
}
