<?php
/**
 * `wp powersuite cache` commands.
 *
 * @package WP_PowerSuite\CLI
 * @since 1.0.7
 */

namespace WP_PowerSuite\CLI;

use WP_PowerSuite\Core\DataRegistry;
use WP_PowerSuite\Core\OptionStore;
use WP_PowerSuite\Core\TransientPurger;

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

/**
 * Clear WP PowerSuite-owned caches and transients.
 *
 * @since 1.0.7
 */
final class CacheCommand {

	/**
	 * Clear WP PowerSuite caches.
	 *
	 * By default this only clears caches and transients owned by WP PowerSuite
	 * (module metadata, plugin transients). The entire site object cache is only
	 * flushed when --all is passed.
	 *
	 * ## OPTIONS
	 *
	 * [--all]
	 * : Also flush the entire WordPress object cache (affects the whole site).
	 *
	 * ## EXAMPLES
	 *
	 *     $ wp powersuite cache clear
	 *     $ wp powersuite cache clear --all
	 *
	 * @when after_wp_load
	 *
	 * @param array<int, string>   $args       Positional arguments (unused).
	 * @param array<string, mixed> $assoc_args Associative arguments.
	 * @return void
	 */
	public function clear( array $args, array $assoc_args ): void {
		DataRegistry::clearCaches();
		OptionStore::getInstance()->clearCache();

		$deleted  = TransientPurger::deleteByPrefix( 'wp_powersuite_' );
		$deleted += TransientPurger::deleteByPrefix( 'wpps_' );

		\WP_CLI::log(
			sprintf(
				/* translators: %d: number of transients deleted */
				_n( 'Cleared %d WP PowerSuite transient.', 'Cleared %d WP PowerSuite transients.', $deleted, 'wp-powersuite' ),
				$deleted
			)
		);

		$all = (bool) \WP_CLI\Utils\get_flag_value( $assoc_args, 'all', false );
		if ( $all ) {
			\WP_CLI::warning( __( 'Flushing the ENTIRE WordPress object cache (all plugins/site).', 'wp-powersuite' ) );
			wp_cache_flush();
			\WP_CLI::success( __( 'WP PowerSuite caches cleared and full object cache flushed.', 'wp-powersuite' ) );
			return;
		}

		\WP_CLI::success( __( 'WP PowerSuite caches cleared.', 'wp-powersuite' ) );
	}
}
