<?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\Data_Objects\Lead;
use Limb_Chatbot\Includes\Data_Objects\Lead_Field;
use Limb_Chatbot\Includes\Data_Objects\Lead_Value;
use Limb_Chatbot\Includes\Data_Objects\Message;
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 {
		return [
			Notification_Role_Resolver::ROLE_USER,
		];
	}

	/**
	 * @inheritDoc
	 */
	public function build_envelope( Chatbot_User $recipient, array $payload ): ?Notification_Envelope {
		$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;
		}

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

		$parts = [];

		$parts[] = __( 'A new lead was captured on your site.', 'limb-chatbot' );

		$parts[] = '<br><br><strong>' . esc_html( __( 'Source',
				'limb-chatbot' ) ) . ':</strong> ' . esc_html( $lead->source_title . ' (' . $lead->source_type . ')' );

		$chat_uuid = $lead->get_chat_uuid();
		if ( ! empty( $chat_uuid ) ) {
			$parts[]  = '<br><strong>' . esc_html( __( 'Chat ID',
					'limb-chatbot' ) ) . ':</strong> ' . esc_html( $chat_uuid );
			$messages = Message::where( [ 'chat_uuid' => $chat_uuid ], 8, 1, 'id', 'DESC' )->get();
			if ( ! empty( $messages ) ) {
				$parts[]  = '<br><strong>' . esc_html( __( 'Last messages', 'limb-chatbot' ) ) . ':</strong><br>';
				$messages = array_reverse( $messages );
				foreach ( $messages as $message ) {
					if ( ! $message instanceof Message ) {
						continue;
					}
					$role    = $message->get_role();
					$role    = $role === Message::ROLE_USER ? __( 'User',
						'limb-chatbot' ) : ( $role === Message::ROLE_ASSISTANT ? __( 'Assistant',
						'limb-chatbot' ) : $role );
					$content = trim( $message->extract_text() );
					if ( $content === '' ) {
						$content = '—';
					}
					$parts[] = '<em>' . esc_html( $role ) . ':</em> ' . esc_html( $content ) . '<br>';
				}
			}
		}

		$values = $lead->get_values()->get();
		if ( ! empty( $values ) ) {
			$parts[] = '<br><strong>' . esc_html( __( 'Collected fields', 'limb-chatbot' ) ) . ':</strong><br>';
			foreach ( $values as $lead_value ) {
				if ( ! $lead_value instanceof Lead_Value ) {
					continue;
				}
				$field = $lead_value->lead_field();
				$label = $field instanceof Lead_Field ? $field->get_label() : (string) $lead_value->get_field_id();
				$value = $lead_value->get_value();
				if ( $value !== null && $value !== '' ) {
					$parts[] = esc_html( $label ) . ': ' . esc_html( (string) $value ) . '<br>';
				}
			}
		}

		$chat_uuid = $lead->get_chat_uuid();
		if ( ! empty( $chat_uuid ) ) {
			$chat_url = admin_url( 'admin.php?page=lbaic-dashboard&menu=chatbot&tab=chats&chat_uuid=' . rawurlencode( $chat_uuid ) );
			$cta_text = __( 'View chat in dashboard', 'limb-chatbot' );
			$parts[]  = '<br><br><p>'
			            . esc_html( __( 'You can check the full conversation in your dashboard.', 'limb-chatbot' ) )
			            . '</p><p ><a href="' . esc_url( $chat_url ) . '">'
			            . esc_html( $cta_text )
			            . '</a></p>';
		}

		$body = implode( '', $parts );

		$name = $recipient->name();
		if ( ! empty( $name ) && is_string( $name ) ) {
			$body = sprintf(
			        /* translators: %s: recipient name */
				        __( 'Hello %s', 'limb-chatbot' ),
				        esc_html( $name )
			        ) . '<br><br>' . $body;
		}

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