<?php
/**
 * Fired when the plugin is uninstalled.
 *
 * Removes all plugin data: options, transients, tracking table, cron events.
 *
 * @package Relatedly
 * @since   2.0.0
 */

defined( 'WP_UNINSTALL_PLUGIN' ) || exit;

global $wpdb;

// Options.
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
$option_keys = [
	'relatedly_settings',
	'relatedly_version',
	'relatedly_table_schema_version',
	'relatedly_labels_cleaned',
	'relatedly_activated_time',
	'relatedly_review_dismissed',
	'relatedly_premium_dismissed',
];
foreach ( $option_keys as $key ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
	delete_option( $key );
}

// Transients — wildcard delete via direct query (no WP API for this).
// 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_relatedly_' ) . '%',
		$wpdb->esc_like( '_transient_timeout_relatedly_' ) . '%'
	)
);

// Tracking table.
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
$table = esc_sql( $wpdb->prefix . 'relatedly_clicks' );
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
$wpdb->query( "DROP TABLE IF EXISTS `{$table}`" );

// Cron events.
foreach ( [ 'relatedly_scheduled_email_report', 'relatedly_data_pruning' ] as $hook ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
	$ts = wp_next_scheduled( $hook ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
	if ( $ts ) {
		wp_unschedule_event( $ts, $hook );
	}
}
