<?php
/**
 * All-in-One WP Migration 
 * Copyright (C) 2014-2018 ServMask Inc.
 *
 * Modified Copyright (C) 2025 Lead Connector
 * 
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

if ( ! defined( 'ABSPATH' ) ) {
	die( 'Well Sir You Cannot Jump Here...haha' );
}

abstract class Lcm_CLI_Base extends WP_CLI_Command {

	public function __construct( $params = array() ) {
		if ( ! defined( 'LC_MIGRATOR_PLUGIN_NAME' ) ) {
			WP_CLI::error_multi_line(
				array(
					__( 'LCM requires LCM plugin to be activated. ', LC_MIGRATOR_PLUGIN_NAME )					
				)
			);
			exit;
		}


		if ( ! is_dir( LC_MIGRATOR_STORAGE_PATH ) ) {
			if ( ! mkdir( LC_MIGRATOR_STORAGE_PATH ) ) {
				WP_CLI::error_multi_line(
					array(
						sprintf( __( 'Lead Connector Migrator is not able to create <strong>%s</strong> folder.', LC_MIGRATOR_PLUGIN_NAME ), LC_MIGRATOR_STORAGE_PATH ),
						__( 'You will need to create this folder and grant it read/write/execute permissions (0777) for the Lead Connector Migrator plugin to function properly.', LC_MIGRATOR_PLUGIN_NAME ),
					)
				);
				exit;
			}
		}

		    if ( ! is_dir( LC_MIGRATOR_BACKUPS_PATH ) ) {
			if ( ! mkdir( LC_MIGRATOR_BACKUPS_PATH ) ) {
				WP_CLI::error_multi_line(
					array(
						sprintf( __( 'Lead Connector Migrator is not able to create <strong>%s</strong> folder.', LC_MIGRATOR_PLUGIN_NAME ), LC_MIGRATOR_BACKUPS_PATH ),
						__( 'You will need to create this folder and grant it read/write/execute permissions (0777) for the Lead Connector Migrator plugin to function properly.', LC_MIGRATOR_PLUGIN_NAME ),
					)
				);
				exit;
			}
		}

		foreach ( $params as $key => $value ) {
			$_GET[ $key ] = $_POST[ $key ] = $value;
		}

		add_filter( 'lcm_completed_timeout', '__return_zero' );
	}

	protected function build_export_params( $args = array(), $assoc_args = array() ) {
		$params = array(
			'cli_args'   => $assoc_args,
			'secret_key' => get_option( LC_MIGRATOR_SECRET_KEY_NAME, false ),
		);

		if ( isset( $assoc_args['password'] ) ) {
			if ( function_exists( 'lcm_can_encrypt' ) && lcm_can_encrypt() ) {
				if ( $assoc_args['password'] === true || empty( $assoc_args['password'] ) ) {
					$assoc_args['password'] = readline( 'Please enter a password to protect this backup: ' );
				}

				if ( empty( $assoc_args['password'] ) ) {
					WP_CLI::error( __( 'Encryption password must not be empty.', LC_MIGRATOR_PLUGIN_NAME ) );
					exit;
				}

				$params['options']['encrypt_backups']  = true;
				$params['options']['encrypt_password'] = $assoc_args['password'];
			} else {
				WP_CLI::error( __( 'Your system doesn\'t support encryption.', LC_MIGRATOR_PLUGIN_NAME ) );
				exit;
			}
		}

		if ( isset( $assoc_args['exclude-spam-comments'] ) ) {
			$params['options']['no_spam_comments'] = true;
		}

		if ( isset( $assoc_args['exclude-post-revisions'] ) ) {
			$params['options']['no_post_revisions'] = true;
		}

		if ( isset( $assoc_args['exclude-media'] ) ) {
			$params['options']['no_media'] = true;
		}

		if ( isset( $assoc_args['exclude-themes'] ) ) {
			$params['options']['no_themes'] = true;
		}

		if ( isset( $assoc_args['exclude-inactive-themes'] ) ) {
			$params['options']['no_inactive_themes'] = true;
		}

		if ( isset( $assoc_args['exclude-muplugins'] ) ) {
			$params['options']['no_muplugins'] = true;
		}

		if ( isset( $assoc_args['exclude-plugins'] ) ) {
			$params['options']['no_plugins'] = true;
		}

		if ( isset( $assoc_args['exclude-inactive-plugins'] ) ) {
			$params['options']['no_inactive_plugins'] = true;
		}

		if ( isset( $assoc_args['exclude-cache'] ) ) {
			$params['options']['no_cache'] = true;
		}

		if ( isset( $assoc_args['exclude-database'] ) ) {
			$params['options']['no_database'] = true;
		} else {

			$excluded_tables = array();
			$included_tables = array();

			// Exclude some of the tables
			if ( isset( $assoc_args['exclude-tables'] ) ) {
				$mysql = Lcm_Database_Utility::create_client();

				// Include table prefixes
				if ( lcm_table_prefix() ) {
					$mysql->add_table_prefix_filter( lcm_table_prefix() );

					// Include table prefixes (Webba Booking and CiviCRM)
					foreach ( array( 'wbk_', 'civicrm_' ) as $table_name ) {
						$mysql->add_table_prefix_filter( $table_name );
					}
				}

				$all_tables = $mysql->get_tables();

				// Prompt for tables to exclude
				if ( $assoc_args['exclude-tables'] === true || empty( $assoc_args['exclude-tables'] ) ) {
					$tables = new cli\Table;

					$tables->setHeaders(
						array(
							'name' => sprintf( 'Tables to exclude (%s)', DB_NAME ),
						)
					);

					foreach ( $all_tables as $table_name ) {
						$tables->addRow(
							array(
								'name' => $table_name,
							)
						);
					}

					$tables->display();
					while ( $table = trim( readline( 'Enter table name to exclude from backup (q=quit, empty=continue): ' ) ) ) {
						switch ( $table ) {
							case 'q':
								exit;

							default:
								if ( ! in_array( $table, $all_tables ) ) {
									WP_CLI::warning( __( 'Unknown table: ', LC_MIGRATOR_PLUGIN_NAME ) . $table );
									break;
								}
								$excluded_tables[] = $table;
						}
					}
				} else {
					$excluded_tables = array_intersect( $all_tables, array_filter( explode( ',', $assoc_args['exclude-tables'] ), 'trim' ) );
				}

				if ( ! empty( $excluded_tables ) ) {
					$params['options']['exclude_db_tables'] = true;
					$params['excluded_db_tables']           = implode( ',', $excluded_tables );
				}
			}

			// Include additional tables
			if ( isset( $assoc_args['include-tables'] ) ) {
				$mysql = Lcm_Database_Utility::create_client();

				// Exclude table prefixes
				if ( lcm_table_prefix() ) {
					$mysql->add_table_prefix_filter( '', sprintf( '(%s|%s|%s)', lcm_table_prefix(), 'wbk_', 'civicrm_' ) );
				} else {
					$mysql->add_table_prefix_filter( '', sprintf( '(%s|%s)', 'wbk_', 'civicrm_' ) );
				}

				$all_tables = $mysql->get_tables();

				// Prompt for tables to include
				if ( $assoc_args['include-tables'] === true || empty( $assoc_args['include-tables'] ) ) {
					$tables = new cli\Table;

					$tables->setHeaders(
						array(
							'name' => sprintf( 'Tables to include (%s)', DB_NAME ),
						)
					);

					foreach ( $all_tables as $table_name ) {
						$tables->addRow(
							array(
								'name' => $table_name,
							)
						);
					}

					$tables->display();
					while ( $table = trim( readline( 'Enter table name to include in backup (q=quit, empty=continue): ' ) ) ) {
						switch ( $table ) {
							case 'q':
								exit;

							default:
								if ( ! in_array( $table, $all_tables ) ) {
									WP_CLI::warning( __( 'Unknown table: ', LC_MIGRATOR_PLUGIN_NAME ) . $table );
									break;
								}
								$included_tables[] = $table;
						}
					}
				} else {
					$included_tables = array_intersect( $all_tables, array_filter( explode( ',', $assoc_args['include-tables'] ), 'trim' ) );
				}

				if ( ! empty( $included_tables ) ) {
					$params['options']['include_db_tables'] = true;
					$params['included_db_tables']           = implode( ',', $included_tables );
				}
			}
		}

		if ( isset( $assoc_args['exclude-email-replace'] ) ) {
			$params['options']['no_email_replace'] = true;
		}

		if ( isset( $assoc_args['replace'] ) ) {
			for ( $i = 0; $i < count( $args ); $i += 2 ) {
				if ( isset( $args[ $i ] ) && isset( $args[ $i + 1 ] ) ) {
					$params['options']['replace']['old_value'][] = $args[ $i ];
					$params['options']['replace']['new_value'][] = $args[ $i + 1 ];
				}
			}
		}

		if ( is_multisite() ) {
			if ( isset( $assoc_args['sites'] ) ) {
				$sites = array();
				if ( ! is_bool( $assoc_args['sites'] ) ) {
					$sites = array_filter( explode( ',', $assoc_args['sites'] ), 'trim' );
				}

				if ( empty( $sites ) ) {
					while ( ( $site_id = readline( 'Enter site ID (q=quit, l=list sites): ' ) ) ) {
						switch ( $site_id ) {
							case 'q':
								exit;

							case 'l':
								WP_CLI::runcommand( 'site list --fields=blog_id,url' );
								break;

							default:
								if ( ! get_blog_details( $site_id ) ) {
									WP_CLI::error_multi_line(
										array(
											__( 'A site with this ID does not exist.', LC_MIGRATOR_PLUGIN_NAME ),
											__( 'To list the sites type `l`.', LC_MIGRATOR_PLUGIN_NAME ),
										)
									);
									break;
								}

								$params['options']['sites'][] = $site_id;
						}
					}
				} else {
					$params['options']['sites'] = $sites;
				}
			}
		}

		return $params;
	}

	protected function run_backup( $params ) {
		// WP_CLI::do_hook( 'lcm_cli_notifications' );
		// WP_CLI::do_hook( 'lcm_cli_commands' );
		// WP_CLI::do_hook( 'lcm_cli_incrementals' );

		// WP_CLI::log( __( 'Backup in progress...', LC_MIGRATOR_PLUGIN_NAME ) );

		// try {
		// 	$params = Lcm_Export_Controller::export( $params );
		// } catch ( Exception $e ) {
		// 	WP_CLI::error( __( sprintf( 'Unable to backup: %s', $e->getMessage() ), LC_MIGRATOR_PLUGIN_NAME ) );
		// 	exit;
		// }

		// WP_CLI::success( __( 'Backup completed.', LC_MIGRATOR_PLUGIN_NAME ) );
		// WP_CLI::log( sprintf( __( 'Backup file: %s', LC_MIGRATOR_PLUGIN_NAME ), lcm_archive_name( $params ) ) );

		// return $params;
	}

	protected function run_restore( $params ) {
		WP_CLI::do_hook( 'lcm_cli_notifications' );
		WP_CLI::do_hook( 'lcm_cli_commands' );
		WP_CLI::do_hook( 'lcm_cli_incrementals' );

		WP_CLI::log( __( 'Restore in progress...', LC_MIGRATOR_PLUGIN_NAME ) );

		try {
			$params = Lcm_Import_Controller::import( $params );
		} catch ( Exception $e ) {
			WP_CLI::error( __( sprintf( 'Unable to import: %s', $e->getMessage() ), LC_MIGRATOR_PLUGIN_NAME ) );
			exit;
		}

		WP_CLI::success( __( 'Restore completed.', LC_MIGRATOR_PLUGIN_NAME ) );

		return $params;
	}
}
