<?php
/**
 * A class that sends email through Brevo.
 *
 * @since 3.0.0
 */

declare( strict_types=1 );
namespace FeData\FastEvents\Mail\Provider;

defined( 'ABSPATH' ) || exit;

use Exception;
use FeData\FastEvents\Mail\AbstractMailer;
use FeData\FastEvents\Utilities\JsonUtil;
use FeData\FastEvents\Utilities\PluginUtil;
use stdClass;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;

/**
 * A class that sends email through Brevo.
 */
final class BrevoMailer extends AbstractMailer {

	/**
	 * Send mail using the Brevo API.
	 *
	 * @since 1.0
	 * @since 1.9 Added event_id and order_id to the message.
	 * @since 2.5.0 Set provider id.
	 *
	 * @param stdClass $order   Order information.
	 * @param string   $bcc     Emailaddress of BBC receiver.
	 * @param string   $subject Subject of the email.
	 * @param string   $msg     HTML mail message.
	 * @param int      $em_type 0=Normal mail, 1=Confirmation email.
	 * @throws Exception If mail can't be sent.
	 */
	protected function provider_send( stdClass $order, string $bcc, string $subject, string $msg, int $em_type ): void {
		$this->provider_id = 'brevo';

		// Prepare the body.
		$data                = new stdClass();
		$data->sender        = new stdClass();
		$data->sender->name  = $this->get_sender_name( $order );
		$data->sender->email = $this->get_sender_email( $order );
		$data->tags          = array( (string) $order->event_id, (string) $order->id, $order->name );

		// Recipient.
		if ( ! empty( $order->name ) ) {
			$data->to[] = array(
				'name'  => $order->name,
				'email' => $order->email,
			);
		} else {
			$data->to[] = array(
				'email' => $order->email,
			);
		}

		// Is there a BCC?
		if ( ! empty( $bcc ) ) {
			$data->bcc[] = array(
				'email' => $bcc,
			);
		}

		// Message.
		// phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
		$data->subject     = $subject;
		$data->htmlContent = $msg;
		$data->textContent = wp_strip_all_tags( $msg );
		// phpcs:enable

		// Send the message.
		$response = wp_safe_remote_post(
			$this->settings->mailer_property( 'server' ),
			array(
				'user-agent' => PluginUtil::get_user_agent(),
				'timeout'    => self::CONNECTION_TIMEOUT,
				'headers'    => array(
					'Accept'       => 'application/json',
					'api-key'      => $this->settings->mailer_property( 'api_key' ),
					'Content-Type' => 'application/json',
				),
				'body'       => JsonUtil::fast_events_json_encode( $data ),
			)
		);

		// Check for errors.
		$this->check_email_provider_api_error( $response, $order, $em_type );
	}

	/**
	 * Extract the email_id used by Brevo.
	 *
	 * @since 2.5.0
	 *
	 * @param array|WP_Error $response API response from provider.
	 */
	protected function set_email_id( WP_Error|array $response ): void {
		$json           = json_decode( wp_remote_retrieve_body( $response ) );
		$this->email_id = trim( $json->{'messageId'}, '<>' );
	}

	/**
	 * Process the Brevo webhook events.
	 *
	 * @since 2.5.0
	 *
	 * @param WP_REST_Request $data Request instance.
	 *
	 * @return WP_REST_Response
	 */
	public function webhook( WP_REST_Request $data ): WP_REST_Response {
		static $error_events = array( 'soft_bounce', 'hard_bounce', 'spam', 'invalid_email', 'deferred', 'blocked', 'error', 'unsubscribed' );
		$this->provider_id   = 'brevo';

		$json = json_decode( $data->get_body() );
		if ( json_last_error() !== JSON_ERROR_NONE ) {
			$this->logger->error(
				'JSON error: ' . json_last_error_msg() . PHP_EOL . PHP_EOL . $data->get_body(),
				array( 'type' => 'Email-' . $this->provider_id )
			);
			return rest_ensure_response( 'Ok' );
		}
		$event_id = absint( $json->tags[0] ?? 0 );
		$order_id = absint( $json->tags[1] ?? 0 );
		if ( in_array( $json->event, $error_events, true ) ) {
			$this->logger->info(
			/* translators: %s is the email provider event name, and the last %s is the provider email id */
				sprintf( __( 'Adding the "%1$s" event to email-id "%1$s": ', 'fast-events' ), $json->event, trim( $json->{'message-id'} ?? '', '<>' ) ),
				array(
					'type'     => 'Email-' . $this->provider_id,
					'event_id' => $event_id,
					'order_id' => $order_id,
					'event'    => $json,
				)
			);
		}

		if ( isset( $json->{'message-id'} ) ) {
			$this->update_email_log( trim( $json->{'message-id'}, '<>' ), $json, $event_id, $order_id );
		}

		return rest_ensure_response( 'Ok' );
	}
}
