<?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_Export_Generate_Cloud_Url {
	const CURL_TIMEOUT = 300;
	const CONNECT_TIMEOUT = 300;

	public static function createSessionUrlFromUploadUrl( $uploadUrl, $contentType = 'application/octet-stream' ) {
        $ch = curl_init($uploadUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, '');
        curl_setopt($ch, CURLOPT_TIMEOUT, self::CURL_TIMEOUT);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::CONNECT_TIMEOUT);
        // Disable SSL verification
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Length: 0',
            'x-goog-resumable: start'
        ));

        $response = curl_exec($ch);
        $curlError = curl_errno($ch);
        $curlErrorMessage = curl_error($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
		$logger = \Lcmigrator\LcMigrator\Logger\Logger::getInstance();
        if ($curlError !== 0) {
            $logger->error("cURL error initializing upload: {$curlError} - {$curlErrorMessage}");
            return null;
        }

        if ($httpCode !== 201) {
            $logger->error("Failed to initialize resumable upload. HTTP Code: {$httpCode}");
            $logger->error("Response: " . $response);
            $logger->error("Response: " . substr($response, 0, 200));
            return null;
        }

        if (!preg_match('/Location: (.+)/i', $response, $matches)) {
            $logger->error("No upload session URL found in response");
            return null;
        }

        return trim($matches[1]);
	}
    public static function execute( $params ) {

		// Set progress
		Lcm_Status::info( __( 'Connecting to Google Cloud Storage...', 'lc-migrator' ), Lcm_Stages::$STAGES['UPLOAD_TO_CLOUD'] );

        // Get archive CRC value
		$archive_crc_value = null;
		if ( isset( $params['archive_crc_value'] ) ) {
			$archive_crc_value = $params['archive_crc_value'];
		}
		// Open achive file
		$archive = new Lcm_Compressor( lcm_archive_path( $params ) );

		// Append EOF block
		$archive->close( true, $archive_crc_value );

        // Generate Cloud URL from GCP
        
        $lcmAdmin = new \Lcmigrator\LcMigrator\Admin\LcMigrator_Admin(LC_MIGRATOR_PLUGIN_NAME, LC_MIGRATOR_VERSION);
        
        $gcsUrl = $lcmAdmin->lc_wp_get("gcp_upload_file", array("site_id" => $params['site_id'], "file_name" => $params['archive']));

        
        $params['upload_url'] = $gcsUrl->uploadUrl[0];

		// Create Session URL From Upload URL
		$sessionUrl = self::createSessionUrlFromUploadUrl($params['upload_url']);

		$params['session_url'] = $sessionUrl;
        // Set Public Url in option 
        $publicUrl = $gcsUrl->publicUrl;
        update_option(LC_MIGRATOR_PUBLIC_URL_RESTORE, $publicUrl);

		// Set progress
		Lcm_Status::info( __( 'Done connecting to Google Cloud Storage.', 'lc-migrator' ), Lcm_Stages::$STAGES['UPLOAD_TO_CLOUD'] );

		return $params;
	}
}