<?php

namespace Limb_Chatbot\Includes\Services\Actions;

use Exception;
use Limb_Chatbot\Includes\Data_Objects\Parameter;
use Limb_Chatbot\Includes\Services\Actions\Action_Callback_Execution_Context;
use Limb_Chatbot\Includes\Services\User_Manager;

class Slack_Message_Builder {
	public function build( string $content, Action_Callback_Execution_Context $context, $title ) {
		$blocks = [];

		$blocks[] = [
			'type' => 'header',
			'text' => [
				'type'  => 'plain_text',
				'text'  => $title,
				'emoji' => true,
			],
		];

		$blocks[] = [ 'type' => 'divider' ];

		$blocks[] = [
			'type' => 'section',
			'text' => [
				'type' => 'mrkdwn',
				'text' => $content,
			],
		];

		$user_info = $this->get_user_info();
		if ( ! empty( $user_info ) ) {
			$blocks[] = [
				'type'   => 'section',
				'fields' => $this->format_user_info_fields( $user_info ),
			];
		}

		$parameters = $context->get_parameters();
		if ( ! empty( $parameters ) ) {
			$blocks[] = [ 'type' => 'divider' ];
			$blocks[] = [
				'type' => 'section',
				'text' => [
					'type' => 'mrkdwn',
					'text' => '*📋 Submitted Parameters:*',
				],
			];
			$blocks[] = [
				'type'   => 'section',
				'fields' => $this->format_parameters_fields( $parameters, $context->get_variables() ),
			];
		}

		$blocks[] = [
			'type'     => 'context',
			'elements' => [
				[
					'type' => 'mrkdwn',
					'text' => sprintf( 'Sent via Limb Chatbot • %s', current_time( 'F j, Y g:i a' ) ),
				],
			],
		];

		return [
			'text'   => $content,
			'blocks' => $blocks,
		];
	}

	private function get_user_info(): array {
		$user_manager = User_Manager::instance();
		$current_user = $user_manager->get_current_user();

		if ( ! $current_user ) {
			return [];
		}

		$user_info = [
			'name'  => $current_user->name(),
			'email' => $current_user->email(),
			'ip'    => $current_user->get_ip(),
		];

		if ( $current_user->is_wp_user() ) {
			$user = get_userdata( $current_user->get_wp_user_id() );
			if ( ! $user || empty( $user->roles ) ) {
				$role = '';
			} else {
				$primary_role = $user->roles[0];
				global $wp_roles;
				$role = $wp_roles->roles[ $primary_role ]['name'] ?? '';
			}
		} else {
			$role = __( 'Guest', 'limb-chatbot' );
		}

		$user_info['role'] = $role;

		return $user_info;
	}

	private function format_user_info_fields( array $user_info ): array {
		$fields = [];

		if ( ! empty( $user_info['name'] ) ) {
			$fields[] = [ 'type' => 'mrkdwn', 'text' => '*👤 User:* ' . $user_info['name'] ];
		}
		if ( ! empty( $user_info['email'] ) ) {
			$fields[] = [ 'type' => 'mrkdwn', 'text' => '*📧 Email:* ' . $user_info['email'] ];
		}
		if ( ! empty( $user_info['role'] ) ) {
			$fields[] = [ 'type' => 'mrkdwn', 'text' => '*🎭 Role:* ' . $user_info['role'] ];
		}
		if ( ! empty( $user_info['ip'] ) ) {
			$fields[] = [ 'type' => 'mrkdwn', 'text' => '*📍 User IP:* ' . $user_info['ip'] ];
		}

		return $fields;
	}

	private function format_parameters_fields( array $parameters, array $variables ): array {
		$fields = [];

		foreach ( $parameters as $key => $parameter ) {
			if ( empty( $variables[ $key ] ) || ! $parameter instanceof Parameter ) {
				continue;
			}

			$value = $variables[ $key ];
			if ( is_array( $value ) || is_object( $value ) ) {
				$value = wp_json_encode( $value, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );
			}
			$value = (string) $value;
			if ( strlen( $value ) > 500 ) {
				$value = substr( $value, 0, 497 ) . '...';
			}

			$fields[] = [
				'type' => 'mrkdwn',
				'text' => '*' . $this->escape_slack_text( $parameter->get_label() ) . ':* ' . $this->escape_slack_text( $value ),
			];
		}

		return $fields;
	}

	private function escape_slack_text( string $text ): string {
		$text = str_replace( '&', '&amp;', $text );
		$text = str_replace( '<', '&lt;', $text );
		$text = str_replace( '>', '&gt;', $text );

		return $text;
	}
}
