<?php

namespace App\Services\Fees;

use App\Models\ClassSection;

class FeeStudentFeeService
{
    public function __construct(
        private FeeGradeService $grades,
        private FeeConfigService $config
    ) {
    }

    public function assignFees(array $students): array
    {
        $fees = $this->config->getFees();
        $firstFee = $fees['first_student_fee'];
        $secondFee = $fees['second_student_fee'];
        $youthFee = $fees['youth_fee'];

        foreach ($students as &$student) {
            $grade = $student['grade'] ?? null;
            if ($grade === null || trim((string) $grade) === '') {
                $sectionId = $student['class_section_id'] ?? null;
                $grade = $sectionId ? ClassSection::getClassSectionNameBySectionId($sectionId) : null;
            }
            $student['grade'] = $this->grades->normalizeGrade($grade);
        }
        unset($student);

        usort($students, function ($a, $b) {
            return $this->grades->compareGrades($a['grade'] ?? '', $b['grade'] ?? '');
        });

        $regularCount = 0;
        foreach ($students as &$student) {
            $gradeLevel = $this->grades->getGradeLevel($student['grade'] ?? '');
            if ($gradeLevel > 9) {
                $student['tuition_fee'] = $youthFee;
            } else {
                $student['tuition_fee'] = ($regularCount === 0) ? $firstFee : $secondFee;
                $regularCount++;
            }
        }
        unset($student);

        return $students;
    }

    public function totalTuitionFee(array $students): float
    {
        $students = $this->assignFees($students);

        $total = 0.0;
        foreach ($students as $student) {
            $total += (float) ($student['tuition_fee'] ?? 0);
        }

        return $total;
    }
}
