<?php
/**
 * Emailit API provider (API v2).
 *
 * @package EmailSmtp
 * @link https://emailit.com/docs/
 * @link https://emailit.com/docs/api-reference/emails/
 */

namespace EmailSmtp\Providers\Emailit;

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 'emailit';
	}

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

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

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

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

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


	public function connect( array $settings ): DeliveryResult {
		$key = $this->secret( $settings, 'emailit_api_key', 'WP_POWERSUITE_EMAILIT_API_KEY' );
		if ( $key === '' ) {
			return DeliveryResult::failure( __( 'Emailit API key is required.', 'wp-powersuite' ), '', 'authentication' );
		}

		// GET /emails validates the Bearer key without sending mail.
		$response = ApiHttpClient::request(
			'GET',
			'https://api.emailit.com/v2/emails?page=1&limit=1',
			[ 'Authorization' => 'Bearer ' . $key ]
		);

		return ApiHttpClient::to_delivery_result(
			$response,
			static function () {
				return [ 'message' => __( 'Emailit API key authenticated successfully.', 'wp-powersuite' ) ];
			}
		);
	}

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

		$key = $this->secret( $settings, 'emailit_api_key', 'WP_POWERSUITE_EMAILIT_API_KEY' );
		if ( $key === '' ) {
			return DeliveryResult::failure( __( 'Emailit API key is required.', 'wp-powersuite' ), '', 'authentication' );
		}

		$from    = $this->from_parts( $message );
		$payload = [
			'from'    => $this->format_address( $from['email'], $from['name'] ),
			'to'      => array_slice( $message->get_to(), 0, 50 ),
			'subject' => $message->get_subject(),
		];

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

		if ( $message->get_cc() !== [] ) {
			$payload['cc'] = array_slice( $message->get_cc(), 0, 50 );
		}
		if ( $message->get_bcc() !== [] ) {
			$payload['bcc'] = array_slice( $message->get_bcc(), 0, 50 );
		}
		if ( is_email( $message->get_reply_to_email() ) ) {
			$payload['reply_to'] = $this->format_address(
				$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 [
						'filename'     => $a['name'],
						'content'      => $a['content'],
						'content_type' => $a['type'] !== '' ? $a['type'] : 'application/octet-stream',
						'encoding'     => 'base64',
					];
				},
				$attachments
			);
		}

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

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

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