<?php
declare( strict_types=1 );

namespace FiboFilters\WpCli;

use FiboFilters\DI\ContainerWrapper;
use FiboFilters\Settings\Storage;
use WP_CLI;

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

/**
 * Maintenance commands
 */
class FibofiltersMaintenanceCommand {
	/**
	 * Reset plugin settings.
	 *
	 * ## OPTIONS
	 *
	 * [--yes]
	 * : Answer yes to the confirmation message.
	 *
	 * @subcommand reset-settings
	 */
	public function reset_settings( array $args, array $assoc_args ): void {
		global $wpdb;

		WP_CLI::confirm( 'Are you sure you want to reset the settings?', $assoc_args );

		$table  = $wpdb->options;
		$column = 'option_name';

		if ( is_multisite() ) {
			$table  = $wpdb->sitemeta;
			$column = 'meta_key';
		}

		$wpdb->query(
			"
			DELETE
			FROM {$table}
			WHERE {$column} LIKE '%fibofilters_%'
		"
		);

		$storage = ContainerWrapper::get_instance()->get( Storage::class );
		$table   = $storage->get_table_name();

		$wpdb->query( "DELETE FROM {$table}" );

		WP_CLI::success( 'The options have been successfully removed.' );
	}

	/**
	 * Run database updates.
	 *
	 * NOTE: This command removes the filters index and does not rebuild it.
	 *
	 * @subcommand update
	 */
	public function update(): void {
		do_action( 'fibofilters/install/install_without_reindexing' );

		WP_CLI::success( 'Database updates run successfully.' );
	}
}
