<?php
/**
 * Maileroo email API provider.
 *
 * @package EmailSmtp
 * @link https://maileroo.com/docs/api-reference/emails/send-email
 */

namespace EmailSmtp\Providers\Maileroo;

use EmailSmtp\Includes\AbstractApiProvider;
use EmailSmtp\Includes\ApiHttpClient;
use EmailSmtp\Includes\DeliveryResult;
use EmailSmtp\Includes\EmailMessage;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class Provider extends AbstractApiProvider {

	public function get_id(): string {
		return 'maileroo';
	}

	public function get_name(): string {
		return __( 'Maileroo', 'wp-powersuite' );
	}

	public function get_description(): string {
		return __( 'Send transactional email through the Maileroo Email API.', 'wp-powersuite' );
	}

	public function get_docs_url(): string {
		return 'https://maileroo.com/docs/api-reference/emails/introduction';
	}

	public function get_icon(): string {
		return 'dashicons-email-alt';
	}

	public function get_required_fields(): array {
		return [ 'maileroo_api_key' ];
	}

	public function connect( array $settings ): DeliveryResult {
		$key = $this->secret( $settings, 'maileroo_api_key', 'WP_POWERSUITE_MAILEROO_API_KEY' );
		if ( $key === '' ) {
			return DeliveryResult::failure( __( 'Maileroo sending key is required.', 'wp-powersuite' ), '', 'authentication' );
		}

		return DeliveryResult::success( __( 'Maileroo sending key saved. Send a test email to verify delivery.', 'wp-powersuite' ) );
	}

	public function send( EmailMessage $message, array $settings ): DeliveryResult {
		$missing = $this->require_from( $message );
		if ( $missing ) {
			return $missing;
		}

		$key = $this->secret( $settings, 'maileroo_api_key', 'WP_POWERSUITE_MAILEROO_API_KEY' );
		if ( $key === '' ) {
			return DeliveryResult::failure( __( 'Maileroo sending key is required.', 'wp-powersuite' ), '', 'authentication' );
		}

		$from = $this->from_parts( $message );
		$map  = static function ( string $email, string $name = '' ): array {
			$item = [ 'address' => $email ];
			if ( $name !== '' ) {
				$item['display_name'] = $name;
			}
			return $item;
		};

		$payload = [
			'from'    => $map( $from['email'], $from['name'] ),
			'to'      => array_map( static fn( string $e ) => $map( $e ), $message->get_to() ),
			'subject' => $message->get_subject(),
		];

		if ( $message->is_html() ) {
			$payload['html']  = $message->get_body();
			$payload['plain'] = $message->get_alt_body() !== ''
				? $message->get_alt_body()
				: wp_strip_all_tags( $message->get_body() );
		} else {
			$payload['plain'] = $message->get_body();
		}

		if ( $message->get_cc() !== [] ) {
			$payload['cc'] = array_map( static fn( string $e ) => $map( $e ), $message->get_cc() );
		}
		if ( $message->get_bcc() !== [] ) {
			$payload['bcc'] = array_map( static fn( string $e ) => $map( $e ), $message->get_bcc() );
		}
		if ( is_email( $message->get_reply_to_email() ) ) {
			$payload['reply_to'] = $map( $message->get_reply_to_email(), $message->get_reply_to_name() );
		}

		$attachments = $this->attachments_as_base64( $message );
		if ( $attachments !== [] ) {
			$payload['attachments'] = array_map(
				static function ( array $a ) {
					return [
						'file_name'    => $a['name'],
						'content_type' => $a['type'] !== '' ? $a['type'] : 'application/octet-stream',
						'content'      => $a['content'],
						'inline'       => false,
					];
				},
				$attachments
			);
		}

		$headers = $this->safe_custom_headers( $message );
		if ( $headers !== [] ) {
			$payload['headers'] = $headers;
		}

		$response = ApiHttpClient::request(
			'POST',
			'https://smtp.maileroo.com/api/v2/emails',
			[ 'Authorization' => 'Bearer ' . $key ],
			$payload
		);

		return ApiHttpClient::to_delivery_result(
			$response,
			static function ( array $res ) {
				$id = '';
				if ( is_array( $res['json'] ) ) {
					$data = $res['json']['data'] ?? $res['json'];
					if ( is_array( $data ) ) {
						$id = (string) ( $data['reference_id'] ?? $data['id'] ?? '' );
					}
				}
				return [
					'message' => __( 'Maileroo accepted the message.', 'wp-powersuite' ),
					'id'      => $id,
				];
			}
		);
	}
}
