<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/modules/email-mailgun.php
// Description: Mailgun email provider module - NUCLEAR+++
// Last Edited: 2026-05-26
// ==================================================

namespace AutoMarketerAI\Modules;

use AutoMarketerAI\AbstractEmailProvider;

if (!defined('ABSPATH')) {
    exit('No direct script access allowed.');
}

final class EmailMailgun extends AbstractEmailProvider
{
    private const API_BASE_US = 'https://api.mailgun.net/v3';
    private const API_BASE_EU = 'https://api.eu.mailgun.net/v3';

    public function get_id(): string { return 'email-mailgun'; }
    public function get_name(): string { return 'Mailgun'; }
    public function get_description(): string { return 'Developer-focused email delivery with powerful routing, logs, and analytics. Trusted by thousands of businesses for transactional email at scale.'; }
    public function get_logo_url(): string { return 'https://automarketer-ai.com/wp-content/uploads/Mailgun-Logo.png'; }

    public function validate_api_key(string $key): bool
    {
        if (strlen($key) < 20) { return false; }
        // GET /v3/domains -- a valid key returns 200, invalid returns 401
        $response = wp_remote_get(self::API_BASE_US . '/domains?limit=1', [
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode('api:' . $key),
            ],
            'timeout' => 10,
        ]);
        if (is_wp_error($response)) { return false; }
        $code = (int) wp_remote_retrieve_response_code($response);
        if ($code === 200) { return true; }
        // EU region fallback
        if ($code === 401 || $code === 403) { return false; }
        $response_eu = wp_remote_get(self::API_BASE_EU . '/domains?limit=1', [
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode('api:' . $key),
            ],
            'timeout' => 10,
        ]);
        if (is_wp_error($response_eu)) { return false; }
        $code_eu = (int) wp_remote_retrieve_response_code($response_eu);
        return $code_eu === 200;
    }

    public function send(string $to_email, string $to_name, string $subject, string $html_body, string $api_key): bool
    {
        if ($to_email === '' || $subject === '' || $html_body === '' || $api_key === '') { return false; }

        $from_name  = \AutoMarketerAI\AbstractEmailProvider::get_sender_name();
        $from_email = \AutoMarketerAI\AbstractEmailProvider::get_sender_email();
        $domain     = $this->get_sending_domain($api_key);

        if ($domain === '') { return false; }

        $base     = $this->get_region_base($api_key);
        $endpoint = $base . '/' . $domain . '/messages';

        $response = wp_remote_post($endpoint, [
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode('api:' . $api_key),
            ],
            'body' => [
                'from'       => $from_name . ' <' . $from_email . '>',
                'to'         => $to_name !== '' ? $to_name . ' <' . $to_email . '>' : $to_email,
                'subject'    => $subject,
                'html'       => $html_body,
                'h:Reply-To' => $from_email,
            ],
            'timeout' => 15,
        ]);

        if (is_wp_error($response)) { return false; }
        $code = (int) wp_remote_retrieve_response_code($response);
        return $code >= 200 && $code < 300;
    }

    protected function get_pricing_note(): string { return 'Free trial includes 100 emails/day. Pay-as-you-go or monthly plans from $15/month.'; }
    protected function get_signup_url(): string { return 'https://signup.mailgun.com/new/signup'; }
    protected function get_signup_label(): string { return 'Create a free account'; }

    // Fetch the first verified sending domain from the account.
    // Returns empty string on failure -- caller must treat as fatal.
    private function get_sending_domain(string $api_key): string
    {
        $cached = get_transient('amai_mailgun_domain_' . substr($api_key, -8));
        if (is_string($cached) && $cached !== '') { return $cached; }

        $base     = $this->get_region_base($api_key);
        $response = wp_remote_get($base . '/domains?limit=10', [
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode('api:' . $api_key),
            ],
            'timeout' => 10,
        ]);

        if (is_wp_error($response)) { return ''; }
        $code = (int) wp_remote_retrieve_response_code($response);
        if ($code !== 200) { return ''; }

        $body = json_decode((string) wp_remote_retrieve_body($response), true);
        if (!is_array($body) || !isset($body['items']) || !is_array($body['items'])) { return ''; }

        foreach ($body['items'] as $item) {
            if (
                isset($item['name'], $item['state']) &&
                is_string($item['name']) &&
                $item['name'] !== '' &&
                $item['state'] === 'active'
            ) {
                set_transient('amai_mailgun_domain_' . substr($api_key, -8), $item['name'], HOUR_IN_SECONDS);
                return $item['name'];
            }
        }

        // Fall back to any domain if none are active
        if (isset($body['items'][0]['name']) && is_string($body['items'][0]['name'])) {
            $domain = $body['items'][0]['name'];
            set_transient('amai_mailgun_domain_' . substr($api_key, -8), $domain, HOUR_IN_SECONDS);
            return $domain;
        }

        return '';
    }

    // Detect EU vs US region by attempting US first then EU on failure.
    // Cached per key suffix for 24 hours.
    private function get_region_base(string $api_key): string
    {
        $cached = get_transient('amai_mailgun_region_' . substr($api_key, -8));
        if ($cached === 'eu') { return self::API_BASE_EU; }

        $response = wp_remote_get(self::API_BASE_US . '/domains?limit=1', [
            'headers' => ['Authorization' => 'Basic ' . base64_encode('api:' . $api_key)],
            'timeout' => 8,
        ]);

        if (!is_wp_error($response) && (int) wp_remote_retrieve_response_code($response) === 200) {
            set_transient('amai_mailgun_region_' . substr($api_key, -8), 'us', DAY_IN_SECONDS);
            return self::API_BASE_US;
        }

        set_transient('amai_mailgun_region_' . substr($api_key, -8), 'eu', DAY_IN_SECONDS);
        return self::API_BASE_EU;
    }
}