<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class EmailService
{
    public function send(
        array|string $to,
        string $subject,
        string $html,
        string $fromKey = 'general',
        array $cc = [],
        array $bcc = []
    ): bool
    {
        $sender = $this->resolveSender($fromKey);

        try {
            Mail::html($html, function ($message) use ($to, $subject, $sender, $cc, $bcc) {
                $message->to($to)->subject($subject);
                if ($sender['email'] !== '') {
                    $message->from($sender['email'], $sender['name']);
                }
                if (!empty($cc)) {
                    $message->cc($cc);
                }
                if (!empty($bcc)) {
                    $message->bcc($bcc);
                }
            });
            return true;
        } catch (\Throwable $e) {
            Log::error('EmailService send failed: ' . $e->getMessage());
            return false;
        }
    }

    private function resolveSender(string $fromKey): array
    {
        $fromKey = $fromKey !== '' ? $fromKey : 'general';
        $json = env('MAIL_SENDERS', '{}');
        $senders = json_decode($json, true);

        if (is_array($senders) && isset($senders[$fromKey])) {
            $info = $senders[$fromKey];
            return [
                'name' => (string) ($info['name'] ?? 'Sender'),
                'email' => (string) ($info['email'] ?? ''),
            ];
        }

        $fallbackAddress = (string) (config('mail.from.address') ?: (getenv('SMTP_USER') ?: ''));
        $fallbackName = (string) (config('mail.from.name') ?: 'Al Rahma Sunday School');

        return [
            'name' => $fallbackName,
            'email' => $fallbackAddress,
        ];
    }
}
