<?php
/**
 * @package Hafenstudios\Kurato
 */

namespace Hafenstudios\Kurato\Mail;

use Hafenstudios\Core\Mail\Message;

defined( 'ABSPATH' ) || exit;

/**
 * SMTP2GO-Versandtreiber. Einfaches, guenstiges Relay mit JSON-API.
 */
final class Smtp2goDriver extends AbstractApiEspDriver {

	private string $api_key;

	/**
	 * @param string $api_key SMTP2GO-API-Key.
	 */
	public function __construct( string $api_key ) {
		$this->api_key = $api_key;
	}

	/**
	 * @return string
	 */
	public function key(): string {
		return 'smtp2go';
	}

	/**
	 * @return string
	 */
	protected function endpoint(): string {
		return 'https://api.smtp2go.com/v3/email/send';
	}

	/**
	 * @return bool
	 */
	protected function is_configured(): bool {
		return '' !== $this->api_key;
	}

	/**
	 * @return string
	 */
	protected function config_error(): string {
		return __( 'Kein SMTP2GO-API-Key hinterlegt.', 'kurato' );
	}

	/**
	 * @param Message $message Nachricht.
	 * @return array{headers:array<string,string>,body:string}
	 */
	protected function build_request( Message $message ): array {
		$sender = '' !== $message->from_name
			? sprintf( '%s <%s>', $message->from_name, $message->from_email )
			: $message->from_email;

		$body = array(
			'sender'  => $sender,
			'to'      => array( $message->to ),
			'subject' => $message->subject,
		);
		if ( $message->is_html ) {
			$body['html_body'] = $message->body;
			// Multipart: Klartext-Alternative als text_body mitsenden (SMTP2GO).
			if ( '' !== $message->text_body ) {
				$body['text_body'] = $message->text_body;
			}
		} else {
			$body['text_body'] = $message->body;
		}

		$custom = array();
		if ( '' !== $message->reply_to ) {
			$custom[] = array( 'header' => 'Reply-To', 'value' => $message->reply_to );
		}
		foreach ( $message->headers as $name => $value ) {
			$custom[] = array( 'header' => $name, 'value' => $value );
		}
		if ( array() !== $custom ) {
			$body['custom_headers'] = $custom;
		}

		return array(
			'headers' => array(
				'X-Smtp2go-Api-Key' => $this->api_key,
				'Content-Type'      => 'application/json',
				'Accept'            => 'application/json',
			),
			'body'    => (string) wp_json_encode( $body ),
		);
	}

	/**
	 * SMTP2GO liefert die ID unter data.email_id.
	 *
	 * @param string $body Response-Body.
	 * @return string
	 */
	protected function parse_message_id( string $body ): string {
		$data = json_decode( $body, true );
		return is_array( $data ) && isset( $data['data']['email_id'] ) ? (string) $data['data']['email_id'] : '';
	}
}
