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

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

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

defined( 'ABSPATH' ) || exit;

/**
 * A class that sends email through Mailgun.
 */
final class MailgunMailer extends AbstractMailer {

	/**
	 * Send mail using the Mailgun 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 = 'mailgun';

		// Prepare the post.
		$data            = array();
		$data['from']    = $this->get_sender_name( $order ) . ' <' . $this->get_sender_email( $order ) . '>';
		$data['v:Event'] = absint( $order->event_id );
		$data['v:Order'] = absint( $order->id );
		$data['v:Name']  = $order->name;

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

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

		// Message.
		$data['subject']  = $subject;
		$data['html']     = $msg;
		$data['h:Sender'] = '<' . $this->get_sender_email( $order ) . '>';
		$data['text']     = wp_strip_all_tags( $msg );

		// 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(
					// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
					'Authorization' => 'Basic ' . base64_encode( 'api:' . $this->settings->mailer_property( 'api_key' ) ),
					// phpcs:enable
				),
				'body'       => $data,
			)
		);

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

	/**
	 * Extract the email_id used by Mailgun.
	 *
	 * @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 = $json->id;
	}

	/**
	 * Process the Mailgun 'failed', 'complained' and 'unsubscribed' events
	 *
	 * @since 1.9.1
	 * @since 2.3.0 Use fast_events_json_encode.
	 * @since 2.5.0 All events are added to the email log, and error events are added to the errorlog as well.
	 *
	 * @param WP_REST_Request $data Request instance.
	 *
	 * @return WP_REST_Response | WP_Error
	 */
	public function webhook( WP_REST_Request $data ): WP_Error|WP_REST_Response {
		static $error_events = array( 'failed', 'complained', 'unsubscribed' );
		$this->provider_id   = 'mailgun';

		$json = json_decode( $data->get_body(), true );
		if ( json_last_error() !== JSON_ERROR_NONE || ! isset( $json['signature'] ) ) {
			$this->logger->error(
				'JSON error: ' . json_last_error_msg() . PHP_EOL . PHP_EOL . $data->get_body(),
				array( 'type' => 'Email-' . $this->provider_id )
			);
			return new WP_Error( 'not_acceptable', 'Invalid data', array( 'status' => 406 ) );
		}

		// Check the signature.
		$sig = $json['signature'];
		if ( isset( $sig['token'] ) && isset( $sig['timestamp'] ) && isset( $sig['signature'] ) && isset( $json['event-data']['event'] ) &&
			hash_hmac( 'sha256', $sig['timestamp'] . $sig['token'], $this->options['mailgun_api_key'] ) === $sig['signature'] ) {
			$event_id = absint( $json['event-data']['user-variables']['Event'] ?? 0 );
			$order_id = absint( $json['event-data']['user-variables']['Order'] ?? 0 );
			if ( in_array( $json['event-data']['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-data']['event'], $json['event-data']['id'] ),
					array(
						'type'     => 'Email-' . $this->provider_id,
						'event_id' => $event_id,
						'order_id' => $order_id,
						'event'    => $json,
					)
				);
			}

			$this->update_email_log( $json['event-data']['id'], json_decode( wp_json_encode( $json['event-data'] ) ), $event_id, $order_id );

			return rest_ensure_response( 'Ok' );
		}
		return new WP_Error( 'not_acceptable', 'Invalid data', array( 'status' => 406 ) );
	}
}
