<?php
/**
 * Backup & Restore platform hooks that must run before the module kernel boots.
 *
 * Loaded from {@see \WP_PowerSuite\Core\BootServiceProvider::loadBackupEarlyBootstrap()} on
 * plugins_loaded priority 1 when the module is enabled so long AJAX ticks stay stable on hosts
 * with zlib output compression enabled.
 *
 * @package BackupRestore
 * @since 1.10.2
 */

namespace BackupRestore;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class EarlyBootstrap {

	/** @var list<string> */
	private const LONG_AJAX_ACTIONS = [
		'wpps_br_restore_tick',
		'wpps_br_restore_step',
		'wpps_br_backup_step',
		'wpps_br_bundle_prepare',
	];

	/** @var list<string> */
	private const BINARY_DOWNLOAD_ACTIONS = [
		'wpps_br_download',
		'wpps_br_download_bundle_ready',
	];

	/**
	 * Run zlib/compression guards for long backup/restore AJAX actions.
	 *
	 * Called immediately when this file is required (plugins_loaded priority 1).
	 */
	public static function boot(): void {
		self::disableZlibForLongBackupRestoreAjax();
		self::disableZlibForBinaryDownloads();
	}

	public static function disableZlibForLongBackupRestoreAjax(): void {
		if ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) {
			return;
		}

		$action = isset( $_REQUEST['action'] ) ? sanitize_key( wp_unslash( $_REQUEST['action'] ) ) : '';
		if ( ! in_array( $action, self::LONG_AJAX_ACTIONS, true ) ) {
			return;
		}

		self::applyZlibGuards();
	}

	public static function disableZlibForBinaryDownloads(): void {
		$action = isset( $_REQUEST['action'] ) ? sanitize_key( wp_unslash( $_REQUEST['action'] ) ) : '';
		if ( ! in_array( $action, self::BINARY_DOWNLOAD_ACTIONS, true ) ) {
			return;
		}

		self::applyZlibGuards();
	}

	private static function applyZlibGuards(): void {
		if ( function_exists( 'ini_set' ) ) {
			// phpcs:ignore WordPress.PHP.IniSet.Risking -- Keeps admin-ajax JSON and binary streams intact on compressed hosts.
			@ini_set( 'zlib.output_compression', '0' );
		}
		if ( function_exists( 'apache_setenv' ) ) {
			// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
			@apache_setenv( 'no-gzip', '1' );
		}
	}
}

EarlyBootstrap::boot();
