<?php
/**
 * WP-CLI commands.
 *
 * @package SmartCategories
 */

defined( 'ABSPATH' ) || exit;

/**
 * Manage WooCommerce smart categories from the command line.
 */
class SCWC_CLI {

	/**
	 * List smart-enabled categories with their managed product counts.
	 *
	 * ## EXAMPLES
	 *
	 *     wp scwc list
	 *
	 * @subcommand list
	 */
	public function list_( $args, $assoc_args ) {
		$rows = array();
		foreach ( SCWC_Term_Rules::get_smart_term_ids() as $term_id ) {
			$term  = get_term( $term_id, SCWC_Term_Rules::TAXONOMY );
			$rows[] = array(
				'id'       => $term_id,
				'name'     => $term ? $term->name : '(?)',
				'products' => SCWC_Assigner::managed_count( $term_id ),
			);
		}
		if ( empty( $rows ) ) {
			WP_CLI::log( 'No enabled smart categories.' );
			return;
		}
		WP_CLI\Utils\format_items( 'table', $rows, array( 'id', 'name', 'products' ) );
	}

	/**
	 * Re-evaluate one smart category synchronously.
	 *
	 * ## OPTIONS
	 *
	 * <term_id>
	 * : The product category term ID.
	 *
	 * ## EXAMPLES
	 *
	 *     wp scwc run 42
	 */
	public function run( $args, $assoc_args ) {
		$term_id = isset( $args[0] ) ? (int) $args[0] : 0;
		if ( ! $term_id ) {
			WP_CLI::error( 'Please provide a category ID.' );
		}
		WP_CLI::log( sprintf( 'Re-evaluating category #%d...', $term_id ) );
		$count = SCWC_Scheduler::run_now( $term_id );
		WP_CLI::success( sprintf( '%d products evaluated. Assigned: %d', $count, SCWC_Assigner::managed_count( $term_id ) ) );
	}

	/**
	 * Re-evaluate every smart category synchronously.
	 *
	 * ## EXAMPLES
	 *
	 *     wp scwc run-all
	 *
	 * @subcommand run-all
	 */
	public function run_all( $args, $assoc_args ) {
		$ids = SCWC_Term_Rules::get_smart_term_ids();
		if ( empty( $ids ) ) {
			WP_CLI::warning( 'No enabled smart categories.' );
			return;
		}
		foreach ( $ids as $term_id ) {
			$count = SCWC_Scheduler::run_now( $term_id );
			WP_CLI::log( sprintf( '#%d → %d products evaluated.', $term_id, $count ) );
		}
		WP_CLI::success( 'All smart categories updated.' );
	}

}
