<?php

namespace App\Models;

use CodeIgniter\Model;
use App\Models\AcademicYearModel;

class GraduationSettingModel extends Model
{
    protected $table            = 'graduation_settings';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $allowedFields    = [
        'academic_year_id', 'final_grade_id', 'announcement_datetime',
        'is_active', 'allow_skl_download', 'custom_message'
    ];

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

    // Get settings for a specific academic year, or active year if null
    public function getSettingsByYear(int $academicYearId)
    {
        return $this->where('academic_year_id', $academicYearId)->first();
    }

    // Get active settings (from active academic year)
    public function getActiveSettings()
    {
        $academicYearModel = new AcademicYearModel();
        $activeYear = $academicYearModel->getActive();

        if (!$activeYear) {
            return null;
        }

        return $this->getSettingsByYear($activeYear['id']);
    }

    // Get final_grade_id for the active academic year
    public function getActiveFinalGradeId()
    {
        $activeSettings = $this->getActiveSettings();
        return $activeSettings['final_grade_id'] ?? null;
    }
}
