<?php

declare( strict_types=1 );

namespace Packetery\Module\Email;

use Packetery\Latte\Engine;
use Packetery\Module\Framework\WpAdapter;

class BugReportEmail {

	/** @var WpAdapter */
	private $wpAdapter;

	/** @var string */
	private $supportEmailAddress;

	/** @var Engine */
	private $latteEngine;

	/** @var BugReportAttachment */
	private $bugReportAttachment;

	public function __construct(
		WpAdapter $wpAdapter,
		string $supportEmailAddress,
		Engine $latteEngine,
		BugReportAttachment $bugReportAttachment
	) {
		$this->wpAdapter           = $wpAdapter;
		$this->supportEmailAddress = $supportEmailAddress;
		$this->latteEngine         = $latteEngine;
		$this->bugReportAttachment = $bugReportAttachment;
	}

	public function sendBugReport( string $replyEmail, string $message, bool $sendCopy ): bool {
		$siteName = $this->wpAdapter->getBlogInfo( 'name', 'raw' );
		// translators: %s is site name
		$subject = sprintf( $this->wpAdapter->__( 'Packeta: Plugin WP - bug report - %s', 'packeta' ), $siteName );

		/**
		 * @var non-empty-list<string> $headers
		 */
		$headers = [
			'Content-Type: text/html; charset=UTF-8',
			"From: {$replyEmail}",
			"Reply-To: {$replyEmail}",
		];

		$to = $this->supportEmailAddress;
		if ( $sendCopy ) {
			$to = [ $this->supportEmailAddress, $replyEmail ];
		}

		return $this->wpAdapter->wpMail(
			$to,
			$subject,
			$this->createEmailBody( $replyEmail, $message, $siteName ),
			$headers,
			$this->bugReportAttachment->createAttachments()
		);
	}

	private function createEmailBody( string $replyEmail, string $message, string $siteName ): string {
		return $this->latteEngine->renderToString(
			PACKETERY_PLUGIN_DIR . '/template/email/bug-report.latte',
			[
				'replyEmail'          => $replyEmail,
				'message'             => $message,
				'siteName'            => $siteName,
				'zipArchiveAvailable' => class_exists( 'ZipArchive' ),
				'translations'        => [
					'bugReportTitle'          => $this->wpAdapter->__( 'Bug report from Packeta plugin', 'packeta' ),
					'website'                 => $this->wpAdapter->__( 'Website:', 'packeta' ),
					'replyEmail'              => $this->wpAdapter->__( 'Email for reply:', 'packeta' ),
					'message'                 => $this->wpAdapter->__( 'Message:', 'packeta' ),
					'autoGenerated'           => $this->wpAdapter->__( 'This report was submitted via the Packeta WordPress plugin.', 'packeta' ),
					'attachmentsNotAvailable' => $this->wpAdapter->__( 'Attachments could not be added to the email because the e-shop server is missing the extension required to create a ZIP file.', 'packeta' ),
				],
			]
		);
	}
}
