<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: modules/email-brevo.php
// Description: Brevo email provider module - NUCLEAR+++
// Last Edited: 2026-05-14
// ==================================================

namespace AutoMarketerAI\Modules;

use AutoMarketerAI\AbstractEmailProvider;

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

final class EmailBrevo extends AbstractEmailProvider
{
    private const API_BASE = 'https://api.brevo.com/v3';

    public function get_id(): string { return 'email-brevo'; }
    public function get_name(): string { return 'Brevo'; }
    public function get_description(): string { return 'All-in-one platform for transactional and marketing email. Generous free tier with no daily sending cap, plus SMS and automation built in.'; }
    public function get_logo_url(): string { return 'https://automarketer-ai.com/wp-content/uploads/Brevo-Logo.png'; }

    public function validate_api_key(string $key): bool
    {
        if (strlen($key) < 20) { return false; }
        $response = wp_remote_get(self::API_BASE . '/account', [
            'headers' => ['api-key' => $key, 'Content-Type' => 'application/json'],
            'timeout' => 10,
        ]);
        if (is_wp_error($response)) { return false; }
        $code = (int) wp_remote_retrieve_response_code($response);
        return $code === 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();
        $payload = [
            'sender'      => ['name' => $from_name, 'email' => $from_email],
            'to'          => [['email' => $to_email, 'name' => $to_name]],
            'subject'     => $subject,
            'htmlContent' => $html_body,
            'replyTo'     => ['email' => $from_email, 'name' => $from_name],
        ];
        $response = wp_remote_post(self::API_BASE . '/smtp/email', [
            'headers' => ['api-key' => $api_key, '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);
        return $code >= 200 && $code < 300;
    }

    protected function get_pricing_note(): string { return 'Free up to 300 emails/day. Paid plans start at $9/month for higher volume.'; }
    protected function get_signup_url(): string { return 'https://app.brevo.com/account/register'; }
    protected function get_signup_label(): string { return 'Create a free account'; }
}