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

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

$serpiq_uninstall_option_prefix = 'serpiq_';

$serpiq_uninstall_delete_data = (int) get_option( $serpiq_uninstall_option_prefix . 'delete_data_on_uninstall', 0 );
if ( 1 !== $serpiq_uninstall_delete_data ) {
	return;
}

global $wpdb;

$serpiq_uninstall_table_prefix = $wpdb->prefix . 'serpiq_';
$serpiq_uninstall_tables       = array(
	'queries',
	'pages',
	'totals',
	'sync_log',
	'alerts',
	'links',
);

foreach ( $serpiq_uninstall_tables as $serpiq_uninstall_table_slug ) {
	$serpiq_uninstall_table_name = $serpiq_uninstall_table_prefix . $serpiq_uninstall_table_slug;
	if ( ! preg_match( '/^[a-zA-Z0-9_]+$/', $serpiq_uninstall_table_name ) ) {
		continue;
	}
	// %i identifier placeholder (WP 6.2+); table name is from fixed allowlist + $wpdb->prefix.
	$wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', $serpiq_uninstall_table_name ) );
}

$serpiq_uninstall_options = array(
	$serpiq_uninstall_option_prefix . 'db_version',
	$serpiq_uninstall_option_prefix . 'delete_data_on_uninstall',
	$serpiq_uninstall_option_prefix . 'google_client_id',
	$serpiq_uninstall_option_prefix . 'google_client_secret',
	$serpiq_uninstall_option_prefix . 'google_token_encrypted',
	$serpiq_uninstall_option_prefix . 'google_token_iv',
	$serpiq_uninstall_option_prefix . 'google_property',
	$serpiq_uninstall_option_prefix . 'last_sync_at',
	$serpiq_uninstall_option_prefix . 'backfill_state',
);

foreach ( $serpiq_uninstall_options as $serpiq_uninstall_option_name ) {
	delete_option( $serpiq_uninstall_option_name );
}

// Cleanup transients (LIKE pattern is escaped for prepare, wildcards appended outside esc_like).
$wpdb->query(
	$wpdb->prepare(
		'DELETE FROM %i WHERE option_name LIKE %s',
		$wpdb->options,
		$wpdb->esc_like( '_transient_serpiq_' ) . '%'
	)
);
$wpdb->query(
	$wpdb->prepare(
		'DELETE FROM %i WHERE option_name LIKE %s',
		$wpdb->options,
		$wpdb->esc_like( '_transient_timeout_serpiq_' ) . '%'
	)
);
