<?php
/**
 * Activity Guard – Telegram Bot Notifier
 *
 * This class handles sending notifications to Telegram via Bot API
 *
 * @package WPNTS\Inc
 */

namespace WPNTS\Inc;

defined('ABSPATH') || die('Hey, what are you doing here? You silly human!');

/**
 * Telegram Notifier class for sending notifications via Telegram Bot API
 *
 * @since 1.0.0
 */
class TelegramNotifier {

	/**
	 * Send notification to Telegram
	 *
	 * @param string $bot_token The Telegram bot token
	 * @param string $chat_id The chat ID to send message to
	 * @param string $message The message to send
	 * @param string $parse_mode Optional. Message parse mode (HTML, Markdown, MarkdownV2)
	 * @param int $timeout Optional. Request timeout in seconds. Default 5.
	 * @param bool $ssl_verify Optional. Whether to verify SSL. Default false.
	 * 
	 * @return array|WP_Error The response from wp_remote_post or WP_Error on failure.
	 * @since 1.0.0
	 */
	public function send_telegram_notification( $bot_token, $chat_id, $message, $parse_mode = 'HTML', $timeout = 5, $ssl_verify = false ) {
		// Return early if required parameters are empty
		if ( empty( $bot_token ) || empty( $chat_id ) ) {
			return new \WP_Error( 'missing_params', 'Bot token or chat ID is empty' );
		}

		// Telegram Bot API URL
		$api_url = "https://api.telegram.org/bot{$bot_token}/sendMessage";

		// Prepare payload
		$payload_data = [
			'chat_id' => $chat_id,
			'text' => $message,
			'parse_mode' => $parse_mode,
			'disable_web_page_preview' => true
		];

		// Prepare arguments for wp_remote_post
		$args = [
			'body'      => $payload_data,
			'timeout'   => $timeout,
			'sslverify' => $ssl_verify,
		];

		// Send the request
		$response = wp_remote_post( $api_url, $args );

		// Check for errors
		if ( is_wp_error( $response ) ) {
			return $response;
		}

		// Parse response
		$response_code = wp_remote_retrieve_response_code( $response );
		$response_body = wp_remote_retrieve_body( $response );
		$decoded_response = json_decode( $response_body, true );

		if ( $response_code !== 200 || ! $decoded_response['ok'] ) {
			$error_message = isset( $decoded_response['description'] ) 
				? $decoded_response['description'] 
				: 'Unknown Telegram API error';
			return new \WP_Error( 'telegram_api_error', $error_message );
		}

		return $decoded_response;
	}

	/**
	 * Format message for Telegram (convert HTML entities, handle emojis)
	 *
	 * @param string $message The original message
	 * @return string Formatted message for Telegram
	 * @since 1.0.0
	 */
	public function format_message_for_telegram( $message ) {
		// Convert HTML entities to plain text for better Telegram display
		$formatted_message = html_entity_decode( $message, ENT_QUOTES, 'UTF-8' );
		
		// Remove HTML tags but keep the content
		$formatted_message = strip_tags( $formatted_message );
		
		// Ensure proper line breaks
		$formatted_message = str_replace( '<br>', "\n", $formatted_message );
		$formatted_message = str_replace( '<br/>', "\n", $formatted_message );
		$formatted_message = str_replace( '<br />', "\n", $formatted_message );
		
		// Clean up multiple line breaks
		$formatted_message = preg_replace( '/\n+/', "\n", $formatted_message );
		
		return trim( $formatted_message );
	}

	/**
	 * Test Telegram bot configuration
	 *
	 * @param string $bot_token The bot token to test
	 * @param string $chat_id The chat ID to test
	 * @return array|WP_Error Test result
	 * @since 1.0.0
	 */
	public function test_telegram_configuration( $bot_token, $chat_id ) {
		$test_message = "🧪 Test message from Activity Guard\n\nYour Telegram bot is configured correctly!";
		
		$result = $this->send_telegram_notification( $bot_token, $chat_id, $test_message );
		
		if ( is_wp_error( $result ) ) {
			return $result;
		}
		
		return [
			'success' => true,
			'message' => 'Test message sent successfully!',
			'telegram_response' => $result
		];
	}

	/**
	 * Get bot information
	 *
	 * @param string $bot_token The bot token
	 * @return array|WP_Error Bot information or error
	 * @since 1.0.0
	 */
	public function get_bot_info( $bot_token ) {
		if ( empty( $bot_token ) ) {
			return new \WP_Error( 'missing_token', 'Bot token is empty' );
		}

		$api_url = "https://api.telegram.org/bot{$bot_token}/getMe";

		$response = wp_remote_get( $api_url, [
			'timeout' => 5,
			'sslverify' => false
		] );

		if ( is_wp_error( $response ) ) {
			return $response;
		}

		$response_code = wp_remote_retrieve_response_code( $response );
		$response_body = wp_remote_retrieve_body( $response );
		$decoded_response = json_decode( $response_body, true );

		if ( $response_code !== 200 || ! $decoded_response['ok'] ) {
			$error_message = isset( $decoded_response['description'] ) 
				? $decoded_response['description'] 
				: 'Invalid bot token';
			return new \WP_Error( 'invalid_token', $error_message );
		}

		return $decoded_response['result'];
	}

	/**
	 * Validate chat ID format
	 *
	 * @param string $chat_id The chat ID to validate
	 * @return bool Is valid
	 * @since 1.0.0
	 */
	public function is_valid_chat_id( $chat_id ) {
		if ( empty( $chat_id ) ) {
			return false;
		}

		// Chat ID can be:
		// - Positive integer for user ID
		// - Negative integer for group/channel ID
		// - String starting with @ for username
		return preg_match( '/^(@[a-zA-Z0-9_]+|[-]?\d+)$/', $chat_id );
	}

	/**
	 * Check if Telegram notifications are enabled globally
	 *
	 * @return bool Whether Telegram notifications are enabled
	 * @since 1.0.0
	 */
	public function is_telegram_enabled() {
		$global_settings = get_option( 'wpnts_global_api_settings' );
		$settings = json_decode( $global_settings, true );
		
		return isset( $settings['telegram_notifications_enabled'] ) && $settings['telegram_notifications_enabled'] === true;
	}

	/**
	 * Get Telegram configuration from global settings
	 *
	 * @return array Telegram configuration
	 * @since 1.0.0
	 */
	public function get_telegram_config() {
		$global_settings = get_option( 'wpnts_global_api_settings' );
		$settings = json_decode( $global_settings, true );
		
		return [
			'bot_token' => $settings['telegram_bot_token'] ?? '',
			'chat_id' => $settings['telegram_chat_id'] ?? '',
			'enabled' => $settings['telegram_notifications_enabled'] ?? false
		];
	}
}