<?php

namespace App\Services\Email;

class EmailSenderOptionsService
{
    public function listSenders(): array
    {
        $json = env('MAIL_SENDERS', '{}');
        $arr = json_decode($json, true);

        if (!is_array($arr) || empty($arr)) {
            $smtpUser = getenv('SMTP_USER') ?: '';
            $name = 'Al Rahma Sunday School';

            return [[
                'key' => 'general',
                'name' => $name,
                'email' => $smtpUser,
                'label' => trim($name . ($smtpUser ? " <{$smtpUser}>" : '')),
            ]];
        }

        $out = [];
        foreach ($arr as $key => $info) {
            $name = $info['name'] ?? 'Sender';
            $email = $info['email'] ?? '';
            $out[] = [
                'key' => (string) $key,
                'name' => (string) $name,
                'email' => (string) $email,
                'label' => trim($name . ($email ? " <{$email}>" : '')),
            ];
        }

        return $out;
    }
}
