<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class SftcyWordaiServiceTelemetry {
	const INSTALLATION_OPTION = 'sftcy_wordai_service_installation_id';

	public static function init() {
		add_action( 'sftcy_wordai_seo_integration_event', array( __CLASS__, 'send' ), 10, 2 );
	}

	public static function send( $action, $status ) {
		$enabled = defined( 'SFTCY_WORDAI_SERVICE_TELEMETRY' ) && SFTCY_WORDAI_SERVICE_TELEMETRY;
		if ( ! apply_filters( 'sftcy_wordai_seo_telemetry_enabled', $enabled ) || ! is_array( $status ) ) {
			return;
		}

		$installation_id = (string) get_option( self::INSTALLATION_OPTION, '' );
		if ( '' === $installation_id ) {
			$installation_id = wp_generate_uuid4();
			update_option( self::INSTALLATION_OPTION, $installation_id, false );
		}

		$integration = SftcyWordaiSeoIntegrationManager::status();
		$active_count = count( $integration['active'] ?? array() );
		$mode = $active_count > 1 ? 'multiple' : ( 1 === $active_count ? 'single' : 'auto' );
		$endpoint = trailingslashit( defined( 'SFTCY_SOFTCOY_API_BASE' ) ? SFTCY_SOFTCOY_API_BASE : 'https://softcoy.com/api/v1' ) . 'services/events';
		$endpoint = apply_filters( 'sftcy_wordai_service_event_endpoint', $endpoint );

		wp_remote_post(
			$endpoint,
			array(
				'timeout' => 2,
				'blocking' => false,
				'headers' => array( 'Content-Type' => 'application/json' ),
				'body' => wp_json_encode(
					array(
						'installation_id' => $installation_id,
						'plugin_slug' => 'wordai',
						'plugin_edition' => 'free',
						'plugin_version' => defined( 'SFTCY_WORDAI_VERSION' ) ? SFTCY_WORDAI_VERSION : '',
						'provider_slug' => sanitize_key( $status['provider'] ?? 'native' ),
						'provider_version' => sanitize_text_field( $integration['selected_version'] ?? '' ),
						'integration_mode' => $mode,
						'action' => sanitize_key( $action ),
						'success' => ! empty( $status['success'] ),
						'duration_ms' => absint( $status['duration_ms'] ?? 0 ),
						'error_code' => sanitize_key( $status['error_code'] ?? '' ),
						'occurred_at' => gmdate( 'c', absint( $status['timestamp'] ?? time() ) ),
					)
				),
			)
		);
	}
}
