<?php
/**
 * My Easy Monogram — Uninstall
 *
 * Fired when the plugin is deleted from WordPress.
 * Notifies MEM API, revokes credentials, removes webhooks,
 * and cleans up all plugin data (connector + live preview).
 *
 * @package Memwc_Connector
 * @since   1.0.0
 */

defined( 'WP_UNINSTALL_PLUGIN' ) || exit;

/**
 * Run the full uninstall routine.
 *
 * Wrapped in a prefixed function so no variables are defined at the
 * global scope of the uninstall script.
 */
function memwc_connector_run_uninstall() {
	// Retrieve connection data BEFORE deleting options.
	$store_secret  = get_option( 'memwc_connector_store_secret', '' );
	$is_connected  = get_option( 'memwc_connector_connected', false );
	$api_key_id    = get_option( 'memwc_connector_api_key_id' );
	$webhook_ids   = get_option( 'memwc_connector_webhook_ids', array() );
	$saved_api_url = get_option( 'memwc_connector_api_base_url', '' );

	// ── Notify MEM API ──────────────────────────────────────────────────────

	if ( $is_connected && ! empty( $store_secret ) ) {
		if ( ! empty( $saved_api_url ) ) {
			$api_base = $saved_api_url;
		} elseif ( defined( 'MEMWC_API_URL' ) ) {
			$api_base = MEMWC_API_URL;
		} else {
			$api_base = 'https://app.myeasymonogram.com';
		}

		$json_body      = wp_json_encode( array( 'storeUrl' => home_url() ) );
		$signature      = base64_encode( hash_hmac( 'sha256', $json_body, $store_secret, true ) );
		$disconnect_url = rtrim( $api_base, '/' ) . '/api/woocommerce/disconnect';

		$response = wp_remote_post( $disconnect_url, array(
			'timeout'   => 30,
			'blocking'  => true,
			'sslverify' => true,
			'headers'   => array(
				'Content-Type'    => 'application/json',
				'Accept'          => 'application/json',
				'X-MEM-Signature' => $signature,
				'X-MEM-Store-Url' => home_url(),
			),
			'body' => $json_body,
		) );

		if ( is_wp_error( $response ) && defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			error_log( 'MEM Connector: Uninstall disconnect failed — ' . $response->get_error_message() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
		}
	}

	// ── Local cleanup (always runs, even if the API call above failed) ──────

	// Revoke WooCommerce REST API keys.
	if ( $api_key_id ) {
		global $wpdb;
		$wpdb->delete( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
			$wpdb->prefix . 'woocommerce_api_keys',
			array( 'key_id' => absint( $api_key_id ) ),
			array( '%d' )
		);
	}

	// Remove WooCommerce webhooks.
	if ( ! empty( $webhook_ids ) && is_array( $webhook_ids ) && function_exists( 'wc_get_webhook' ) ) {
		foreach ( $webhook_ids as $webhook_id ) {
			$webhook = wc_get_webhook( absint( $webhook_id ) );
			if ( $webhook ) {
				$webhook->delete( true );
			}
		}
	}

	// Delete all plugin options (connector + live preview).
	$options = array(
		'memwc_connector_store_secret',
		'memwc_connector_store_snapshot',
		'memwc_connector_webhook_url',
		'memwc_connector_connected',
		'memwc_connector_connected_at',
		'memwc_connector_api_key_id',
		'memwc_connector_webhook_ids',
		'memwc_connector_api_base_url',
		'memwc_connector_version',
		'memwc_widget_settings',
		'memwc_shop_url',
	);

	foreach ( $options as $option ) {
		delete_option( $option );
	}
}

memwc_connector_run_uninstall();
