<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/modules/email-mandrill.php
// Description: Mailchimp Transactional (Mandrill) 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 EmailMandrill extends AbstractEmailProvider
{
    private const API_BASE = 'https://mandrillapp.com/api/1.0';

    public function get_id(): string { return 'email-mandrill'; }
    public function get_name(): string { return 'Mailchimp Transactional'; }
    public function get_description(): string { return 'Enterprise-grade transactional email from Mailchimp. Exceptional deliverability, detailed analytics, and built-in reputation monitoring.'; }
    public function get_logo_url(): string { return 'https://automarketer-ai.com/wp-content/uploads/Mandrill-Logo.png'; }

    public function validate_api_key(string $key): bool
    {
        if (strlen($key) < 10) { return false; }
        $response = wp_remote_post(self::API_BASE . '/users/info.json', [
            'headers' => ['Content-Type' => 'application/json'],
            'body'    => (string) json_encode(['key' => $key]),
            'timeout' => 10,
        ]);
        if (is_wp_error($response)) { return false; }
        $code = (int) wp_remote_retrieve_response_code($response);
        if ($code !== 200) { return false; }
        $body = json_decode((string) wp_remote_retrieve_body($response), true);
        // Valid response contains a username field; invalid contains a 'status' => 'error'
        return is_array($body) && isset($body['username']) && !isset($body['status']);
    }

    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();

        $payload = [
            'key'     => $api_key,
            'message' => [
                'html'       => $html_body,
                'subject'    => $subject,
                'from_email' => $from_email,
                'from_name'  => $from_name,
                'to'         => [
                    [
                        'email' => $to_email,
                        'name'  => $to_name,
                        'type'  => 'to',
                    ],
                ],
                'headers' => [
                    'Reply-To' => $from_email,
                ],
                'important'        => false,
                'track_opens'      => true,
                'track_clicks'     => false,
                'auto_text'        => true,
                'preserve_recipients' => false,
            ],
        ];

        $response = wp_remote_post(self::API_BASE . '/messages/send.json', [
            'headers' => ['Content-Type' => 'application/json'],
            'body'    => (string) json_encode($payload),
            'timeout' => 15,
        ]);

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

        $body = json_decode((string) wp_remote_retrieve_body($response), true);
        if (!is_array($body) || !isset($body[0]['status'])) { return false; }
        // Mandrill returns an array of send results; status 'sent' or 'queued' = success
        return in_array($body[0]['status'], ['sent', 'queued', 'scheduled'], true);
    }

    protected function get_pricing_note(): string { return 'Requires a paid Mailchimp plan. Pricing starts at $20/month for 500k emails.'; }
    protected function get_signup_url(): string { return 'https://mailchimp.com/features/transactional-email/'; }
    protected function get_signup_label(): string { return 'Learn more'; }
}