<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/includes/class-mailer.php
// Description: Intercepts wp_mail via pre_wp_mail and routes through active email provider HTTP API - NUCLEAR+++
// Last Edited: 2026-05-10
// ==================================================

namespace AutoMarketerAI;

defined('ABSPATH') || exit;

final class Mailer
{
    private const KNOWN_PROVIDERS = ['email-elastic', 'email-sendgrid'];

    public static function init(): void
    {
        add_filter('pre_wp_mail', [self::class, 'intercept'], 10, 2);
        add_filter('wp_mail_from',      [self::class, 'fromAddress']);
        add_filter('wp_mail_from_name', [self::class, 'fromName']);
    }

    // returns true (sent), false (failed), or null (fall through to WP default)
    public static function intercept(mixed $return, array $atts): mixed
    {
        // internal install -- always use EE directly, skip module lookup
        if (defined('AMAI_INTERNAL_INSTALL') && AMAI_INTERNAL_INSTALL) {
            $api_key = KeyVault::decrypt((string) get_option('amai_api_key_email-elastic', ''));
            if ($api_key === '') {
                return null;
            }
            $module_file = AMAI_PLUGIN_DIR . 'modules/email-elastic.php';
            if (!is_file($module_file)) {
                return null;
            }
            require_once $module_file;
            $class = \AutoMarketerAI\Modules\EmailElastic::class;
        } else {
            $provider_id = self::getActiveProviderId();
            if ($provider_id === '') {
                return null;
            }
            $api_key = KeyVault::decrypt((string) get_option('amai_api_key_' . $provider_id, ''));
            if ($api_key === '') {
                return null;
            }
            $module_file = AMAI_PLUGIN_DIR . 'modules/' . $provider_id . '.php';
            if (!is_file($module_file)) {
                return null;
            }
            require_once $module_file;
            $class_map = [
                'email-elastic'  => \AutoMarketerAI\Modules\EmailElastic::class,
                'email-sendgrid' => \AutoMarketerAI\Modules\EmailSendgrid::class,
            ];
            $class = $class_map[$provider_id] ?? '';
            if ($class === '' || !class_exists($class)) {
                return null;
            }
        }

        $to      = is_array($atts['to']) ? implode(',', $atts['to']) : (string) ($atts['to'] ?? '');
        $subject = (string) ($atts['subject'] ?? '');
        $message = (string) ($atts['message'] ?? '');
        $headers = $atts['headers'] ?? [];

        // detect html content-type
        $is_html = false;
        foreach ((array) $headers as $h) {
            if (stripos((string) $h, 'content-type') !== false && stripos((string) $h, 'text/html') !== false) {
                $is_html = true;
                break;
            }
        }
        $html_body = $is_html ? $message : nl2br(esc_html($message));

        $to_email = trim(explode(',', $to)[0]);

        $module = new $class();
        $result = $module->send($to_email, '', $subject, $html_body, $api_key);

        return $result ? true : false;
    }

    public static function fromAddress(string $email): string
    {
        $override = AbstractEmailProvider::get_sender_email();
        return $override !== '' ? $override : $email;
    }

    public static function fromName(string $name): string
    {
        $override = AbstractEmailProvider::get_sender_name();
        return $override !== '' ? $override : $name;
    }

    public static function getActiveProviderId(): string
    {
        $modules = (array) get_option('amai_active_modules', []);
        foreach (self::KNOWN_PROVIDERS as $id) {
            if (in_array($id, $modules, true)) {
                return $id;
            }
        }
        return '';
    }

    public static function getActiveProviderName(): string
    {
        $id = self::getActiveProviderId();
        $names = [
            'email-elastic'  => 'Elastic Email',
            'email-sendgrid' => 'SendGrid',
        ];
        return $names[$id] ?? '';
    }

    public static function hasKey(): bool
    {
        $id = self::getActiveProviderId();
        if ($id === '') {
            return false;
        }
        $key = KeyVault::decrypt((string) get_option('amai_api_key_' . $id, ''));
        return $key !== '';
    }
}