<?php
/**
 * `wp blaminhor domain-changer ...` — Domain Changer commands (read-only).
 *
 * Migrating a domain rewrites every serialised reference across every
 * WordPress table — a destructive operation that's safer kept in the
 * admin UI with its built-in pre-flight backup. The CLI exposes the
 * read-only history + a pointer to `wp search-replace` for automation.
 *
 * @package BlaminhorEssentials
 */

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

if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
	return;
}

class Blaminhor_Essentials_CLI_Domain_Changer extends Blaminhor_Essentials_CLI_Module {

	/**
	 * @var string
	 */
	protected $module_id = 'domain-changer';

	/**
	 * Show the current domain + the last recorded migration.
	 *
	 * ## OPTIONS
	 *
	 * [--format=<format>]
	 * : Render format. Default: table.
	 *
	 * ## EXAMPLES
	 *
	 *     $ wp blaminhor domain-changer info
	 *
	 * @when after_wp_load
	 *
	 * @param array $args       Positional args (unused).
	 * @param array $assoc_args Associative args.
	 */
	public function info( $args, $assoc_args ) {
		$module   = $this->get_module_instance();
		$settings = $module->get_effective_settings();

		$rows = array(
			array( 'key' => 'current_siteurl',     'value' => (string) get_option( 'siteurl' ) ),
			array( 'key' => 'current_home',        'value' => (string) get_option( 'home' ) ),
			array( 'key' => 'last_change_date',    'value' => (string) $settings['last_change_date'] ),
			array( 'key' => 'last_old_domain',     'value' => (string) $settings['last_old_domain'] ),
			array( 'key' => 'last_new_domain',     'value' => (string) $settings['last_new_domain'] ),
			array( 'key' => 'backup_before_change','value' => $settings['backup_before_change'] ? 'true' : 'false' ),
		);
		$this->format_for_output( $rows, $assoc_args, array( 'key', 'value' ) );
	}

	/**
	 * Update Domain Changer settings (toggles, not the migration itself).
	 *
	 * ## OPTIONS
	 *
	 * [--backup-before-change=<bool>]
	 * : Run the Backup module before a migration.
	 *
	 * @when after_wp_load
	 *
	 * @param array $args       Positional args (unused).
	 * @param array $assoc_args Associative args.
	 */
	public function set( $args, $assoc_args ) {
		$this->ensure_capabilities();
		$module  = $this->get_module_instance();
		$current = $module->get_effective_settings();

		$data = array(
			'last_change_date' => (string) $current['last_change_date'],
			'last_old_domain'  => (string) $current['last_old_domain'],
			'last_new_domain'  => (string) $current['last_new_domain'],
		);

		if ( isset( $assoc_args['backup-before-change'] ) ) {
			if ( $this->parse_bool( $assoc_args['backup-before-change'] ) ) {
				$data['backup_before_change'] = '1';
			}
		} elseif ( ! empty( $current['backup_before_change'] ) ) {
			$data['backup_before_change'] = '1';
		}

		$result = $module->apply_settings( $data );
		if ( is_wp_error( $result ) ) {
			WP_CLI::error( $result->get_error_message() );
		}

		blaminhor_essentials_log( 'Domain Changer settings updated via WP-CLI.', 'info', 'cli', array( 'event' => 'domain_changer_set' ) );
		WP_CLI::success( __( 'Domain Changer settings updated.', 'blaminhor-essentials' ) );
	}

	/**
	 * Print a recommended migration recipe (does NOT execute it).
	 *
	 * Migrating a domain across every table — including serialised options
	 * and meta — is safer with the core `wp search-replace` command than
	 * with our own preview/execute UI run from the CLI. This sub-command
	 * prints the commands to run; the user (or their IA) executes them.
	 *
	 * ## OPTIONS
	 *
	 * --old=<old>
	 * : Old domain (no scheme). Example: old-site.com
	 *
	 * --new=<new>
	 * : New domain (no scheme). Example: new-site.com
	 *
	 * @subcommand migration-recipe
	 * @when after_wp_load
	 *
	 * @param array $args       Positional args (unused).
	 * @param array $assoc_args Associative args.
	 */
	public function migration_recipe( $args, $assoc_args ) {
		if ( empty( $assoc_args['old'] ) || empty( $assoc_args['new'] ) ) {
			WP_CLI::error( __( 'Both --old=<domain> and --new=<domain> are required.', 'blaminhor-essentials' ) );
		}
		$old = trim( (string) $assoc_args['old'] );
		$new = trim( (string) $assoc_args['new'] );

		WP_CLI::log( '' );
		WP_CLI::log( __( 'Recommended migration recipe (run each line manually after a fresh backup):', 'blaminhor-essentials' ) );
		WP_CLI::log( '' );
		WP_CLI::log( sprintf( '  wp blaminhor backup info        # confirm backup dir healthy' ) );
		WP_CLI::log( sprintf( '  wp db export pre-migration.sql  # cold DB snapshot' ) );
		WP_CLI::log( sprintf( '  wp search-replace "https://%s" "https://%s" --all-tables --skip-columns=guid --dry-run', $old, $new ) );
		WP_CLI::log( sprintf( '  wp search-replace "https://%s" "https://%s" --all-tables --skip-columns=guid', $old, $new ) );
		WP_CLI::log( sprintf( '  wp search-replace "http://%s"  "https://%s" --all-tables --skip-columns=guid', $old, $new ) );
		WP_CLI::log( sprintf( '  wp option update siteurl "https://%s"', $new ) );
		WP_CLI::log( sprintf( '  wp option update home    "https://%s"', $new ) );
		WP_CLI::log( '  wp cache flush' );
		WP_CLI::log( '  wp blaminhor cache purge        # if Cache module active' );
		WP_CLI::log( '' );
		WP_CLI::log( __( 'For a guided wizard with serialised data preview, open Admin → Blaminhor → Domain Changer.', 'blaminhor-essentials' ) );
	}
}
