<?php

namespace App\Services\School;

use App\Models\Student;
use Illuminate\Support\Str;

class AdmissionNumberGenerator
{
    public function generate(?int $year = null): string
    {
        $year = $year ?? (int) now()->format('Y');
        $prefix = "SHS-{$year}-";

        $latest = Student::query()
            ->where('admission_number', 'like', $prefix.'%')
            ->orderByDesc('admission_number')
            ->value('admission_number');

        $sequence = 1;

        if (is_string($latest)) {
            $suffix = Str::afterLast($latest, '-');
            $sequence = max(1, (int) $suffix + 1);
        }

        return sprintf('%s%03d', $prefix, $sequence);
    }
}
