<?php
/**
 * Plugin uninstall handler.
 *
 * Runs when the plugin is deleted via the WordPress admin.
 * Removes all plugin data including options, post meta, transients, and scheduled actions.
 *
 * @package AgenticWP
 * @link https://developer.wordpress.org/plugins/plugin-basics/uninstall-methods/
 */

// Security check: only run when called by WordPress during uninstallation.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	die;
}

/**
 * Delete all plugin data for a single site.
 *
 * @param int|null $site_id Optional site ID for multisite cleanup.
 */
function agenticwp_delete_site_data( $site_id = null ) {
	global $wpdb;

	// Switch to site if multisite.
	if ( $site_id && is_multisite() ) {
		switch_to_blog( $site_id );
	}

	// Delete all plugin options (21 total).
	$options = array(
		'agentic_wp_version',
		'agentic_wp_openai_key',
		'agentic_wp_model',
		'agentic_wp_reasoning_effort',
		'agentic_wp_max_output_tokens',
		'agentic_wp_enable_toast_notifications',
		'agentic_wp_enable_web_search',
		'agentic_wp_message_history_limit',
		'agentic_wp_create_post_directions',
		'agentic_wp_sample_prompts',
		'agentic_wp_default_image_id',
		'agentic_wp_organization_name',
		'agentic_wp_organization_logo',
		'agentic_wp_organization_email',
		'agentic_wp_organization_phone',
		'agentic_wp_actions',
		'agentic_wp_action_categories',
		'agenticwp_jobs',
		'agenticwp_as_test_count',
		'agenticwp_as_test_last_run',
		'agenticwp_usage_stats',
	);

	foreach ( $options as $option ) {
		delete_option( $option );
	}

	// Delete all plugin post meta (3 meta keys).
	delete_post_meta_by_key( '_agenticwp_meta_description' );
	delete_post_meta_by_key( '_agenticwp_schema_headline' );
	delete_post_meta_by_key( '_agenticwp_schema_description' );

	// Clear all plugin transients (WordPress has no native prefix deletion).
	// 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_agenticwp_' ) . '%',
			$wpdb->esc_like( '_transient_timeout_agenticwp_' ) . '%'
		)
	);

	// Unschedule all Action Scheduler actions (safety check).
	if ( function_exists( 'as_unschedule_all_actions' ) ) {
		as_unschedule_all_actions( '', array(), 'agenticwp_jobs' );
		as_unschedule_all_actions( '', array(), 'agenticwp_test' );
	}

	// Restore to original site if multisite.
	if ( $site_id && is_multisite() ) {
		restore_current_blog();
	}
}

// Handle multisite cleanup.
if ( is_multisite() ) {
	// Get all site IDs in the network.
	$agenticwp_site_ids = get_sites( array( 'fields' => 'ids' ) );

	foreach ( $agenticwp_site_ids as $agenticwp_site_id ) {
		agenticwp_delete_site_data( $agenticwp_site_id );
	}

	// Delete network-wide options if any exist (currently none defined).
} else {
	// Single site cleanup.
	agenticwp_delete_site_data();
}
