<?php
declare(strict_types=1);

if (!defined('ABSPATH')) {
	exit;
}

/**
 * Sends a mail and verifies if it was sent via SMTP.
 */
function dsproofwp_send_mail_verified(string $to, string $subject, string $body, array $headers = [])
{
    $phpmailer_instance = null;
    $init_handler = function (&$phpmailer) use (&$phpmailer_instance) {
        $phpmailer_instance = $phpmailer;
    };

    $mail_error = null;
    $error_handler = function (WP_Error $error) use (&$mail_error) {
        $mail_error = $error->get_error_message();
    };

    add_action('phpmailer_init', $init_handler);
    add_action('wp_mail_failed', $error_handler);

    $sent = wp_mail($to, $subject, $body, $headers);

    remove_action('phpmailer_init', $init_handler);
    remove_action('wp_mail_failed', $error_handler);

    if ($mail_error) {
        return new WP_Error('dsproofwp_email_failed', 'Mailer error: ' . $mail_error, ['status' => 500]);
    }

    if ($phpmailer_instance && $phpmailer_instance->Mailer !== 'smtp') {
        return new WP_Error(
            'dsproofwp_smtp_not_configured',
            'No SMTP configuration detected. Please configure an SMTP plugin (e.g. WP Mail SMTP).',
            ['status' => 500]
        );
    }

    if (!$sent) {
        return new WP_Error('dsproofwp_email_failed', 'Email failed to send.', ['status' => 500]);
    }

    return true;
}
