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

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

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;

defined( 'ABSPATH' ) || exit;

/**
 * A class that sends email through Sendgrid.
 */
final class SendgridMailer extends AbstractMailer {

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

		// Do we have a name?
		if ( ! empty( $order->name ) ) {
			$to = array(
				array(
					'email' => $order->email,
					'name'  => $order->name,
				),
			);
		} else {
			$to = array(
				array(
					'email' => $order->email,
				),
			);
		}

		// Is there a bcc?
		if ( ! empty( $bcc ) ) {
			$rcpts = array(
				array(
					'to'  => $to,
					'bcc' => array(
						array(
							'email' => $bcc,
						),
					),
				),
			);
		} else {
			$rcpts = array(
				array(
					'to' => $to,
				),
			);
		}

		// Prepare the body.
		$data = array(
			'personalizations' => $rcpts,
			'from'             => array(
				'email' => $this->get_sender_email( $order ),
				'name'  => $this->get_sender_name( $order ),
			),
			'subject'          => $subject,
			'content'          => array(
				array(
					'type'  => 'text/plain',
					'value' => wp_strip_all_tags( $msg ),
				),
				array(
					'type'  => 'text/html',
					'value' => $msg,
				),
			),
			'custom_args'      => array(
				'Event' => absint( $order->event_id ),
				'Order' => absint( $order->id ),
				'Name'  => $order->name,
			),
		);

		// 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(
					'Authorization' => 'Bearer ' . $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 Sendgrid.
	 *
	 * @since 2.5.0
	 *
	 * @param array|WP_Error $response API response from provider.
	 */
	protected function set_email_id( WP_Error|array $response ): void {
		$this->email_id = wp_remote_retrieve_header( $response, 'X-Message-Id' );
	}

	/**
	 * Process the Sendgrid webhook 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( 'deferred', 'bounce', 'dropped', 'spamreport', 'unsubscribe', 'group_unsubscribe' );
		$this->provider_id   = 'sendgrid';

		// Check for valid JSON.
		$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' );
		}

		// Walk through all events.
		foreach ( $json as $item ) {
			if ( isset( $item->event ) ) {
				// phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
				$event_id = absint( $item->Event ?? 0 );
				$order_id = absint( $item->Order ?? 0 );
				// phpcs:enable
				if ( in_array( $item->event, $error_events, true ) ) {
					$email_id = explode( '.', $item->sg_message_id )[0];
					$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' ), $item->event, $email_id ),
						array(
							'type'     => 'Email-' . $this->provider_id,
							'event_id' => $event_id,
							'order_id' => $order_id,
							'event'    => $item,
						)
					);
				}

				$this->update_email_log( explode( '.', $item->sg_message_id )[0], $item, $event_id, $order_id );
			}
		}

		return rest_ensure_response( 'Ok' );
	}
}
