<?php

namespace App\Services\Grading;

use Illuminate\Support\Facades\DB;

class StrongCategoryAverageCalculator
{
    public function calculate(string $table, int $studentId, string $semester, string $schoolYear, ?int $classSectionId = null): array
    {
        $query = DB::table($table)
            ->where('student_id', $studentId)
            ->where('semester', $semester)
            ->where('school_year', $schoolYear);

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

        $rows = $query->get();
        $included = [];
        $pending = [];
        $excluded = [];

        foreach ($rows as $row) {
            $status = (string) ($row->status ?? 'pending');
            $score = $row->score ?? null;
            $maxPoints = isset($row->max_points) && is_numeric($row->max_points) && (float) $row->max_points > 0
                ? (float) $row->max_points
                : 100.0;

            if ($status === 'pending' || $status === '') {
                $pending[] = $row;
                continue;
            }

            if (in_array($status, ['excused', 'not_assigned'], true)) {
                $excluded[] = $row;
                continue;
            }

            if ($status === 'missing') {
                $included[] = 0.0;
                continue;
            }

            if ($status === 'scored' && $score !== null && is_numeric($score)) {
                $included[] = ((float) $score / $maxPoints) * 100;
            }
        }

        return [
            'average' => count($included) > 0 ? round(array_sum($included) / count($included), 2) : null,
            'included_count' => count($included),
            'excluded_count' => count($excluded),
            'pending_count' => count($pending),
            'has_pending' => count($pending) > 0,
        ];
    }
}
