<?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_Validate
{

	public static function execute($params)
	{

		// Verify file if size > 2GB and PHP = 32-bit
		if (!lcm_is_filesize_supported(lcm_archive_path($params))) {
			throw new Lcm_Import_Exception(
				wp_kses(
					__(
						'Your server uses 32-bit PHP and cannot process files larger than 2GB. Please switch to 64-bit PHP and try again.',
						'lc-migrator'
					),
					lcm_allowed_html_tags()
				)
			);
		}

		// Verify file name extension
		if (!lcm_is_filename_supported(lcm_archive_path($params))) {
			throw new Lcm_Import_Exception(
				wp_kses(
					__(
						'Invalid file type. Please ensure your file is a <strong>.lc_migrator</strong> backup created with Lead Connector Migrator.',
						'lc-migrator'
					),
					lcm_allowed_html_tags()
				)
			);
		}

		// Set progress
		Lcm_Status::info(__('Unpacking configuration...', 'lc-migrator'));

		// Open the archive file for reading
		$archive = new Lcm_Extractor(lcm_archive_path($params));

		// Validate the archive file consistency
		if (!$archive->is_valid()) {
			throw new Lcm_Import_Exception(
				wp_kses(
					__('The archive file appears to be corrupted. Please try downloading or transferring the file again.', 'lc-migrator'),
					lcm_allowed_html_tags()
				)
			);
		}

		// Unpack package.json and multisite.json files
		$archive->extract_by_files_array(lcm_storage_path($params), array(LC_MIGRATOR_PACKAGE_FILE, LC_MIGRATOR_MULTISITE_NAME));

		// Check package.json file
		if (false === is_file(lcm_package_path($params))) {
			throw new Lcm_Import_Exception(
				wp_kses(
					__(
						'Please ensure your file was created with the Lead Connector Migrator plugin.',
						'lc-migrator'
					),
					lcm_allowed_html_tags()
				)
			);
		}

		// Set archive CRC value
		$params['archive_crc_value'] = $archive->get_archive_crc_value();

		// Set archive CRC size
		$params['archive_crc_size'] = $archive->get_archive_crc_size();

		// Close the archive file
		$archive->close();

		return $params;
	}
}
