<?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 {
		return [
			Notification_Role_Resolver::ROLE_USER,
		];
	}

	/**
	 * @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;
		}

		$chat = Chat::where( [ 'uuid' => $chat_uuid ] )->first();
		if ( ! $chat instanceof Chat ) {
			return null;
		}

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

		$parts = [];
		$name  = $recipient->name();
		if ( ! empty( $name ) && is_string( $name ) ) {
			$parts[] = sprintf(
			/* translators: %s: recipient name */
				__( 'Hello %s', 'limb-chatbot' ),
				esc_html( $name )
			);
		}
		$parts[] = __( 'A new chat was created on your site.', 'limb-chatbot' );
		$parts[] = '<strong>' . esc_html( __( 'Chat ID:', 'limb-chatbot' ) ) . '</strong> ' . esc_html( $chat_uuid );
		$parts[] = __( 'The visitor can continue the conversation in the chatbot.', 'limb-chatbot' );

		$chat_url = admin_url( 'admin.php?page=lbaic-dashboard&menu=chatbot&tab=chats&chat_uuid=' . rawurlencode( $chat_uuid ) );
		$link     = '<a href="' . esc_url( $chat_url ) . '" style="color: #2563eb;">' . esc_html( __( 'View chat in dashboard', 'limb-chatbot' ) ) . '</a>';
		$parts[]  = esc_html( __( 'You can check the full conversation in your dashboard.', 'limb-chatbot' ) ) . ' ' . $link;

		$body = implode( '<br><br>', $parts );

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