<?php
/**
 * Slack Notifier class for sending chat notifications to Slack
 *
 * This class handles sending notifications and messages to Slack
 * when users send messages or agents/AI respond.
 *
 * @package Askany
 * @since 1.0.0
 */

namespace Askany;

/**
 * Slack Notifier class for sending chat notifications to Slack
 *
 * @package Askany
 * @since 1.0.0
 */
class SlackNotifier {
	/**
	 * API Manager instance.
	 *
	 * @var ApiManager
	 */
	private $api_manager;

	/**
	 * Constructor for SlackNotifier class.
	 *
	 * @param ApiManager $api_manager The API manager instance.
	 */
	public function __construct( $api_manager ) {
		$this->api_manager = $api_manager;
	}

	/**
	 * Initialize the Slack notifier.
	 *
	 * @return void
	 */
	public function init() {
		// Hook into chat message events
		add_action( 'askany_user_message_saved', array( $this, 'handle_user_message' ), 10, 3 );
		add_action( 'askany_agent_message_saved', array( $this, 'handle_agent_message' ), 10, 3 );
		add_action( 'askany_ai_message_saved', array( $this, 'handle_ai_message' ), 10, 3 );
	}

	/**
	 * Handle user message notification.
	 *
	 * @param string $session_id The session ID.
	 * @param string $message The message content.
	 * @param array  $user_data User data.
	 *
	 * @return void
	 */
	public function handle_user_message( $session_id, $message, $user_data ) {
		$settings = $this->get_slack_settings();
		
		if ( ! $this->is_slack_enabled( $settings ) || ! $settings['notify_user_messages'] ) {
			return;
		}

		$user_name = $user_data['name'] ?? $user_data['display_name'] ?? __( 'Anonymous User', 'askany' );
		$user_name = (string) $user_name; // Ensure string type
		
		$slack_message = array(
			'text' => sprintf( __( '💬 New message from %s', 'askany' ), $user_name ),
			'username' => 'Askany',
			'icon_emoji' => ':speech_balloon:',
			'attachments' => array(
				array(
					'color' => '#36a64f',
					'fields' => array(
						array(
							'title' => __( 'User', 'askany' ),
							'value' => $user_name,
							'short' => true,
						),
						array(
							'title' => __( 'Session ID', 'askany' ),
							'value' => substr( (string) $session_id, 0, 8 ) . '...',
							'short' => true,
						),
						array(
							'title' => __( 'Message', 'askany' ),
							'value' => $this->truncate_message( (string) $message ),
							'short' => false,
						),
					),
					'footer' => 'Askany Live Chat',
					'ts' => time(),
				),
			),
		);

		$this->send_to_slack( $slack_message, $settings );
	}

	/**
	 * Handle agent message notification.
	 *
	 * @param string $session_id The session ID.
	 * @param string $message The message content.
	 * @param array  $agent_data Agent data.
	 *
	 * @return void
	 */
	public function handle_agent_message( $session_id, $message, $agent_data ) {
		$settings = $this->get_slack_settings();
		
		if ( ! $this->is_slack_enabled( $settings ) || ! $settings['forward_agent_messages'] ) {
			return;
		}

		$agent_name = $agent_data['display_name'] ?? __( 'Agent', 'askany' );
		$agent_name = (string) $agent_name; // Ensure string type
		
		$slack_message = array(
			'text' => sprintf( __( '👤 Agent response from %s', 'askany' ), $agent_name ),
			'username' => 'Askany',
			'icon_emoji' => ':bust_in_silhouette:',
			'attachments' => array(
				array(
					'color' => '#3AA3E3',
					'fields' => array(
						array(
							'title' => __( 'Agent', 'askany' ),
							'value' => $agent_name,
							'short' => true,
						),
						array(
							'title' => __( 'Session ID', 'askany' ),
							'value' => substr( (string) $session_id, 0, 8 ) . '...',
							'short' => true,
						),
						array(
							'title' => __( 'Response', 'askany' ),
							'value' => $this->truncate_message( (string) $message ),
							'short' => false,
						),
					),
					'footer' => 'Askany Live Chat',
					'ts' => time(),
				),
			),
		);

		$this->send_to_slack( $slack_message, $settings );
	}

	/**
	 * Handle AI message notification.
	 *
	 * @param string $session_id The session ID.
	 * @param string $message The message content.
	 * @param array  $ai_data AI data.
	 *
	 * @return void
	 */
	public function handle_ai_message( $session_id, $message, $ai_data ) {
		$settings = $this->get_slack_settings();
		
		if ( ! $this->is_slack_enabled( $settings ) || ! $settings['forward_ai_messages'] ) {
			return;
		}

		$slack_message = array(
			'text' => __( '🤖 AI Assistant Response', 'askany' ),
			'username' => 'Askany',
			'icon_emoji' => ':robot_face:',
			'attachments' => array(
				array(
					'color' => '#FF6B6B',
					'fields' => array(
						array(
							'title' => __( 'AI Assistant', 'askany' ),
							'value' => __( 'Askany AI', 'askany' ),
							'short' => true,
						),
						array(
							'title' => __( 'Session ID', 'askany' ),
							'value' => substr( (string) $session_id, 0, 8 ) . '...',
							'short' => true,
						),
						array(
							'title' => __( 'Response', 'askany' ),
							'value' => $this->truncate_message( (string) $message ),
							'short' => false,
						),
					),
					'footer' => 'Askany Live Chat',
					'ts' => time(),
				),
			),
		);

		$this->send_to_slack( $slack_message, $settings );
	}

	/**
	 * Send message to Slack.
	 *
	 * @param array $message The message data.
	 * @param array $settings Slack settings.
	 *
	 * @return bool True on success, false on failure.
	 */
	private function send_to_slack( $message, $settings ) {
		if ( empty( $settings['webhook_url'] ) ) {
			return false;
		}

		// Add channel if specified
		if ( ! empty( $settings['channel'] ) ) {
			$message['channel'] = $settings['channel'];
		}

		$response = wp_remote_post( $settings['webhook_url'], array(
			'body' => wp_json_encode( $message ),
			'headers' => array(
				'Content-Type' => 'application/json',
			),
			'timeout' => 15,
		) );

		if ( is_wp_error( $response ) ) {
			// error_log( 'Askany Slack notification failed: ' . $response->get_error_message() );
			return false;
		}

		$response_code = wp_remote_retrieve_response_code( $response );
		
		if ( $response_code !== 200 ) {
			// error_log( 'Askany Slack notification failed with response code: ' . $response_code );
			return false;
		}

		return true;
	}

	/**
	 * Get Slack settings.
	 *
	 * @return array Slack settings.
	 */
	private function get_slack_settings() {
		$settings = $this->api_manager->get_settings();
		
		$default_settings = array(
			'enabled' => false,
			'webhook_url' => '',
			'channel' => '#general',
			'notify_user_messages' => true,
			'forward_agent_messages' => false,
			'forward_ai_messages' => false,
		);

		return isset( $settings['slack'] ) ? array_merge( $default_settings, $settings['slack'] ) : $default_settings;
	}

	/**
	 * Check if Slack is enabled.
	 *
	 * @param array $settings Slack settings.
	 *
	 * @return bool True if enabled, false otherwise.
	 */
	private function is_slack_enabled( $settings ) {
		return ! empty( $settings['enabled'] ) && ! empty( $settings['webhook_url'] );
	}

	/**
	 * Truncate message for Slack display.
	 *
	 * @param string $message The message to truncate.
	 * @param int    $length Maximum length.
	 *
	 * @return string Truncated message.
	 */
	private function truncate_message( $message, $length = 200 ) {
		// Ensure message is a string
		$message = (string) $message;
		
		if ( strlen( $message ) <= $length ) {
			return $message;
		}

		return substr( $message, 0, $length ) . '...';
	}
}