<?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' );
}

class Lcm_Import_Controller {

	public static function import( $params = array() ) {
		global $lcm_params;

		// Set params
		if ( empty( $params ) ) {
			$params = stripslashes_deep( array_merge( $_GET, $_POST ) );
		}

		// Set priority
		if ( ! isset( $params['priority'] ) ) {
			$params['priority'] = 10;
		}

        
		$lcm_params = $params;

		// Set secret key
		$secret_key = null;
		if ( isset( $params['secret_key'] ) ) {
			$secret_key = trim( $params['secret_key'] );
		}

		lcm_setup_environment();
		lcm_setup_errors();

		// try {
		// 	// Ensure that unauthorized people cannot access import action
		// 	lcm_verify_secret_key( $secret_key );
		// } catch ( Lcm_Not_Valid_Secret_Key_Exception $e ) {
		// 	exit;
		// }

        if(defined('WP_CLI')){
            WP_CLI::log( 'Import in progress...' );
            WP_CLI::log( json_encode( $params ) );
        }
		// Loop over filters
		if ( ( $filters = lcm_get_filters( 'lcm_import' ) ) ) {
			while ( $hooks = current( $filters ) ) {
				if ( intval( $params['priority'] ) === key( $filters ) ) {
					foreach ( $hooks as $hook ) {
						try {

							// Run function hook
							$params = call_user_func_array( $hook['function'], array( $params ) );

						} catch ( Lcm_Upload_Exception $e ) {
							do_action( 'lcm_status_upload_error', $params, $e );

							if ( defined( 'WP_CLI' ) ) {
								/* translators: 1: Error code, 2: Error message. */
								WP_CLI::error( sprintf( __( 'Import failed. Code: %1$s. %2$s', 'lc-migrator' ), $e->getCode(), $e->getMessage() ) );
							}

							status_header( $e->getCode() );
							lcm_json_response( array( 'errors' => array( array( 'code' => $e->getCode(), 'message' => $e->getMessage() ) ) ) );
							exit;
						} catch ( Lcm_Database_Exception $e ) {
							do_action( 'lcm_status_import_error', $params, $e );

							if ( defined( 'WP_CLI' ) ) {
								/* translators: 1: Error code, 2: Error message. */
								WP_CLI::error( sprintf( __( 'Import failed (database error). Code: %1$s. %2$s', 'lc-migrator' ), $e->getCode(), $e->getMessage() ) );
							}

							status_header( $e->getCode() );
							lcm_json_response( array( 'errors' => array( array( 'code' => $e->getCode(), 'message' => $e->getMessage() ) ) ) );
							exit;
						} catch ( Exception $e ) {
							do_action( 'lcm_status_import_error', $params, $e );

							if ( defined( 'WP_CLI' ) ) {
								/* translators: Error message. */
								WP_CLI::error( sprintf( __( 'Import failed: %s', 'lc-migrator' ), $e->getMessage() ) );
							}

							Lcm_Status::error( __( 'Import failed', 'lc-migrator' ), $e->getMessage() );
							exit;
						}
					}

					// Set completed
					$completed = true;
					if ( isset( $params['completed'] ) ) {
						$completed = (bool) $params['completed'];
					}

					// Do request
					if ( $completed === false || ( $next = next( $filters ) ) && ( $params['priority'] = key( $filters ) ) ) {
						if ( defined( 'WP_CLI' ) ) {
							if ( ! defined( 'DOING_CRON' ) ) {
								continue;
							}
						}

						if ( isset( $params['lcm_manual_import'] ) || isset( $params['lcm_manual_restore'] ) ) {
							lcm_json_response( $params );
							exit;
						}

						wp_remote_request(
							apply_filters( 'lcm_http_import_url', add_query_arg( array( 'lcm_import' => 1 ), admin_url( 'admin-ajax.php?action=lcm_import' ) ) ),
							array(
								'method'    => apply_filters( 'lcm_http_import_method', 'POST' ),
								'timeout'   => apply_filters( 'lcm_http_import_timeout', 10 ),
								'blocking'  => apply_filters( 'lcm_http_import_blocking', false ),
								'sslverify' => apply_filters( 'lcm_http_import_sslverify', false ),
								'headers'   => apply_filters( 'lcm_http_import_headers', array() ),
								'body'      => apply_filters( 'lcm_http_import_body', $params ),
							)
						);
						exit;
					}
				}

				next( $filters );
			}
		}

		return $params;
	}

	public static function max_chunk_size() {
		return min(
			lcm_parse_size( ini_get( 'post_max_size' ), LC_MIGRATOR_URL_FILE_CHUNK_SIZE ),
			lcm_parse_size( ini_get( 'upload_max_filesize' ), LC_MIGRATOR_URL_FILE_CHUNK_SIZE ),
			lcm_parse_size( LC_MIGRATOR_URL_FILE_CHUNK_SIZE )
		);
	}
}
