<?php

namespace App\Services\Invoices;

class InvoiceGradeService
{
    public function __construct(private int $gradeFee)
    {
    }

    public function isKindergarten(string $grade): bool
    {
        $g = strtolower(trim($grade));
        return in_array($g, ['KG', 'kg', 'k', 'kindergarten', 'k-g', 'k.g', 'k g'], true);
    }

    public function compareGrades(string $gradeA, string $gradeB): int
    {
        $valA = $this->getGradeLevel($gradeA);
        $valB = $this->getGradeLevel($gradeB);

        if ($valA['level'] !== $valB['level']) {
            return $valA['level'] <=> $valB['level'];
        }

        return strcmp($valA['suffix'] ?? '', $valB['suffix'] ?? '');
    }

    public function gradeLevelInt(string $grade): int
    {
        $gl = $this->getGradeLevel($grade);
        return (int) ($gl['level'] ?? 0);
    }

    public function getGradeLevel($grade): array
    {
        if (is_numeric($grade)) {
            $num = (int) $grade;
            if ($num === 13) {
                return ['level' => 1, 'suffix' => '', 'classId' => 13];
            }
            return ['level' => $num, 'suffix' => '', 'classId' => null];
        }

        if (!is_string($grade)) {
            return ['level' => 999, 'suffix' => '', 'classId' => null];
        }

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

        $kg = ['K', 'KG', 'K G', 'KINDER', 'KINDERGARTEN'];
        if (in_array($g, $kg, true)) {
            return ['level' => 1, 'suffix' => '', 'classId' => 13];
        }

        $pk = ['PK', 'P K', 'PREK', 'PRE K', 'PRE-K', 'PRE KINDER', 'PREKINDER'];
        if (in_array($g, $pk, true)) {
            return ['level' => -1, 'suffix' => '', 'classId' => null];
        }

        if (preg_match('/^Y(?:OUTH)?(?:\s*(\d+))?$/', $g, $m)) {
            $n = isset($m[1]) && $m[1] !== '' ? max(1, (int) $m[1]) : 1;
            return [
                'level' => $this->gradeFee + $n,
                'suffix' => '',
                'classId' => null,
            ];
        }

        if (preg_match('/^(?:GR?ADE\s*)?(\d{1,2})\s*([A-Z]*)$/', $g, $m)) {
            return [
                'level' => (int) $m[1],
                'suffix' => $m[2] ?? '',
                'classId' => null,
            ];
        }

        return ['level' => 999, 'suffix' => '', 'classId' => null];
    }
}
