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

if (!function_exists('afb_email_opt')) {
    function afb_email_opt($key, $default = '') {
        return function_exists('get_option') ? (string)get_option($key, $default) : $default;
    }
}

if (!function_exists('afb_email_default_from_name')) {
    function afb_email_default_from_name() {
        return wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
    }
}

if (!function_exists('afb_email_default_from_email')) {
    function afb_email_default_from_email() {
        $domain = parse_url(home_url(), PHP_URL_HOST) ?: 'localhost';
        if (substr($domain, 0, 4) === 'www.') $domain = substr($domain, 4);
        return 'no-reply@' . $domain;
    }
}

if (!function_exists('afb_email_token_replace')) {
    function afb_email_token_replace($str, array $vars) {
        return preg_replace_callback('/\{\{\s*([a-zA-Z0-9_\.]+)\s*\}\}/', function ($m) use ($vars) {
            $key = $m[1];
            return isset($vars[$key]) ? (string)$vars[$key] : '';
        }, (string)$str);
    }
}

if (!function_exists('afb_email_normalize_recipients')) {
    function afb_email_normalize_recipients($val) {
        if (is_callable($val)) $val = call_user_func($val, []);
        if (is_string($val)) $val = array_filter(array_map('trim', preg_split('/[,;]+/', $val)));
        return array_values(array_unique(array_filter((array)$val)));
    }
}
