<?php
/**
 * Plugin Deactivator
 *
 * Handles plugin deactivation tasks including:
 * - Clearing scheduled events
 * - Clearing temporary caches
 * - Cleaning up transient data
 *
 * Note: This does NOT delete user data - that happens only on uninstall.
 *
 * @package FormConnector
 * @subpackage Setup
 */

declare(strict_types=1);

namespace FormConnector\Core\Setup;

defined('ABSPATH') || exit;

/**
 * Deactivator class
 */
class Deactivator {

	/**
	 * Run deactivation tasks
	 *
	 * Called when the plugin is deactivated.
	 * Only cleans up temporary data, NOT user settings or logs.
	 *
	 * @return void
	 */
	public static function deactivate(): void {
		self::unschedule_events();
		self::clear_caches();

		// Log deactivation for debugging
		if (defined('WP_DEBUG') && WP_DEBUG) {
			error_log('[FormConnector] Plugin deactivated.');
		}
	}

	/**
	 * Unschedule all cron events
	 *
	 * @return void
	 */
	private static function unschedule_events(): void {
		// Clear license check cron
		$timestamp = wp_next_scheduled('fc_daily_license_check');
		if ($timestamp) {
			wp_unschedule_event($timestamp, 'fc_daily_license_check');
		}

		// Clear log cleanup cron
		$timestamp = wp_next_scheduled('fc_daily_log_cleanup');
		if ($timestamp) {
			wp_unschedule_event($timestamp, 'fc_daily_log_cleanup');
		}

		// Clear all events for this plugin's hooks
		wp_clear_scheduled_hook('fc_daily_license_check');
		wp_clear_scheduled_hook('fc_daily_log_cleanup');

		// Clear retry queue cron
		\FormConnector\Features\Retry\RetryQueue::get_instance()->unschedule_cron();
		wp_clear_scheduled_hook(\FormConnector\Features\Retry\RetryQueue::CRON_HOOK);

		// Clear logs retention cron
		if (class_exists(\FormConnector\Features\Logs\RetentionCron::class)) {
			\FormConnector\Features\Logs\RetentionCron::unschedule();
			wp_clear_scheduled_hook(\FormConnector\Features\Logs\RetentionCron::CRON_HOOK);
		}

		// Clear CareHQ health ping cron
		\FormConnector\Integration\Health\HealthPing::unschedule_cron();
	}

	/**
	 * Clear all plugin caches and transients
	 *
	 * @return void
	 */
	private static function clear_caches(): 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 (like sales channels cache)
		$wpdb->query(
			"DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_fc_carehq_sales_channels_%'"
		);
		$wpdb->query(
			"DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_fc_carehq_sales_channels_%'"
		);

		// Clear object cache if available
		if (function_exists('wp_cache_flush_group')) {
			wp_cache_flush_group('formconnector');
		}
	}
}
