<?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( 'Kangaroos cannot jump here' );
}

class Lcm_Export_Upload_To_Cloud {

	public static function execute( $params, $gcloud = null ) {

		$params['completed'] = false;

		// Validate upload URL
		if ( ! isset( $params['session_url'] ) ) {
			throw new Lcm_Import_Exception( __( 'Google Cloud Storage Upload URL is not specified.', LC_MIGRATOR_PLUGIN_NAME ) );
		}

		// Set archive offset
		if ( ! isset( $params['archive_offset'] ) ) {
			$params['archive_offset'] = 0;
		}

		// Set archive size
		if ( ! isset( $params['archive_size'] ) ) {
			$params['archive_size'] = lcm_archive_bytes( $params );
		}

		// Set file chunk size for upload
		$file_chunk_size = get_option( 'lcm_gcloud_storage_file_chunk_size', LCM_MIGRATOR_GCLOUD_STORAGE_FILE_CHUNK_SIZE );

		// Set file range start
		if ( ! isset( $params['file_range_start'] ) ) {
			$params['file_range_start'] = 0;
		}

		// Set file range end
		if ( ! isset( $params['file_range_end'] ) ) {
			$params['file_range_end'] = min( $file_chunk_size, $params['archive_size'] ) - 1;
		}

		// Set upload retries
		if ( ! isset( $params['upload_retries'] ) ) {
			$params['upload_retries'] = 0;
		}

		// Set upload backoff
		if ( ! isset( $params['upload_backoff'] ) ) {
			$params['upload_backoff'] = 1;
		}

		// Set GCloud Storage client
		if ( is_null( $gcloud ) ) {
			$gcloud = new Lcm_GCloud_Storage_Client(
				$params['session_url']
			);
		}

		// Open the archive file for reading
		$archive = fopen( lcm_archive_path( $params ), 'rb' );
		// Read file chunk data
		if ( ( fseek( $archive, $params['archive_offset'] ) !== -1 )
				&& ( $file_chunk_data = fread( $archive, $file_chunk_size ) ) ) {

			$gcloud->load_upload_url( $params['session_url'] );

			try {

				$params['upload_retries'] += 1;
				$params['upload_backoff'] *= 2;

				// Upload file chunk data
				if ( ( $response = $gcloud->upload_file_chunk( $file_chunk_data, $params['archive_size'], $params['file_range_start'], $params['file_range_end'], $params['session_url'] ) ) ) {
					if ( isset( $response['id'] ) ) {
						$params['file_id'] = $response['id'];
					}
				}

				// Unset upload retries
				unset( $params['upload_retries'] );
				unset( $params['upload_backoff'] );

			} catch ( Lcm_Connect_Exception $e ) {
				sleep( $params['upload_backoff'] );
				if ( $params['upload_retries'] <= 5 ) {
					return $params;
				}

				throw $e;
			}

			// Set archive offset
			$params['archive_offset'] = ftell( $archive );

			// Set file range start
			if ( $params['archive_size'] <= ( $params['file_range_start'] + $file_chunk_size ) ) {
				$params['file_range_start'] = $params['archive_size'] - 1;
			} else {
				$params['file_range_start'] = $params['file_range_start'] + $file_chunk_size;
			}

			// Set file range end
			if ( $params['archive_size'] <= ( $params['file_range_end'] + $file_chunk_size ) ) {
				$params['file_range_end'] = $params['archive_size'] - 1;
			} else {
				$params['file_range_end'] = $params['file_range_end'] + $file_chunk_size;
			}

			// Set archive details
			$name = lcm_archive_name( $params );
			$size = lcm_archive_size( $params );

			// Get progress
			$progress = (int) ( ( $params['archive_offset'] / $params['archive_size'] ) * 100 );

			// Set progress
			if ( defined( 'WP_CLI' ) ) {
				WP_CLI::log(
					sprintf(
						__( 'Uploading %s (%s) [%d%% complete]', LC_MIGRATOR_PLUGIN_NAME ),
						$name,
						$size,
						$progress
					)
				);
			} else {
				Lcm_Status::info(
					sprintf(
						__(
							'Uploading Backup File Of %s - %d%% complete',
							LC_MIGRATOR_PLUGIN_NAME
						),
						// $name,
						$size,
						$progress
					),
					Lcm_Stages::$STAGES['UPLOAD_TO_CLOUD']
				);
			}
		} else {

			// Set last backup date
			update_option( 'lcm_gcloud_storage_timestamp', time() );

			// Unset storage class
			unset( $params['storage_class'] );

			// Unset upload URL
			unset( $params['upload_url'] );

			// Unset archive offset
			unset( $params['archive_offset'] );

			// Unset archive size
			unset( $params['archive_size'] );

			// Unset file range start
			unset( $params['file_range_start'] );

			// Unset file range end
			unset( $params['file_range_end'] );

			// Unset completed
			unset( $params['completed'] );
			// Send Event That Upload Is Completed 
			$event = new Lcm_Events('LC_MIGRATOR_EXPORT_UPLOAD_COMPLETED', [
				'user_id' => get_current_user_id(),
				'string_1' => get_site_url(),
				'string_3' => lcm_archive_name( $params ),
				'string_5' => $params['site_id'] ?? 'Unknown site ID',
				'string_4' => lcm_archive_size( $params ),
			]);
			$event->send();
		}

		// Close the archive file
		fclose( $archive );

		return $params;
	}
}
