Files
alrahma_sunday_school_api/app/Services/Badges/BadgeStudentLookupService.php
T
2026-04-23 00:04:35 -04:00

79 lines
2.3 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services\Badges;
use App\Models\Student;
use App\Models\StudentClass;
class BadgeStudentLookupService
{
public function __construct(
protected BadgeTextFormatter $formatter
) {
}
/**
* Load students for badge printing: valid school_id (QR payload), ordered by name.
*
* @param int[] $studentIds
* @return array<int, array{student_id:int, fullname:string, grade:string, academic_year:string, school_id:string}>
*/
public function fetchForBadges(array $studentIds, ?string $schoolYear): array
{
$studentIds = $this->formatter->normalizeIds($studentIds);
if ($studentIds === []) {
return [];
}
$rows = Student::query()
->whereIn('id', $studentIds)
->where('is_active', 1)
->orderBy('lastname')
->orderBy('firstname')
->get();
$out = [];
foreach ($rows as $student) {
$schoolId = trim((string) ($student->school_id ?? ''));
if ($schoolId === '' || !preg_match('/^[A-Za-z0-9_-]+$/', $schoolId)) {
continue;
}
$fullname = Student::getFullName($student->toArray());
$grade = $this->resolveGrade((int) $student->id, (string) ($student->registration_grade ?? ''));
$academicYear = $schoolYear ?? (string) ($student->school_year ?? '');
$academicYear = $this->formatter->norm($academicYear);
$out[] = [
'student_id' => (int) $student->id,
'fullname' => $fullname !== '' ? $fullname : 'Student',
'grade' => $grade,
'academic_year' => $academicYear,
'school_id' => $schoolId,
];
}
return $out;
}
protected function resolveGrade(int $studentId, string $registrationGrade): string
{
$registrationGrade = $this->formatter->norm($registrationGrade);
if ($registrationGrade !== '') {
return $registrationGrade;
}
try {
$g = StudentClass::getStudentGrade($studentId);
$g = $this->formatter->norm((string) $g);
return $g !== '' ? $g : '—';
} catch (\Throwable) {
return '—';
}
}
}