Files
alrahma_sunday_school_api/app/Services/EmergencyContacts/EmergencyContactDirectoryService.php
T
2026-06-11 11:46:12 -04:00

91 lines
2.8 KiB
PHP

<?php
namespace App\Services\EmergencyContacts;
use App\Models\EmergencyContact;
use App\Models\Student;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
class EmergencyContactDirectoryService
{
public function groups(?array $parentIds = null): array
{
$parentIds = ! empty($parentIds)
? array_values(array_filter(array_map('intval', $parentIds), static fn ($id) => $id > 0))
: EmergencyContact::query()
->distinct()
->pluck('parent_id')
->filter(static fn ($id) => (int) $id > 0)
->values()
->all();
$groups = [];
foreach ($parentIds as $parentId) {
$parentId = (int) $parentId;
$parent = User::query()->find($parentId);
$parentName = $parent
? trim((string) $parent->firstname.' '.(string) $parent->lastname)
: 'Unknown Parent';
if ($parentName === '') {
$parentName = 'Unknown Parent';
}
$parentPhone = $parent ? (string) ($parent->cellphone ?? '') : '';
$secondPhone = $this->secondParentPhone($parentId);
$students = Student::query()
->select(['id', 'firstname', 'lastname', 'school_id'])
->where('parent_id', $parentId)
->get()
->toArray();
$contacts = EmergencyContact::query()
->where('parent_id', $parentId)
->orderBy('updated_at', 'DESC')
->get()
->toArray();
$groups[] = [
'parent_id' => $parentId,
'parent_name' => $parentName,
'parent_phones' => array_values(array_filter([
$parentPhone,
$secondPhone,
], static fn ($value) => (string) $value !== '')),
'students' => $students,
'contacts' => $contacts,
];
}
return $groups;
}
private function secondParentPhone(int $parentId): string
{
try {
if (! Schema::hasTable('parents')) {
return '';
}
if (! Schema::hasColumn('parents', 'secondparent_phone')) {
return '';
}
$phone = DB::table('parents')
->where('firstparent_id', $parentId)
->orderByDesc('updated_at')
->value('secondparent_phone');
return $phone ? (string) $phone : '';
} catch (\Throwable $e) {
Log::debug('EmergencyContactDirectoryService: could not load second parent phone: '.$e->getMessage());
return '';
}
}
}