<?php

declare(strict_types=1);

class GradeService
{
    private array $gradeScale = [
        ['min' => 90.00, 'max' => 100.00, 'grade' => 'A+'],
        ['min' => 80.00, 'max' => 89.9999, 'grade' => 'A'],
        ['min' => 70.00, 'max' => 79.9999, 'grade' => 'B+'],
        ['min' => 60.00, 'max' => 69.9999, 'grade' => 'B'],
        ['min' => 50.00, 'max' => 59.9999, 'grade' => 'C'],
        ['min' => 33.00, 'max' => 49.9999, 'grade' => 'D'],
        ['min' => 0.00, 'max' => 32.9999, 'grade' => 'F']
    ];

    public function getSubjectGrade(float $obtainedMarks, float $totalMarks, string $attendanceStatus = 'Present'): string
    {
        if ($attendanceStatus === 'Absent' || $totalMarks <= 0.0) {
            return 'F';
        }
        $percentage = round(($obtainedMarks / $totalMarks) * 100, 2);
        return $this->calculateGrade($percentage);
    }

    public function getOverallGrade(float $percentage): string
    {
        return $this->calculateGrade($percentage);
    }

    public function calculateGrade(float $percentage): string
    {
        $percentage = min($percentage, 100.0);
        foreach ($this->gradeScale as $scale) {
            if ($percentage >= $scale['min'] && $percentage <= $scale['max']) {
                return $scale['grade'];
            }
        }
        return 'F';
    }

    public function getResultStatus(float $obtainedMarks, float $totalMarks, string $attendanceStatus = 'Present', float $passPercentage = 33.0): string
    {
        if ($attendanceStatus === 'Absent' || $totalMarks <= 0.0) {
            return 'Fail';
        }
        $requiredMarks = ($totalMarks * $passPercentage) / 100;
        return $obtainedMarks >= $requiredMarks ? 'Pass' : 'Fail';
    }

    public function formatPercentage(float $percentage): float
    {
        return round($percentage, 2);
    }
}