<?php
// includes/functions/emails/mailer.php
if (!defined('ABSPATH')) exit;

/**
 * Low-level sender. Always sends HTML (with UTF-8) via wp_mail.
 * $args keys: from_name, from_email, reply_to, cc, bcc, headers (extra array), attachments (array)
 */
if (!function_exists('afb_mailer_send')) {
    function afb_mailer_send($to, $subject, $html, $text = '', array $args = []) {
        $to = is_array($to) ? $to : array_map('trim', explode(',', (string)$to));
        $to = array_values(array_filter($to));

        if (!$to) return false;

        $headers = [
            'Content-Type: text/html; charset=UTF-8',
        ];

        $from_name  = $args['from_name']  ?? afb_email_default_from_name();
        $from_email = $args['from_email'] ?? afb_email_default_from_email();
        if ($from_email) $headers[] = 'From: ' . sprintf('%s <%s>', $from_name, $from_email);

        if (!empty($args['reply_to'])) $headers[] = 'Reply-To: ' . $args['reply_to'];
        if (!empty($args['cc']))      $headers[] = 'Cc: ' . (is_array($args['cc']) ? implode(',', $args['cc']) : $args['cc']);
        if (!empty($args['bcc']))     $headers[] = 'Bcc: ' . (is_array($args['bcc']) ? implode(',', $args['bcc']) : $args['bcc']);

        if (!empty($args['headers']) && is_array($args['headers'])) {
            $headers = array_merge($headers, $args['headers']);
        }

        $attachments = !empty($args['attachments']) && is_array($args['attachments']) ? $args['attachments'] : [];

        $headers = apply_filters('afb/email/headers', $headers, $to, $subject);
        $html    = apply_filters('afb/email/html', $html, $to, $subject);
        $subject = apply_filters('afb/email/subject', $subject, $to);

        $ok = wp_mail($to, $subject, $html, $headers, $attachments);

        do_action('afb/email/' . ($ok ? 'sent' : 'failed'), [
            'to'          => $to,
            'subject'     => $subject,
            'ok'          => (bool)$ok,
            'attachments' => $attachments,
        ]);

        return (bool)$ok;
    }
}
