<?php

namespace Limb_Chatbot\Includes\Services\Notifications\Types;

use Limb_Chatbot\Includes\Data_Objects\Chat;
use Limb_Chatbot\Includes\Data_Objects\Chatbot_User;
use Limb_Chatbot\Includes\Services\Notifications\Notification_Envelope;
use Limb_Chatbot\Includes\Services\Notifications\Notification_Role_Resolver;

/**
 * Notification type: new chat created.
 *
 * Sent to website admins when a new chat is created. Dynamic content includes chat UUID.
 *
 * @package Limb_Chatbot\Includes\Services\Notifications\Types
 * @since 1.0.15
 */
class Chat_Created_Notification_Type extends Abstract_Notification_Type {

	const TYPE_KEY = 'chat_created';

	/**
	 * @inheritDoc
	 */
	public function get_key(): string {
		return self::TYPE_KEY;
	}

	/**
	 * @inheritDoc
	 */
	public function get_target_roles(): array {
		// Receiver filtering is driven by `lbaic.plugin.notifications`.
		// This is just a fallback when the setting is missing.
		return [
			Notification_Role_Resolver::ROLE_GUEST,
			Notification_Role_Resolver::ROLE_USER,
			Notification_Role_Resolver::ROLE_AGENT,
			Notification_Role_Resolver::ROLE_ADMIN,
		];
	}

	/**
	 * @inheritDoc
	 */
	public function build_envelope( Chatbot_User $recipient, array $payload ): ?Notification_Envelope {
		$chat_uuid = $payload['chat_uuid'] ?? null;
		if ( empty( $chat_uuid ) || ! is_string( $chat_uuid ) ) {
			return null;
		}

		$vars = $this->build_template_vars( $chat_uuid );
		$template = $this->get_email_template_config();

		$subject_template = ! empty( $template['subject'] ) ? $template['subject'] : sprintf(
			/* translators: %s: site name */
			__( '[%s] New chat created', 'limb-chatbot' ),
			get_bloginfo( 'name' )
		);

		$body_template = ! empty( $template['body'] ) ? $template['body'] : implode( '<br><br>', [
			__( 'A new chat was created on your site.', 'limb-chatbot' ),
			'<strong>' . esc_html( __( 'Chat ID:', 'limb-chatbot' ) ) . '</strong> {{chat_id}}',
			__( 'Conversation preview:', 'limb-chatbot' ),
			'{{chat_summary}}',
		] );

		$subject = $this->apply_template_variables( (string) $subject_template, $vars );
		$subject = $this->append_subject_identifier( $subject, $vars['chat_id'] ?? '' );
		$body    = $this->apply_template_variables( (string) $body_template, $vars );

		return $this->create_envelope(
			'email',
			$subject,
			$body,
			$this->build_channel_payload( $payload ),
			'text/html'
		);
	}
}
