<?php

namespace Limb_Chatbot\Includes\Services\Notifications\Types;

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 action entry (e.g. form submission without a captured lead).
 *
 * @package Limb_Chatbot\Includes\Services\Notifications\Types
 * @since 2.0.0
 */
class Action_Entry_Notification_Type extends Abstract_Notification_Type {

	const TYPE_KEY = 'action_entry';

	/**
	 * @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 ) ) {
			$chat_uuid = null;
		}

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

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

		$body_template = ! empty( $template['body'] ) ? (string) $template['body'] : implode( '<br><br>', [
			__( 'A new action entry was submitted 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( $subject_template, $vars );
		$subject = $this->append_subject_identifier(
			$subject,
			(string) ( $payload['action_submission_id'] ?? $payload['action_id'] ?? '' )
		);
		$body    = $this->apply_template_variables( $body_template, $vars );

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

