<?php

namespace App\Services\BroadcastEmail;

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

class BroadcastEmailRecipientService
{
    public function parentsWithEmails(): array
    {
        $parents = User::getParents();

        return array_values(array_filter($parents, static function ($parent) {
            $email = $parent['email'] ?? '';
            return is_string($email) && trim($email) !== '';
        }));
    }

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

        return DB::table('users')
            ->select('users.id', 'users.email', DB::raw('CONCAT(users.firstname, " ", users.lastname) AS name'))
            ->whereIn('users.id', $ids)
            ->whereNotNull('users.email')
            ->where('users.email', '!=', '')
            ->get()
            ->map(fn ($row) => (array) $row)
            ->all();
    }
}
