<?php
/**
 * Admin iframe preview endpoint (Lite).
 *
 * @package Vareon_Calculator_Suite_Lite
 */

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

/**
 * Verify current user can access preview frame.
 *
 * @param string $context Preview context.
 * @return bool
 */
function vareoncalc_lite_preview_frame_can_access( $context = 'settings' ) {
	if ( 'editor' === $context ) {
		return current_user_can( 'edit_posts' ) || current_user_can( 'edit_pages' );
	}

	return current_user_can( 'manage_options' );
}

/**
 * Build loader configuration payload for preview frame.
 *
 * @return array<string,mixed>
 */
function vareoncalc_lite_preview_frame_get_cfg() {
	$options    = get_option( 'vareoncalc_lite_options', vareoncalc_default_options() );
	$dev_nonce  = function_exists( 'vareoncalc_get_dev_nonce' ) ? vareoncalc_get_dev_nonce() : '';
	$plugin_url = set_url_scheme( VAREONCALC_URL, is_ssl() ? 'https' : 'http' );
	$theme_id   = isset( $options['theme_preset'] ) ? sanitize_key( (string) $options['theme_preset'] ) : 'light';
	if ( ! in_array( $theme_id, array( 'light', 'dark', 'modern' ), true ) ) {
		$theme_id = 'light';
	}

	return array(
		'defaultTheme'      => $theme_id,
		'branding'          => ! empty( $options['branding'] ),
		'proEnabled'        => vareoncalc_is_pro(),
		'version'           => VAREONCALC_VER,
		'assetVersion'      => function_exists( 'vareoncalc_get_asset_version' ) ? vareoncalc_get_asset_version() : VAREONCALC_VER,
		'useMinifiedAssets' => function_exists( 'vareoncalc_should_use_minified_assets' ) ? vareoncalc_should_use_minified_assets() : ! ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ),
		'edition'           => vareoncalc_get_version(),
		'pluginUrl'         => $plugin_url,
		'devNonce'          => $dev_nonce,
		'layout'            => $options['calculator_layout'] ?? 'compact',
		'formatting'        => array(
			'currencyCode'      => $options['currency_code'] ?? 'USD',
			'currencySymbol'    => $options['currency_symbol'] ?? '$',
			'currencyPosition'  => $options['currency_position'] ?? 'before',
			'currencySpacing'   => $options['currency_spacing'] ?? 'none',
			'currencyDecimals'  => (int) ( $options['currency_decimals'] ?? 2 ),
			'numberDecimals'    => (int) ( $options['number_decimals'] ?? 2 ),
			'percentDecimals'   => (int) ( $options['percent_decimals'] ?? 1 ),
			'thousandSeparator' => $options['thousand_separator'] ?? 'comma',
			'decimalSeparator'  => $options['decimal_separator'] ?? 'dot',
		),
		'measurement'       => array( 'system' => $options['measurement_system'] ?? 'mixed' ),
		'accessibility'     => array(),
		'debug'             => (bool) ( defined( 'VAREON_DEBUG' ) && VAREON_DEBUG ),
	);
}

/**
 * Render sandboxed iframe preview page.
 *
 * @param string $runtime_relative_path Runtime script path relative to plugin URL.
 * @return void
 */
function vareoncalc_lite_preview_frame_render_page( $runtime_relative_path = 'assets/js/preview-frame-runtime.js' ) {
	$nonce = isset( $_GET['nonce'] ) ? sanitize_text_field( wp_unslash( $_GET['nonce'] ) ) : '';
	if ( ! wp_verify_nonce( $nonce, 'vareoncalc_preview_frame' ) ) {
		wp_die(
			esc_html__( 'Invalid preview nonce.', 'vareon-calculator-suite-lite' ),
			esc_html__( 'Unauthorized', 'vareon-calculator-suite-lite' ),
			array( 'response' => 403 )
		);
	}

	$context = isset( $_GET['context'] ) ? sanitize_key( wp_unslash( $_GET['context'] ) ) : 'settings';
	if ( ! in_array( $context, array( 'settings', 'editor' ), true ) ) {
		$context = 'settings';
	}

	if ( ! vareoncalc_lite_preview_frame_can_access( $context ) ) {
		wp_die(
			esc_html__( 'You are not allowed to view this preview.', 'vareon-calculator-suite-lite' ),
			esc_html__( 'Unauthorized', 'vareon-calculator-suite-lite' ),
			array( 'response' => 403 )
		);
	}

	nocache_headers();
	if ( ! headers_sent() ) {
		header( 'X-Frame-Options: SAMEORIGIN' );
		header( 'Content-Type: text/html; charset=' . get_bloginfo( 'charset' ) );
		header( 'Referrer-Policy: same-origin' );
	}

	$cfg = vareoncalc_lite_preview_frame_get_cfg();
	if ( 'settings' === $context ) {
		$cfg['design'] = array(
			'preview_surface_width' => 645,
		);
	}
	$asset_version     = function_exists( 'vareoncalc_get_asset_version' ) ? vareoncalc_get_asset_version() : VAREONCALC_VER;
	$plugin_url        = set_url_scheme( VAREONCALC_URL, is_ssl() ? 'https' : 'http' );
	$style_handle      = 'vareoncalc-lite-preview-frame-style';
	$calc_style_handle = 'vareoncalc-lite-preview-frame-calculators';
	$loader_handle     = 'vareoncalc-lite-preview-frame-loader';
	$runtime_handle    = 'vareoncalc-lite-preview-frame-runtime';
	$body_classes      = array( 'vareoncalc-preview-frame-body', 'vareoncalc-preview-frame-body--' . $context );
	$mount_style       = '';
	$runtime_rel       = ltrim( (string) $runtime_relative_path, '/' );
	$styles_asset      = function_exists( 'vareoncalc_get_resolved_asset' )
		? vareoncalc_get_resolved_asset( 'assets/styles.css' )
		: array(
			'url'     => $plugin_url . 'assets/styles.css',
			'version' => VAREONCALC_VER,
		);
	$calc_styles_asset = function_exists( 'vareoncalc_get_resolved_asset' )
		? vareoncalc_get_resolved_asset( 'assets/calculators.css' )
		: array(
			'url'     => $plugin_url . 'assets/calculators.css',
			'version' => VAREONCALC_VER,
		);
	$loader_asset      = function_exists( 'vareoncalc_get_resolved_asset' )
		? vareoncalc_get_resolved_asset( 'js/vareoncalc-loader.js' )
		: array(
			'url'     => $plugin_url . 'js/vareoncalc-loader.js',
			'version' => $asset_version,
		);
	$runtime_asset     = function_exists( 'vareoncalc_get_resolved_asset' )
		? vareoncalc_get_resolved_asset( $runtime_rel )
		: array(
			'url'     => $plugin_url . $runtime_rel,
			'version' => $asset_version,
		);
	$theme_css         = function_exists( 'vareoncalc_get_theme_css' ) ? vareoncalc_get_theme_css() : '';
	$inline_cfg_js     = 'window.VAREONCALC_CFG = ' . wp_json_encode( $cfg ) . ';';
	$inline_cfg_js    .= 'window.vareoncalc_CFG = window.VAREONCALC_CFG;';
	$inline_cfg_js    .= 'window.VAREON_DEBUG = !!(window.VAREONCALC_CFG && window.VAREONCALC_CFG.debug);';

	wp_register_style( $style_handle, $styles_asset['url'], array(), $styles_asset['version'] );
	wp_enqueue_style( $style_handle );
	wp_register_style( $calc_style_handle, $calc_styles_asset['url'], array( $style_handle ), $calc_styles_asset['version'] );
	wp_enqueue_style( $calc_style_handle );
	if ( '' !== trim( (string) $theme_css ) ) {
		wp_add_inline_style( $style_handle, wp_strip_all_tags( (string) $theme_css ) );
	}

	wp_register_script( $loader_handle, $loader_asset['url'], array( 'wp-i18n' ), $loader_asset['version'], true );
	wp_script_add_data( $loader_handle, 'type', 'module' );
	wp_set_script_translations( $loader_handle, 'vareon-calculator-suite-lite', VAREONCALC_DIR . 'languages' );
	wp_add_inline_script( $loader_handle, $inline_cfg_js, 'before' );
	wp_enqueue_script( $loader_handle );
	if ( function_exists( 'vareoncalc_enqueue_importmap_bridge' ) ) {
		vareoncalc_enqueue_importmap_bridge();
	}

	wp_register_script( $runtime_handle, $runtime_asset['url'], array(), $runtime_asset['version'], true );
	wp_enqueue_script( $runtime_handle );
	$initial_preview_config = array( 'type' => 'loan' );
	$mount_data_config      = '';
	if ( in_array( $context, array( 'settings', 'editor' ), true ) ) {
		if ( 'settings' === $context ) {
			$initial_preview_config['design'] = array( 'preview_surface_width' => 645 );
			$mount_style                      = 'max-width:645px;width:100%;margin:0 auto;';
		}
		$mount_data_config = wp_json_encode( $initial_preview_config );
	}
	?>
<!doctype html>
<html <?php language_attributes(); ?>>
<head>
	<meta charset="<?php bloginfo( 'charset' ); ?>">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<style>
		html, body { margin: 0; padding: 0; overflow: hidden; background: transparent; }
		#vareoncalc-preview-frame-mount { width: 100%; }
		body.vareoncalc-preview-frame-body--settings #vareoncalc-preview-frame-mount > .vareoncalc-card {
			height: auto !important;
			max-height: none !important;
			padding-bottom: 0 !important;
		}
		body.vareoncalc-preview-frame-body--settings #vareoncalc-preview-frame-mount > .vareoncalc-card > .vareoncalc-content {
			padding-bottom: 24px !important;
			box-sizing: border-box !important;
		}
	</style>
	<?php wp_print_styles(); ?>
	<?php wp_print_head_scripts(); ?>
</head>
<body class="<?php echo esc_attr( implode( ' ', $body_classes ) ); ?>">
	<?php if ( '' !== $mount_data_config ) : ?>
		<div id="vareoncalc-preview-frame-mount" class="vareoncalc" data-config="<?php echo esc_attr( $mount_data_config ); ?>"<?php echo '' !== $mount_style ? ' style="' . esc_attr( $mount_style ) . '"' : ''; ?>></div>
	<?php else : ?>
		<div id="vareoncalc-preview-frame-mount" class="vareoncalc"<?php echo '' !== $mount_style ? ' style="' . esc_attr( $mount_style ) . '"' : ''; ?>></div>
	<?php endif; ?>
	<?php
	// The preview frame calls wp_print_footer_scripts() directly — not
	// wp_footer() — so WP's Script Modules hooks never fire and the
	// importmap bridge registered above has no output path.  Always emit
	// the inline importmap so bare specifiers resolve.
	vareoncalc_print_inline_importmap( true );
	?>
	<?php wp_print_footer_scripts(); ?>
</body>
</html>
	<?php
	wp_die();
}

/**
 * Legacy preview frame endpoint (editor compatibility).
 *
 * @return void
 */
function vareoncalc_lite_preview_frame_render() {
	vareoncalc_lite_preview_frame_render_page( 'assets/js/preview-frame-runtime.js' );
}

/**
 * V2 preview frame endpoint (settings split view).
 *
 * @return void
 */
function vareoncalc_lite_preview_frame_render_v2() {
	vareoncalc_lite_preview_frame_render_page( 'assets/js/preview-frame-runtime-v2.js' );
}

add_action( 'wp_ajax_vareoncalc_lite_preview_frame', 'vareoncalc_lite_preview_frame_render' );
add_action( 'wp_ajax_vareoncalc_lite_preview_frame_v2', 'vareoncalc_lite_preview_frame_render_v2' );
