<?php

function displayMark($mark)
{
    if (floatval($mark) === 0.0) {
        return '-';
    }
        return $mark;
}

function displayGrade($array, &$temp_count)
{
    $total_marks_index = $temp_count;
    $grade_index = $temp_count + 1; 
    $result = (floatval($array[$total_marks_index]) === 0.0) ? '-' : $array[$grade_index];
    $temp_count = $grade_index;
    return $result;
}

function get_grade($temp_marks, $total_marks)
{
    if ($total_marks <= 0) {
        return 'Invalid total marks'; // Handle zero or negative total_marks
    }

    $temp = ($temp_marks / $total_marks) * 100;

    if ($temp >= 91 && $temp <= 100) {
        return 'A 1';
    } elseif ($temp >= 81 && $temp < 91) {
        return 'A 2';
    } elseif ($temp >= 71 && $temp < 81) {
        return 'B 1';
    } elseif ($temp >= 61 && $temp < 71) {
        return 'B 2';
    } elseif ($temp >= 51 && $temp < 61) {
        return 'C 1';
    } elseif ($temp >= 41 && $temp < 51) {
        return 'C 2';
    } elseif ($temp >= 33 && $temp < 41) {
        return 'D';
    } else {
        return 'E';
    }
}

function calculatePercentage($marksData) {
    $totalObtained = 0;
    $totalMax = 0;
    
    for ($i = 2; $i <= 49; $i += 6) {
        $subjectName = $marksData[$i] ?? '';
    
        if (empty(trim($subjectName))) {
            continue;
        }
        
        $subjectType = $marksData[$i + 1] ?? '';
        
        // Get theory marks
        $theoryMax = (float)($marksData[$i + 2] ?? 0);
        $theoryMarks = (float)($marksData[$i + 3] ?? 0);
        
        // Get practical marks
        $practicalMax = (float)($marksData[$i + 4] ?? 0);
        $practicalMarks = (float)($marksData[$i + 5] ?? 0);
        
        // Calculate subject totals
        $subjectTotalMarks = $theoryMax + $practicalMax;
        $subjectObtainedMarks = $theoryMarks + $practicalMarks;
        
        // Only include Mandatory (M) and Optional (O) subjects in overall percentage
        if ($subjectType === 'M' || $subjectType === 'O') {
            $totalObtained += $subjectObtainedMarks;
            $totalMax += $subjectTotalMarks;
        }
    }
    
    // Calculate overall percentage
    $percentage = $totalMax > 0 ? round(($totalObtained / $totalMax) * 100, 2) : 0;
    
    return $percentage;
}