<?php
/**
 * WP-CLI commands for CartCue maintenance.
 *
 * @package CartCue
 */

namespace CartCue;

defined( 'ABSPATH' ) || exit;

final class CLI {

	public static function register(): void {
		if ( ! class_exists( 'WP_CLI' ) ) {
			return;
		}

		\WP_CLI::add_command( 'cartcue prune-logs', [ __CLASS__, 'prune_logs' ] );
		\WP_CLI::add_command( 'cartcue run-win-back', [ __CLASS__, 'run_win_back' ] );
		\WP_CLI::add_command( 'cartcue list-plays', [ __CLASS__, 'list_plays' ] );
	}

	/**
	 * Prune workflow logs older than N days.
	 *
	 * ## OPTIONS
	 *
	 * [--days=<days>]
	 * : Days of logs to keep. Default: 90.
	 *
	 * @param array<int, string>    $args
	 * @param array<string, string> $assoc
	 */
	public static function prune_logs( array $args, array $assoc ): void {
		$days = (int) ( $assoc['days'] ?? 90 );
		Plugin::instance()->logger->prune( $days );
		\WP_CLI::success( "Pruned logs older than {$days} days." );
	}

	/**
	 * Run the win-back customer check immediately.
	 *
	 * @param array<int, string>    $args
	 * @param array<string, string> $assoc
	 */
	public static function run_win_back( array $args, array $assoc ): void {
		do_action( 'cartcue_process_win_back' );
		\WP_CLI::success( 'Win-back check completed.' );
	}

	/**
	 * List all plays with status and run count.
	 *
	 * @param array<int, string>    $args
	 * @param array<string, string> $assoc
	 */
	public static function list_plays( array $args, array $assoc ): void {
		global $wpdb;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery
		$rows = $wpdb->get_results(
			$wpdb->prepare(
				'SELECT id, name, trigger_slug, status, run_count FROM %i ORDER BY id ASC',
				DB::workflows()
			),
			ARRAY_A
		) ?: [];

		if ( empty( $rows ) ) {
			\WP_CLI::warning( 'No plays found.' );
			return;
		}

		\WP_CLI\Utils\format_items( 'table', $rows, [ 'id', 'name', 'trigger_slug', 'status', 'run_count' ] );
	}
}
