<?php
/**
 * Embed Template for Changeloger Pro
 * Lightweight template for iframe embedding - uses same rendering as main frontend
 *
 * @package Changeloger_Pro
 */

// Security check.
if (!defined('ABSPATH')) {
	exit;
}

// Allow iframe embedding.
header('X-Frame-Options: ALLOWALL');
header('Content-Security-Policy: frame-ancestors *');

// Get embed parameters.
$product_id = isset($_GET['product']) ? absint($_GET['product']) : 0;
$embed_type = isset($_GET['type']) ? sanitize_key($_GET['type']) : 'releases';
$theme = isset($_GET['theme']) ? sanitize_key($_GET['theme']) : 'light';

// Validate embed type.
$valid_types = ['releases', 'feedback', 'roadmap'];
if (!in_array($embed_type, $valid_types, true)) {
	$embed_type = 'releases';
}

// Get product info.
$product = get_term($product_id, 'cha_product');
$product_name = $product && !is_wp_error($product) ? $product->name : '';

// Get settings for watermark.
$settings = get_option('changeloger_settings', []);
$show_watermark = !isset($settings['show_embed_watermark']) || !empty($settings['show_embed_watermark']);
$brand_color = $settings['brand_color'] ?? '#4f46e5';

// Get free plugin URL for assets.
$free_plugin_url = defined('CHANGELOGER_URL') ? CHANGELOGER_URL : plugin_dir_url(dirname(__FILE__, 2)) . 'changeloger/';

// Enqueue required styles and scripts from free plugin.
wp_enqueue_style(
	'cha-release-hub-css',
	$free_plugin_url . 'assets/css/release-hub.css',
	[],
	'1.0.0'
);
wp_enqueue_style(
	'cha-frontend-css',
	$free_plugin_url . 'assets/css/frontend-changelog.css',
	[],
	'1.0.0'
);
wp_enqueue_script(
	'cha-release-hub-js',
	$free_plugin_url . 'assets/js/release-hub.js',
	[],
	'1.0.0',
	true
);

// Enqueue frontend changelog JS for excerpt expand ("Continue Reading")
// and change-section accordion toggles.
wp_enqueue_script(
	'cha-frontend-js',
	$free_plugin_url . 'assets/js/frontend-changelog.js',
	[],
	'1.0.0',
	true
);

// Enqueue feedback/roadmap assets from Pro plugin.
if ('feedback' === $embed_type) {
	Changeloger_Frontend::enqueue_feedback_assets($settings, $product_id);
} elseif ('roadmap' === $embed_type && class_exists('Changeloger_Pro_Frontend')) {
	Changeloger_Pro_Frontend::enqueue_embed_assets($embed_type, $product_id);
}

/**
 * Remove all external scripts/styles and other injections.
 * This ensures the embed page is clean and only contains Changeloger content.
 */

// Remove all actions from wp_head except essential ones.
remove_all_actions('wp_head');

// Re-add only essential wp_head actions.
add_action('wp_head', 'wp_enqueue_scripts', 1);
add_action('wp_head', 'wp_print_styles', 8);
add_action('wp_head', 'wp_print_head_scripts', 9);

// Remove all actions from wp_footer except essential ones.
remove_all_actions('wp_footer');

// Re-add only essential wp_footer actions.
add_action('wp_footer', 'wp_print_footer_scripts', 20);

// Re-add subscribe modal so the modal HTML + inline chaSubscribeData script render.
if ( class_exists( 'Changeloger_Pro_Frontend' ) ) {
	add_action( 'wp_footer', [ 'Changeloger_Pro_Frontend', 'render_subscribe_modal' ] );
}

// Remove all actions from wp_print_styles that might add unwanted styles.
remove_all_actions('wp_print_styles');
add_action('wp_print_styles', 'print_late_styles', 1);

// Dequeue all styles except our own.
add_action(
	'wp_print_styles',
	function () {
		global $wp_styles;
		if ( ! isset( $wp_styles ) || ! $wp_styles instanceof WP_Styles ) {
			return;
		}

		$allowed_handles = [
			'cha-release-hub-css',
			'cha-frontend-css',
			'cha-common-css',
			'cha-feedback-frontend',
			'cha-feedback-frontend-css',
			'cha-roadmap-frontend-css',
			'changeloger-pro-interactions',
			'changeloger-pro-subscribe',
		];

		foreach ( $wp_styles->queue as $handle ) {
			if ( ! in_array( $handle, $allowed_handles, true ) && strpos( $handle, 'cha-' ) !== 0 ) {
				wp_dequeue_style( $handle );
			}
		}
	},
	100
);

// Dequeue all scripts except our own.
add_action(
	'wp_print_scripts',
	function () {
		global $wp_scripts;
		if ( ! isset( $wp_scripts ) || ! $wp_scripts instanceof WP_Scripts ) {
			return;
		}

		$allowed_handles = [
			'cha-release-hub-js',
			'cha-frontend-js',
			'cha-feedback-frontend',
			'cha-roadmap-frontend-js',
			'changeloger-pro-interactions',
			'changeloger-pro-release-frontend',
			'changeloger-pro-subscribe',
			'wp-api-fetch',
			'wp-url',
			'wp-hooks',
			'wp-i18n',
			'wp-polyfill',
			'react',
			'react-dom',
		];

		foreach ( $wp_scripts->queue as $handle ) {
			if ( ! in_array( $handle, $allowed_handles, true ) && strpos( $handle, 'cha-' ) !== 0 ) {
				wp_dequeue_script( $handle );
			}
		}
	},
	100
);

// Remove admin bar.
add_filter('show_admin_bar', '__return_false');

// Remove emoji scripts.
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');

// Remove other WordPress default head items.
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wp_shortlink_wp_head');
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10);
remove_action('wp_head', 'feed_links', 2);
remove_action('wp_head', 'feed_links_extra', 3);
remove_action('wp_head', 'rest_output_link_wp_head', 10);
remove_action('wp_head', 'wp_oembed_add_discovery_links', 10);
remove_action('wp_head', 'wp_resource_hints', 2);

?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>

<head>
	<meta charset="<?php bloginfo('charset'); ?>">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>
		<?php echo esc_html($product_name ? $product_name . ' - ' . ucfirst($embed_type) : ucfirst($embed_type)); ?>
	</title>
	<style>
		/* Minimal embed container styles */
		* {
			box-sizing: border-box;
		}

		body {
			font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
			margin: 0;
			padding: 20px;
			background:
				<?php echo 'dark' === $theme ? '#1a1a2e' : '#ffffff'; ?>
			;
			color:
				<?php echo 'dark' === $theme ? '#e0e0e0' : '#333333'; ?>
			;
			--changeloger_brand_color: <?php echo esc_attr($brand_color); ?>;
		}

		.cha-embed-container {
			padding-top: 40px;
		}
		.cha-embed-header {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 15px 24px;
			padding-right:35px;
			border-bottom: 1px solid
				<?php echo 'dark' === $theme ? '#333' : '#e5e5e5'; ?>
			;
			background: #fff;
			z-index: 999;
		}

		.cha-embed-header h2 {
			font-size: 18px;
			font-weight: 600;
			margin: 0;
		}

		.cha-embed-branding {
			font-size: 11px;
			color:
				<?php echo 'dark' === $theme ? '#888' : '#999'; ?>
			;
		}

		.cha-embed-branding a {
			color: inherit;
			text-decoration: none;
		}

		.cha-embed-branding a:hover {
			text-decoration: underline;
			color: var(--changeloger_brand_color);
		}

		.cha-embed-empty {
			text-align: center;
			padding: 40px 20px;
			color:
				<?php echo 'dark' === $theme ? '#888' : '#666'; ?>
			;
		}
	</style>
	<?php wp_head(); ?>
</head>

<body class="cha-embed-body cha-embed-theme-<?php echo esc_attr($theme); ?>">
	<div class="cha-embed-container">
		<?php if ($product_id): ?>

			<?php if ($show_watermark): ?>
				<div class="cha-embed-header">
					<h2><?php echo esc_html($product_name); ?></h2>
					<div class="cha-embed-branding">
						<?php esc_html_e('Powered by', 'changeloger'); ?>
						<a href="https://spider-themes.net/changeloger" target="_blank"
							rel="noopener">Changeloger</a>
					</div>
				</div>
			<?php endif; ?>


			<?php
			// Render content using SAME methods as regular frontend.
			switch ($embed_type) {
				case 'releases':
					// Use the exact same render method as release hub.
					if (class_exists('Changeloger_Frontend')) {
						Changeloger_Frontend::render_changelog(['product_id' => $product_id]);
					}
					break;

				case 'feedback':
					// Render the same React app container as release hub.
					?>
					<div id="cha-feedback-app" data-product-id="<?php echo esc_attr($product_id); ?>"></div>
					<?php
					break;

				case 'roadmap':
					// Render the same React app container as release hub.
					?>
					<div id="cha-roadmap-root" data-product="<?php echo esc_attr($product_id); ?>"></div>
					<?php
					break;
			}
			?>
		<?php else: ?>
			<div class="cha-embed-empty">
				<p><?php esc_html_e('No product specified.', 'changeloger'); ?></p>
			</div>
		<?php endif; ?>
	</div>
	<?php wp_footer(); ?>
</body>

</html>
