<?php
/**
 * Uninstall script for ChatSell Widgets plugin
 *
 * This file is executed when the plugin is deleted through WordPress admin.
 * It cleans up all plugin data from the database.
 */

// If uninstall not called from WordPress, then exit
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

// Revoke the WooCommerce API key the connect flow created for ChatSell. It is
// a live read credential for this store; deleting the plugin without removing
// it would leave it working, listed under WooCommerce → Advanced → REST API
// with nothing left to explain what it is for.
// The class constant CSWidgets_Plugin::WC_KEY_DESCRIPTION is out of reach here —
// uninstall.php runs without loading the plugin — so the description is repeated
// literally. It must stay in step with that constant.
$cswidgets_wc_key_description = 'ChatSell (auto-generated)';

global $wpdb;
$cswidgets_options    = get_option( 'cswidgets_options' );
$cswidgets_keys_table = $wpdb->prefix . 'woocommerce_api_keys';

// A site that never ran WooCommerce has no such table, and querying it anyway
// would only log a database error on the way out.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL -- a table name cannot be bound.
$cswidgets_keys_table_exists = $wpdb->get_var(
	$wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $cswidgets_keys_table ) )
) === $cswidgets_keys_table;

if ( $cswidgets_keys_table_exists ) {
	if ( is_array( $cswidgets_options ) && ! empty( $cswidgets_options['wc_key_id'] ) ) {
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery -- matches provision_wc_key() in the plugin.
		$wpdb->delete(
			$cswidgets_keys_table,
			array( 'key_id' => absint( $cswidgets_options['wc_key_id'] ) ),
			array( '%d' )
		);
	}

	// The recorded id covers only the key from the most recent connect. A store
	// that reconnected before an older plugin version learned to purge, or whose
	// options row was lost, can still hold keys we minted — they are just as
	// live. Scoped to our exact description so a merchant's own keys, and any
	// created by another integration, are never touched.
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery -- matches purge_stale_wc_keys() in the plugin.
	$wpdb->delete(
		$cswidgets_keys_table,
		array( 'description' => $cswidgets_wc_key_description ),
		array( '%s' )
	);
}

// Remove plugin options
delete_option( 'cswidgets_options' );
delete_option( 'cswidgets_legacy_options_migrated' );
delete_option( 'chatsell_options' );

// Remove any transients
delete_transient( 'cswidgets_cache' );

// The sync hooks schedule single events; left behind they fire forever against
// a plugin that no longer exists.
wp_clear_scheduled_hook( 'cswidgets_sync_product_delayed' );
wp_clear_scheduled_hook( 'cswidgets_sync_knowledge_source_delayed' );

// Additional data cleanup can be added here if the plugin stores
// user meta or post meta in future versions.
