<?php
/**
 * 247ChatMate — Email Delivery Foundation (Normal + Agency)
 * ---------------------------------------------------------
 * Shared, lightweight email helper for normal user lead alerts,
 * weekly summaries and agency routing tests.
 *
 * Current locked rule:
 * - Do not spoof agency/client/customer mailboxes as the From address.
 * - Use the site/host's existing WordPress sender route for delivery.
 * - Present the visible sender name as 247ChatMate.
 * - Use Reply-To for the correct agency/client/customer reply path.
 * - External providers such as Postmark/Brevo remain a later checkpoint.
 */

defined('ABSPATH') || exit;

if (!function_exists('matewa_email_delivery_from_name')) {
    function matewa_email_delivery_from_name() {
        return '247ChatMate';
    }
}


if (!function_exists('matewa_email_delivery_safe_sender_email')) {
    function matewa_email_delivery_safe_sender_email() {
        $host = wp_parse_url(home_url('/'), PHP_URL_HOST);
        $host = strtolower(preg_replace('/[^a-z0-9\.\-]/', '', (string) $host));
        $host = preg_replace('/^www\./', '', $host);
        if ('' !== $host && false !== strpos($host, '.')) {
            foreach (array('leads@' . $host, 'wordpress@' . $host, 'noreply@' . $host) as $email) {
                if (is_email($email)) {
                    return $email;
                }
            }
        }
        $admin_email = sanitize_email((string) get_option('admin_email', ''));
        return is_email($admin_email) ? $admin_email : '';
    }
}

if (!function_exists('matewa_email_delivery_from_filter')) {
    function matewa_email_delivery_from_filter($email) {
        $safe = matewa_email_delivery_safe_sender_email();
        return is_email($safe) ? $safe : $email;
    }
}

if (!function_exists('matewa_email_delivery_from_name_filter')) {
    function matewa_email_delivery_from_name_filter($name) {
        return matewa_email_delivery_from_name();
    }
}

if (!function_exists('matewa_email_delivery_sanitise_subject')) {
    function matewa_email_delivery_sanitise_subject($subject) {
        $subject = sanitize_text_field((string) $subject);
        return wp_specialchars_decode($subject, ENT_QUOTES);
    }
}

if (!function_exists('matewa_email_delivery_headers')) {
    function matewa_email_delivery_headers($args = array()) {
        $args = is_array($args) ? $args : array();
        $content_type = isset($args['content_type']) ? (string) $args['content_type'] : 'text/plain';
        $content_type = ('text/html' === strtolower($content_type)) ? 'text/html' : 'text/plain';

        $headers = array('Content-Type: ' . $content_type . '; charset=UTF-8');

        $reply_to = isset($args['reply_to']) ? sanitize_email((string) $args['reply_to']) : '';
        if (is_email($reply_to)) {
            $headers[] = 'Reply-To: ' . $reply_to;
        }

        return $headers;
    }
}

if (!function_exists('matewa_email_delivery_send')) {
    function matewa_email_delivery_send($to, $subject, $message, $args = array()) {
        $to = sanitize_email((string) $to);
        if (!is_email($to)) {
            return false;
        }

        $subject = matewa_email_delivery_sanitise_subject($subject);
        $headers = matewa_email_delivery_headers($args);

        add_filter('wp_mail_from_name', 'matewa_email_delivery_from_name_filter', 99);
        add_filter('wp_mail_from', 'matewa_email_delivery_from_filter', 99);
        $sent = wp_mail($to, $subject, (string) $message, $headers);
        remove_filter('wp_mail_from_name', 'matewa_email_delivery_from_name_filter', 99);
        remove_filter('wp_mail_from', 'matewa_email_delivery_from_filter', 99);

        return (bool) $sent;
    }
}

if (!function_exists('matewa_email_delivery_send_result')) {
    function matewa_email_delivery_send_result($to, $subject, $message, $args = array()) {
        $to = sanitize_email((string) $to);
        $result = array(
            'to'     => $to,
            'sent'   => false,
            'method' => 'wordpress_default_sender_247chatmate_name',
            'error'  => '',
        );

        if (!is_email($to)) {
            $result['error'] = 'Invalid recipient email.';
            return $result;
        }

        $last_mail_error = '';
        $failure_hook = function($wp_error) use (&$last_mail_error) {
            if (is_wp_error($wp_error)) {
                $last_mail_error = $wp_error->get_error_message();
            }
        };

        add_action('wp_mail_failed', $failure_hook, 10, 1);
        $sent = matewa_email_delivery_send($to, $subject, $message, $args);
        remove_action('wp_mail_failed', $failure_hook, 10);

        if ($sent) {
            $result['sent'] = true;
            return $result;
        }

        $result['error'] = '' !== $last_mail_error ? $last_mail_error : 'wp_mail returned false.';
        return $result;
    }
}
