<?php

namespace App\Models\Concerns;

use App\Support\SchoolYear\SchoolYearContext;
use CodeIgniter\Model;

trait SchoolYearScopedModelTrait
{
    public function forSchoolYear(SchoolYearContext|string|int $schoolYear): Model
    {
        if ($schoolYear instanceof SchoolYearContext) {
            if ($this->fieldExists('school_year_id')) {
                return $this->where($this->table . '.school_year_id', $schoolYear->id());
            }

            return $this->where($this->table . '.school_year', $schoolYear->yearName());
        }

        if (is_int($schoolYear)) {
            return $this->where($this->table . '.school_year_id', $schoolYear);
        }

        return $this->where($this->table . '.school_year', $schoolYear);
    }

    private function fieldExists(string $field): bool
    {
        return in_array($field, $this->db->getFieldNames($this->table), true);
    }
}
