<?php
/**
 * Deactivator class.
 *
 * @package DokanKits\Setup
 * @since   3.0.0
 */

namespace DokanKits\Setup;

use DokanKits\Core\Data\Models\Settings;
use DokanKits\Core\Data\Stores\SettingsDataStore;
use DokanKits\Core\Interfaces\Runnable;
use Throwable;

/**
 * Class Deactivator
 *
 * Handles plugin deactivation
 *
 * @since 3.0.0
 * @package DokanKits\Setup
 */
class Deactivator implements Runnable {
	/**
	 * Run on plugin deactivation
	 *
	 * @return void
	 */
	public function run(): void {
		try {
			// Get system settings if they exist.
			$data_store = dokan_kits_get_container()->get( SettingsDataStore::class );
			$settings   = $data_store->get_settings_by_name( 'system' );

			// Update only if settings exist.
			if ( $settings instanceof Settings ) {
				$settings->update( 'is_active', false );
				$settings->update( 'last_deactivation_time', time() );
				$settings->save();
			}

			// Clear caches.
			wp_cache_flush();

			/**
			 * Action that fires after plugin deactivation
			 *
			 * @param Settings|null $system_settings The system settings object or null if not found.
			 */
			do_action( 'dokan_kits_deactivated', $settings ?? null );
		} catch ( Throwable $e ) {
			// Handle any exceptions that occur during the process.
			// Log error or perform cleanup operations if needed.
			error_log( 'Dokan Kits deactivation error: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
		}
	}
}
