<?php

namespace App\Services\ClassPreparation;

use App\Models\Configuration;
use Illuminate\Support\Facades\DB;

class ClassPreparationContextService
{
    /** cache for roster presence per term */
    private array $rosterPresenceCache = [];

    public function getSchoolYear(): string
    {
        return (string) (Configuration::getConfig('school_year') ?? '');
    }

    public function getSemester(): string
    {
        return (string) (Configuration::getConfig('semester') ?? '');
    }

    public function hasRosterForSemester(string $schoolYear, string $semester): bool
    {
        $year = trim((string) $schoolYear);
        $sem = trim((string) $semester);
        if ($year === '' || $sem === '') {
            return false;
        }

        $key = sprintf('sem:%s:%s', $year, $sem);
        if (array_key_exists($key, $this->rosterPresenceCache)) {
            return $this->rosterPresenceCache[$key];
        }

        $cnt = DB::table('student_class')
            ->where('school_year', $year)
            ->where('semester', $sem)
            ->count();

        $this->rosterPresenceCache[$key] = $cnt > 0;
        return $this->rosterPresenceCache[$key];
    }
}
