<?php

namespace App\Services\Scores;

use App\Interfaces\ScoreCalculatorInterface;
use Illuminate\Support\Facades\DB;

class QuizCalculator implements ScoreCalculatorInterface
{
    public function calculate(int $studentId, string $semester, string $schoolYear, ?int $classSectionId = null): array
    {
        $q = DB::table('quiz')
            ->select('score')
            ->where('student_id', $studentId)
            ->where('semester', $semester)
            ->where('school_year', $schoolYear);

        if ($classSectionId !== null) {
            $q->where('class_section_id', $classSectionId);
        }

        $rows = $q->get();
        $total = 0.0;
        $count = 0;
        foreach ($rows as $row) {
            $score = $row->score ?? null;
            if ($score === null || $score === '' || !is_numeric($score)) {
                continue;
            }
            $total += (float) $score;
            $count++;
        }

        $avg = $count > 0 ? round($total / $count, 2) : null;

        return ['quiz_avg' => $avg !== null ? (float) $avg : null];
    }
}
