<?php
/**
 * Form Connector Uninstall
 *
 * This file is executed when the plugin is deleted from WordPress.
 * It removes ALL plugin data including:
 * - Database tables
 * - Options
 * - Transients
 * - User meta
 * - Scheduled events
 *
 * IMPORTANT: This file is called directly by WordPress, not through the plugin.
 * Therefore, we cannot use the plugin's classes or constants directly.
 *
 * @package FormConnector
 * @since   3.0.0
 */

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

// Prevent direct access
if (!defined('ABSPATH')) {
	exit;
}

/**
 * Main uninstall class
 * 
 * Using a class to avoid polluting the global namespace and to organize cleanup.
 */
class FormConnector_Uninstaller {

	/**
	 * Run the uninstaller
	 */
	public static function uninstall(): void {
		// Check if multisite and run accordingly
		if (is_multisite()) {
			self::uninstall_multisite();
		} else {
			self::uninstall_single_site();
		}
	}

	/**
	 * Uninstall for multisite
	 */
	private static function uninstall_multisite(): void {
		global $wpdb;

		// Get all blog IDs
		$blog_ids = $wpdb->get_col("SELECT blog_id FROM {$wpdb->blogs}");

		foreach ($blog_ids as $blog_id) {
			switch_to_blog($blog_id);
			self::cleanup_site_data();
			restore_current_blog();
		}

		// Also clean up network-level data if any
		self::cleanup_network_data();
	}

	/**
	 * Uninstall for single site
	 */
	private static function uninstall_single_site(): void {
		self::cleanup_site_data();
	}

	/**
	 * Clean up all site-specific data
	 */
	private static function cleanup_site_data(): void {
		global $wpdb;

		// 1. Drop database tables
		self::drop_tables();

		// 2. Delete all plugin options
		self::delete_options();

		// 3. Delete all transients
		self::delete_transients();

		// 4. Clear scheduled events
		self::clear_scheduled_events();

		// 5. Clean up user meta
		self::delete_user_meta();

		// 6. Clear any cached data
		self::clear_caches();
	}

	/**
	 * Drop custom database tables
	 */
	private static function drop_tables(): void {
		global $wpdb;

		// Submissions log table
		$table_name = $wpdb->prefix . 'fc_submissions_log';
		$wpdb->query("DROP TABLE IF EXISTS {$table_name}");
	}

	/**
	 * Delete all plugin options
	 */
	private static function delete_options(): void {
		// Plugin settings
		delete_option('fc_settings');
		delete_option('fc_plugin_version');
		delete_option('fc_db_version');
		delete_option('fc_log_table_version');

		// License options
		delete_option('fc_license_key');
		delete_option('fc_license_data');

		// CareHQ API settings
		delete_option('fc_carehq_account_id');
		delete_option('fc_carehq_api_key');
		delete_option('fc_carehq_api_secret');
		delete_option('fc_carehq_api_url');
		delete_option('fc_carehq_timeout');
		delete_option('fc_carehq_sales_channel_id');
		delete_option('fc_carehq_plugin_update');

		// Form mappings
		delete_option('fc_form_mappings');
		delete_option('fc_conditional_mappings');

		// Homes data
		delete_option('fc_homes');
		delete_option('fc_homes_data');

		// Error logs
		delete_option('fc_carehq_error_log');

		// Legacy options from v2.x (clean these up too)
		delete_option('cfc_license_key');
		delete_option('cfc_license_data');
		delete_option('cfc_sales_channel_id');
		delete_option('cfc_api_key');
		delete_option('cfc_api_secret');
		delete_option('cfc_account_id');
		delete_option('cfc_form_mappings');
		delete_option('cfc_settings');

		// Widget visibility settings
		delete_option('fc_dismissed_notices');
	}

	/**
	 * Delete all transients
	 */
	private static function delete_transients(): void {
		global $wpdb;

		// Delete known transients
		$transients = [
			'fc_license_cache',
			'fc_license_validated',
			'fc_carehq_connection_cache',
			'fc_carehq_locations',
			'fc_homes_cache',
		];

		foreach ($transients as $transient) {
			delete_transient($transient);
		}

		// Delete transients with dynamic names using SQL
		// This catches all fc_ prefixed transients
		$wpdb->query(
			"DELETE FROM {$wpdb->options} 
			WHERE option_name LIKE '_transient_fc_%' 
			OR option_name LIKE '_transient_timeout_fc_%'"
		);

		// Also clean up legacy cfc_ transients
		$wpdb->query(
			"DELETE FROM {$wpdb->options} 
			WHERE option_name LIKE '_transient_cfc_%' 
			OR option_name LIKE '_transient_timeout_cfc_%'"
		);

		// Site transients (for multisite)
		$wpdb->query(
			"DELETE FROM {$wpdb->sitemeta} 
			WHERE meta_key LIKE '_site_transient_fc_%' 
			OR meta_key LIKE '_site_transient_timeout_fc_%'"
		);
	}

	/**
	 * Clear scheduled events
	 */
	private static function clear_scheduled_events(): void {
		// Clear all events for this plugin's hooks
		wp_clear_scheduled_hook('fc_daily_license_check');
		wp_clear_scheduled_hook('fc_daily_log_cleanup');

		// Legacy hooks
		wp_clear_scheduled_hook('cfc_license_check');
	}

	/**
	 * Delete user meta related to the plugin
	 */
	private static function delete_user_meta(): void {
		global $wpdb;

		// Delete any user meta with fc_ prefix
		$wpdb->query(
			"DELETE FROM {$wpdb->usermeta} 
			WHERE meta_key LIKE 'fc_%' 
			OR meta_key LIKE 'cfc_%'"
		);
	}

	/**
	 * Clear any cached data
	 */
	private static function clear_caches(): void {
		// Clear object cache if available
		if (function_exists('wp_cache_flush_group')) {
			wp_cache_flush_group('formconnector');
		}

		// Flush rewrite rules in case we added any
		flush_rewrite_rules();
	}

	/**
	 * Clean up network-level data for multisite
	 */
	private static function cleanup_network_data(): void {
		global $wpdb;

		// Delete network-level options if any
		if (is_multisite()) {
			delete_site_option('fc_network_settings');
			delete_site_option('fc_network_license');
		}
	}
}

// Run the uninstaller
FormConnector_Uninstaller::uninstall();
