<?php

declare(strict_types=1);

final class LabReferenceService
{
    public static function all(): array
    {
        return DB::pdo()
            ->query(
                'SELECT * FROM lab_reference_ranges ORDER BY analyzer_name COLLATE NOCASE,species_code,sort_order,parameter_code COLLATE NOCASE',
            )
            ->fetchAll(PDO::FETCH_ASSOC);
    }
    public static function forAnimal(string $species): array
    {
        $species = SpeciesService::normalize($species);
        $s = DB::pdo()->prepare(
            'SELECT analyzer_code,analyzer_name,parameter_code,parameter_name,unit,reference_min,reference_max FROM lab_reference_ranges WHERE species_code=? AND active=1 ORDER BY analyzer_name COLLATE NOCASE,sort_order,parameter_code COLLATE NOCASE',
        );
        $s->execute([$species]);
        $out = [];
        foreach ($s->fetchAll(PDO::FETCH_ASSOC) as $r) {
            $key = $r['analyzer_code'];
            $out[$key]['label'] = $r['analyzer_name'];
            $out[$key]['parameters'][] = [
                'code' => $r['parameter_code'],
                'name' => $r['parameter_name'],
                'unit' => $r['unit'],
                'min' => $r['reference_min'],
                'max' => $r['reference_max'],
            ];
        }
        return $out;
    }
}
