<?php
/**
 * Fired when the plugin is uninstalled.
 */

if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

global $wpdb;

$options = [
	'_storevoiceai_apikey',
	'_storevoiceai_access_token',
	'_storevoiceai_serversecret',
	'_storevoiceai_site_key',
	'_storevoiceai_site_registered',
	'_storevoiceai_system_email',
	'_storevoiceai_needs_registration',
	'_storevoiceai_last_synced_license',
	'_storevoiceai_agentid',
	'_storevoiceai_assistant_name',
	'_storevoiceai_assistant_voice',
	'_storevoiceai_assistant_first_message',
	'_storevoiceai_shipping_policy',
	'_storevoiceai_returns_policy',
	'_storevoiceai_owner_email',
	'_storevoiceai_knowledge_base_pages',
	'_storevoiceai_onboarding_complete',
	'_storevoiceai_onboarding_redirect',
	'_storevoiceai_onboarding_step',
	'_storevoiceai_onboarding_escalation',
	'_storevoiceai_onboarding_escalation_value',
	'_storevoiceai_onboarding_working_hours',
];

if ( is_multisite() ) {
	$blog_ids = $wpdb->get_col( "SELECT blog_id FROM {$wpdb->blogs}" );
	foreach ( $blog_ids as $blog_id ) {
		switch_to_blog( $blog_id );
		storevoiceai_delete_site_data( $wpdb, $options );
		restore_current_blog();
	}
} else {
	storevoiceai_delete_site_data( $wpdb, $options );
}

/**
 * Deletes all plugin data for a single site.
 *
 * @param wpdb  $wpdb
 * @param array $options
 */
function storevoiceai_delete_site_data( $wpdb, $options ) {
	foreach ( $options as $option ) {
		delete_option( $option );
	}

	// Remove per-user meta for all users who visited the dashboard.
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->delete( $wpdb->usermeta, [ 'meta_key' => '_storevoiceai_dashboard_tour_seen' ], [ '%s' ] );

	// Remove rate-limiting transients (60-second TTL but may still be present).
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->query(
		$wpdb->prepare(
			"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
			$wpdb->esc_like( '_transient_storevoiceai_call_rl_' ) . '%',
			$wpdb->esc_like( '_transient_timeout_storevoiceai_call_rl_' ) . '%'
		)
	);

	// Remove the WooCommerce REST API key created during site registration.
	if ( $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->prefix}woocommerce_api_keys'" ) ) {
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$wpdb->delete(
			$wpdb->prefix . 'woocommerce_api_keys',
			[ 'description' => 'StoreVoiceAI Integration' ],
			[ '%s' ]
		);
	}
}
