<?php
/**
 * File Path: includes/admin/tabs/imp-exp/class-mbs-tab-child-settings-import.php
 *
 * Import / Export Tab — Settings Import Child
 *
 * Handles preview and apply functionality for importing Settings as JSON.
 * Requires active plugin registration (any tier — FREE registered, PRO, or PUB).
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

// phpcs:disable WordPress.Security.NonceVerification -- nonce verified in parent class verify_save() / check_admin_referer() before $_POST access; PHPCS cannot trace cross-method nonce verification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput -- input sanitized at point of use (sanitize_text_field, absint, wp_kses_post, etc.); false positives from PHPCS not tracing sanitization helpers called before this method
class MBS_Tab_Child_Settings_Import {

	use MBS_Ajax_Import_Export_Guard;

	public function handle_ajax_mbs_import_settings_preview(): void {
		$this->verify_import_export_request();

		if ( ! get_option( 'mbs_license_registered', false ) ) {
			wp_send_json_error( array( 'message' => 'Settings import requires an activated plugin registration. Registration is free — visit the License tab to register.' ) );
		}

		$uploaded = $_FILES['file'] ?? null;
		if ( ! $uploaded || $uploaded['error'] !== UPLOAD_ERR_OK ) {
			wp_send_json_error( array( 'message' => 'File upload failed.' ) );
		}

		// S-09: Validate file extension before reading.
		$upload_name = isset( $uploaded['name'] ) ? sanitize_file_name( wp_unslash( $uploaded['name'] ) ) : '';
		if ( 'json' !== strtolower( pathinfo( $upload_name, PATHINFO_EXTENSION ) ) ) {
			wp_send_json_error( array( 'message' => 'Only .json files are accepted for settings import.' ) );
		}

		if ( ! is_uploaded_file( $uploaded['tmp_name'] ) ) {
			wp_send_json_error( array( 'message' => 'Invalid file upload.' ) );
		}

		$json     = file_get_contents( $uploaded['tmp_name'] );
		$imported = json_decode( $json, true );

		if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $imported ) ) {
			wp_send_json_error( array( 'message' => 'Invalid JSON file.' ) );
		}

		$excluded = MBS_Settings_IO_Keys::get_excluded_keys();
		$imported = array_diff_key( $imported, array_flip( $excluded ) );

		$all_options = wp_load_alloptions();
		$current     = array();
		foreach ( $all_options as $key => $value ) {
			if ( 0 === strpos( $key, 'mbs_setting_' ) && ! in_array( $key, $excluded, true ) ) {
				$current[ $key ] = is_serialized( $value ) ? unserialize( $value, array( 'allowed_classes' => false ) ) : $value;
			}
		}

		$diff = array(
			'added'   => array_diff_key( $imported, $current ),
			'changed' => array(),
			'removed' => array_diff_key( $current, $imported ),
		);

		foreach ( $imported as $k => $v ) {
			if ( array_key_exists( $k, $current ) && $v !== $current[ $k ] ) {
				$diff['changed'][ $k ] = array( 'old' => $current[ $k ], 'new' => $v );
			}
		}

		$token = wp_generate_password( 32, false );
		set_transient( 'mbs_settings_import_' . get_current_user_id() . '_' . $token, $imported, 300 );

		wp_send_json_success( array(
			'diff'    => $diff,
			'token'   => $token,
			'message' => 'Settings preview ready – review changes before applying.',
		) );
	}

	public function handle_ajax_mbs_import_settings_apply(): void {
		$this->verify_import_export_request();

		if ( ! get_option( 'mbs_license_registered', false ) ) {
			wp_send_json_error( array( 'message' => 'Settings import requires an activated plugin registration. Registration is free — visit the License tab to register.' ) );
		}

		$token = sanitize_text_field( wp_unslash( $_POST['token'] ?? '' ) );
		if ( empty( $token ) ) {
			wp_send_json_error( array( 'message' => 'Missing confirmation token.' ) );
		}

		$import_data = get_transient( 'mbs_settings_import_' . get_current_user_id() . '_' . $token );
		if ( false === $import_data || ! is_array( $import_data ) ) {
			wp_send_json_error( array( 'message' => 'Confirmation window expired. Please re-upload the settings file.' ) );
		}

		delete_transient( 'mbs_settings_import_' . get_current_user_id() . '_' . $token );

		// S-01: Delegate to the authoritative write path. MBS_Import_Settings_Applier
		// owns all key filtering, sanitization, section-order routing, and cache flush.
		$result = MBS_Import_Settings_Applier::apply( $import_data );

		wp_send_json_success( array(
			'applied' => $result['applied'],
			'skipped' => $result['skipped'],
			'message' => sprintf( '%d settings applied, %d skipped. Page will refresh to show changes.', $result['applied'], $result['skipped'] ),
		) );
	}
}
