<?php

namespace GriffinForms\Includes\Mailer;

class MailgunMail extends Format
{
    public function sendEmail()
    {
        $domain = $this->mail_options['mailgun_domain'] ?? '';
        $api_key = $this->mail_options['mailgun_api_key'] ?? '';
        $region = $this->mail_options['mailgun_region'] ?? 'us';

        if (empty($domain) || empty($api_key)) {
            return new \WP_Error('mailgun_config_missing', __('Mailgun domain or API key missing.', 'griffinforms-form-builder'));
        }

        $base = ($region === 'eu') ? 'https://api.eu.mailgun.net' : 'https://api.mailgun.net';
        $endpoint = sprintf('%s/v3/%s/messages', rtrim($base, '/'), $domain);

        $params = [
            'from'    => sprintf('%s <%s>', $this->mail_options['sender_name'], $this->mail_options['sender_email']),
            'to'      => $this->recipient,
            'subject' => $this->subject,
            'html'    => $this->content,
        ];

        if (!empty($this->mail_options['reply_to'])) {
            $params['h:Reply-To'] = $this->mail_options['reply_to'];
        }

        $response = wp_remote_post($endpoint, [
            'timeout' => 15,
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode('api:' . $api_key),
            ],
            'body'    => $params,
        ]);

        if (is_wp_error($response)) {
            $this->log->add('error', $this->log_item_type, $this->log_item_id, get_current_user_id(), sprintf(__('Mailgun send failed (%1$s): %2$s', 'griffinforms-form-builder'), $this->getRecipientDescriptor(), $response->get_error_message()), $this->getLogCategory());
            return $response;
        }

        $code = wp_remote_retrieve_response_code($response);
        if ($code >= 200 && $code < 300) {
            $this->log->add('info', $this->log_item_type, $this->log_item_id, get_current_user_id(), sprintf(__('Mailgun email successfully sent (%s)', 'griffinforms-form-builder'), $this->getRecipientDescriptor()), $this->getLogCategory());
            return true;
        }

        $body = wp_remote_retrieve_body($response);
        $this->log->add('error', $this->log_item_type, $this->log_item_id, get_current_user_id(), sprintf(__('Mailgun send failed (%1$s): %2$s', 'griffinforms-form-builder'), $this->getRecipientDescriptor(), $body), $this->getLogCategory());
        return new \WP_Error('mailgun_send_failed', sprintf(__('Mailgun responded with status %d', 'griffinforms-form-builder'), $code));
    }
}
