<?php

namespace App\Services\Communication;

use App\Models\FamilyStudent;
use Illuminate\Support\Facades\DB;

class CommunicationFamilyService
{
    public function familiesForStudent(int $studentId): array
    {
        return FamilyStudent::getFamiliesForStudent($studentId);
    }

    public function guardiansForFamily(int $familyId): array
    {
        return DB::table('family_guardians as fg')
            ->join('users as u', 'u.id', '=', 'fg.user_id')
            ->where('fg.family_id', $familyId)
            ->select(
                'u.id as user_id',
                'u.firstname',
                'u.lastname',
                'u.email',
                'fg.relation',
                'fg.is_primary',
                'fg.receive_emails',
                'fg.receive_sms'
            )
            ->get()
            ->map(fn ($row) => (array) $row)
            ->all();
    }

    public function guardianSalutation(int $familyId): string
    {
        $rows = DB::table('family_guardians as fg')
            ->join('users as u', 'u.id', '=', 'fg.user_id')
            ->where('fg.family_id', $familyId)
            ->where('fg.receive_emails', 1)
            ->orderByDesc('fg.is_primary')
            ->orderBy('u.lastname')
            ->orderBy('u.firstname')
            ->select('u.firstname', 'u.lastname')
            ->get()
            ->map(fn ($row) => (array) $row)
            ->all();

        if (empty($rows)) {
            return 'Parent/Guardian';
        }

        $names = array_map(static function ($row) {
            return trim(($row['firstname'] ?? '') . ' ' . ($row['lastname'] ?? ''));
        }, $rows);

        return implode(' & ', $names);
    }
}
