<?php
/**
 * Uninstall cleanup for Content Performance Analyzer.
 *
 * Freemius owns the uninstall lifecycle, so this runs on the SDK's
 * `after_uninstall` action rather than from an uninstall.php file. The SDK
 * refuses to deploy a package containing uninstall.php, and its own hook is
 * the safer place regardless: Freemius::_uninstall_plugin_hook() returns
 * early while either the free or the premium copy is still active, so
 * deleting the leftover free plugin after upgrading to Pro can no longer
 * destroy a paying customer's data.
 *
 * @package ContentPerformanceAnalyzer
 */

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

/**
 * Remove all plugin data for the current site.
 *
 * @return void
 */
function cpanalyzer_uninstall_cleanup_site() {
	global $wpdb;

	$option_keys = array(
		'cpanalyzer_ai_provider',
		'cpanalyzer_batch_size',
		'cpanalyzer_batch_status',
		'cpanalyzer_content_data',
		'cpanalyzer_conversion_events',
		'cpanalyzer_db_version',
		'cpanalyzer_debug_mode',
		'cpanalyzer_enable_auto_scan',
		'cpanalyzer_ga_prev_rows',
		'cpanalyzer_ga_rows',
		'cpanalyzer_gsc_rows',
		'cpanalyzer_install_date',
		'cpanalyzer_internal_link_suggestions',
		'cpanalyzer_last_full_scan',
		'cpanalyzer_link_analysis_status',
		'cpanalyzer_log_errors',
		'cpanalyzer_oauth_access_token',
		'cpanalyzer_oauth_client_id',
		'cpanalyzer_oauth_client_secret',
		'cpanalyzer_oauth_connected_email',
		'cpanalyzer_oauth_connection_error',
		'cpanalyzer_oauth_mode',
		'cpanalyzer_install_token',
		'cpanalyzer_psi_pages',
		'cpanalyzer_llms_txt_enable',
		'cpanalyzer_ai_model',
		'cpanalyzer_oauth_refresh_token',
		'cpanalyzer_oauth_token_expires',
		'cpanalyzer_off_peak_hour',
		'cpanalyzer_off_peak_timezone',
		'cpanalyzer_openai_key',
		'cpanalyzer_page_actions',
		'cpanalyzer_page_flags',
		'cpanalyzer_pagespeed_api_key',
		'cpanalyzer_pagespeed_cache_hours',
		'cpanalyzer_pagespeed_categories',
		'cpanalyzer_pagespeed_enable',
		'cpanalyzer_pagespeed_rate_limit',
		'cpanalyzer_pagespeed_strategy',
		'cpanalyzer_posts_for_link_analysis',
		'cpanalyzer_pro_license',
		'cpanalyzer_property_id',
		'cpanalyzer_serper_api_key',
		'cpanalyzer_site_url',
		'cpanalyzer_status_msg',
		'cpanalyzer_flag_snapshot',
		'cpanalyzer_new_flags',
		'cpanalyzer_ai_drain_state',
		'cpanalyzer_snapshot_last_capture',
		'cpanalyzer_refreshed_map',
		'cpanalyzer_ai_quota',
		'cpanalyzer_data_health',
		'cpanalyzer_recovery_news',
		'cpanalyzer_verdict_check_day',
		'cpanalyzer_review_ask_state',
		'cpanalyzer_trigger_collection_on_load',
		'cpanalyzer_url_upload_order',
		'cpanalyzer_verify_ssl',
		'cpanalyzer_version',
	);

	foreach ( $option_keys as $option_key ) {
		delete_option( $option_key );
	}

	// Post meta written by the FAQ answer-block feature.
	delete_post_meta_by_key( '_cpanalyzer_faq' );
	delete_post_meta_by_key( '_cpanalyzer_faq_external' );

	// One-time OAuth state markers on user accounts.
	delete_metadata( 'user', 0, 'cpanalyzer_oauth_state', '', true );
	delete_metadata( 'user', 0, 'cpanalyzer_hosted_state', '', true );

	$transient_keys = array(
		'cpanalyzer_install_token_backoff',
		'cpanalyzer_batch_running',
		'cpanalyzer_batch_start_time',
		'cpanalyzer_batch_timestamp',
		'cpanalyzer_ai_drain_lock',
		'cpanalyzer_event_logs',
		'cpanalyzer_oauth_state',
		'cpanalyzer_pending_ai_payload',
		'cpanalyzer_pending_content_analysis',
		'cpanalyzer_gsc_trend_data',
		'cpanalyzer_gsc_cannibalization',
		'cpanalyzer_gsc_yoy_data',
		'cpanalyzer_inbound_link_map',
	);

	foreach ( $transient_keys as $transient_key ) {
		delete_transient( $transient_key );
	}

	// Per-keyword SERP feature caches use hashed suffixes — sweep by prefix.
	global $wpdb;
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One-time uninstall cleanup of prefixed transients.
	$wpdb->query(
		"DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_cpanalyzer_serp_feat_%' OR option_name LIKE '_transient_timeout_cpanalyzer_serp_feat_%'"
	);

	$cron_hooks = array(
		'cpanalyzer_daily_refresh',
		'cpanalyzer_off_peak_scan',
		'cpanalyzer_batch_process',
		'cpanalyzer_background_content_analysis',
		'cpanalyzer_cleanup_stuck_processes',
		'cpanalyzer_process_link_analysis',
		'cpanalyzer_ai_drain',
	);

	foreach ( $cron_hooks as $cron_hook ) {
		wp_clear_scheduled_hook( $cron_hook );
	}

	// Remove the "interlinks applied" flag from every post that has it.
	delete_metadata( 'post', 0, '_cpanalyzer_interlinks_applied', '', true );
	delete_metadata( 'post', 0, '_cpanalyzer_refresh_of', '', true );
	delete_metadata( 'post', 0, '_cpanalyzer_refresh_draft', '', true );

	// Drop the plugin's custom table.
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- Dropping plugin table on uninstall
	$wpdb->query( "DROP TABLE IF EXISTS `{$wpdb->prefix}cpanalyzer_urls`" );
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- Dropping plugin table on uninstall
	$wpdb->query( "DROP TABLE IF EXISTS `{$wpdb->prefix}cpanalyzer_snapshots`" );
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- Dropping plugin table on uninstall
	$wpdb->query( "DROP TABLE IF EXISTS `{$wpdb->prefix}cpanalyzer_artifacts`" );
}

/**
 * Remove plugin data across the whole installation.
 *
 * Registered on the Freemius `after_uninstall` action from the main plugin
 * file. WordPress loads the plugin before firing a registered uninstall
 * hook, so every function this depends on is available.
 *
 * @return void
 */
function cpanalyzer_run_uninstall_cleanup() {
	if ( is_multisite() ) {
		// Clean every site in the network.
		$site_ids = get_sites( array( 'fields' => 'ids' ) );

		foreach ( $site_ids as $site_id ) {
			switch_to_blog( $site_id );
			cpanalyzer_uninstall_cleanup_site();
			restore_current_blog();
		}
	} else {
		cpanalyzer_uninstall_cleanup_site();
	}

	wp_cache_flush();
}
