builder(); $builder->select('score') ->where('student_id', $studentId) ->where('semester', $semester) ->where('school_year', $schoolYear); if ($classSectionId !== null) { $builder->where('class_section_id', $classSectionId); } // Execute the query and get the results $query = $builder->get(); $results = $query->getResultArray(); // If there are no scores, return null if (empty($results)) { return null; } // Calculate the average score (ignore blank/null/non-numeric) $totalScore = 0.0; $scoreCount = 0; foreach ($results as $result) { $score = $result['score'] ?? null; if ($score === null || (is_string($score) && trim($score) === '') || $score === '' || !is_numeric($score)) { continue; } $totalScore += (float) $score; $scoreCount++; } if ($scoreCount === 0) { return null; } return $totalScore / $scoreCount; } }