<?php

namespace App\Services\Incidents;

use App\Models\ClassSection;
use App\Models\StudentClass;
use Illuminate\Support\Facades\DB;

class IncidentLookupService
{
    public function gradeOptionsWithActiveStudents(?string $schoolYear = null): array
    {
        $studentCounts = StudentClass::getStudentCountsBySection($schoolYear);
        if (empty($studentCounts)) {
            return [];
        }

        $classSections = ClassSection::query()
            ->orderBy('class_section_name', 'ASC')
            ->whereIn('class_section_id', array_keys($studentCounts))
            ->get()
            ->map(fn ($row) => $row->toArray())
            ->all();

        $grades = [];
        foreach ($classSections as $section) {
            $grades[] = [
                'id' => $section['class_section_id'],
                'name' => $section['class_section_name'],
            ];
        }

        return $grades;
    }

    public function gradeNameMap(array $gradeValues): array
    {
        $gradeIds = [];
        foreach ($gradeValues as $gradeValue) {
            if (is_numeric($gradeValue)) {
                $gradeIds[(int) $gradeValue] = true;
            }
        }

        if (empty($gradeIds)) {
            return [];
        }

        $rows = ClassSection::query()
            ->select('class_section_id', 'class_section_name')
            ->whereIn('class_section_id', array_keys($gradeIds))
            ->get()
            ->map(fn ($row) => $row->toArray())
            ->all();

        $gradeMap = [];
        foreach ($rows as $row) {
            $gradeMap[(int) $row['class_section_id']] = (string) ($row['class_section_name'] ?? '');
        }

        return $gradeMap;
    }

    public function updaterNameMap(array $userIds): array
    {
        $userIds = array_values(array_filter(array_unique(array_map('intval', $userIds))));
        if (empty($userIds)) {
            return [];
        }

        $rows = DB::table('users')
            ->select('id', 'firstname', 'lastname')
            ->whereIn('id', $userIds)
            ->get()
            ->map(fn ($row) => $row instanceof \Illuminate\Contracts\Support\Arrayable ? $row->toArray() : (array) $row)
            ->all();

        $map = [];
        foreach ($rows as $row) {
            $id = $row['id'] ?? $row['user_id'] ?? null;
            if ($id === null) {
                continue;
            }
            $name = trim((string) ($row['firstname'] ?? '') . ' ' . (string) ($row['lastname'] ?? ''));
            $map[(int) $id] = $name !== '' ? $name : ('User #' . $id);
        }

        return $map;
    }
}
