<?php

namespace SoftminalB2B\Support;

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

/**
 * A WordPress Site Health check for email deliverability.
 *
 * The B2B suite sends invoices, approvals, registration decisions and quotes by
 * email — but only ever through `wp_mail()`; it never owns delivery. On the
 * default PHP `mail()` transport those messages are frequently dropped or
 * spam-filtered, and the merchant has no idea until a buyer complains.
 *
 * Rather than nag with an admin banner, this surfaces a *Recommended* item under
 * Tools → Site Health when no SMTP transport is detected, and clears itself the
 * moment one is active — the WordPress-native place for deliverability guidance.
 */
class MailHealth
{
    private static bool $registered = false;

    public static function init(): void
    {
        if (self::$registered) {
            return;
        }

        self::$registered = true;

        add_filter('site_status_tests', [self::class, 'register']);
    }

    /**
     * @param array<string, mixed> $tests
     * @return array<string, mixed>
     */
    public static function register($tests)
    {
        $tests['direct']['smb2b_email_delivery'] = [
            'label' => __('B2B email deliverability', 'softminal-b2b-wholesale-for-woocommerce'),
            'test'  => [self::class, 'run'],
        ];

        return $tests;
    }

    /**
     * @return array<string, mixed>
     */
    public static function run()
    {
        $badge = [
            'label' => __('Email', 'softminal-b2b-wholesale-for-woocommerce'),
            'color' => 'blue',
        ];

        if (self::hasSmtp()) {
            return [
                'label'       => __('B2B emails are sent through a mail service', 'softminal-b2b-wholesale-for-woocommerce'),
                'status'      => 'good',
                'badge'       => $badge,
                'description' => '<p>' . esc_html__('An SMTP mail service is active, so B2B invoices, approvals and quotes should deliver reliably.', 'softminal-b2b-wholesale-for-woocommerce') . '</p>',
                'test'        => 'smb2b_email_delivery',
            ];
        }

        return [
            'label'       => __('B2B emails may not be delivered reliably', 'softminal-b2b-wholesale-for-woocommerce'),
            'status'      => 'recommended',
            'badge'       => $badge,
            'description' => '<p>' . esc_html__('B2B Suite sends invoices, approvals, registration decisions and quotes by email. Your site appears to use WordPress’s default mail, which many inboxes reject or route to spam. For reliable delivery, install and configure an SMTP mail service (for example FluentSMTP, WP Mail SMTP or Post SMTP).', 'softminal-b2b-wholesale-for-woocommerce') . '</p>',
            'actions'     => sprintf(
                '<p><a href="%1$s">%2$s</a></p>',
                esc_url(admin_url('plugin-install.php?s=smtp&tab=search&type=term')),
                esc_html__('Browse SMTP plugins', 'softminal-b2b-wholesale-for-woocommerce')
            ),
            'test'        => 'smb2b_email_delivery',
        ];
    }

    /**
     * Best-effort detection of an SMTP mail transport: any of the common SMTP
     * plugins being active, or an add-on signalling it through the filter.
     */
    public static function hasSmtp(): bool
    {
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $known = [
            'fluent-smtp/fluent-smtp.php',
            'wp-mail-smtp/wp_mail_smtp.php',
            'wp-mail-smtp-pro/wp_mail_smtp.php',
            'post-smtp/postman-smtp.php',
            'easy-wp-smtp/easy-wp-smtp.php',
            'smtp-mailer/main.php',
            'wp-ses/wp-ses.php',
            'gmail-smtp/main.php',
        ];

        foreach ($known as $plugin) {
            if (is_plugin_active($plugin)) {
                return true;
            }
        }

        /**
         * Let an add-on or a custom mu-plugin declare that a reliable mail
         * transport is configured, to suppress the Site Health recommendation.
         *
         * @param bool $active
         */
        return (bool) apply_filters('smb2b_smtp_active', false);
    }
}
