<?php
/**
 * Plugin deactivation reporter.
 *
 * Posts a single best-effort report to the backend when the plugin is
 * deactivated from wp-admin → Plugins. This lets us distinguish:
 *   - manual deactivation (hook fires)
 *   - WP fatal-error auto-deactivate (hook does NOT fire — WordPress 5.2+
 *     "site health" recovery silently disables the plugin without running
 *     the deactivation hook)
 *   - uninstall / files removed (no PHP runs at all)
 *
 * The report is fire-and-forget: short timeout, non-blocking, swallow all
 * errors. Plugin deactivation must never be slowed or blocked by us.
 *
 * See workplans/active/RESEARCH-EarlyPluginDeactivation.md step #3.
 *
 * @package ClearPost
 */

if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * Report deactivation to the backend.
 */
function saiap_report_deactivation_to_backend() {
	if ( ! defined( 'SAIAP_PREMIUM_API_URL' ) || ! SAIAP_PREMIUM_API_URL ) {
		return;
	}

	$domain = wp_parse_url( home_url(), PHP_URL_HOST );
	if ( empty( $domain ) ) {
		return;
	}

	$license_key = get_option( 'saiap_license_key', '' );

	// Active plugins (excluding ourselves). Helps test the H2 plugin-conflict
	// hypothesis — if we see the same sibling repeatedly in deactivation
	// reports, that's the lead.
	$active_plugins = array();
	if ( function_exists( 'get_option' ) ) {
		$raw = get_option( 'active_plugins', array() );
		if ( is_array( $raw ) ) {
			$self = plugin_basename( SAIAP_PLUGIN_FILE );
			foreach ( $raw as $slug ) {
				if ( is_string( $slug ) && $slug !== $self ) {
					$active_plugins[] = $slug;
				}
			}
		}
	}

	$body = array(
		'domain'               => $domain,
		'license_key'          => $license_key,
		'plugin_version'       => defined( 'SAIAP_VERSION' ) ? SAIAP_VERSION : null,
		'wp_version'           => function_exists( 'get_bloginfo' ) ? get_bloginfo( 'version' ) : null,
		'php_version'          => PHP_VERSION,
		'active_plugins'       => $active_plugins,
		// True when the current request has an admin user with the
		// `activate_plugins` capability — i.e., an admin clicked Deactivate
		// in wp-admin. False/null when WP itself or a CLI is calling.
		'can_activate_plugins' => function_exists( 'current_user_can' ) ? current_user_can( 'activate_plugins' ) : null,
	);

	$url = trailingslashit( SAIAP_PREMIUM_API_URL ) . 'api/trial/plugin-deactivated';

	// Synchronous request with a short timeout. We use sync (not
	// `blocking => false`) because non-blocking on plugin deactivation can
	// silently drop the request as PHP tears the worker down. 3 seconds is
	// the same budget the dashboard uses for other backend pings.
	wp_remote_post(
		$url,
		array(
			'timeout'  => 3,
			'blocking' => true,
			'headers'  => array( 'Content-Type' => 'application/json' ),
			'body'     => wp_json_encode( $body ),
		)
	);

	// Intentionally do nothing with the response. Errors are swallowed; this
	// is best-effort instrumentation, not a contract.
}

/**
 * Register the deactivation hook. This fires only on manual deactivation
 * from wp-admin → Plugins. WP's fatal-error auto-deactivate path does NOT
 * fire register_deactivation_hook, by design — absence of a report on a
 * gone namespace is itself evidence.
 */
register_deactivation_hook( SAIAP_PLUGIN_FILE, 'saiap_report_deactivation_to_backend' );
