<?php

namespace App\Libraries\Tuition;

final class GradeLevelParser
{
    public static function parse($grade, int $gradeFee = 9): int
    {
        if (is_numeric($grade)) {
            return (int) $grade;
        }

        if (!is_string($grade)) {
            return 999;
        }

        $value = strtoupper(trim($grade));
        $value = preg_replace('/\s+/', ' ', $value) ?? $value;
        $value = str_replace(['.', '_', '-'], ['', '', ' '], $value);

        if (in_array($value, ['K', 'KG', 'K G', 'KINDER', 'KINDERGARTEN'], true)) {
            return 1;
        }

        if (in_array($value, ['PK', 'P K', 'PREK', 'PRE K', 'PRE KINDER', 'PREKINDER'], true)) {
            return -1;
        }

        if (preg_match('/^Y(?:OUTH)?\s*(\d+)?$/', $value, $matches)) {
            $offset = isset($matches[1]) && $matches[1] !== '' ? max(1, (int) $matches[1]) : 1;
            return $gradeFee + $offset;
        }

        if (preg_match('/^(?:GR?ADE\s*)?(\d{1,2})\s*([A-Z]*)$/', $value, $matches)) {
            return (int) $matches[1];
        }

        return 999;
    }
}
