<?php

namespace Limb_Chatbot\Includes\Services\Notifications\Types;

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

/**
 * Notification type: lead captured.
 *
 * Sent to website admins when a lead is collected (via action or widget).
 * Payload: lead_id, optional chat_uuid. Body includes lead source, field values, and last 4 messages when from chat.
 *
 * @package Limb_Chatbot\Includes\Services\Notifications\Types
 * @since 1.0.15
 */
class Lead_Captured_Notification_Type extends Abstract_Notification_Type {

	const TYPE_KEY = 'lead_captured';

	/**
	 * @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 {
		// todo rename to contacts
		$lead_id = isset( $payload['lead_id'] ) ? (int) $payload['lead_id'] : null;
		if ( empty( $lead_id ) ) {
			return null;
		}

		$lead = Lead::find( $lead_id );
		if ( ! $lead instanceof Lead ) {
			return null;
		}

		$chat_uuid = $payload['chat_uuid'] ?? null;
		if ( empty( $chat_uuid ) || ! is_string( $chat_uuid ) ) {
			$chat_uuid = $lead->get_chat_uuid();
		}

		$vars     = $this->build_template_vars( ! empty( $chat_uuid ) && is_string( $chat_uuid ) ? $chat_uuid : null );
		$template = $this->get_email_template_config();

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

		$body_template = ! empty( $template['body'] ) ? (string) $template['body'] : implode( '<br><br>', [
			__( 'A new lead was captured 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) $lead->get_id() );
		$body    = $this->apply_template_variables( $body_template, $vars );

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