<?php
/**
 * Code Snippet Module
 *
 * Manages custom code snippets (HTML, CSS, JavaScript, PHP) with auto-insert
 * in header, body, or footer, or shortcode placement.
 *
 * Hooks (extend from themes/plugins):
 * - `wpps_code_snippet_the_content_priority` (int) — priority for content location injection (default 12, after block rendering).
 * - `wpps_code_snippet_output` (string $code, string $type, \WP_Post $post) — filter stored code before execute/output.
 * - `wpps_code_snippet_php_before_eval` (string $code, ?\WP_Post $post, string $context) — $context: merged_run_everywhere|merged_frontend_only|single (merged strings call this once per snippet before concat).
 * - `wpps_code_snippet_merged_php_code` (string $merged, string $context, array $line_map) — $context matches merge batch; $line_map is snippet_id => [ start, end ] line numbers in merged string.
 * - `wpps_code_snippet_merge_frontend_only_php` (bool) — after the Settings value; filter to force merged (true) or separate (false) Frontend Only PHP.
 * - `wpps_code_snippet_merge_run_everywhere_php` (bool) — after the Settings value; filter to force merged (true) or separate (false) Run Everywhere / Admin Only PHP.
 * - `wpps_code_snippet_use_eval` (bool, string $code) — when true, run snippet PHP via eval() instead of a temp include file (legacy).
 * - `wpps_code_snippet_after_php_eval` (string $output, \WP_Post $post, string $context) — after PHP capture; $context: single|php_file_include.
 * - `wpps_code_snippet_merged_php_output` (string $buffer, \WP_Post[] $posts, string $context) — after merged Frontend Only eval output; $context is `merged_frontend_only`.
 * - `wpps_code_snippet_error_log_max_entries` (int $max) — cap stored log rows (default 50, clamped 1–500).
 * - `wpps_code_snippet_shutdown_fatal_types` (int[] $e_* constants) — which error types trigger shutdown auto-deactivate (default includes E_USER_ERROR).
 * - `wpps_code_snippet_auto_deactivate_admin_notice` (bool, \WP_Post $post, string $message) — show dashboard notice when a snippet is drafted due to PHP error.
 * - `wpps_snippet_loaded` ( \WP_Post $post, string $location ) — after snippet runs.
 * - `wpps_code_snippet_disallowed_php` (string[]) — extra regex fragments to block in PHP.
 * - `wpps_code_snippet_php_auto_deactivate_locations` (string[]) — locations where PHP errors draft the snippet (default includes frontend_conditional_logic).
 * - `wpps_code_snippet_force_runtime_test_with_hooks`, `wpps_code_snippet_runtime_test_fire_admin_notices` — save-time test toggles.
 * - `wpps_code_snippet_php_binary` (string|null $path) — return absolute path to PHP CLI for `php -l` save-time syntax check (Plesk/FPM often has no `php` in web PATH).
 * - `wpps_code_snippet_skip_php_syntax_check` (bool) — if true, skip CLI syntax check on save (hosts with exec disabled or no CLI).
 * - `wpps_code_snippet_private_storage_path` (string) — absolute private dir for PHP include files (outside document root).
 * - Constant `WP_POWERSUITE_SNIPPET_PATH` — same as the filter, preferred when defined in wp-config.php.
 * - PHP file storage fails closed: never writes snippet source under a web-mapped path. If no private
 *   directory is available, PHP/HTML keep running from the database.
 * - Threat scanner is defense-in-depth for obvious dangerous patterns, not a PHP sandbox.
 *
 *
 * @package CodeSnippet
 * @since 1.0.0
 */

namespace CodeSnippet;

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

use WP_PowerSuite\Core\Contracts\DataLocationsInterface;
use WP_PowerSuite\Core\AbstractModule;
use WP_PowerSuite\Core\TemporarySessionGuard;
use WP_PowerSuite\Core\WordPressPaths;

require_once __DIR__ . '/snippet-php-eval.php';
require_once __DIR__ . '/includes/class-premium-php-js-runtime.php';
require_once __DIR__ . '/includes/class-conditional-catalog.php';
require_once __DIR__ . '/includes/class-premium-targeting.php';
require_once __DIR__ . '/class-wpps-revisions.php';
require_once __DIR__ . '/class-wpps-revisions-display.php';
require_once __DIR__ . '/class-snippet-private-storage.php';
require_once __DIR__ . '/class-snippet-threat-scanner.php';
require_once __DIR__ . '/includes/class-import-export.php';

/**
 * Plugin brand name for snippet markers (respects white label).
 */
function wpps_cs_brand_name(): string {
	return function_exists( 'wp_powersuite_get_plugin_name' ) ? wp_powersuite_get_plugin_name() : 'WP PowerSuite';
}

class Module extends AbstractModule implements DataLocationsInterface {

	private const MODULE_ID = 'code-snippet';

	/**
	 * Flat location labels for list display (admin table).
	 *
	 * @return array<string, string>
	 */
	public static function getLocations(): array {
		$flat = [];
		foreach ( self::getLocationsForUI() as $cat ) {
			foreach ( $cat['sections'] as $section ) {
				foreach ( $section['locations'] as $loc ) {
					$flat[ $loc['value'] ] = $loc['label'];
				}
			}
		}
		$flat['shortcode'] = __( 'Shortcode only', 'wppowersuite-lite' );
		return $flat;
	}

	/**
	 * Locations that require PHP code type only.
	 *
	 * @return string[]
	 */
	public static function getPhpOnlyLocations(): array {
		return [ 'admin_only', 'run_everywhere', 'frontend_only', 'frontend_conditional_logic' ];
	}

	/**
	 * Locations that require WooCommerce.
	 *
	 * @return string[]
	 */
	public static function getWooLocations(): array {
		return [
			'woo_before_shop_loop',
			'woo_after_shop_loop',
			'woo_before_single_product',
			'woo_after_single_product',
			'woo_before_add_to_cart',
			'woo_after_add_to_cart',
			'woo_before_checkout',
			'woo_after_checkout',
			'woo_before_cart',
			'woo_after_cart',
		];
	}

	/**
	 * Flat list of all location slugs for validation.
	 *
	 * @return string[]
	 */
	public static function getAllLocationSlugs(): array {
		$slugs = [ 'shortcode' ];
		foreach ( self::getLocationsForUI() as $cat ) {
			foreach ( $cat['sections'] as $section ) {
				foreach ( $section['locations'] as $loc ) {
					$slugs[] = $loc['value'];
				}
			}
		}
		return $slugs;
	}

	/**
	 * Get the shortcode string for a snippet.
	 *
	 * @param int    $snippet_id      Snippet post ID.
	 * @param string $custom_shortcode Optional custom shortcode slug.
	 * @return string Shortcode string e.g. [wpps_code id="123"] or [my_snippet].
	 */
	public static function getShortcodeForSnippet( int $snippet_id, string $custom_shortcode = '' ): string {
		$custom = preg_replace( '/[^a-z0-9_]/', '', strtolower( $custom_shortcode ) );
		if ( $custom !== '' ) {
			return '[' . $custom . ']';
		}
		return '[wpps_code id="' . $snippet_id . '"]';
	}

	/**
	 * Styled control back to the snippets list.
	 *
	 * @return string Escaped HTML.
	 */
	public static function backToSnippetsButton(): string {
		return sprintf(
			'<p class="wpps-cs-back"><a href="%s" class="button">&larr; %s</a></p>',
			esc_url( admin_url( 'admin.php?page=powersuite-code-snippet' ) ),
			esc_html__( 'Back to Snippets', 'wppowersuite-lite' )
		);
	}

	/**
	 * Locations for UI panel: categories, labels, descriptions.
	 * Structure: [ 'global' => [ 'sections' => [ [ 'heading' => '...', 'locations' => [ [ 'value' => '...', 'label' => '...', 'desc' => '...' ] ] ] ] ], ... ]
	 *
	 * @return array<string, array{sections: array}>
	 */
	public static function getLocationsForUI(): array {
		return [
			'global' => [
				'label'   => __( 'Global', 'wppowersuite-lite' ),
				'sections' => [
					[
						'heading'  => __( 'Site Wide (Frontend)', 'wppowersuite-lite' ),
						'locations' => [
							[
								'value' => 'header',
								'label' => __( 'Site Wide Header', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet between the head tags of your website on all pages.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'body',
								'label' => __( 'Site Wide Body', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert the snippet just after the opening body tag.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'footer',
								'label' => __( 'Site Wide Footer', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert the snippet in the footer just before the closing body tag.', 'wppowersuite-lite' ),
							],
						],
					],
					[
						'heading'  => __( 'Admin Area', 'wppowersuite-lite' ),
						'locations' => [
							[
								'value' => 'admin_header',
								'label' => __( 'Admin header', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet in the wp-admin header area.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'admin_footer',
								'label' => __( 'Admin footer', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet in the wp-admin footer.', 'wppowersuite-lite' ),
							],
						],
					],
					[
						'heading'  => __( 'CSS Selector', 'wppowersuite-lite' ),
						'css_selector' => true,
						'locations' => [
							[
								'value' => 'before_element',
								'label' => __( 'Before HTML Element', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet before a specific HTML element using CSS selector.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'after_element',
								'label' => __( 'After HTML Element', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet after a specific HTML element using CSS selector.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'start_element',
								'label' => __( 'At Start of HTML Element', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet at the start (prepend) inside the targeted element.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'end_element',
								'label' => __( 'At End of HTML Element', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet at the end (append) inside the targeted element.', 'wppowersuite-lite' ),
							],
						],
					],
					[
						'heading'  => __( 'PHP Snippets Only', 'wppowersuite-lite' ),
						'php_only' => true,
						'locations' => [
							[
								'value' => 'admin_only',
								'label' => __( 'Admin Only (PHP)', 'wppowersuite-lite' ),
								'desc'  => __( 'Execute PHP snippet on admin_init. Use for admin-only hooks.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'run_everywhere',
								'label' => __( 'Run Everywhere', 'wppowersuite-lite' ),
								'desc'  => __( 'Execute PHP snippet on plugins_loaded. Use for init hooks, register post types, etc.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'frontend_only',
								'label' => __( 'Frontend Only', 'wppowersuite-lite' ),
								'desc'  => __( 'Execute PHP snippet on plugins_loaded, but only on the frontend.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'frontend_conditional_logic',
								'label' => __( 'Frontend Conditional Logic', 'wppowersuite-lite' ),
								'desc'  => __( 'Execute PHP snippet on wp hook (after page data loads). Use with conditional logic rules.', 'wppowersuite-lite' ),
							],
						],
					],
				],
			],
			'page_specific' => [
				'label'   => __( 'Page-Specific', 'wppowersuite-lite' ),
				'sections' => [
					[
						'heading'  => __( 'Single Post / Page Content', 'wppowersuite-lite' ),
						'locations' => [
							[
								'value' => 'before_content',
								'label' => __( 'Insert Before Content', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet before the main content of posts and pages.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'after_content',
								'label' => __( 'Insert After Content', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet after the main content of posts and pages.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'content_25',
								'label' => __( '25% through content', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet at 25% through the post content.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'content_33',
								'label' => __( '33% through content', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet at 33% through the post content.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'content_50',
								'label' => __( '50% through content', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet at 50% through the post content.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'content_66',
								'label' => __( '66% through content', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet at 66% through the post content.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'content_75',
								'label' => __( '75% through content', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet at 75% through the post content.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'content_80',
								'label' => __( '80% through content', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet at 80% through the post content.', 'wppowersuite-lite' ),
							],
						],
					],
					[
						'heading'  => __( 'Paragraph', 'wppowersuite-lite' ),
						'locations' => [
							[
								'value' => 'before_paragraph',
								'label' => __( 'Insert Before Paragraph', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet before a specific paragraph number.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'after_paragraph',
								'label' => __( 'Insert After Paragraph', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet after a specific paragraph number.', 'wppowersuite-lite' ),
							],
						],
					],
					[
						'heading'  => __( 'Archives / Categories / Tags', 'wppowersuite-lite' ),
						'locations' => [
							[
								'value' => 'before_excerpt',
								'label' => __( 'Insert Before Excerpt', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet before the excerpt on archive pages.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'after_excerpt',
								'label' => __( 'Insert After Excerpt', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet after the excerpt on archive pages.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'between_posts',
								'label' => __( 'Between Posts', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet between each post in archive loops.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'before_post',
								'label' => __( 'Before Post', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet before a specific post number in archive loops.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'after_post',
								'label' => __( 'After Post', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet after a specific post number in archive loops.', 'wppowersuite-lite' ),
							],
						],
					],
				],
			],
			'ecommerce' => [
				'label'   => __( 'eCommerce', 'wppowersuite-lite' ),
				'sections' => [
					[
						'heading'  => __( 'WooCommerce', 'wppowersuite-lite' ),
						'locations' => [
							[
								'value' => 'woo_before_shop_loop',
								'label' => __( 'Before Shop Loop', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet before the product loop on shop/archive pages.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'woo_after_shop_loop',
								'label' => __( 'After Shop Loop', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet after the product loop on shop/archive pages.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'woo_before_single_product',
								'label' => __( 'Before Single Product', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet before the single product content.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'woo_after_single_product',
								'label' => __( 'After Single Product', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet after the single product content.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'woo_before_add_to_cart',
								'label' => __( 'Before Add to Cart', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet before the add to cart button.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'woo_after_add_to_cart',
								'label' => __( 'After Add to Cart', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet after the add to cart button.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'woo_before_checkout',
								'label' => __( 'Before Checkout', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet before the checkout form.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'woo_after_checkout',
								'label' => __( 'After Checkout', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet after the checkout form.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'woo_before_cart',
								'label' => __( 'Before Cart', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet before the cart contents.', 'wppowersuite-lite' ),
							],
							[
								'value' => 'woo_after_cart',
								'label' => __( 'After Cart', 'wppowersuite-lite' ),
								'desc'  => __( 'Insert snippet after the cart contents.', 'wppowersuite-lite' ),
							],
						],
					],
				],
			],
		];
	}
	private const MODULE_VERSION = '1.0.0';
	private const POST_TYPE = 'wpps_code_snippet';
	private const CACHE_OPTION = 'wpps_code_snippet_cache';
	/** Cache payload version: v2 stores post IDs only. */
	private const CACHE_VERSION = 2;
	private const SHORTCODE_CACHE_OPTION = 'wpps_code_snippet_shortcode_map';
	private const SAFE_MODE_PARAM = 'wpps-cs-safe-mode';
	private const ERROR_LOG_OPTION = 'wpps_code_snippet_errors';
	private const SETTINGS_OPTION = 'wpps_code_snippet_settings';
	private const LAST_PHP_ERROR_META = '_wpps_last_php_error';
	private const AUTO_DEACTIVATE_NOTICE_OPTION = 'wpps_cs_auto_deactivate_notice';
	/** Run after do_blocks/wpautop so percentage/paragraph insertion uses rendered HTML. */
	private const CONTENT_FILTER_PRIORITY = 12;

/** @var \WP_Post|null Last PHP snippet executed (for fatal error handling). */
	private ?\WP_Post $last_executed_php_snippet = null;

	/**
	 * Normalized PHP snippet file path => snippet post ID for this request.
	 * Closures throw later (wp_footer etc.); the temp/private path is how we attribute that fatal.
	 *
	 * @var array<string, int>
	 */
	private array $php_snippet_file_index = [];

	/**
	 * PHP snippets that ran this request (id => post), for deferred fatals when the file path is gone.
	 *
	 * @var array<int, \WP_Post>
	 */
	private array $php_snippets_ran = [];

	/** @var array<int, true> Post IDs that already had the_content locations injected this request. */
	private array $content_locations_injected = [];

	/** @var array<int, true> Post IDs that already had excerpt/archive snippet locations injected. */
	private array $excerpt_locations_injected = [];

	/** @var array<int, true> Post IDs that already received after_post output (avoids excerpt + content double). */
	private array $after_post_injected = [];

	/** @var string|null Exact snippet source preserved through wp_insert_post sanitizers. */
	private static ?string $snippet_save_content_override = null;

	/** @var array<string, \WP_Hook>|null Suspended content_save_pre hooks during snippet persist. */
	private static ?array $suspended_content_save_filters = null;

	/**
	 * Map snippet post ID => [ 'start' => 1-based line in merged eval, 'end' => line ] (inclusive).
	 * Set only during merged PHP eval; used for fatals and accurate deactivation.
	 *
	 * @var array<int, array{start:int,end:int}>
	 */
	private array $merged_php_line_map = [];

	/** @var string[] Stack of output locations (for admin bar tracking). */
	private array $output_location_stack = [];

	/** @var bool True if body snippets were output via wp_body_open (skip buffer injection). */
	private bool $body_snippets_output_via_hook = false;

	/** @var array<int, bool> Snippet IDs whose post meta has already been primed this request. */
	private array $meta_primed = [];

	/**
	 * Captured Frontend Only PHP output deferred until the document head (avoids early echo).
	 *
	 * @var string[]
	 */
	private array $deferred_frontend_only_output = [];

	/**
	 * Snippet ID => location for snippets postponed until the main query exists.
	 *
	 * @var array<int, string>
	 */
	private array $deferred_query_conditional = [];

	/** @var bool True once the `wp` runner for postponed snippets is registered. */
	private bool $deferred_query_hook_added = false;

	public function getId(): string {
		return self::MODULE_ID;
	}

	public function getName(): string {
		return __( 'Code Snippet', 'wppowersuite-lite' );
	}

	public function getVersion(): string {
		return self::MODULE_VERSION;
	}

	public function getDescription(): string {
		return __( 'Managed snippets for head, body, footer, or shortcodes—HTML, CSS, JS, and PHP.', 'wppowersuite-lite' );
	}

	public function getContext(): string|array {
		return [ 'admin', 'frontend', 'ajax' ];
	}

	public function getDependencies(): array {
		return [];
	}


	protected function registerHooks(): void {
		require_once __DIR__ . '/safe-mode.php';

		// If boot was deferred past init:5, register immediately so queries still work.
		if ( did_action( 'init' ) ) {
			$this->registerPostType();
		} else {
			add_action( 'init', [ $this, 'registerPostType' ], 5 );
		}

		// Fatal error handling: catch errors that bypass try/catch.
		register_shutdown_function( [ $this, 'maybeDisableSnippetFromShutdown' ] );

		// Snippet list cache: clear on save or any _wpps_* meta change (even if module disabled).
		add_action( 'save_post_' . self::POST_TYPE, [ $this, 'clearCache' ], 10, 3 );
		add_action( 'updated_post_meta', [ $this, 'maybeClearSnippetCacheFromMeta' ], 10, 4 );
		add_action( 'added_post_meta', [ $this, 'maybeClearSnippetCacheFromMeta' ], 10, 4 );
		add_action( 'deleted_post_meta', [ $this, 'maybeClearSnippetCacheFromDeletedMeta' ], 10, 4 );
		add_action( 'wp_trash_post', [ $this, 'clearCacheIfSnippetPost' ], 10, 1 );
		add_action( 'untrash_post', [ $this, 'clearCacheIfSnippetPost' ], 10, 1 );
		add_action( 'before_delete_post', [ $this, 'clearCacheIfSnippetPost' ], 10, 1 );

		if ( is_admin() ) {
			add_action( 'admin_init', [ $this, 'maybeDismissAutoDeactivateNotice' ], 1 );
			add_action( 'admin_notices', [ $this, 'renderAutoDeactivateAdminNotice' ], 5 );
			add_action( 'admin_notices', [ $this, 'renderPrivateStorageFallbackNotice' ], 6 );
		}

		// Tracker must exist before Run Everywhere / Frontend Only execute. Plugin boot
		// is plugins_loaded:5, so those snippets run immediately in this method.
		$this->initAdminBarTracker();

		// Run Everywhere / Frontend Only (plugins_loaded — PHP-only locations).
		// When boot tier defers init past plugins_loaded, run immediately.
		if ( did_action( 'plugins_loaded' ) ) {
			$this->runPhpEverywhereSnippets();
		} else {
			add_action( 'plugins_loaded', [ $this, 'runPhpEverywhereSnippets' ], 10 );
		}
		// Admin Only: advertised as admin_init (not the Run Everywhere batch).
		add_action( 'admin_init', [ $this, 'runAdminOnlySnippets' ], 1 );
		add_action( 'wp_head', [ $this, 'flushDeferredFrontendOnlyOutput' ], 1 );

		if ( class_exists( PremiumTargeting::class, false ) ) {
			PremiumTargeting::register();
		}

		// Frontend Conditional Logic (wp hook - after page data, for conditional logic)
		add_action( 'wp', [ $this, 'outputFrontendConditionalLogicSnippets' ], 1 );

		// Admin header/footer: one callback per hook at priority 9.
		add_action( 'admin_head', [ $this, 'outputAdminHeaderSnippets' ], 9 );
		add_action( 'admin_footer', [ $this, 'outputAdminFooterSnippets' ], 9 );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueueFileBasedSnippets' ], 5 );

		// WooCommerce (when active)
		if ( class_exists( 'WooCommerce' ) ) {
		add_action( 'woocommerce_before_shop_loop', [ $this, 'outputWooBeforeShopLoopSnippets' ], 10 );
		add_action( 'woocommerce_after_shop_loop', [ $this, 'outputWooAfterShopLoopSnippets' ], 10 );
		add_action( 'woocommerce_before_single_product', [ $this, 'outputWooBeforeSingleProductSnippets' ], 10 );
		add_action( 'woocommerce_after_single_product', [ $this, 'outputWooAfterSingleProductSnippets' ], 10 );
		add_action( 'woocommerce_before_add_to_cart_button', [ $this, 'outputWooBeforeAddToCartSnippets' ], 10 );
		add_action( 'woocommerce_after_add_to_cart_button', [ $this, 'outputWooAfterAddToCartSnippets' ], 10 );
		add_action( 'woocommerce_before_checkout_form', [ $this, 'outputWooBeforeCheckoutSnippets' ], 10 );
		add_action( 'woocommerce_after_checkout_form', [ $this, 'outputWooAfterCheckoutSnippets' ], 10 );
		add_action( 'woocommerce_before_cart', [ $this, 'outputWooBeforeCartSnippets' ], 10 );
		add_action( 'woocommerce_after_cart', [ $this, 'outputWooAfterCartSnippets' ], 10 );
		}

		// Frontend: site-wide, content, archive, shortcode
		if ( ! is_admin() && ! ( defined( 'REST_REQUEST' ) && REST_REQUEST ) && ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) && ! ( defined( 'DOING_CRON' ) && DOING_CRON ) ) {
		add_action( 'wp_enqueue_scripts', [ $this, 'enqueueFileBasedSnippets' ], 5 );
		// Site-wide header/body/footer: one callback per hook at priority 10. All snippets for that
		// location run inside it in _wpps_priority order so PHP snippets can register theme hooks predictably.
		add_action( 'wp_head', [ $this, 'outputHeaderSnippets' ], 10 );
		add_action( 'wp_body_open', [ $this, 'outputBodySnippetsViaHook' ], 10 );
		add_action( 'wp_footer', [ $this, 'outputFooterSnippets' ], 10 );
		add_action( 'wp_footer', [ $this, 'trackBufferedBodySnippetsForAdminBar' ], 99990 );
		add_action( 'wp_footer', [ $this, 'outputElementSelectorSnippets' ], 99998 );
		add_filter(
			'the_content',
			[ $this, 'filterTheContent' ],
			(int) apply_filters( 'wpps_code_snippet_the_content_priority', self::CONTENT_FILTER_PRIORITY )
		);
		add_filter( 'get_the_excerpt', [ $this, 'filterTheExcerpt' ], 10, 2 );
		add_action( 'loop_start', [ $this, 'onLoopStart' ], 10, 1 );
		add_action( 'the_post', [ $this, 'onThePost' ], 10, 2 );
		add_shortcode( 'wpps_code', [ $this, 'shortcodeHandler' ] );
		add_action( 'init', [ $this, 'registerCustomShortcodes' ], 20 );
		add_action( 'template_redirect', [ $this, 'maybeStartElementBuffer' ], 1 );
		}

		// Admin: menu and AJAX
		if ( is_admin() ) {
		if ( class_exists( Wpps_Revisions::class, false ) ) {
			new Wpps_Revisions();
		}
		add_action( 'admin_menu', [ $this, 'addAdminMenu' ], 20 );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueueCodeSnippetAssets' ] );
		add_action( 'wp_ajax_wpps_cs_save_snippet', [ $this, 'ajaxSaveSnippet' ] );
		add_action( 'wp_ajax_wpps_cs_delete_snippet', [ $this, 'ajaxDeleteSnippet' ] );
		add_action( 'wp_ajax_wpps_cs_toggle_snippet', [ $this, 'ajaxToggleSnippet' ] );
		add_action( 'wp_ajax_wpps_cs_list_snippets', [ $this, 'ajaxListSnippets' ] );
		add_action( 'wp_ajax_wpps_cs_get_snippet', [ $this, 'ajaxGetSnippet' ] );
		add_action( 'wp_ajax_wpps_cs_load_revisions_compare', [ $this, 'ajaxLoadRevisionsCompare' ] );
		add_action( 'wp_ajax_wpps_cs_get_revisions_list', [ $this, 'ajaxGetRevisionsList' ] );
		add_action( 'wp_ajax_wpps_cs_restore_revision', [ $this, 'ajaxRestoreRevision' ] );
		add_action( 'admin_post_wpps_cs_export', [ $this, 'handleExport' ] );
		add_action( 'admin_post_wpps_cs_import', [ $this, 'handleImport' ] );
		}

	}

	/**
	 * Start the admin-bar loaded-snippet tracker before any snippet executes.
	 */
	private function initAdminBarTracker(): void {
		try {
			require_once __DIR__ . '/admin-bar.php';
			new \Wpps_Cs_Admin_Bar( $this );
		} catch ( \Throwable $e ) {
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				error_log(
					sprintf(
						wpps_cs_brand_name() . ' Code Snippet: Admin bar init failed: %s in %s:%d',
						$e->getMessage(),
						$e->getFile(),
						$e->getLine()
					)
				);
			}
			if ( is_admin() && current_user_can( 'manage_options' ) ) {
				add_action(
					'admin_notices',
					static function () use ( $e ) {
						echo '<div class="notice notice-warning"><p>';
						printf(
							/* translators: %s: error message */
							esc_html__( 'Code Snippet admin bar could not load: %s', 'wppowersuite-lite' ),
							esc_html( $e->getMessage() )
						);
						echo '</p></div>';
					}
				);
			}
		}
	}

	/**
	 * Record body snippets that will inject after wp_footer via the output buffer.
	 *
	 * Those execute in {@see processElementBuffer()} after the admin-bar script prints,
	 * so they must be listed here or they never appear in "Loaded on this page".
	 */
	public function trackBufferedBodySnippetsForAdminBar(): void {
		if ( $this->body_snippets_output_via_hook ) {
			return;
		}
		foreach ( $this->getSnippetsForLocation( 'body' ) as $post ) {
			if ( ! $post instanceof \WP_Post || $this->isLoadAsFile( $post ) ) {
				continue;
			}
			if ( ! $this->passesProLicense( $post ) || ! $this->isSnippetScheduled( $post ) || ! $this->passesConditionalLogic( $post ) || ! $this->passesDeviceCheck( $post ) ) {
				continue;
			}
			do_action( 'wpps_snippet_loaded', $post, 'body' );
		}
	}

	/**
	 * Get current output location (for admin bar tracking).
	 *
	 * @return string
	 */
	public function getCurrentOutputLocation(): string {
		if ( empty( $this->output_location_stack ) ) {
			return '';
		}
		return (string) end( $this->output_location_stack );
	}

	public function registerPostType(): void {
		register_post_type(
			self::POST_TYPE,
			[
				'labels'          => [
					'name'          => __( 'Code Snippets', 'wppowersuite-lite' ),
					'singular_name' => __( 'Code Snippet', 'wppowersuite-lite' ),
				],
				'public'          => false,
				'show_ui'         => false,
				'show_in_rest'    => false,
				'can_export'      => false,
				'supports'        => [ 'title', 'editor' ],
				'rewrite'         => false,
				'capability_type' => 'wpps_code_snippet',
				'map_meta_cap'    => false,
				// Only administrators (manage_options) may create/edit/import snippets.
				'capabilities'    => [
					'edit_post'          => 'manage_options',
					'read_post'          => 'manage_options',
					'delete_post'        => 'manage_options',
					'edit_posts'         => 'manage_options',
					'edit_others_posts'  => 'manage_options',
					'delete_posts'       => 'manage_options',
					'publish_posts'      => 'manage_options',
					'read_private_posts' => 'manage_options',
					'create_posts'       => 'manage_options',
				],
			]
		);
	}

	/**
	 * Check if Safe Mode is active (disables all snippets).
	 *
	 * @return bool
	 */
	public static function isSafeMode(): bool {
		if ( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) {
			return false;
		}
		return isset( $_GET[ self::SAFE_MODE_PARAM ] ) && sanitize_key( wp_unslash( $_GET[ self::SAFE_MODE_PARAM ] ) ) === '1';
	}

	/**
	 * Whether this Pro module may run (add-on + license, or Full edition).
	 */
	public static function isProLicensed(): bool {
		return function_exists( 'wp_powersuite_is_license_valid' ) && wp_powersuite_is_license_valid();
	}

	/**
	 * Whether JS/PHP runtime classes are loaded.
	 */
	private static function ensureProRuntimeLoaded(): bool {
		return class_exists( PremiumPhpJsRuntime::class, false )
			&& function_exists( 'wp_powersuite_code_snippet_eval' );
	}

	/**
	 * Whether JS/PHP snippets may execute.
	 */
	public static function canRunProCodeTypes(): bool {
		return self::ensureProRuntimeLoaded() && self::isProLicensed();
	}

	/**
	 * Why JS/PHP snippets are blocked, or null when they may be used.
	 */
	public static function proCodeTypeBlockReason(): ?string {
		if ( self::canRunProCodeTypes() ) {
			return null;
		}

		if ( self::isProLicensed() ) {
			return __( 'JavaScript and PHP snippets need the WP PowerSuite Pro files. Reinstall or update the Pro add-on, then try again.', 'wppowersuite-lite' );
		}

		return __( 'Code Snippet requires WP PowerSuite Pro and an active license.', 'wppowersuite-lite' );
	}

	/**
	 * Code types that require PRO.
	 *
	 * @param string $type html|css|js|php
	 */
	public static function isProCodeType( string $type ): bool {
		return in_array( $type, [ 'js', 'php' ], true );
	}

	/**
	 * Whether a snippet uses PRO-only settings (device targeting or conditional logic).
	 */
	public function snippetUsesProFeatures( \WP_Post $post ): bool {
		if ( self::isProLicensed() ) {
			return false;
		}
		$device = get_post_meta( $post->ID, '_wpps_device_type', true ) ?: 'all';
		if ( $device !== 'all' ) {
			return true;
		}
		return get_post_meta( $post->ID, '_wpps_conditional_enabled', true ) === '1';
	}

	/**
	 * Block activation/execution when PRO is required but missing.
	 */
	public function getProLicenseBlockReason( \WP_Post $post ): ?string {
		$type = get_post_meta( $post->ID, '_wpps_code_type', true ) ?: 'html';
		if ( ! self::isProCodeType( $type ) ) {
			return null;
		}

		return self::proCodeTypeBlockReason();
	}

	/**
	 * @return bool True when the snippet may run on the current request.
	 */
	private function passesProLicense( \WP_Post $post ): bool {
		return $this->getProLicenseBlockReason( $post ) === null;
	}

	/**
	 * Get active snippets for a location, ordered by priority.
	 *
	 * @param string $location One of: header, body, footer.
	 * @return array Array of WP_Post objects.
	 */
	private function getSnippetsForLocation( string $location ): array {
		if ( ! apply_filters( 'wpps_do_auto_insert', true ) ) {
			return [];
		}
		$cache = get_transient( self::CACHE_OPTION );
		if ( is_array( $cache ) && (int) ( $cache['_v'] ?? 0 ) === self::CACHE_VERSION && isset( $cache[ $location ] ) && is_array( $cache[ $location ] ) ) {
			$posts = $this->hydrateSnippetPostsByIds( $cache[ $location ] );
			$this->primeSnippetMeta( $posts );
			return $posts;
		}

		$query = new \WP_Query(
			[
				'post_type'              => self::POST_TYPE,
				'post_status'            => 'publish',
				'posts_per_page'         => -1,
				'no_found_rows'          => true,
				'update_post_term_cache' => false,
				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- load published snippets for one insert location.
				'meta_query'             => [
					'relation' => 'AND',
					[
						'key'   => '_wpps_auto_insert',
						'value' => '1',
					],
					[
						'key'   => '_wpps_location',
						'value' => $location,
					],
				],
				// Sort in PHP so snippets missing _wpps_priority are not dropped.
				'orderby'                => 'ID',
				'order'                  => 'ASC',
			]
		);

		$snippets = $query->posts;
		// WP_Query already primed meta for these; record so we don't re-prime on later cache hits.
		foreach ( $snippets as $p ) {
			if ( $p instanceof \WP_Post ) {
				$this->meta_primed[ $p->ID ] = true;
			}
		}
		usort(
			$snippets,
			static function ( $a, $b ): int {
				if ( ! $a instanceof \WP_Post || ! $b instanceof \WP_Post ) {
					return 0;
				}
				$pa = (int) ( get_post_meta( $a->ID, '_wpps_priority', true ) ?: 10 );
				$pb = (int) ( get_post_meta( $b->ID, '_wpps_priority', true ) ?: 10 );
				if ( $pa === $pb ) {
					return $a->ID <=> $b->ID;
				}
				return $pa <=> $pb;
			}
		);
		$ids = [];
		foreach ( $snippets as $p ) {
			if ( $p instanceof \WP_Post ) {
				$ids[] = (int) $p->ID;
			}
		}
		$this->updateCache( $location, $ids );
		return $snippets;
	}

	/**
	 * Hydrate published snippet posts from cached IDs (order preserved).
	 *
	 * @param list<int|string> $ids Post IDs.
	 * @return list<\WP_Post>
	 */
	private function hydrateSnippetPostsByIds( array $ids ): array {
		$ids = array_values(
			array_unique(
				array_filter(
					array_map( 'absint', $ids ),
					static fn( int $id ): bool => $id > 0
				)
			)
		);
		if ( $ids === [] ) {
			return [];
		}
		$query = new \WP_Query(
			[
				'post_type'              => self::POST_TYPE,
				'post_status'            => 'publish',
				'post__in'               => $ids,
				'orderby'                => 'post__in',
				'posts_per_page'         => count( $ids ),
				'no_found_rows'          => true,
				'update_post_term_cache' => false,
			]
		);
		$by_id = [];
		foreach ( $query->posts as $p ) {
			if ( $p instanceof \WP_Post ) {
				$by_id[ (int) $p->ID ] = $p;
			}
		}
		$ordered = [];
		foreach ( $ids as $id ) {
			if ( isset( $by_id[ $id ] ) ) {
				$ordered[] = $by_id[ $id ];
			}
		}
		return $ordered;
	}

	/**
	 * Prime the post-meta cache for snippet objects pulled from the transient.
	 *
	 * WP_Post objects restored from a transient do not carry a warm meta cache, so the
	 * first get_post_meta() on each would hit the DB. Priming once per request collapses
	 * those N lookups into a single query.
	 *
	 * @param array $snippets Array of WP_Post objects.
	 */
	private function primeSnippetMeta( array $snippets ): void {
		$ids = [];
		foreach ( $snippets as $p ) {
			if ( $p instanceof \WP_Post && empty( $this->meta_primed[ $p->ID ] ) ) {
				$ids[]                       = $p->ID;
				$this->meta_primed[ $p->ID ] = true;
			}
		}
		if ( $ids !== [] ) {
			update_meta_cache( 'post', $ids );
		}
	}

	/**
	 * @param list<int> $snippet_ids Ordered post IDs for the location.
	 */
	private function updateCache( string $location, array $snippet_ids ): void {
		$cache = get_transient( self::CACHE_OPTION );
		if ( ! is_array( $cache ) || (int) ( $cache['_v'] ?? 0 ) !== self::CACHE_VERSION ) {
			$cache = [ '_v' => self::CACHE_VERSION ];
		}
		$cache['_v']            = self::CACHE_VERSION;
		$cache[ $location ]     = array_values( array_map( 'absint', $snippet_ids ) );
		set_transient( self::CACHE_OPTION, $cache, HOUR_IN_SECONDS );
	}

	public function clearCache( int $post_id, \WP_Post $post, bool $update ): void {
		if ( $post->post_type !== self::POST_TYPE ) {
			return;
		}
		$this->bustSnippetCaches();
	}

	/**
	 * Clear location and shortcode lookup transients.
	 */
	private function bustSnippetCaches(): void {
		delete_transient( self::CACHE_OPTION );
		delete_transient( self::SHORTCODE_CACHE_OPTION );
	}

	/**
	 * Public cache bust for JSON import (called once per pack).
	 */
	public function bustSnippetCachesAfterImport(): void {
		$this->bustSnippetCaches();
	}

	/**
	 * Invalidate location cache when snippet meta changes (e.g. quick edit, imports, REST).
	 *
	 * @param int    $meta_id    Meta row ID.
	 * @param int    $object_id  Post ID.
	 * @param string $meta_key   Meta key.
	 * @param mixed  $_meta_value Stored value (unused).
	 */
	public function maybeClearSnippetCacheFromMeta( int $meta_id, int $object_id, string $meta_key, $_meta_value ): void {
		if ( $meta_key === '' ) {
			return;
		}
		if ( strpos( $meta_key, '_wpps_' ) !== 0 ) {
			return;
		}
		if ( get_post_type( $object_id ) !== self::POST_TYPE ) {
			return;
		}
		$this->bustSnippetCaches();
	}

	/**
	 * Clear location cache when a snippet post is trashed, restored, or deleted.
	 *
	 * @param int $post_id Post ID.
	 */
	public function clearCacheIfSnippetPost( int $post_id ): void {
		if ( $post_id <= 0 ) {
			return;
		}
		if ( get_post_type( $post_id ) !== self::POST_TYPE ) {
			return;
		}
		$this->bustSnippetCaches();
	}

	/**
	 * Same as maybeClearSnippetCacheFromMeta for deleted meta rows.
	 *
	 * @param int[]|mixed $meta_ids Deleted meta row IDs (unused).
	 * @param int         $object_id Post ID.
	 * @param string      $meta_key  Meta key.
	 * @param mixed       $_meta_value Former value (unused).
	 */
	public function maybeClearSnippetCacheFromDeletedMeta( $meta_ids, int $object_id, string $meta_key, $_meta_value ): void {
		if ( $meta_key === '' || strpos( $meta_key, '_wpps_' ) !== 0 ) {
			return;
		}
		if ( get_post_type( $object_id ) !== self::POST_TYPE ) {
			return;
		}
		$this->bustSnippetCaches();
	}

	/**
	 * Max error log rows to keep (newest wins).
	 */
	private function getErrorLogMaxEntries(): int {
		$max = (int) apply_filters( 'wpps_code_snippet_error_log_max_entries', 50 );
		if ( $max < 1 ) {
			$max = 1;
		}
		if ( $max > 500 ) {
			$max = 500;
		}
		return $max;
	}

	/**
	 * Queue a dismissible admin notice after auto-deactivate (shutdown or caught Throwable).
	 */
	private function notifyAutoDeactivateInAdmin( \WP_Post $post, string $message ): void {
		if ( ! apply_filters( 'wpps_code_snippet_auto_deactivate_admin_notice', true, $post, $message ) ) {
			return;
		}
		update_option(
			self::AUTO_DEACTIVATE_NOTICE_OPTION,
			[
				'snippet_id' => $post->ID,
				'title'      => $post->post_title,
				'message'    => $message,
				'time'       => time(),
			],
			false
		);
	}

	/**
	 * Dismiss auto-deactivate dashboard notice.
	 */
	public function maybeDismissAutoDeactivateNotice(): void {
		if ( ! isset( $_GET['wpps_cs_dismiss_ad'], $_GET['_wpnonce'] ) ) {
			return;
		}
		if ( sanitize_key( wp_unslash( $_GET['wpps_cs_dismiss_ad'] ) ) !== '1' ) {
			return;
		}
		if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'wpps_cs_dismiss_ad' ) ) {
			return;
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		delete_option( self::AUTO_DEACTIVATE_NOTICE_OPTION );
		$target = wp_get_referer() ?: admin_url( 'index.php' );
		wp_safe_redirect( remove_query_arg( [ 'wpps_cs_dismiss_ad', '_wpnonce' ], $target ) );
		exit;
	}

	public function renderPrivateStorageFallbackNotice(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( $page !== 'powersuite-code-snippet' ) {
			return;
		}
		if ( SnippetPrivateStorage::isAvailable() ) {
			return;
		}
		echo '<div class="notice notice-warning"><p>';
		echo '<strong>' . esc_html__( 'Code Snippet:', 'wppowersuite-lite' ) . '</strong> ';
		echo esc_html__( 'Private file storage is unavailable, so PHP/HTML snippets run from the database only. File-based PHP loading stays off until a private directory outside the public site is configured.', 'wppowersuite-lite' );
		echo ' <a href="' . esc_url( admin_url( 'admin.php?page=powersuite-code-snippet&view=settings' ) ) . '">' . esc_html__( 'Storage settings', 'wppowersuite-lite' ) . '</a>';
		echo '</p></div>';
	}

	public function renderAutoDeactivateAdminNotice(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		$data = get_option( self::AUTO_DEACTIVATE_NOTICE_OPTION );
		if ( ! is_array( $data ) || empty( $data['snippet_id'] ) ) {
			return;
		}
		$id    = (int) $data['snippet_id'];
		$title = isset( $data['title'] ) ? (string) $data['title'] : '';
		$msg   = isset( $data['message'] ) ? (string) $data['message'] : '';
		$edit  = admin_url( 'admin.php?page=powersuite-code-snippet&action=edit&id=' . $id );
		$dismiss_url = wp_nonce_url( admin_url( 'admin.php?wpps_cs_dismiss_ad=1' ), 'wpps_cs_dismiss_ad' );
		echo '<div class="notice notice-error is-dismissible"><p>';
		echo '<strong>' . esc_html__( 'Code Snippet: a snippet was auto-deactivated after a PHP error.', 'wppowersuite-lite' ) . '</strong> ';
		if ( $title !== '' ) {
			echo esc_html( $title );
			echo ' — ';
		}
		if ( $msg !== '' ) {
			echo esc_html( $msg );
		}
		echo ' ';
		printf(
			'<a href="%1$s">%2$s</a> · <a href="%3$s">%4$s</a>',
			esc_url( $edit ),
			esc_html__( 'Edit snippet', 'wppowersuite-lite' ),
			esc_url( $dismiss_url ),
			esc_html__( 'Dismiss', 'wppowersuite-lite' )
		);
		echo '</p></div>';
	}

	/**
	 * Error types that trigger shutdown-based snippet deactivation.
	 *
	 * @return int[]
	 */
	private function shutdownFatalErrorTypes(): array {
		$default = [ E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR ];
		$types   = apply_filters( 'wpps_code_snippet_shutdown_fatal_types', $default );
		if ( ! is_array( $types ) ) {
			$types = $default;
		}
		$out = [];
		foreach ( $types as $t ) {
			if ( is_int( $t ) ) {
				$out[] = $t;
			}
		}
		return $out !== [] ? array_values( array_unique( $out ) ) : $default;
	}

	/**
	 * Run PHP snippets for Run Everywhere (merged eval) + Frontend Only.
	 * Admin Only runs separately on admin_init via {@see runAdminOnlySnippets()}.
	 * Frontend Only echoed output is deferred to wp_head.
	 */
	public function runPhpEverywhereSnippets(): void {
		$snippets    = $this->getSnippetsForLocation( 'run_everywhere' );
		$merge_items = [];
		$loc         = 'run_everywhere';
		foreach ( $snippets as $post ) {
			$type = get_post_meta( $post->ID, '_wpps_code_type', true ) ?: 'html';
			if ( $type !== 'php' ) {
				continue;
			}
			if ( $this->maybeDeferForQueryConditionals( $post, 'run_everywhere' ) ) {
				continue;
			}
			if ( ! $this->passesProLicense( $post ) || ! $this->passesConditionalLogic( $post ) || ! $this->passesDeviceCheck( $post ) || ! $this->isSnippetScheduled( $post ) ) {
				continue;
			}
			$php_file = $this->getPhpSnippetFilePath( $post );
			if ( $this->shouldLoadPhpFromFile( $post ) ) {
				$this->ensurePhpSnippetFileIfNeeded( $post );
				if ( file_exists( $php_file ) ) {
					$this->loadPhpFromFile( $php_file, $post );
					do_action( 'wpps_snippet_loaded', $post, get_post_meta( $post->ID, '_wpps_location', true ) ?: $loc );
					continue;
				}
			}
			$snippet_code = $this->getPhpCodeForExecution( $post );
			if ( ! is_string( $snippet_code ) || $snippet_code === '' ) {
				continue;
			}
			$snippet_code = apply_filters( 'wpps_code_snippet_php_before_eval', $snippet_code, $post, 'merged_run_everywhere' );
			if ( $this->isPhpExecutionBlocked( $snippet_code ) ) {
				continue;
			}
			$merge_items[] = [ 'post' => $post, 'code' => $snippet_code, 'loc' => get_post_meta( $post->ID, '_wpps_location', true ) ?: $loc ];
		}
		if ( $merge_items !== [] ) {
			$merge_re = (bool) self::getSetting( 'merge_run_everywhere_php', false );
			$merge_re = apply_filters( 'wpps_code_snippet_merge_run_everywhere_php', $merge_re );
			if ( $merge_re ) {
				$built = $this->buildMergedPhpStringAndLineMap( $merge_items );
				if ( $built['code'] !== '' && $built['last_post'] ) {
					$merged = apply_filters( 'wpps_code_snippet_merged_php_code', $built['code'], 'run_everywhere_admin', $built['line_map'] );
					if ( ! is_string( $merged ) ) {
						$merged = $built['code'];
					}
					if ( $this->safeExecutePhpMerged( $merged, $built['last_post'], $built['line_map'], 'run_everywhere_admin' ) ) {
						foreach ( $merge_items as $item ) {
							do_action( 'wpps_snippet_loaded', $item['post'], $item['loc'] );
						}
					}
				}
			} else {
				foreach ( $merge_items as $item ) {
					if ( ! isset( $item['post'], $item['code'], $item['loc'] ) || ! $item['post'] instanceof \WP_Post ) {
						continue;
					}
					if ( $this->safeExecutePhpSideEffects( (string) $item['code'], $item['post'], 'run_everywhere_admin' ) ) {
						do_action( 'wpps_snippet_loaded', $item['post'], $item['loc'] );
					}
				}
			}
		}

		if ( ! is_admin() ) {
			$this->runFrontendOnlySnippets();
		}
	}

	/**
	 * Run Admin Only PHP snippets on admin_init.
	 */
	public function runAdminOnlySnippets(): void {
		if ( ! is_admin() ) {
			return;
		}
		$snippets    = $this->getSnippetsForLocation( 'admin_only' );
		$merge_items = [];
		foreach ( $snippets as $post ) {
			$type = get_post_meta( $post->ID, '_wpps_code_type', true ) ?: 'html';
			if ( $type !== 'php' ) {
				continue;
			}
			if ( $this->maybeDeferForQueryConditionals( $post, 'admin_only' ) ) {
				continue;
			}
			if ( ! $this->passesProLicense( $post ) || ! $this->passesConditionalLogic( $post ) || ! $this->passesDeviceCheck( $post ) || ! $this->isSnippetScheduled( $post ) ) {
				continue;
			}
			$php_file = $this->getPhpSnippetFilePath( $post );
			if ( $this->shouldLoadPhpFromFile( $post ) ) {
				$this->ensurePhpSnippetFileIfNeeded( $post );
				if ( file_exists( $php_file ) ) {
					$this->loadPhpFromFile( $php_file, $post );
					do_action( 'wpps_snippet_loaded', $post, 'admin_only' );
					continue;
				}
			}
			$snippet_code = $this->getPhpCodeForExecution( $post );
			if ( ! is_string( $snippet_code ) || $snippet_code === '' ) {
				continue;
			}
			$snippet_code = apply_filters( 'wpps_code_snippet_php_before_eval', $snippet_code, $post, 'merged_run_everywhere' );
			if ( $this->isPhpExecutionBlocked( $snippet_code ) ) {
				continue;
			}
			$merge_items[] = [ 'post' => $post, 'code' => $snippet_code, 'loc' => 'admin_only' ];
		}
		if ( $merge_items === [] ) {
			return;
		}
		$merge_re = (bool) self::getSetting( 'merge_run_everywhere_php', false );
		$merge_re = apply_filters( 'wpps_code_snippet_merge_run_everywhere_php', $merge_re );
		if ( $merge_re ) {
			$built = $this->buildMergedPhpStringAndLineMap( $merge_items );
			if ( $built['code'] !== '' && $built['last_post'] ) {
				$merged = apply_filters( 'wpps_code_snippet_merged_php_code', $built['code'], 'admin_only', $built['line_map'] );
				if ( ! is_string( $merged ) ) {
					$merged = $built['code'];
				}
				if ( $this->safeExecutePhpMerged( $merged, $built['last_post'], $built['line_map'], 'admin_only' ) ) {
					foreach ( $merge_items as $item ) {
						do_action( 'wpps_snippet_loaded', $item['post'], $item['loc'] );
					}
				}
			}
			return;
		}
		foreach ( $merge_items as $item ) {
			if ( ! isset( $item['post'], $item['code'], $item['loc'] ) || ! $item['post'] instanceof \WP_Post ) {
				continue;
			}
			if ( $this->safeExecutePhpSideEffects( (string) $item['code'], $item['post'], 'admin_only' ) ) {
				do_action( 'wpps_snippet_loaded', $item['post'], $item['loc'] );
			}
		}
	}

	/**
	 * Run Frontend Only PHP snippets; defer any echoed HTML until wp_head.
	 */
	private function runFrontendOnlySnippets(): void {
		$merge_fe = (bool) self::getSetting( 'merge_frontend_only_php', false );
		$merge_fe = apply_filters( 'wpps_code_snippet_merge_frontend_only_php', $merge_fe );
		$frontend = $this->getSnippetsForLocation( 'frontend_only' );
		$fe_items = [];
		foreach ( $frontend as $post ) {
			$type = get_post_meta( $post->ID, '_wpps_code_type', true ) ?: 'html';
			if ( $type !== 'php' ) {
				continue;
			}
			if ( $this->maybeDeferForQueryConditionals( $post, 'frontend_only' ) ) {
				continue;
			}
			if ( ! $this->passesProLicense( $post ) || ! $this->passesConditionalLogic( $post ) || ! $this->passesDeviceCheck( $post ) || ! $this->isSnippetScheduled( $post ) ) {
				continue;
			}
			$php_file = $this->getPhpSnippetFilePath( $post );
			if ( $this->shouldLoadPhpFromFile( $post ) ) {
				$this->ensurePhpSnippetFileIfNeeded( $post );
				if ( file_exists( $php_file ) ) {
					$output = $this->loadPhpFromFile( $php_file, $post );
					if ( $output !== '' ) {
						$this->deferFrontendOnlyOutput( $post->post_title, $output );
					}
					do_action( 'wpps_snippet_loaded', $post, 'frontend_only' );
					continue;
				}
			}
			$snippet_code = $this->getPhpCodeForExecution( $post );
			if ( ! is_string( $snippet_code ) || $snippet_code === '' ) {
				continue;
			}
			if ( ! $merge_fe ) {
				$output = $this->executeSnippet( $post );
				if ( $output !== '' ) {
					$this->deferFrontendOnlyOutput( $post->post_title, $output );
				}
				continue;
			}
			$snippet_code = apply_filters( 'wpps_code_snippet_php_before_eval', $snippet_code, $post, 'merged_frontend_only' );
			if ( $this->isPhpExecutionBlocked( $snippet_code ) ) {
				continue;
			}
			$fe_items[] = [ 'post' => $post, 'code' => $snippet_code ];
		}
		if ( ! $merge_fe || $fe_items === [] ) {
			return;
		}
		$built = $this->buildMergedPhpStringAndLineMap( $fe_items );
		if ( $built['code'] === '' || ! $built['last_post'] ) {
			return;
		}
		$merged = apply_filters( 'wpps_code_snippet_merged_php_code', $built['code'], 'merged_frontend_only', $built['line_map'] );
		if ( ! is_string( $merged ) ) {
			$merged = $built['code'];
		}
		$merged_posts = [];
		foreach ( $fe_items as $it ) {
			if ( isset( $it['post'] ) && $it['post'] instanceof \WP_Post ) {
				$merged_posts[] = $it['post'];
			}
		}
		$label = count( $fe_items ) === 1 ? $fe_items[0]['post']->post_title : __( 'Frontend Only (merged)', 'wppowersuite-lite' );
		ob_start();
		$ok = $this->safeExecutePhpMerged( $merged, $built['last_post'], $built['line_map'], 'merged_frontend_only' );
		if ( $ok ) {
			$buf = ob_get_clean();
			$buf = apply_filters( 'wpps_code_snippet_merged_php_output', is_string( $buf ) ? $buf : '', $merged_posts, 'merged_frontend_only' );
			if ( is_string( $buf ) && $buf !== '' ) {
				$this->deferFrontendOnlyOutput( $label, $buf );
			}
			foreach ( $fe_items as $it ) {
				if ( isset( $it['post'] ) && $it['post'] instanceof \WP_Post ) {
					do_action( 'wpps_snippet_loaded', $it['post'], 'frontend_only' );
				}
			}
		} else {
			ob_end_clean();
		}
	}

	/**
	 * Queue Frontend Only markup for wp_head (never echo during plugins_loaded).
	 */
	private function deferFrontendOnlyOutput( string $label, string $output ): void {
		$block  = "\n<!-- " . esc_attr( wpps_cs_brand_name() ) . ' Code Snippet: ' . esc_attr( $label ) . " -->\n";
		$block .= $output;
		$block .= "\n<!-- /" . esc_attr( wpps_cs_brand_name() ) . " -->\n";
		$this->deferred_frontend_only_output[] = $block;
	}

	/**
	 * Print deferred Frontend Only PHP output in the document head.
	 */
	public function flushDeferredFrontendOnlyOutput(): void {
		if ( $this->deferred_frontend_only_output === [] ) {
			return;
		}
		foreach ( $this->deferred_frontend_only_output as $block ) {
			echo $block; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Intentional: user snippet output.
		}
		$this->deferred_frontend_only_output = [];
	}

	public function outputFrontendConditionalLogicSnippets(): void {
		if ( ! is_admin() ) {
			$this->outputSnippetsForLocation( 'frontend_conditional_logic', true );
		}
	}

	public function outputAdminHeaderSnippets(): void {
		$this->outputSnippets( 'admin_header' );
	}

	public function outputAdminFooterSnippets(): void {
		$this->outputSnippets( 'admin_footer' );
	}

	public function outputWooBeforeShopLoopSnippets(): void {
		$this->outputSnippets( 'woo_before_shop_loop' );
	}

	public function outputWooAfterShopLoopSnippets(): void {
		$this->outputSnippets( 'woo_after_shop_loop' );
	}

	public function outputWooBeforeSingleProductSnippets(): void {
		$this->outputSnippets( 'woo_before_single_product' );
	}

	public function outputWooAfterSingleProductSnippets(): void {
		$this->outputSnippets( 'woo_after_single_product' );
	}

	public function outputWooBeforeAddToCartSnippets(): void {
		$this->outputSnippets( 'woo_before_add_to_cart' );
	}

	public function outputWooAfterAddToCartSnippets(): void {
		$this->outputSnippets( 'woo_after_add_to_cart' );
	}

	public function outputWooBeforeCheckoutSnippets(): void {
		$this->outputSnippets( 'woo_before_checkout' );
	}

	public function outputWooAfterCheckoutSnippets(): void {
		$this->outputSnippets( 'woo_after_checkout' );
	}

	public function outputWooBeforeCartSnippets(): void {
		$this->outputSnippets( 'woo_before_cart' );
	}

	public function outputWooAfterCartSnippets(): void {
		$this->outputSnippets( 'woo_after_cart' );
	}

	public function outputHeaderSnippets(): void {
		$this->outputSnippets( 'header' );
	}

	/**
	 * Output body snippets via wp_body_open (when theme supports it).
	 * Avoids output buffer; fallback is buffer injection in processElementBuffer.
	 */
	public function outputBodySnippetsViaHook(): void {
		$snippets = $this->getSnippetsForLocation( 'body' );
		if ( empty( $snippets ) ) {
			return;
		}
		$this->body_snippets_output_via_hook = true;
		$this->outputSnippets( 'body' );
	}

	public function outputFooterSnippets(): void {
		$this->outputSnippets( 'footer' );
	}

	/**
	 * Output element selector snippets via client-side JS injection.
	 * Avoids DOMDocument parsing of full page (can blank large builder-heavy pages).
	 */
	public function outputElementSelectorSnippets(): void {
		$modes = [
			'before_element' => 'before',
			'after_element'  => 'after',
			'start_element'  => 'start',
			'end_element'    => 'end',
		];
		$injections = [];
		foreach ( $modes as $loc => $mode ) {
			$this->output_location_stack[] = $loc;
			$snippets = $this->getSnippetsForLocation( $loc );
			foreach ( $snippets as $post ) {
				$sel = get_post_meta( $post->ID, '_wpps_location_selector', true );
				if ( $sel === '' ) {
					continue;
				}
				$out = $this->executeSnippet( $post );
				if ( $out === '' ) {
					continue;
				}
				$idx = get_post_meta( $post->ID, '_wpps_location_element_index', true );
				$injections[] = [
					'selector' => $sel,
					'output'   => $out,
					'mode'     => $mode,
					'index'    => ( $idx === '' || $idx === false ) ? -1 : (int) $idx,
				];
			}
			array_pop( $this->output_location_stack );
		}
		if ( empty( $injections ) ) {
			return;
		}
		?>
		<?php ob_start(); ?>
		(function() {
			var inj = <?php echo wp_json_encode( $injections ); ?>;
			function adoptNode(node) {
				if (node.nodeName === 'SCRIPT') {
					var s = document.createElement('script');
					for (var ai = 0; ai < node.attributes.length; ai++) {
						var attr = node.attributes[ai];
						s.setAttribute(attr.name, attr.value);
					}
					s.text = node.text || node.textContent || '';
					return s;
				}
				if (node.nodeType === 1 && node.children) {
					var scripts = node.querySelectorAll('script');
					for (var si = 0; si < scripts.length; si++) {
						var old = scripts[si];
						var neu = adoptNode(old);
						if (old.parentNode) old.parentNode.replaceChild(neu, old);
					}
				}
				return node;
			}
			function insertHtml(el, html, mode) {
				var w = document.createElement('div');
				w.innerHTML = html;
				var f = document.createDocumentFragment();
				while (w.firstChild) f.appendChild(adoptNode(w.removeChild(w.firstChild)));
				if (mode === 'before') el.parentNode.insertBefore(f, el);
				else if (mode === 'after') el.parentNode.insertBefore(f, el.nextSibling);
				else if (mode === 'start') el.insertBefore(f, el.firstChild);
				else if (mode === 'end') el.appendChild(f);
			}
			function run() {
				inj.forEach(function(i) {
					var targets = document.querySelectorAll(i.selector);
					if (!targets.length) return;
					var nodes = i.index >= 0 && targets[i.index] ? [targets[i.index]] : Array.prototype.slice.call(targets);
					nodes.forEach(function(el) {
						insertHtml(el, i.output, i.mode);
					});
				});
			}
			if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', run);
			else run();
		})();
<?php \WP_PowerSuite\Core\InlineAssets::script( 'wpps-ia-modules-code-snippet-module-php-script-1', (string) ob_get_clean() ); ?>
		<?php
	}

	/** @var int Loop post counter for before_post/after_post. */
	private int $loop_post_index = 0;

	public function onLoopStart( \WP_Query $query ): void {
		if ( $query->is_main_query() ) {
			$this->loop_post_index = 0;
		}
	}

	public function onThePost( \WP_Post $post, \WP_Query $query ): void {
		if ( ! $query->is_main_query() || ! in_the_loop() ) {
			return;
		}
		$this->loop_post_index++;

		// On archive/loop pages the theme often renders the_excerpt() instead of
		// the_content(), so the_content-based injection never runs. the_post fires for
		// every post regardless, so emit the loop-position locations here. Singular
		// views keep using the_content (handled in filterTheContent) for correct placement.
		if ( is_singular() ) {
			return;
		}
		$this->echoArchiveLoopSnippets( 'before_post' );
		$this->echoArchiveLoopSnippets( 'between_posts' );
	}

	/**
	 * Echo loop-position snippets (before_post / between_posts) during archive loops.
	 */
	private function echoArchiveLoopSnippets( string $location ): void {
		$snippets = $this->getSnippetsForLocation( $location );
		if ( empty( $snippets ) ) {
			return;
		}
		$this->output_location_stack[] = $location;
		foreach ( $snippets as $post ) {
			if ( $location === 'between_posts' ) {
				if ( $this->loop_post_index <= 1 ) {
					continue;
				}
			} else {
				$param = (int) ( get_post_meta( $post->ID, '_wpps_location_param', true ) ?: 1 );
				if ( $param !== $this->loop_post_index ) {
					continue;
				}
			}
			$out = $this->executeSnippet( $post );
			if ( $out === '' ) {
				continue;
			}
			echo "\n<!-- " . esc_attr( wpps_cs_brand_name() ) . ' Code Snippet: ' . esc_attr( $post->post_title ) . " -->\n";
			echo $out; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			echo "\n<!-- /" . esc_attr( wpps_cs_brand_name() ) . " -->\n";
		}
		array_pop( $this->output_location_stack );
	}

	public function filterTheContent( string $content ): string {
		if ( ! $this->shouldInjectIntoPostContent( $content ) ) {
			return $content;
		}
		$post_id = (int) get_the_ID();
		if ( $post_id > 0 && isset( $this->content_locations_injected[ $post_id ] ) ) {
			return $content;
		}
		$locations = [
			'before_content',
			'after_content',
			'content_25',
			'content_33',
			'content_50',
			'content_66',
			'content_75',
			'content_80',
			'before_paragraph',
			'after_paragraph',
			'between_posts',
			'before_post',
			'after_post',
		];
		foreach ( $locations as $loc ) {
			// Loop-position locations are emitted on the_post for archive loops (so they
			// work with excerpt-based themes). Skip them here to avoid double output;
			// singular views still place them via the_content below.
			if ( ! is_singular() && in_array( $loc, [ 'before_post', 'between_posts' ], true ) ) {
				continue;
			}
			$snippets = $this->getSnippetsForLocation( $loc );
			if ( empty( $snippets ) ) {
				continue;
			}
			$this->output_location_stack[] = $loc;
			$prepend_locs = [ 'before_content', 'between_posts', 'before_post' ];
			if ( in_array( $loc, $prepend_locs, true ) ) {
				$snippets = array_reverse( $snippets );
			}
			foreach ( $snippets as $post ) {
				$param = (int) ( get_post_meta( $post->ID, '_wpps_location_param', true ) ?: 1 );
				$out   = $this->executeSnippet( $post );
				if ( $out === '' ) {
					continue;
				}
				switch ( $loc ) {
					case 'before_content':
						$content = $out . $content;
						break;
					case 'after_content':
						$content = $content . $out;
						break;
					case 'between_posts':
						if ( $this->loop_post_index > 1 ) {
							$content = $out . $content;
						}
						break;
					case 'before_post':
					case 'after_post':
						if ( $param === $this->loop_post_index ) {
							if ( $loc === 'after_post' && $post_id > 0 && isset( $this->after_post_injected[ $post_id ] ) ) {
								break;
							}
							$content = $loc === 'before_post' ? ( $out . $content ) : ( $content . $out );
							if ( $loc === 'after_post' && $post_id > 0 ) {
								$this->after_post_injected[ $post_id ] = true;
							}
						}
						break;
					case 'before_paragraph':
					case 'after_paragraph':
						$content = $this->insertAtParagraph( $content, $out, $param, $loc === 'before_paragraph' );
						break;
					case 'content_25':
					case 'content_33':
					case 'content_50':
					case 'content_66':
					case 'content_75':
					case 'content_80':
						$pct    = (int) str_replace( 'content_', '', $loc );
						$content = $this->insertAtPercentage( $content, $out, $pct );
						break;
				}
			}
			array_pop( $this->output_location_stack );
		}
		if ( $post_id > 0 ) {
			$this->content_locations_injected[ $post_id ] = true;
		}
		return $content;
	}

	private function insertAtParagraph( string $content, string $insert, int $paragraph_num, bool $before ): string {
		if ( $paragraph_num < 1 ) {
			$paragraph_num = 1;
		}

		if ( $before ) {
			if ( ! preg_match_all( '/<p\b[^>]*>/i', $content, $m, PREG_OFFSET_CAPTURE ) ) {
				return $content;
			}
			if ( ! isset( $m[0][ $paragraph_num - 1 ] ) ) {
				return $content;
			}
			$pos = $m[0][ $paragraph_num - 1 ][1];
			return substr( $content, 0, $pos ) . $insert . substr( $content, $pos );
		}

		if ( ! preg_match_all( '/<\/p>/i', $content, $m, PREG_OFFSET_CAPTURE ) ) {
			return $content;
		}
		if ( ! isset( $m[0][ $paragraph_num - 1 ] ) ) {
			return $content;
		}
		$match = $m[0][ $paragraph_num - 1 ];
		$pos   = $match[1] + strlen( $match[0] );
		return substr( $content, 0, $pos ) . $insert . substr( $content, $pos );
	}

	private function insertAtPercentage( string $content, string $insert, int $pct ): string {
		$len = strlen( $content );
		if ( $len < 10 ) {
			return $insert . $content;
		}
		$target = (int) floor( $len * $pct / 100 );

		// Prefer block boundaries in rendered HTML (paragraphs, headings, lists, etc.).
		if ( preg_match_all( '/<\/(?:p|h[1-6]|li|blockquote|figure)>/i', $content, $m, PREG_OFFSET_CAPTURE ) ) {
			$best  = null;
			$bestd = null;
			foreach ( $m[0] as $match ) {
				$boundary = $match[1] + strlen( $match[0] );
				$dist     = abs( $boundary - $target );
				if ( $bestd === null || $dist < $bestd ) {
					$bestd = $dist;
					$best  = $boundary;
				}
			}
			if ( $best !== null ) {
				return substr( $content, 0, $best ) . $insert . substr( $content, $best );
			}
		}

		// No block closers: insert at the next tag close at/after the target so we never
		// cut through an HTML tag. Falls back to appending if none found.
		$gt  = strpos( $content, '>', $target );
		$pos = $gt !== false ? $gt + 1 : $len;
		return substr( $content, 0, $pos ) . $insert . substr( $content, $pos );
	}

	public function filterTheExcerpt( string $excerpt, \WP_Post $post ): string {
		if ( ! in_the_loop() || ! is_main_query() ) {
			return $excerpt;
		}
		$post_id = (int) $post->ID;
		if ( $post_id > 0 && isset( $this->excerpt_locations_injected[ $post_id ] ) ) {
			return $excerpt;
		}

		$out_before = '';
		$out_after  = '';

		$before = $this->getSnippetsForLocation( 'before_excerpt' );
		$this->output_location_stack[] = 'before_excerpt';
		foreach ( $before as $p ) {
			$out_before .= $this->executeSnippet( $p );
		}
		array_pop( $this->output_location_stack );

		$after = $this->getSnippetsForLocation( 'after_excerpt' );
		$this->output_location_stack[] = 'after_excerpt';
		foreach ( $after as $p ) {
			$out_after .= $this->executeSnippet( $p );
		}
		array_pop( $this->output_location_stack );

		// Excerpt-based archive themes never run the_content; append after_post here instead.
		if ( ! is_singular() ) {
			$after_post_snippets = $this->getSnippetsForLocation( 'after_post' );
			if ( ! empty( $after_post_snippets ) && ! isset( $this->after_post_injected[ $post_id ] ) ) {
				$this->output_location_stack[] = 'after_post';
				$after_post_added              = false;
				foreach ( $after_post_snippets as $p ) {
					$param = (int) ( get_post_meta( $p->ID, '_wpps_location_param', true ) ?: 1 );
					if ( $param !== $this->loop_post_index ) {
						continue;
					}
					$out = $this->executeSnippet( $p );
					if ( $out !== '' ) {
						$out_after         .= $out;
						$after_post_added   = true;
					}
				}
				array_pop( $this->output_location_stack );
				if ( $after_post_added && $post_id > 0 ) {
					$this->after_post_injected[ $post_id ] = true;
				}
			}
		}

		if ( $out_before === '' && $out_after === '' ) {
			return $excerpt;
		}

		if ( $post_id > 0 ) {
			$this->excerpt_locations_injected[ $post_id ] = true;
		}

		return $out_before . $excerpt . $out_after;
	}

	/**
	 * Whether the_content filter should inject snippets for the current request.
	 *
	 * @param string $content Post content passed to the filter.
	 */
	private function shouldInjectIntoPostContent( string $content ): bool {
		if ( trim( $content ) === '' ) {
			return false;
		}
		if ( is_singular() ) {
			$queried_id = (int) get_queried_object_id();
			$current_id = (int) get_the_ID();
			if ( $queried_id > 0 && $current_id > 0 && $queried_id !== $current_id ) {
				return false;
			}
			return true;
		}
		return in_the_loop() && is_main_query();
	}

	/**
	 * Output snippets for a location. For PHP-only locations, only PHP snippets run.
	 *
	 * @param string $location Location slug.
	 * @param bool   $php_only If true, only output PHP snippets.
	 */
	private function outputSnippetsForLocation( string $location, bool $php_only = false ): void {
		$this->output_location_stack[] = $location;
		$snippets = $this->getSnippetsForLocation( $location );
		foreach ( $snippets as $post ) {
			$type = get_post_meta( $post->ID, '_wpps_code_type', true ) ?: 'html';
			if ( $php_only && $type !== 'php' ) {
				continue;
			}
			$output = $this->executeSnippet( $post );
			if ( $output !== '' ) {
				echo "\n<!-- " . esc_attr( wpps_cs_brand_name() ) . ' Code Snippet: ' . esc_attr( $post->post_title ) . " -->\n";
				echo $output; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
				echo "\n<!-- /" . esc_attr( wpps_cs_brand_name() ) . " -->\n";
			}
		}
		array_pop( $this->output_location_stack );
	}

	private function outputSnippets( string $location ): void {
		$this->output_location_stack[] = $location;
		$snippets = $this->getSnippetsForLocation( $location );
		foreach ( $snippets as $post ) {
			if ( $this->isLoadAsFile( $post ) ) {
				continue;
			}
			$output = $this->executeSnippet( $post );
			if ( $output !== '' ) {
				echo "\n<!-- " . esc_attr( wpps_cs_brand_name() ) . ' Code Snippet: ' . esc_attr( $post->post_title ) . " -->\n";
				echo $output; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Intentional: user code.
				echo "\n<!-- /" . esc_attr( wpps_cs_brand_name() ) . " -->\n";
			}
		}
		array_pop( $this->output_location_stack );
	}

	/**
	 * Check if snippet uses file-based loading (JS/CSS only).
	 */
	private function isLoadAsFile( \WP_Post $post ): bool {
		$type = get_post_meta( $post->ID, '_wpps_code_type', true ) ?: 'html';
		if ( ! in_array( $type, [ 'js', 'css' ], true ) ) {
			return false;
		}
		$per_snippet = get_post_meta( $post->ID, '_wpps_load_as_file', true ) === '1';
		if ( $per_snippet ) {
			return true;
		}
		return self::getSetting( 'load_snippets_as_files', false );
	}

	/**
	 * Enqueue JS/CSS snippets that use file-based loading.
	 */
	public function enqueueFileBasedSnippets(): void {
		$locs = is_admin()
			? [ 'admin_header', 'admin_footer' ]
			: [ 'header', 'body', 'footer' ];
		foreach ( $locs as $loc ) {
			$snippets = $this->getSnippetsForLocation( $loc );
			foreach ( $snippets as $post ) {
				if ( ! $this->isLoadAsFile( $post ) ) {
					continue;
				}
				// Same gates as executeSnippet() — file path previously skipped these.
				if ( ! $this->passesProLicense( $post ) || ! $this->isSnippetScheduled( $post ) || ! $this->passesConditionalLogic( $post ) || ! $this->passesDeviceCheck( $post ) ) {
					continue;
				}
				$type  = get_post_meta( $post->ID, '_wpps_code_type', true ) ?: 'html';
				$code  = $post->post_content;
				$code  = preg_replace( '/^\s*<' . 'script[^>]*>|<\/script>\s*$/i', '', $code );
				$code  = preg_replace( '/^\s*<' . 'style[^>]*>|<\/style>\s*$/i', '', $code );
				$code  = trim( $code );
				$file  = $this->getSnippetFilePath( $post, $type );
				$url   = $this->getSnippetFileUrl( $post, $type );
				if ( $file && $url && $this->ensureSnippetFile( $post, $type, $code ) ) {
					$handle    = 'wpps-snippet-' . $post->ID;
					$in_footer = in_array( $loc, [ 'footer', 'body', 'admin_footer' ], true );
					$ver       = is_readable( $file ) ? (string) filemtime( $file ) : self::MODULE_VERSION;
					if ( $type === 'js' ) {
						wp_enqueue_script( $handle, $url, [], $ver, $in_footer );
					} else {
						wp_enqueue_style( $handle, $url, [], $ver );
					}
					// Same tracking as executeSnippet() / wpps_code_snippet_output (those paths are skipped for file-based assets).
					do_action( 'wpps_snippet_loaded', $post, $loc );
				}
			}
		}
	}

	/**
	 * Public directory for enqueued JS/CSS snippet assets only (never PHP).
	 */
	private function getSnippetFileDir(): string {
		$dir = trailingslashit( WordPressPaths::uploadsDir() ) . 'wp-powersuite/snippets';
		if ( ! is_dir( $dir ) ) {
			wp_mkdir_p( $dir );
			$index = $dir . '/index.php';
			if ( ! file_exists( $index ) ) {
				// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- silencer in uploads/wp-powersuite/snippets.
				file_put_contents( $index, '<?php // Silence is golden.' );
			}
		}
		$this->ensurePublicAssetDirSecurity( $dir );
		return $dir;
	}

	/**
	 * Get sanitized filesystem slug for snippet files.
	 *
	 * Uses sanitize_title( post_title ) first so names match the visible title, work better for
	 * non-ASCII titles, and update when the title changes. Falls back to post_name (WordPress slug),
	 * then to a generic prefix. The post ID is always appended in the path, so names stay unique.
	 */
	private function getSnippetFileSlug( \WP_Post $post ): string {
		$title_slug = sanitize_file_name( sanitize_title( $post->post_title ) );
		if ( $title_slug !== '' ) {
			return substr( $title_slug, 0, 80 );
		}
		if ( isset( $post->post_name ) && is_string( $post->post_name ) && $post->post_name !== '' ) {
			$slug = sanitize_file_name( $post->post_name );
			if ( $slug !== '' ) {
				return substr( $slug, 0, 80 );
			}
		}
		return 'snippet';
	}

	private function getSnippetFilePath( \WP_Post $post, string $type ): string {
		$ext = $type === 'js' ? 'js' : 'css';
		return $this->getSnippetFileDir() . '/' . $this->getSnippetFileSlug( $post ) . '-' . $post->ID . '.' . $ext;
	}

	private function getSnippetFileUrl( \WP_Post $post, string $type ): string {
		$ext  = $type === 'js' ? 'js' : 'css';
		$slug = $this->getSnippetFileSlug( $post );
		return trailingslashit( WordPressPaths::uploadsUrl() ) . 'wp-powersuite/snippets/' . $slug . '-' . $post->ID . '.' . $ext;
	}

	/**
	 * Harden public JS/CSS asset directory: deny PHP execution/access.
	 */
	private function ensurePublicAssetDirSecurity( string $dir ): void {
		static $secured = false;
		if ( $secured ) {
			return;
		}
		$secured  = true;
		$htaccess = $dir . '/.htaccess';
		$rules    = '# ' . wpps_cs_brand_name() . ": public snippet assets — block PHP\n"
			. "<FilesMatch \"\\.(?i:php|phtml|phar|php\\d+)$\">\n"
			. "\tRequire all denied\n"
			. "</FilesMatch>\n"
			. "<IfModule !mod_authz_core.c>\n"
			. "\t<FilesMatch \"\\.(?i:php|phtml|phar|php\\d+)$\">\n"
			. "\t\tOrder deny,allow\n"
			. "\t\tDeny from all\n"
			. "\t</FilesMatch>\n"
			. "</IfModule>\n";
		if ( ! file_exists( $htaccess ) || @file_get_contents( $htaccess ) !== $rules ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
			@file_put_contents( $htaccess, $rules );
		}
		$webconfig = $dir . '/web.config';
		$iis       = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
			. "<configuration>\n"
			. "\t<system.webServer>\n"
			. "\t\t<security>\n"
			. "\t\t\t<requestFiltering>\n"
			. "\t\t\t\t<fileExtensions>\n"
			. "\t\t\t\t\t<add fileExtension=\".php\" allowed=\"false\" />\n"
			. "\t\t\t\t\t<add fileExtension=\".phtml\" allowed=\"false\" />\n"
			. "\t\t\t\t\t<add fileExtension=\".phar\" allowed=\"false\" />\n"
			. "\t\t\t\t</fileExtensions>\n"
			. "\t\t\t</requestFiltering>\n"
			. "\t\t</security>\n"
			. "\t</system.webServer>\n"
			. "</configuration>\n";
		if ( ! file_exists( $webconfig ) || @file_get_contents( $webconfig ) !== $iis ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
			@file_put_contents( $webconfig, $iis );
		}
		$nginx_readme = $dir . '/NGINX-SECURITY.txt';
		$nginx_note   = wpps_cs_brand_name() . " Code Snippet public assets\n\n"
			. "This folder must contain only .js / .css (and index.php / deny rules).\n"
			. "PHP/HTML includes use private storage outside the public site — never under wp-content.\n\n"
			. "Nginx: deny PHP under this path, for example:\n"
			. "  location ~* /wp-content/uploads/wp-powersuite/snippets/.*\\.(?i:php|phtml|phar)$ { deny all; return 404; }\n";
		if ( ! file_exists( $nginx_readme ) ) {
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
			@file_put_contents( $nginx_readme, $nginx_note );
		}
		$this->purgeLegacyPublicPhpSnippetFiles( $dir );
	}

	private function purgeLegacyPublicPhpSnippetFiles( string $public_dir ): void {
		static $purged = false;
		if ( $purged || ! is_dir( $public_dir ) ) {
			return;
		}
		$purged = true;
		foreach ( glob( trailingslashit( $public_dir ) . '*.php' ) ?: [] as $file ) {
			$base = basename( (string) $file );
			if ( $base === 'index.php' ) {
				continue;
			}
			if ( is_string( $file ) && is_file( $file ) ) {
				wp_delete_file( $file );
			}
		}
	}

	private function getPhpSnippetFilePath( \WP_Post $post ): string {
		$dir = SnippetPrivateStorage::getDir();
		if ( $dir === '' ) {
			return '';
		}
		return $dir . '/' . $this->getSnippetFileSlug( $post ) . '-' . $post->ID . '.' . SnippetPrivateStorage::FILE_EXT;
	}

	private function buildPhpSnippetFilePayload( \WP_Post $post ): string {
		$type = get_post_meta( $post->ID, '_wpps_code_type', true ) ?: 'html';
		$code = is_string( $post->post_content ) ? $post->post_content : '';
		if ( $type === 'php' ) {
			$code  = preg_replace( '/^\s*(?:(?:<' . '?php|<\?)\s*)+/i', '', $code );
			$close = chr( 63 ) . chr( 62 );
			$code  = preg_replace( '/\s*' . preg_quote( $close, '/' ) . '\s*$/', '', (string) $code );
			return '<' . '?php' . "\n" . trim( (string) $code ) . "\n";
		}
		return '<' . '?php echo ' . var_export( $code, true ) . ';' . "\n";
	}

	private function ensurePhpSnippetFile( \WP_Post $post ): bool {
		$type = get_post_meta( $post->ID, '_wpps_code_type', true ) ?: 'html';
		if ( ! in_array( $type, [ 'php', 'html' ], true ) ) {
			return false;
		}
		if ( ! SnippetPrivateStorage::isAvailable() ) {
			return false;
		}
		$file = $this->getPhpSnippetFilePath( $post );
		if ( $file === '' ) {
			return false;
		}
		$dir = dirname( $file );
		if ( ! is_dir( $dir ) || ! wp_is_writable( $dir ) ) {
			return false;
		}
		$payload = $this->buildPhpSnippetFilePayload( $post );
		if ( file_exists( $file ) && is_readable( $file ) ) {
			$existing = file_get_contents( $file );
			if ( is_string( $existing ) && hash_equals( hash( 'sha256', $existing ), hash( 'sha256', $payload ) ) ) {
				$this->cleanupOrphanSnippetFilesForPost( $post );
				return true;
			}
		}
		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
		$ok = false !== file_put_contents( $file, $payload );
		if ( $ok ) {
			// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_operations_chmod -- owner-only perms on private PHP snippet files.
			@chmod( $file, 0600 );
			$this->cleanupOrphanSnippetFilesForPost( $post );
		}
		return $ok;
	}

	private function cleanupOrphanSnippetFilesForPost( \WP_Post $post ): void {
		$id        = (int) $post->ID;
		$canonical = $this->getPhpSnippetFilePath( $post );
		$canonical = $canonical !== '' ? wp_normalize_path( $canonical ) : '';

		$dirs = array_filter(
			[
				SnippetPrivateStorage::getDir(),
				SnippetPrivateStorage::legacyPublicPhpDir(),
				SnippetPrivateStorage::legacyWebFallbackDir(),
			]
		);
		foreach ( $dirs as $dir ) {
			if ( ! is_dir( $dir ) ) {
				continue;
			}
			foreach ( [ SnippetPrivateStorage::FILE_EXT, 'php' ] as $ext ) {
				foreach ( glob( trailingslashit( $dir ) . '*-' . $id . '.' . $ext ) ?: [] as $file ) {
					if ( ! is_string( $file ) || ! is_file( $file ) ) {
						continue;
					}
					if ( $canonical !== '' && strcasecmp( wp_normalize_path( $file ), $canonical ) === 0 ) {
						continue;
					}
					wp_delete_file( $file );
				}
			}
		}

		$public = $this->getSnippetFileDir();
		if ( ! is_dir( $public ) ) {
			return;
		}
		foreach ( [ 'js', 'css', 'php' ] as $ext ) {
			$keep = ( $ext === 'js' || $ext === 'css' )
				? wp_normalize_path( $this->getSnippetFilePath( $post, $ext ) )
				: '';
			foreach ( glob( trailingslashit( $public ) . '*-' . $id . '.' . $ext ) ?: [] as $file ) {
				if ( ! is_string( $file ) || ! is_file( $file ) ) {
					continue;
				}
				$norm = wp_normalize_path( $file );
				if ( $keep !== '' && strcasecmp( $norm, $keep ) === 0 ) {
					continue;
				}
				wp_delete_file( $file );
			}
		}
	}

	/**
	 * Load and execute PHP snippet from file.
	 *
	 * @param string   $file File path.
	 * @param \WP_Post $post Snippet post.
	 * @return string Output.
	 */
	private function loadPhpFromFile( string $file, \WP_Post $post ): string {
		if ( ! class_exists( PremiumPhpJsRuntime::class, false ) ) {
			return '';
		}
		$resolved = $this->resolveAllowedPhpSnippetFile( $file );
		if ( $resolved === '' ) {
			return '';
		}
		$scan_code = $this->getPhpBodyFromSnippetFile( $resolved );
		if ( $scan_code === '' || $this->isCodeNotAllowed( $scan_code ) ) {
			return '';
		}
		$this->last_executed_php_snippet = $post;
		$this->indexPhpSnippetFile( $resolved, $post );
		ob_start();
		try {
			PremiumPhpJsRuntime::includeResolvedFile( $resolved );
		} catch ( \Throwable $e ) {
			ob_end_clean();
			$this->logSnippetError(
				$post,
				$e,
				[
					'merge_context' => 'php_file_include',
					'eval_line'     => $e->getLine(),
					'snippet_line'  => $e->getLine(),
				]
			);
			if ( $this->shouldAutoDeactivateSnippetForPhpError( $post ) ) {
				wp_update_post( [ 'ID' => $post->ID, 'post_status' => 'draft' ] );
				update_post_meta( $post->ID, '_wpps_auto_deactivated', time() );
				update_post_meta( $post->ID, '_wpps_auto_deactivated_error', $e->getMessage() );
				$this->bustSnippetCaches();
				$this->notifyAutoDeactivateInAdmin( $post, $e->getMessage() );
			}
			return '';
		}
		$this->last_executed_php_snippet = null;
		$out = ob_get_clean();
		$out = apply_filters( 'wpps_code_snippet_after_php_eval', is_string( $out ) ? $out : '', $post, 'php_file_include' );
		return is_string( $out ) ? $out : '';
	}

	/**
	 * Check if snippet should load from file (global setting + type).
	 */
	private function shouldLoadPhpFromFile( \WP_Post $post ): bool {
		if ( ! class_exists( PremiumPhpJsRuntime::class, false ) ) {
			return false;
		}
		if ( ! SnippetPrivateStorage::isAvailable() ) {
			return false;
		}
		$type = get_post_meta( $post->ID, '_wpps_code_type', true ) ?: 'html';
		if ( ! in_array( $type, [ 'php', 'html' ], true ) ) {
			return false;
		}
		if ( get_post_meta( $post->ID, '_wpps_load_as_file', true ) === '1' ) {
			return true;
		}
		$auto = get_post_meta( $post->ID, '_wpps_auto_insert', true ) === '1';
		if ( ! $auto ) {
			return false;
		}
		if ( self::getSetting( 'load_snippets_as_files', false ) ) {
			return true;
		}
		// Mixed PHP/HTML templates (ob_start with inline markup) — same class as file-based PHP execution.
		if ( $type === 'php' && is_string( $post->post_content ) && strpos( $post->post_content, chr( 63 ) . chr( 62 ) ) !== false ) {
			return true;
		}
		return false;
	}

	private function ensurePhpSnippetFileIfNeeded( \WP_Post $post ): bool {
		if ( ! $this->shouldLoadPhpFromFile( $post ) ) {
			return false;
		}
		return $this->ensurePhpSnippetFile( $post );
	}

	private function resolveAllowedPhpSnippetFile( string $file ): string {
		if ( ! SnippetPrivateStorage::isPathAllowed( $file ) ) {
			return '';
		}
		$resolved = realpath( $file );
		return $resolved ? wp_normalize_path( $resolved ) : '';
	}

	private function ensureSnippetFile( \WP_Post $post, string $type, string $code ): bool {
		if ( ! in_array( $type, [ 'js', 'css' ], true ) ) {
			return false;
		}
		$file = $this->getSnippetFilePath( $post, $type );
		if ( ! $file || ! wp_is_writable( dirname( $file ) ) ) {
			return false;
		}
		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- JS/CSS only, under uploads/wp-powersuite/snippets.
		return false !== file_put_contents( $file, $code );
	}

	/**
	 * Start output buffering only for body snippets (when theme doesn't support wp_body_open).
	 * Element selector snippets use client-side JS injection to avoid DOMDocument issues.
	 */
	public function maybeStartElementBuffer(): void {
		$body = $this->getSnippetsForLocation( 'body' );
		if ( empty( $body ) ) {
			return;
		}
		ob_start( [ $this, 'processElementBuffer' ] );
	}

	/**
	 * Process buffered HTML and inject snippets before/after target elements.
	 *
	 * @param string $buffer Full page HTML.
	 * @return string Modified HTML.
	 */
	public function processElementBuffer( string $buffer ): string {
		try {
			return $this->processElementBufferInner( $buffer );
		} catch ( \Throwable $e ) {
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				error_log(
					sprintf(
						wpps_cs_brand_name() . ' Code Snippet: processElementBuffer failed: %s in %s:%d',
						$e->getMessage(),
						$e->getFile(),
						$e->getLine()
					)
				);
			}
			return $buffer;
		}
	}

	/**
	 * Inner logic for processElementBuffer (wrapped in try-catch by caller).
	 *
	 * @param string $buffer Full page HTML.
	 * @return string Modified HTML.
	 */
	private function processElementBufferInner( string $buffer ): string {
		if ( $buffer === '' || strlen( $buffer ) < 50 ) {
			return $buffer;
		}
		$body_snippets = $this->getSnippetsForLocation( 'body' );

		// Inject body snippets right after <body> (only if wp_body_open didn't run - themes that don't support it).
		if ( ! $this->body_snippets_output_via_hook && ! empty( $body_snippets ) && preg_match( '/<body[^>]*>/i', $buffer ) ) {
			$body_out = '';
			$this->output_location_stack[] = 'body';
			foreach ( $body_snippets as $post ) {
				// File-based assets are already enqueued — skip to avoid double output.
				if ( $this->isLoadAsFile( $post ) ) {
					continue;
				}
				$out = $this->executeSnippet( $post );
				if ( $out !== '' ) {
					$body_out .= "\n<!-- " . esc_attr( wpps_cs_brand_name() ) . ' Code Snippet: ' . esc_attr( $post->post_title ) . " -->\n";
					$body_out .= $out;
					$body_out .= "\n<!-- /" . esc_attr( wpps_cs_brand_name() ) . " -->\n";
				}
			}
			if ( $body_out !== '' ) {
				$buffer = preg_replace( '/(<body[^>]*>)/i', '$1' . $body_out, $buffer, 1 );
			}
			array_pop( $this->output_location_stack );
		}

		// Element selector snippets are injected via JS in outputElementSelectorSnippets.
		return $buffer;
	}

	/**
	 * Check if a snippet is within its schedule window.
	 *
	 * @param \WP_Post $post Snippet post.
	 * @return bool True if snippet should run (no schedule or within window).
	 */
	private function isSnippetScheduled( \WP_Post $post ): bool {
		$enabled = get_post_meta( $post->ID, '_wpps_schedule_enabled', true ) === '1';
		if ( ! $enabled ) {
			return true;
		}
		$start = get_post_meta( $post->ID, '_wpps_schedule_start', true );
		$end   = get_post_meta( $post->ID, '_wpps_schedule_end', true );
		$tz    = wp_timezone();
		$now   = time();
		if ( is_string( $start ) && $start !== '' ) {
			$start_ts = $this->scheduleStringToTimestamp( $start, $tz );
			if ( $start_ts !== null && $now < $start_ts ) {
				return false;
			}
		}
		if ( is_string( $end ) && $end !== '' ) {
			$end_ts = $this->scheduleStringToTimestamp( $end, $tz );
			if ( $end_ts !== null && $now > $end_ts ) {
				return false;
			}
		}
		return true;
	}

	/**
	 * Parse a datetime-local schedule string (e.g. "2026-06-21T19:30") in the site
	 * timezone and return its UTC epoch timestamp, comparable against time().
	 *
	 * @return int|null Timestamp, or null when the value cannot be parsed.
	 */
	private function scheduleStringToTimestamp( string $value, \DateTimeZone $tz ): ?int {
		$value = trim( str_replace( 'T', ' ', $value ) );
		if ( $value === '' ) {
			return null;
		}
		try {
			$dt = new \DateTimeImmutable( $value, $tz );
		} catch ( \Exception $e ) {
			return null;
		}
		return $dt->getTimestamp();
	}

	/**
	 * Whether any enabled rule needs the resolved main query (Type of Page / Post Type).
	 *
	 * @param \WP_Post $post Snippet post.
	 * @return bool
	 */
	private function conditionalRulesNeedQuery( \WP_Post $post ): bool {
		if ( ! class_exists( PremiumTargeting::class, false ) || ! self::isProLicensed() ) {
			return false;
		}
		return PremiumTargeting::conditionalRulesNeedQuery( $post );
	}

	/**
	 * Postpone PHP-location snippets whose rules cannot be judged before the `wp` hook.
	 *
	 * Page and post-type rules have no answer at plugins_loaded / admin_init, so evaluating
	 * them there would either suppress the snippet or (with "rules do NOT match") invert to
	 * always-run. On the frontend the snippet is queued for `wp`; admin requests have no main
	 * query to wait for, so the snippet is skipped instead of running against the rule.
	 *
	 * @return bool True when the caller must skip this snippet for now.
	 */
	private function maybeDeferForQueryConditionals( \WP_Post $post, string $location ): bool {
		if ( did_action( 'wp' ) || ! $this->conditionalRulesNeedQuery( $post ) ) {
			return false;
		}
		if ( is_admin() ) {
			return true;
		}
		$this->deferred_query_conditional[ $post->ID ] = $location;
		if ( ! $this->deferred_query_hook_added ) {
			$this->deferred_query_hook_added = true;
			add_action( 'wp', [ $this, 'runDeferredQueryConditionalSnippets' ], 1 );
		}
		return true;
	}

	/**
	 * Run snippets postponed by {@see maybeDeferForQueryConditionals()} now that the query exists.
	 */
	public function runDeferredQueryConditionalSnippets(): void {
		if ( $this->deferred_query_conditional === [] ) {
			return;
		}
		$queue                            = $this->deferred_query_conditional;
		$this->deferred_query_conditional = [];
		foreach ( $queue as $post_id => $location ) {
			$post = get_post( (int) $post_id );
			if ( ! $post instanceof \WP_Post || $post->post_status !== 'publish' ) {
				continue;
			}
			if ( get_post_meta( $post->ID, '_wpps_code_type', true ) !== 'php' ) {
				continue;
			}
			if ( ! $this->passesProLicense( $post ) || ! $this->passesConditionalLogic( $post ) || ! $this->passesDeviceCheck( $post ) || ! $this->isSnippetScheduled( $post ) ) {
				continue;
			}
			$this->output_location_stack[] = $location;
			if ( $location === 'frontend_only' ) {
				$output = $this->executeSnippet( $post );
				if ( $output !== '' ) {
					$this->deferFrontendOnlyOutput( $post->post_title, $output );
				}
			} else {
				$this->runPhpSnippetSideEffects( $post, $location );
			}
			array_pop( $this->output_location_stack );
		}
	}

	/**
	 * Execute one PHP snippet for its side effects only (hook registration, no output).
	 */
	private function runPhpSnippetSideEffects( \WP_Post $post, string $location ): void {
		if ( $this->shouldLoadPhpFromFile( $post ) ) {
			$this->ensurePhpSnippetFileIfNeeded( $post );
			$file = $this->getPhpSnippetFilePath( $post );
			if ( file_exists( $file ) ) {
				$this->loadPhpFromFile( $file, $post );
				do_action( 'wpps_snippet_loaded', $post, $location );
				return;
			}
		}
		$code = $this->getPhpCodeForExecution( $post );
		if ( ! is_string( $code ) || $code === '' ) {
			return;
		}
		$code = apply_filters( 'wpps_code_snippet_php_before_eval', $code, $post, 'single' );
		if ( ! is_string( $code ) || $this->isPhpExecutionBlocked( $code ) ) {
			return;
		}
		if ( $this->safeExecutePhpSideEffects( $code, $post, 'run_everywhere_admin' ) ) {
			do_action( 'wpps_snippet_loaded', $post, $location );
		}
	}

	/**
	 * Check if snippet passes conditional logic rules.
	 *
	 * @param \WP_Post $post Snippet post.
	 * @return bool
	 */
	private function passesConditionalLogic( \WP_Post $post ): bool {
		if ( ! class_exists( PremiumTargeting::class, false ) || ! self::isProLicensed() ) {
			return true;
		}
		return PremiumTargeting::passesConditionalLogic( $post );
	}

	/**
	 * Sanitize conditional rules from POST (supports groups or flat).
	 *
	 * @param array $raw Raw rules from request.
	 * @return array Sanitized rules with 'show' and 'groups'.
	 */
	private function sanitizeConditionalRules( array $raw ): array {
		$sanitize_rule = function ( $r ) {
			$type = sanitize_key( $r['type'] ?? 'url' );
			if ( ! ConditionalCatalog::isKnownType( $type ) ) {
				$type = 'url';
			}
			$operator = sanitize_key( $r['operator'] ?? 'contains' );
			if ( ! in_array( $operator, ConditionalCatalog::OPERATORS, true ) ) {
				$operator = 'contains';
			}
			$key = isset( $r['key'] ) ? sanitize_text_field( (string) $r['key'] ) : '';
			$key = preg_replace( '/[^a-zA-Z0-9_\-]/', '', $key );
			if ( strlen( $key ) > 64 ) {
				$key = substr( $key, 0, 64 );
			}
			$value = sanitize_text_field( (string) ( $r['value'] ?? '' ) );
			if ( strlen( $value ) > 200 ) {
				$value = substr( $value, 0, 200 );
			}
			return [
				'type'     => $type,
				'operator' => $operator,
				'key'      => $key,
				'value'    => $value,
			];
		};
		if ( isset( $raw['groups'] ) && is_array( $raw['groups'] ) ) {
			$groups = [];
			foreach ( array_slice( $raw['groups'], 0, 10 ) as $group ) {
				if ( ! is_array( $group ) ) {
					continue;
				}
				$rules_in_group = [];
				foreach ( array_slice( $group, 0, 20 ) as $r ) {
					if ( is_array( $r ) && isset( $r['type'] ) ) {
						$rules_in_group[] = $sanitize_rule( $r );
					}
				}
				if ( ! empty( $rules_in_group ) ) {
					$groups[] = $rules_in_group;
				}
			}
			return [
				'show'   => isset( $raw['show'] ) && $raw['show'] === '0' ? '0' : '1',
				'groups' => ! empty( $groups ) ? $groups : [ [ $sanitize_rule( [ 'type' => 'url', 'operator' => 'contains', 'value' => '' ] ) ] ],
			];
		}
		$flat = [];
		foreach ( array_slice( $raw, 0, 20 ) as $r ) {
			if ( is_array( $r ) && isset( $r['type'] ) ) {
				$flat[] = $sanitize_rule( $r );
			}
		}
		return [
			'show'   => '1',
			'groups' => ! empty( $flat ) ? [ $flat ] : [ [ $sanitize_rule( [ 'type' => 'url', 'operator' => 'contains', 'value' => '' ] ) ] ],
		];
	}

	/**
	 * Check if snippet passes device type restriction.
	 *
	 * @param \WP_Post $post Snippet post.
	 * @return bool
	 */
	private function passesDeviceCheck( \WP_Post $post ): bool {
		if ( ! class_exists( PremiumTargeting::class, false ) || ! self::isProLicensed() ) {
			return true;
		}
		return PremiumTargeting::passesDeviceCheck( $post );
	}

	/**
	 * Execute a snippet and return its output.
	 *
	 * @param \WP_Post|int $snippet Post or ID.
	 * @return string
	 */
	public function executeSnippet( $snippet ): string {
		if ( ! apply_filters( 'wpps_do_auto_insert', true ) ) {
			return '';
		}
		$post = $snippet instanceof \WP_Post ? $snippet : get_post( $snippet );
		if ( ! $post || $post->post_type !== self::POST_TYPE || $post->post_status !== 'publish' ) {
			return '';
		}

		if ( ! $this->passesProLicense( $post ) ) {
			return '';
		}

		if ( ! $this->isSnippetScheduled( $post ) ) {
			return '';
		}

		if ( ! $this->passesConditionalLogic( $post ) ) {
			return '';
		}

		if ( ! $this->passesDeviceCheck( $post ) ) {
			return '';
		}

		$code = $post->post_content;
		$type = get_post_meta( $post->ID, '_wpps_code_type', true ) ?: 'html';

		// Set global so user PHP snippets can access current location (e.g. header, body, footer).
		$loc = $this->getCurrentOutputLocation();
		if ( $loc === '' ) {
			$loc = get_post_meta( $post->ID, '_wpps_location', true ) ?: '';
		}
		$GLOBALS['wpps_location'] = $loc;

		$output = $this->executeByType( $code, $type, $post );
		// PHP can run with empty output. HTML/JS/CSS "loaded" with no markup means it was dropped.
		if ( $type === 'php' || ( is_string( $output ) && $output !== '' ) ) {
			do_action( 'wpps_snippet_loaded', $post, $loc );
		}
		return $output;
	}

	private function executeByType( string $code, string $type, \WP_Post $post ): string {
		if ( in_array( $type, [ 'php', 'html' ], true ) && $this->shouldLoadPhpFromFile( $post ) ) {
			$this->ensurePhpSnippetFileIfNeeded( $post );
			// HTML is markup, not PHP. Including the echo-wrapper file runs it through the
			// PHP threat scanner, which treats JS template literals (`...`) as shell backticks
			// and silently drops the snippet. Print HTML the same way WPCode does.
			if ( $type === 'html' ) {
				return apply_filters( 'wpps_code_snippet_output', $code, $type, $post );
			}
			$file = $this->getPhpSnippetFilePath( $post );
			if ( $file !== '' && file_exists( $file ) ) {
				$out = $this->loadPhpFromFile( $file, $post );
				return apply_filters( 'wpps_code_snippet_output', $out, $type, $post );
			}
		}

		$code = apply_filters( 'wpps_code_snippet_output', $code, $type, $post );
		if ( ! is_string( $code ) || trim( $code ) === '' ) {
			return '';
		}

		switch ( $type ) {
			case 'php':
				if ( ! self::canRunProCodeTypes() ) {
					return '';
				}
				return $this->safeExecutePhp( $code, $post );
			case 'js':
				if ( ! self::canRunProCodeTypes() ) {
					return '';
				}
				return PremiumPhpJsRuntime::wrapJs( $code, 'wpps-cs-js-' . (int) $post->ID );
			case 'css':
				\WP_PowerSuite\Core\InlineAssets::styleNow( 'wpps-cs-css-' . (int) $post->ID, $code );
				return '';
			case 'html':
			default:
				return $code;
		}
	}

	/**
	 * Get raw PHP code for execution (stripped of tags).
	 *
	 * @param \WP_Post $post Snippet post.
	 * @return string
	 */
	private function getPhpCodeForExecution( \WP_Post $post ): string {
		$code = $post->post_content;
		$code = preg_replace( '/^\s*(?:(?:<' . '?php|<\?)\s*)+/i', '', $code );
		$close = chr( 63 ) . chr( 62 );
		$code = preg_replace( '/\s*' . preg_quote( $close, '/' ) . '\s*$/', '', $code );
		$code = trim( $code );
		if ( $code === '' || $this->isCodeNotAllowed( $code ) ) {
			return '';
		}
		$code = apply_filters( 'wpps_code_snippet_output', $code, 'php', $post );
		if ( $this->isPhpExecutionBlocked( $code ) ) {
			return '';
		}
		return $code;
	}

	/**
	 * Build one eval string and a line map (1-based lines in merged code) per snippet ID.
	 *
	 * @param array<int, array{post: \WP_Post, code: string}> $items Ordered merge items.
	 * @return array{code: string, line_map: array<int, array{start:int,end:int}>, last_post: ?\WP_Post}
	 */
	private function buildMergedPhpStringAndLineMap( array $items ): array {
		$line_map   = [];
		$parts      = [];
		$line       = 1;
		$last_post  = null;
		foreach ( $items as $item ) {
			$post = $item['post'];
			$code = $item['code'];
			if ( ! $post instanceof \WP_Post || ! is_string( $code ) || $code === '' ) {
				continue;
			}
			$last_post    = $post;
			$num_lines    = substr_count( $code, "\n" ) + 1;
			$start        = $line;
			$end          = $line + $num_lines - 1;
			$line_map[ $post->ID ] = [ 'start' => $start, 'end' => $end ];
			$parts[]      = $code;
			$line         = $end + 1;
		}
		return [
			'code'     => implode( "\n", $parts ),
			'line_map' => $line_map,
			'last_post' => $last_post,
		];
	}

	/**
	 * @param array<int, array{start:int,end:int}> $line_map
	 */
	private function resolvePostFromMergedPhpLine( int $eval_line, array $line_map ): ?\WP_Post {
		if ( $eval_line < 1 || $line_map === [] ) {
			return null;
		}
		foreach ( $line_map as $snippet_id => $range ) {
			if ( $eval_line >= $range['start'] && $eval_line <= $range['end'] ) {
				$p = get_post( (int) $snippet_id );
				return ( $p && $p->post_type === self::POST_TYPE ) ? $p : null;
			}
		}
		return null;
	}

	/**
	 * Locations where a PHP error moves the snippet to draft.
	 *
	 * @return string[]
	 */
	private function phpErrorAutoDeactivateLocations(): array {
		$default = self::getAllLocationSlugs();
		$locs    = apply_filters( 'wpps_code_snippet_php_auto_deactivate_locations', $default );
		if ( ! is_array( $locs ) ) {
			return $default;
		}
		$out = [];
		foreach ( $locs as $x ) {
			if ( is_string( $x ) && $x !== '' ) {
				$out[] = $x;
			}
		}
		return $out !== [] ? array_values( array_unique( $out ) ) : $default;
	}

	private function shouldAutoDeactivateSnippetForPhpError( \WP_Post $post ): bool {
		$type = get_post_meta( $post->ID, '_wpps_code_type', true ) ?: 'html';
		if ( $type !== 'php' ) {
			return false;
		}
		$loc = get_post_meta( $post->ID, '_wpps_location', true ) ?: '';
		return in_array( $loc, $this->phpErrorAutoDeactivateLocations(), true );
	}

	/**
	 * Return an error message when a snippet must not be activated, or null if OK.
	 *
	 * @param \WP_Post $post Snippet post.
	 * @return string|null
	 */
	private function getSnippetActivationBlockReason( \WP_Post $post ): ?string {
		if ( $post->post_type !== self::POST_TYPE ) {
			return __( 'Invalid snippet.', 'wppowersuite-lite' );
		}
		$pro_block = $this->getProLicenseBlockReason( $post );
		if ( $pro_block !== null ) {
			return $pro_block;
		}
		$type = get_post_meta( $post->ID, '_wpps_code_type', true ) ?: 'html';
		if ( $type !== 'php' ) {
			return null;
		}
		$code = is_string( $post->post_content ) ? $post->post_content : '';
		$syntax_err = self::checkPhpSyntax( $code );
		if ( $syntax_err !== null ) {
			return __( 'PHP syntax error:', 'wppowersuite-lite' ) . ' ' . $syntax_err;
		}
		$runtime_err = $this->testPhpSnippetRuntime( $code );
		if ( $runtime_err !== null ) {
			return __( 'PHP error:', 'wppowersuite-lite' ) . ' ' . $runtime_err;
		}
		return null;
	}

	/**
	 * Validate code type vs insertion location on save.
	 *
	 * @return string|null Error message or null.
	 */
	private function validateTypeLocationPair( string $type, string $loc ): ?string {
		if ( in_array( $loc, self::getPhpOnlyLocations(), true ) && $type !== 'php' ) {
			return __( 'This location requires a PHP snippet.', 'wppowersuite-lite' );
		}
		if ( in_array( $loc, self::getWooLocations(), true ) && ! class_exists( 'WooCommerce' ) ) {
			return __( 'This location requires WooCommerce.', 'wppowersuite-lite' );
		}
		return null;
	}

	/**
	 * Sanitize CSS selector for element-based insertion (reject script-like characters).
	 */
	private function sanitizeLocationSelector( string $selector ): string {
		$selector = trim( $selector );
		if ( $selector === '' || preg_match( '/[<>{}]/', $selector ) ) {
			return '';
		}
		return sanitize_text_field( $selector );
	}

	/**
	 * Normalize a custom shortcode slug (shared by create/update/restore).
	 */
	private function sanitizeCustomShortcode( string $custom ): string {
		return (string) preg_replace( '/[^a-z0-9_]/', '', strtolower( sanitize_key( $custom ) ) );
	}

	/**
	 * Validate custom shortcode slug uniqueness and reserved names.
	 * Used by create, update, and revision restore — keep as the single gate.
	 *
	 * @return string|null Error message or null.
	 */
	private function validateCustomShortcode( string $custom, int $exclude_id = 0 ): ?string {
		$custom = $this->sanitizeCustomShortcode( $custom );
		if ( $custom === '' ) {
			return null;
		}
		if ( in_array( $custom, [ 'wpps_code' ], true ) ) {
			return __( 'This shortcode name is reserved.', 'wppowersuite-lite' );
		}
		$existing_id = $this->findSnippetIdByCustomShortcode( $custom );
		if ( $existing_id !== null && ( $exclude_id <= 0 || $existing_id !== $exclude_id ) ) {
			return __( 'Another snippet already uses this custom shortcode.', 'wppowersuite-lite' );
		}
		if ( shortcode_exists( $custom ) ) {
			return __( 'This shortcode name is already registered on your site.', 'wppowersuite-lite' );
		}
		return null;
	}

	/**
	 * Find snippet post ID by custom shortcode meta.
	 */
	private function findSnippetIdByCustomShortcode( string $custom ): ?int {
		$query = new \WP_Query(
			[
				'post_type'      => self::POST_TYPE,
				'post_status'    => 'any',
				'posts_per_page' => 1,
				'fields'         => 'ids',
				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- resolve one snippet by custom shortcode.
				'meta_query'     => [
					[
						'key'   => '_wpps_custom_shortcode',
						'value' => $custom,
					],
				],
			]
		);
		if ( empty( $query->posts ) ) {
			return null;
		}
		return (int) $query->posts[0];
	}

	/**
	 * Store last PHP error JSON on the snippet for the editor (optional diagnostics).
	 *
	 * @param array<string, mixed> $context
	 */
	private function recordSnippetLastPhpError( \WP_Post $post, string $message, array $context = [] ): void {
		$payload = [
			'time'    => current_time( 'mysql' ),
			'message' => $message,
			'context' => $context,
		];
		update_post_meta( $post->ID, self::LAST_PHP_ERROR_META, wp_json_encode( $payload ) );
	}

	/**
	 * Execute merged PHP code (Run Everywhere + Admin Only + optional Frontend Only merge).
	 *
	/**
	 * Run user snippet PHP via the Pro overlay runtime. No-op in Lite.
	 */
	private function evalSnippetPhp( string $code ): void {
		if ( $code === '' || ! class_exists( PremiumPhpJsRuntime::class, false ) ) {
			return;
		}
		$post = $this->last_executed_php_snippet;
		PremiumPhpJsRuntime::run(
			$code,
			function ( string $file ) use ( $post ) {
				if ( $post instanceof \WP_Post ) {
					$this->indexPhpSnippetFile( $file, $post );
				}
			}
		);
	}

	private function indexPhpSnippetFile( string $file, \WP_Post $post ): void {
		$norm = wp_normalize_path( $file );
		if ( $norm !== '' ) {
			$this->php_snippet_file_index[ $norm ] = (int) $post->ID;
		}
		$real = realpath( $file );
		if ( is_string( $real ) && $real !== '' ) {
			$this->php_snippet_file_index[ wp_normalize_path( $real ) ] = (int) $post->ID;
		}
		$this->php_snippets_ran[ (int) $post->ID ] = $post;
	}

	/**
	 * Attribute a shutdown/uncaught error to the snippet that defined the throwing code.
	 *
	 * @param array<string, mixed> $error error_get_last() shape.
	 */
	private function resolveSnippetPostFromError( array $error ): ?\WP_Post {
		$file = isset( $error['file'] ) ? wp_normalize_path( (string) $error['file'] ) : '';
		if ( $file !== '' ) {
			if ( isset( $this->php_snippet_file_index[ $file ] ) ) {
				$p = get_post( $this->php_snippet_file_index[ $file ] );
				if ( $p && $p->post_type === self::POST_TYPE ) {
					return $p;
				}
			}
			$real = realpath( $file );
			if ( is_string( $real ) && $real !== '' ) {
				$norm = wp_normalize_path( $real );
				if ( isset( $this->php_snippet_file_index[ $norm ] ) ) {
					$p = get_post( $this->php_snippet_file_index[ $norm ] );
					if ( $p && $p->post_type === self::POST_TYPE ) {
						return $p;
					}
				}
			}
			if ( preg_match( '/-(\d+)\.[a-z0-9]+$/i', basename( $file ), $m ) ) {
				$p = get_post( (int) $m[1] );
				if ( $p && $p->post_type === self::POST_TYPE ) {
					return $p;
				}
			}
		}
		if ( $this->merged_php_line_map !== [] ) {
			$eval_line = isset( $error['line'] ) ? (int) $error['line'] : 0;
			$from_map  = $this->resolvePostFromMergedPhpLine( $eval_line, $this->merged_php_line_map );
			if ( $from_map instanceof \WP_Post ) {
				return $from_map;
			}
		}
		if ( $this->last_executed_php_snippet instanceof \WP_Post ) {
			return $this->last_executed_php_snippet;
		}
		if ( count( $this->php_snippets_ran ) === 1 ) {
			$only = reset( $this->php_snippets_ran );
			return $only instanceof \WP_Post ? $only : null;
		}
		return null;
	}

	/**
	 * Write snippet PHP to a temp file for include-based execution.
	 */
	private function createTempPhpSnippetFile( string $code ): string {
		if ( ! class_exists( PremiumPhpJsRuntime::class, false ) ) {
			return '';
		}
		return PremiumPhpJsRuntime::createTempPhpSnippetFile( $code );
	}

	/**
	 * Run hook-registration PHP (no output capture). One snippet per call.
	 */
	private function safeExecutePhpSideEffects( string $code, \WP_Post $post, string $context = 'side_effects' ): bool {
		if ( $this->isPhpExecutionBlocked( $code ) ) {
			return true;
		}

		$this->last_executed_php_snippet = $post;
		try {
			$this->evalSnippetPhp( $code );
		} catch ( \Throwable $e ) {
			$this->logSnippetError(
				$post,
				$e,
				[
					'merge_context' => $context,
					'eval_line'     => $e->getLine(),
					'snippet_line'  => $e->getLine(),
				]
			);
			if ( $this->shouldAutoDeactivateSnippetForPhpError( $post ) ) {
				wp_update_post( [ 'ID' => $post->ID, 'post_status' => 'draft' ] );
				update_post_meta( $post->ID, '_wpps_auto_deactivated', time() );
				update_post_meta( $post->ID, '_wpps_auto_deactivated_error', $e->getMessage() );
				$this->bustSnippetCaches();
				$this->notifyAutoDeactivateInAdmin( $post, $e->getMessage() );
			}
			$this->last_executed_php_snippet = null;
			return false;
		}
		$this->last_executed_php_snippet = null;
		return true;
	}

	/**
	 * Clear stored auto-deactivation / last-error state for a snippet.
	 *
	 * The "automatically deactivated due to a PHP error" notice is driven entirely by
	 * stored post meta and persists until cleared. We call this when a snippet is
	 * successfully (re)activated so a resolved error stops nagging the user.
	 */
	private function clearSnippetErrorState( int $post_id ): void {
		delete_post_meta( $post_id, '_wpps_auto_deactivated' );
		delete_post_meta( $post_id, '_wpps_auto_deactivated_error' );
		delete_post_meta( $post_id, self::LAST_PHP_ERROR_META );
	}

	private function safeExecutePhpMerged( string $code, \WP_Post $fallback, array $line_map, string $context = 'merged' ): bool {
		if ( $this->isPhpExecutionBlocked( $code ) ) {
			return true;
		}
		$this->merged_php_line_map        = $line_map;
		$this->last_executed_php_snippet  = $fallback;
		try {
			$this->evalSnippetPhp( $code );
		} catch ( \Throwable $e ) {
			$at_line = $e->getLine();
			$post    = $this->resolvePostFromMergedPhpLine( $at_line, $line_map ) ?? $fallback;
			$rel     = null;
			if ( isset( $line_map[ $post->ID ] ) ) {
				$rel = $at_line - $line_map[ $post->ID ]['start'] + 1;
			}
			$this->logSnippetError(
				$post,
				$e,
				[
					'merge_context' => $context,
					'eval_line'     => $at_line,
					'snippet_line'  => $rel,
				]
			);
			if ( $this->shouldAutoDeactivateSnippetForPhpError( $post ) ) {
				wp_update_post( [ 'ID' => $post->ID, 'post_status' => 'draft' ] );
				update_post_meta( $post->ID, '_wpps_auto_deactivated', time() );
				update_post_meta( $post->ID, '_wpps_auto_deactivated_error', $e->getMessage() );
				$this->bustSnippetCaches();
				$this->notifyAutoDeactivateInAdmin( $post, $e->getMessage() );
			}
			$this->merged_php_line_map       = [];
			$this->last_executed_php_snippet = null;
			return false;
		}
		$this->merged_php_line_map        = [];
		$this->last_executed_php_snippet  = null;
		return true;
	}

	private function safeExecutePhp( string $code, \WP_Post $post ): string {
		// Strip PHP opening/closing tags — eval expects raw PHP only.
		$code = preg_replace( '/^\s*(?:(?:<' . '?php|<\?)\s*)+/i', '', $code );
		$close = chr( 63 ) . chr( 62 );
		$code = preg_replace( '/\s*' . preg_quote( $close, '/' ) . '\s*$/', '', $code );
		$code = trim( $code );
		if ( $code === '' ) {
			return '';
		}

		if ( $this->isCodeNotAllowed( $code ) ) {
			return '';
		}

		$code = apply_filters( 'wpps_code_snippet_php_before_eval', $code, $post, 'single' );
		if ( $this->isPhpExecutionBlocked( $code ) ) {
			return '';
		}

		$this->last_executed_php_snippet = $post;
		ob_start();
		try {
			$this->evalSnippetPhp( $code );
		} catch ( \Throwable $e ) {
			ob_end_clean();
			$this->logSnippetError(
				$post,
				$e,
				[
					'merge_context' => 'single',
					'eval_line'     => $e->getLine(),
					'snippet_line'  => $e->getLine(),
				]
			);
			if ( $this->shouldAutoDeactivateSnippetForPhpError( $post ) ) {
				wp_update_post( [ 'ID' => $post->ID, 'post_status' => 'draft' ] );
				update_post_meta( $post->ID, '_wpps_auto_deactivated', time() );
				update_post_meta( $post->ID, '_wpps_auto_deactivated_error', $e->getMessage() );
				$this->bustSnippetCaches();
				$this->notifyAutoDeactivateInAdmin( $post, $e->getMessage() );
			}
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				return '<!-- ' . esc_html( wpps_cs_brand_name() ) . ' PHP Error: ' . esc_html( $e->getMessage() ) . ' -->';
			}
			return '';
		}
		$this->last_executed_php_snippet = null;
		$out = ob_get_clean();
		$out = apply_filters( 'wpps_code_snippet_after_php_eval', $out, $post, 'single' );
		return apply_filters( 'wpps_code_snippet_output', is_string( $out ) ? $out : '', 'php', $post );
	}

	/**
	 * Shutdown handler: catch fatal errors from PHP snippets and auto-deactivate.
	 *
	 * @return void
	 */
	public function maybeDisableSnippetFromShutdown(): void {
		$error = error_get_last();
		if ( ! $error || ! isset( $error['type'], $error['message'] ) ) {
			return;
		}
		if ( $error['type'] === E_NOTICE ) {
			return;
		}
		$fatal_types = $this->shutdownFatalErrorTypes();
		if ( ! in_array( $error['type'], $fatal_types, true ) ) {
			return;
		}
		if ( ! $this->isErrorFromSnippet( $error ) ) {
			return;
		}
		$eval_line = isset( $error['line'] ) ? (int) $error['line'] : 0;
		$post      = $this->resolveSnippetPostFromError( $error );
		if ( ! $post || $post->post_type !== self::POST_TYPE ) {
			return;
		}
		$extra = [
			'merge_context' => $this->merged_php_line_map !== [] ? 'merged_fatal' : 'deferred_fatal',
			'eval_line'     => $eval_line,
			'snippet_line'  => null,
		];
		if ( isset( $this->merged_php_line_map[ $post->ID ] ) && $eval_line > 0 ) {
			$extra['snippet_line'] = $eval_line - $this->merged_php_line_map[ $post->ID ]['start'] + 1;
		} elseif ( $eval_line > 0 ) {
			$extra['snippet_line'] = $eval_line;
		}
		$this->logSnippetErrorFromShutdown( $post, $error, $extra );
		if ( $this->shouldAutoDeactivateSnippetForPhpError( $post ) ) {
			wp_update_post( [ 'ID' => $post->ID, 'post_status' => 'draft' ] );
			update_post_meta( $post->ID, '_wpps_auto_deactivated', time() );
			update_post_meta( $post->ID, '_wpps_auto_deactivated_error', $error['message'] ?? '' );
			$this->bustSnippetCaches();
			$this->notifyAutoDeactivateInAdmin( $post, (string) ( $error['message'] ?? '' ) );
		}
		$this->merged_php_line_map = [];
	}

	/**
	 * Check if error originated from our eval'd snippet code.
	 *
	 * @param array $error Error from error_get_last().
	 * @return bool
	 */
	private function isErrorFromSnippet( array $error ): bool {
		if ( $this->last_executed_php_snippet instanceof \WP_Post ) {
			return true;
		}

		$msg  = $error['message'] ?? '';
		$file = $error['file'] ?? '';
		$norm = is_string( $file ) ? wp_normalize_path( $file ) : '';
		if ( $norm !== '' && isset( $this->php_snippet_file_index[ $norm ] ) ) {
			return true;
		}
		$pattern = '/\bwp-powersuite\b.*\bmodule\.php\b/';
		if ( preg_match( $pattern, $file ) ) {
			return true;
		}
		if ( str_contains( $file, 'snippet-php-eval.php' ) ) {
			return true;
		}
		// eval()'d code often reports as "eval()'d code" or similar.
		if ( str_contains( $msg, 'eval()' ) || str_contains( $file, 'eval()' ) ) {
			return true;
		}
		$storage = SnippetPrivateStorage::getDir();
		if ( $storage !== '' && $file !== '' ) {
			$dir  = realpath( $storage );
			$errf = realpath( $file );
			if ( $dir && $errf && strpos( $errf, $dir ) === 0 ) {
				return true;
			}
		}
		if ( $file !== '' && str_ends_with( wp_normalize_path( $file ), '.' . SnippetPrivateStorage::FILE_EXT ) ) {
			return true;
		}
		if ( $file !== '' && str_contains( wp_normalize_path( (string) $file ), 'wpps_snip_' ) ) {
			return true;
		}
		return false;
	}

	/**
	 * Log snippet error from shutdown (fatal) - no Throwable.
	 *
	 * @param \WP_Post             $post  Snippet post.
	 * @param array                $error Error array.
	 * @param array<string, mixed> $extra merge_context, eval_line, snippet_line, etc.
	 */
	private function logSnippetErrorFromShutdown( \WP_Post $post, array $error, array $extra = [] ): void {
		$msg = $error['message'] ?? '';
		$this->recordSnippetLastPhpError(
			$post,
			$msg,
			array_merge(
				[
					'source' => 'shutdown',
					'file'   => $error['file'] ?? '',
					'line'   => $error['line'] ?? 0,
				],
				$extra
			)
		);
		if ( ! get_option( 'wpps_cs_error_logging', false ) ) {
			return;
		}
		$logs = get_option( self::ERROR_LOG_OPTION, [] );
		if ( ! is_array( $logs ) ) {
			$logs = [];
		}
		$row = [
			'time'     => current_time( 'mysql' ),
			'snippet'  => $post->ID,
			'title'    => $post->post_title,
			'message'  => $msg,
			'file'     => $error['file'] ?? '',
			'line'     => $error['line'] ?? 0,
			'location' => get_post_meta( $post->ID, '_wpps_location', true ) ?: '',
		];
		if ( $extra !== [] ) {
			$row['merge_context'] = $extra['merge_context'] ?? '';
			$row['snippet_line']  = $extra['snippet_line'] ?? null;
		}
		$logs[] = $row;
		$logs = array_slice( $logs, -$this->getErrorLogMaxEntries() );
		update_option( self::ERROR_LOG_OPTION, $logs, false );
	}

	/**
	 * Log snippet error if error logging is enabled.
	 *
	 * @param \WP_Post             $post  Snippet post.
	 * @param \Throwable           $e     Exception.
	 * @param array<string, mixed> $extra merge_context, eval_line, snippet_line, location overrides.
	 */
	private function logSnippetError( \WP_Post $post, \Throwable $e, array $extra = [] ): void {
		$this->recordSnippetLastPhpError(
			$post,
			$e->getMessage(),
			array_merge(
				[
					'source' => 'catch',
					'file'   => $e->getFile(),
					'line'   => $e->getLine(),
				],
				$extra
			)
		);
		if ( ! get_option( 'wpps_cs_error_logging', false ) ) {
			return;
		}
		$logs = get_option( self::ERROR_LOG_OPTION, [] );
		if ( ! is_array( $logs ) ) {
			$logs = [];
		}
		$row = [
			'time'     => current_time( 'mysql' ),
			'snippet'  => $post->ID,
			'title'    => $post->post_title,
			'message'  => $e->getMessage(),
			'file'     => $e->getFile(),
			'line'     => $e->getLine(),
			'location' => get_post_meta( $post->ID, '_wpps_location', true ) ?: '',
		];
		if ( $extra !== [] ) {
			$row['merge_context'] = $extra['merge_context'] ?? '';
			$row['snippet_line']  = $extra['snippet_line'] ?? null;
		}
		$logs[] = $row;
		$logs = array_slice( $logs, -$this->getErrorLogMaxEntries() );
		update_option( self::ERROR_LOG_OPTION, $logs, false );
	}

	/**
	 * Strip leading PHP tags from code for storage. Ensures we never save <?php in DB.
	 *
	 * @param string $code Raw code from editor.
	 * @return string Code with leading <?php/<? stripped.
	 */
	public static function stripPhpTagsForStorage( string $code ): string {
		$code = preg_replace( '/^\s*(?:(?:<' . '?php|<\?)\s*)+/i', '', $code );
		$close = chr( 63 ) . chr( 62 );
		$code = preg_replace( '/\s*' . preg_quote( $close, '/' ) . '\s*$/', '', $code );
		return trim( $code );
	}

	/**
	 * Strip script tags from JS code for storage. Ensures we never save <' . 'script> in DB.
	 * Handles multiple outer wrappers (e.g. <' . 'script><' . 'script>code</script></script>).
	 *
	 * @param string $code Raw code from editor.
	 * @return string Code with script tags stripped.
	 */
	public static function stripJsTagsForStorage( string $code ): string {
		$code = trim( $code );
		while ( preg_match( '/^\s*<' . 'script[^>]*>/i', $code ) && preg_match( '/<\/script>\s*$/i', $code ) ) {
			$code = preg_replace( '/^\s*<' . 'script[^>]*>\s*/i', '', $code );
			$code = preg_replace( '/\s*<\/script>\s*$/i', '', $code );
			$code = trim( $code );
		}
		return $code;
	}

	/**
	 * Resolve PHP CLI binary for `php -l` (syntax check). Web SAPIs (e.g. php-fpm on Plesk) often
	 * have no `php` on PATH; PHP_BINDIR usually points at the matching CLI.
	 *
	 * @return string Executable path or `php` to rely on PATH.
	 */
	private static function resolvePhpCliBinary(): string {
		$filtered = apply_filters( 'wpps_code_snippet_php_binary', null );
		if ( is_string( $filtered ) && $filtered !== '' && is_file( $filtered ) && is_executable( $filtered ) ) {
			return $filtered;
		}

		$candidates = [];
		if ( defined( 'PHP_BINARY' ) && is_string( PHP_BINARY ) && PHP_BINARY !== '' ) {
			$candidates[] = PHP_BINARY;
		}
		if ( defined( 'PHP_BINDIR' ) && is_string( PHP_BINDIR ) && PHP_BINDIR !== '' ) {
			$bindir = rtrim( PHP_BINDIR, '/\\' );
			$sep    = DIRECTORY_SEPARATOR;
			if ( PHP_OS_FAMILY === 'Windows' ) {
				$candidates[] = $bindir . $sep . 'php.exe';
				$candidates[] = $bindir . $sep . 'php-cli.exe';
			} else {
				$candidates[] = $bindir . $sep . 'php';
				$candidates[] = $bindir . $sep . 'php-cli';
			}
		}

		foreach ( $candidates as $bin ) {
			if ( ! is_string( $bin ) || $bin === '' ) {
				continue;
			}
			$base = strtolower( pathinfo( $bin, PATHINFO_FILENAME ) );
			if ( $base === 'php-fpm' || str_starts_with( $base, 'php-fpm' ) ) {
				continue;
			}
			if ( is_file( $bin ) && is_executable( $bin ) ) {
				return $bin;
			}
		}

		return 'php';
	}

	/**
	 * True when `php -l` failed because the host could not run the PHP CLI, not because of invalid code.
	 */
	private static function isPhpLintEnvironmentFailure( string $combined_output, int $exit_code ): bool {
		// Typical shell: 127 = command not found, 126 = not executable.
		if ( in_array( $exit_code, [ 126, 127 ], true ) ) {
			return true;
		}
		$out = $combined_output;
		// Real lint failures from PHP itself (always treat as syntax/code issues, not environment).
		if ( preg_match( '/PHP\s+Parse\s+error|Parse\s+error\s*:|syntax error,\s*unexpected|syntax error, unexpected|Errors parsing/i', $out ) ) {
			return false;
		}
		// Could not invoke PHP CLI (Plesk, hardened PHP-FPM, Windows PATH, SELinux, etc.).
		return (bool) preg_match(
			'/\bnot found\b|No such file or directory|not recognized as an internal or external command|Cannot run|Operation not permitted|Permission denied|Exec format error|bad ELF interpreter|failed to map segment/i',
			$out
		);
	}

	/**
	 * Check PHP code for syntax errors before saving.
	 *
	 * @param string $code Raw PHP code (without <?php tags).
	 * @return string|null Error message if invalid, null if valid.
	 */
	public static function checkPhpSyntax( string $code ): ?string {
		if ( apply_filters( 'wpps_code_snippet_skip_php_syntax_check', false ) ) {
			return null;
		}
		$code = trim( $code );
		if ( $code === '' ) {
			return null;
		}

		// Prefer the active web SAPI tokenizer (same PHP as runtime). php -l often uses a
		// different CLI binary and returns useless "Errors parsing /tmp/..." for large snippets.
		// Always lint the full snippet — mixed PHP/HTML (ob_start + HTML + return) is valid as one
		// unit; splitting on close-tags falsely reports "Unclosed '{'".
		$tokenizer_error = self::lintPhpWithTokenizer( $code );
		if ( $tokenizer_error !== null ) {
			return $tokenizer_error;
		}

		// Mixed templates are already validated by the tokenizer; php -l is unreliable for them.
		if ( strpos( $code, chr( 63 ) . chr( 62 ) ) !== false ) {
			return null;
		}

		return self::lintPhpWithCli( $code );
	}

	/**
	 * Normalize ParseError text (avoid "on line X on line Y").
	 */
	private static function formatParseErrorMessage( \ParseError $e ): string {
		$message = (string) $e->getMessage();
		$message = preg_replace( '/\s+in\s+\S+\s+on line \d+\s*$/i', '', $message );
		$message = preg_replace( '/\s+on line \d+\s*$/i', '', (string) $message );
		$message = trim( (string) $message );

		$line = max( 1, (int) $e->getLine() - 1 ); // subtract synthetic <?php line
		$formatted = $message . ' on line ' . $line;

		if ( preg_match( '/unexpected token "&"/i', $message ) ) {
			$formatted .= '. ' . __(
				'Tip: an unescaped single quote in JavaScript/CSS inside a PHP single-quoted string often causes this. Wrap large scripts in a nowdoc or use double quotes.',
				'wppowersuite-lite'
			);
		}

		if ( preg_match( '/unexpected identifier "s"/i', $message ) ) {
			$formatted .= '. ' . __(
				'Tip: an unescaped apostrophe in a PHP single-quoted string (e.g. __("It\'s …")) often causes this. Escape it as \' or use double quotes.',
				'wppowersuite-lite'
			);
		}

		return $formatted;
	}

	/**
	 * Extract a human-readable message from php -l output, or null when inconclusive.
	 *
	 * @param string[] $output Lines from exec().
	 */
	private static function parsePhpLintMessage( array $output ): ?string {
		foreach ( $output as $line ) {
			$line = trim( (string) $line );
			if ( $line === '' ) {
				continue;
			}
			if ( preg_match( '/^(?:PHP\s+)?Parse error:\s*(.+)$/i', $line, $matches ) ) {
				return self::stripPhpLintLocationSuffix( $matches[1] );
			}
			if ( preg_match( '/^syntax error,\s*unexpected/i', $line ) ) {
				return self::stripPhpLintLocationSuffix( $line );
			}
		}

		$joined = trim( implode( ' ', array_map( 'trim', $output ) ) );
		if ( $joined === '' ) {
			return null;
		}

		// php -l sometimes prints only "Errors parsing /path" with no parse details (CLI mismatch).
		if ( preg_match( '/^Errors parsing\b/i', $joined ) && ! preg_match( '/(?:Parse error|syntax error,\s*unexpected)/i', $joined ) ) {
			return null;
		}

		if ( preg_match( '/(?:Parse error|syntax error,\s*unexpected)/i', $joined ) ) {
			$message = preg_replace( '/^.*?(?:(?:PHP\s+)?Parse error:\s*|syntax error,\s*)/i', '', $joined );
			return self::stripPhpLintLocationSuffix( (string) $message );
		}

		return null;
	}

	/**
	 * Remove trailing "in /path on line N" from a php -l message.
	 */
	private static function stripPhpLintLocationSuffix( string $message ): string {
		$message = preg_replace( '/\s+in\s+\S+\s+on line \d+\s*$/', '', $message );
		return trim( (string) $message );
	}

	/**
	 * Run php -l when the CLI binary is available.
	 */
	private static function lintPhpWithCli( string $code ): ?string {
		$full = '<' . '?php' . "\n" . $code . "\n";
		$tmp  = tempnam( sys_get_temp_dir(), 'wpps_php_' );
		if ( ! $tmp ) {
			return null;
		}
		$ok = file_put_contents( $tmp, $full );
		if ( $ok === false ) {
			wp_delete_file( $tmp );
			return null;
		}
		$output = [];
		$binary = self::resolvePhpCliBinary();
		$cmd    = sprintf( '%s -l %s 2>&1', escapeshellarg( $binary ), escapeshellarg( $tmp ) );
		if ( ! function_exists( 'exec' ) || in_array( 'exec', array_map( 'trim', explode( ',', (string) ini_get( 'disable_functions' ) ) ), true ) ) {
			wp_delete_file( $tmp );
			return null;
		}
		exec( $cmd, $output, $ret );
			wp_delete_file( $tmp );
		if ( $ret !== 0 && ! empty( $output ) ) {
			$msg = implode( "\n", $output );
			if ( self::isPhpLintEnvironmentFailure( $msg, $ret ) ) {
				return null;
			}
			return self::parsePhpLintMessage( $output );
		}
		return null;
	}

	/**
	 * Tokenizer-based syntax check (fallback when php -l / exec is unavailable).
	 */
	private static function lintPhpWithTokenizer( string $code ): ?string {
		if ( ! function_exists( 'token_get_all' ) ) {
			return null;
		}
		$full = '<' . '?php' . "\n" . $code . "\n";
		try {
			token_get_all( $full, TOKEN_PARSE );
		} catch ( \ParseError $e ) {
			return self::formatParseErrorMessage( $e );
		}
		return null;
	}

	/**
	 * Decode snippet source from admin save request (base64 preferred to avoid &/form parsing issues).
	 */
	private static function decodeSnippetCodeFromRequest(): string {
		if ( isset( $_POST['code_b64'] ) && is_string( $_POST['code_b64'] ) && $_POST['code_b64'] !== '' ) {
			$decoded = base64_decode( wp_unslash( $_POST['code_b64'] ), true ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
			if ( is_string( $decoded ) ) {
				return $decoded;
			}
		}

		return isset( $_POST['code'] ) ? wp_unslash( $_POST['code'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
	}

	/**
	 * Force wp_insert_post_data to keep raw snippet code (KSES and other filters must not run).
	 *
	 * @param array<string, mixed> $data    Slashed post data for the DB.
	 * @param array<string, mixed> $postarr Raw post args.
	 * @return array<string, mixed>
	 */
	public static function filterSnippetInsertPostData( array $data, array $postarr ): array {
		if ( self::$snippet_save_content_override === null ) {
			return $data;
		}
		if ( ( $postarr['post_type'] ?? '' ) !== self::POST_TYPE ) {
			return $data;
		}
		$data['post_content'] = wp_slash( self::$snippet_save_content_override );

		return $data;
	}

	private function prepareSnippetContentSaveFilters( string $code ): void {
		self::$snippet_save_content_override = $code;
		add_filter( 'wp_insert_post_data', [ self::class, 'filterSnippetInsertPostData' ], 9999, 2 );
	}

	private function clearSnippetContentSaveFilters(): void {
		remove_filter( 'wp_insert_post_data', [ self::class, 'filterSnippetInsertPostData' ], 9999 );
		self::$snippet_save_content_override = null;
	}

	private function suspendContentSaveFilters(): void {
		global $wp_filter;

		if ( self::$suspended_content_save_filters !== null ) {
			return;
		}
		self::$suspended_content_save_filters = [];
		foreach ( [ 'content_save_pre', 'content_filtered_save_pre' ] as $hook ) {
			if ( isset( $wp_filter[ $hook ] ) ) {
				self::$suspended_content_save_filters[ $hook ] = $wp_filter[ $hook ];
				unset( $wp_filter[ $hook ] );
			}
		}
	}

	private function restoreContentSaveFilters(): void {
		global $wp_filter;

		if ( self::$suspended_content_save_filters === null ) {
			return;
		}
		foreach ( self::$suspended_content_save_filters as $hook => $callbacks ) {
			$wp_filter[ $hook ] = $callbacks;
		}
		self::$suspended_content_save_filters = null;
	}

	private function writeSnippetPostContentExact( int $post_id, string $code ): bool {
		global $wpdb;

		$updated = $wpdb->update(
			$wpdb->posts,
			[ 'post_content' => wp_slash( $code ) ],
			[ 'ID' => $post_id ],
			[ '%s' ],
			[ '%d' ]
		);
		if ( $updated !== false ) {
			clean_post_cache( $post_id );
		}

		return $updated !== false;
	}

	/**
	 * Insert or update a snippet post without letting core/plugins mutate post_content.
	 *
	 * @param array<string, mixed> $post_data wp_insert_post / wp_update_post args (post_content should match $code).
	 * @return int|\WP_Error Post ID or error.
	 */
	private function persistSnippetPost( array $post_data, string $code ) {
		kses_remove_filters();
		$this->suspendContentSaveFilters();

		$this->prepareSnippetContentSaveFilters( $code );

		$is_update = isset( $post_data['ID'] ) && (int) $post_data['ID'] > 0;
		$result    = $is_update ? wp_update_post( $post_data, true ) : wp_insert_post( $post_data, true );

		$this->clearSnippetContentSaveFilters();
		$this->restoreContentSaveFilters();
		kses_init_filters();

		if ( is_wp_error( $result ) ) {
			return $result;
		}
		if ( ! $result ) {
			return new \WP_Error( 'wpps_cs_save_failed', __( 'Could not save snippet.', 'wppowersuite-lite' ) );
		}

		$post_id = (int) $result;
		$saved   = get_post( $post_id );
		$stored  = ( $saved instanceof \WP_Post && is_string( $saved->post_content ) ) ? $saved->post_content : '';
		if ( $stored !== $code ) {
			$this->writeSnippetPostContentExact( $post_id, $code );
		}

		return $post_id;
	}

	/**
	 * Hooks to restore after snippet test eval. Output hooks are the usual targets of
	 * add_action() in snippets; leaving them registered confuses some admin-side code that
	 * walks $wp_filter (e.g. method_exists() on callbacks) during admin_notices.
	 *
	 * @var string[]
	 */
	private const SNIPPET_TEST_HOOK_ROLLBACK_TAGS = [
		'wp_footer',
		'wp_head',
		'wp_body_open',
		'admin_footer',
		'admin_head',
	];

	/**
	 * Undo hook mutations on high-traffic output hooks after test eval (see self::SNIPPET_TEST_HOOK_ROLLBACK_TAGS).
	 *
	 * @param array<string, \WP_Hook> $snapshots Cloned WP_Hook instances keyed by tag (only rollback tags).
	 * @param string[]                $had_tag   Tags that had a WP_Hook before eval (same list).
	 */
	private function rollbackHookStateAfterSnippetTest( array $snapshots, array $had_tag ): void {
		global $wp_filter;
		foreach ( self::SNIPPET_TEST_HOOK_ROLLBACK_TAGS as $tag ) {
			if ( isset( $snapshots[ $tag ] ) ) {
				$wp_filter[ $tag ] = $snapshots[ $tag ];
				continue;
			}
			if ( ! isset( $had_tag[ $tag ] ) && isset( $wp_filter[ $tag ] ) ) {
				unset( $wp_filter[ $tag ] );
			}
		}
	}

	/**
	 * Test-run PHP snippet to catch runtime errors (e.g. fatal on first line).
	 *
	 * Snippets that call add_action/add_filter are skipped here (see regex below); syntax still
	 * runs via checkPhpSyntax(). We do not call do_action( 'admin_notices' ) after eval — several
	 * popular admin plugins throw TypeError (method_exists null) during that hook in admin-ajax.
	 * Optional: add_filter( 'wpps_code_snippet_runtime_test_fire_admin_notices', '__return_true' ).
	 * Force hook-registration test: add_filter( 'wpps_code_snippet_force_runtime_test_with_hooks', '__return_true' ).
	 *
	 * @param string $code Raw PHP code (without <?php tags).
	 * @return string|null Error message if runtime error, null if ok.
	 */
	/**
	 * Catch Woo/EDD helpers used without a function_exists() guard when that plugin is not loaded.
	 * Hook-based snippets skip full eval, so this is how we surface WPCode-style "undefined function" at save.
	 */
	private function getUndefinedPluginFunctionWarning( string $code ): ?string {
		$known = [
			'is_product'       => 'WooCommerce',
			'is_shop'          => 'WooCommerce',
			'is_cart'          => 'WooCommerce',
			'is_checkout'      => 'WooCommerce',
			'is_account_page'  => 'WooCommerce',
			'is_woocommerce'   => 'WooCommerce',
			'wc_get_product'   => 'WooCommerce',
			'edd_is_checkout'  => 'Easy Digital Downloads',
		];
		foreach ( $known as $fn => $plugin ) {
			if ( ! preg_match( '/\b' . preg_quote( $fn, '/' ) . '\s*\(/', $code ) ) {
				continue;
			}
			if ( preg_match( '/function_exists\s*\(\s*[\'"]' . preg_quote( $fn, '/' ) . '[\'"]\s*\)/', $code ) ) {
				continue;
			}
			if ( $plugin === 'WooCommerce' && preg_match( '/class_exists\s*\(\s*[\'"]WooCommerce[\'"]/', $code ) ) {
				continue;
			}
			if ( function_exists( $fn ) ) {
				continue;
			}
			return sprintf(
				/* translators: 1: PHP function name, 2: plugin name */
				__( 'Call to undefined function %1$s(). This function is provided by %2$s. Guard it with function_exists( \'%1$s\' ) so the snippet does not fatal when that plugin is not loaded.', 'wppowersuite-lite' ),
				$fn,
				$plugin
			);
		}
		return null;
	}

	private function testPhpSnippetRuntime( string $code ): ?string {
		$pro_block = self::proCodeTypeBlockReason();
		if ( $pro_block !== null ) {
			return $pro_block;
		}
		$code = trim( $code );
		if ( $code === '' ) {
			return null;
		}

		$blocked = SnippetThreatScanner::getRuntimeBlockReason( $code );
		if ( $blocked !== null ) {
			return $blocked;
		}
		$code = preg_replace( '/^\s*(?:(?:<' . '?php|<\?)\s*)+/i', '', $code );
		$close = chr( 63 ) . chr( 62 );
		$code = preg_replace( '/\s*' . preg_quote( $close, '/' ) . '\s*$/', '', $code );
		$code = trim( $code );
		if ( $code === '' ) {
			return null;
		}

		$undefined = $this->getUndefinedPluginFunctionWarning( $code );
		if ( $undefined !== null ) {
			return $undefined;
		}

		if ( ! apply_filters( 'wpps_code_snippet_force_runtime_test_with_hooks', false, $code )
			&& preg_match( '/\badd_(?:action|filter)\s*\(/', $code ) ) {
			// Still compile-check hook-heavy snippets; we only skip executing them here.
			$syntax_err = self::checkPhpSyntax( $code );
			if ( $syntax_err !== null ) {
				return $syntax_err;
			}
			return null;
		}

		global $wp_filter;
		$snapshots = [];
		$had_tag   = [];
		foreach ( self::SNIPPET_TEST_HOOK_ROLLBACK_TAGS as $tag ) {
			if ( isset( $wp_filter[ $tag ] ) && $wp_filter[ $tag ] instanceof \WP_Hook ) {
				$snapshots[ $tag ] = clone $wp_filter[ $tag ];
				$had_tag[ $tag ]   = true;
			}
		}

		ob_start();
		try {
			$this->evalSnippetPhp( $code );
		} catch ( \Throwable $e ) {
			ob_end_clean();
			$this->rollbackHookStateAfterSnippetTest( $snapshots, $had_tag );
			return $e->getMessage();
		}
		$this->rollbackHookStateAfterSnippetTest( $snapshots, $had_tag );

		if ( apply_filters( 'wpps_code_snippet_runtime_test_fire_admin_notices', false, $code ) ) {
			try {
				do_action( 'admin_notices' );
			} catch ( \Throwable $e ) {
				ob_end_clean();
				return $e->getMessage();
			}
		}
		ob_end_clean();
		return null;
	}

	private function isCodeNotAllowed( string $code ): bool {
		return SnippetThreatScanner::isRuntimeBlocked( $code );
	}

	/**
	 * True when PHP must not run (empty, non-string, or blocked after filters).
	 */
	private function isPhpExecutionBlocked( $code ): bool {
		if ( ! is_string( $code ) || trim( $code ) === '' ) {
			return true;
		}
		return $this->isCodeNotAllowed( $code );
	}

	/**
	 * Extract raw PHP body from a snippet file on disk (for threat scanning before include).
	 */
	private function getPhpBodyFromSnippetFile( string $resolved_path ): string {
		$raw = file_get_contents( $resolved_path );
		if ( ! is_string( $raw ) || $raw === '' ) {
			return '';
		}
		$code  = preg_replace( '/^\s*(?:(?:<' . '?php|<\?)\s*)+/i', '', $raw );
		$close = chr( 63 ) . chr( 62 );
		$code  = preg_replace( '/\s*' . preg_quote( $close, '/' ) . '\s*$/', '', (string) $code );
		return trim( (string) $code );
	}

	/**
	 * Remove on-disk snippet asset files for a post (private PHP + public JS/CSS + legacy).
	 */
	private function deleteSnippetDiskFiles( \WP_Post $post ): void {
		$id   = (int) $post->ID;
		$dirs = array_unique(
			array_filter(
				[
					SnippetPrivateStorage::getDir(),
					SnippetPrivateStorage::legacyPublicPhpDir(),
					$this->getSnippetFileDir(),
				]
			)
		);
		foreach ( $dirs as $dir ) {
			if ( ! is_dir( $dir ) ) {
				continue;
			}
			foreach ( [ SnippetPrivateStorage::FILE_EXT, 'php', 'js', 'css' ] as $ext ) {
				foreach ( glob( trailingslashit( $dir ) . '*-' . $id . '.' . $ext ) ?: [] as $file ) {
					if ( is_string( $file ) && is_file( $file ) ) {
						wp_delete_file( $file );
					}
				}
			}
		}
	}

	/**
	 * Permanently delete a snippet, its disk files, and revision rows.
	 */
	private function deleteSnippetCompletely( int $id ): bool {
		$post = get_post( $id );
		if ( ! $post || $post->post_type !== self::POST_TYPE ) {
			return false;
		}
		$this->deleteSnippetDiskFiles( $post );
		if ( class_exists( Wpps_Revisions::class, false ) ) {
			$revisions = new Wpps_Revisions();
			$revisions->delete_for_snippet( $id );
		}
		wp_delete_post( $id, true );
		return true;
	}

	public function shortcodeHandler( array $atts ): string {
		$atts = shortcode_atts( [ 'id' => 0 ], $atts, 'wpps_code' );
		$id   = absint( $atts['id'] );
		if ( $id === 0 ) {
			return '';
		}
		$this->output_location_stack[] = 'shortcode';
		$out = $this->executeSnippet( $id );
		array_pop( $this->output_location_stack );
		return $out;
	}

	/**
	 * Register custom shortcodes for snippets that use them.
	 */
	public function registerCustomShortcodes(): void {
		$map = get_transient( self::SHORTCODE_CACHE_OPTION );
		if ( ! is_array( $map ) ) {
			$map = $this->buildCustomShortcodeMap();
			set_transient( self::SHORTCODE_CACHE_OPTION, $map, HOUR_IN_SECONDS );
		}
		foreach ( $map as $custom => $snippet_id ) {
			$custom     = (string) $custom;
			$snippet_id = (int) $snippet_id;
			if ( $custom === '' || $snippet_id <= 0 ) {
				continue;
			}
			add_shortcode(
				$custom,
				function ( $atts ) use ( $snippet_id ) {
					$this->output_location_stack[] = 'shortcode';
					$out = $this->executeSnippet( $snippet_id );
					array_pop( $this->output_location_stack );
					return $out;
				}
			);
		}
	}

	/**
	 * Build map of custom shortcode slug => snippet post ID.
	 *
	 * @return array<string, int>
	 */
	private function buildCustomShortcodeMap(): array {
		$map      = [];
		$snippets = $this->getAllSnippets( [ 'post_status' => 'publish' ] );
		foreach ( $snippets as $post ) {
			$auto_insert = get_post_meta( $post->ID, '_wpps_auto_insert', true ) === '1';
			if ( $auto_insert ) {
				continue;
			}
			$custom = get_post_meta( $post->ID, '_wpps_custom_shortcode', true );
			if ( ! is_string( $custom ) || $custom === '' ) {
				continue;
			}
			$map[ $custom ] = $post->ID;
		}
		return $map;
	}

	/**
	 * Get snippet counts (all, active, inactive) in a single query.
	 *
	 * @return array{all: int, active: int, inactive: int}
	 */
	public function getSnippetCounts(): array {
		global $wpdb;
		$table = $wpdb->posts;
		$type  = self::POST_TYPE;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$rows = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT post_status, COUNT(*) as cnt FROM {$table} WHERE post_type = %s AND post_status IN ('publish','draft','private','pending') GROUP BY post_status",
				$type
			),
			ARRAY_A
		);
		$counts = [ 'all' => 0, 'active' => 0, 'inactive' => 0 ];
		foreach ( $rows as $row ) {
			$cnt = (int) $row['cnt'];
			$counts['all'] += $cnt;
			if ( $row['post_status'] === 'publish' ) {
				$counts['active'] = $cnt;
			} else {
				$counts['inactive'] += $cnt;
			}
		}
		return $counts;
	}

	/**
	 * Get all snippets (for admin).
	 *
	 * @param array $args Query args.
	 * @return \WP_Post[]
	 */
	public function getAllSnippets( array $args = [] ): array {
		$defaults = [
			'post_type'      => self::POST_TYPE,
			'post_status'    => 'any',
			'posts_per_page' => -1,
			'orderby'        => 'modified',
			'order'          => 'DESC',
		];
		$args = array_merge( $defaults, $args );
		if ( isset( $args['orderby'] ) && $args['orderby'] === 'priority' ) {
			// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- admin list sort by snippet priority.
			$args['meta_key'] = '_wpps_priority';
			$args['orderby']  = 'meta_value_num';
		}
		$query = new \WP_Query( $args );
		return $query->posts;
	}

	public function addAdminMenu(): void {
		add_submenu_page(
			'powersuite',
			__( 'Code Snippets', 'wppowersuite-lite' ),
			__( 'Code Snippets', 'wppowersuite-lite' ),
			'manage_options',
			'powersuite-code-snippet',
			[ $this, 'renderAdminPage' ]
		);
	}

	public function enqueueCodeSnippetAssets( string $hook_suffix ): void {
		$page   = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
		$action = isset( $_GET['action'] ) ? sanitize_key( wp_unslash( $_GET['action'] ) ) : '';
		if ( $page !== 'powersuite-code-snippet' ) {
			return;
		}
		$css_path = __DIR__ . '/assets/cs-admin.css';
		$css_ver  = is_readable( $css_path ) ? (string) filemtime( $css_path ) : self::MODULE_VERSION;
		$css_url  = function_exists( 'wp_powersuite_module_asset_url' )
			? wp_powersuite_module_asset_url( __FILE__, 'assets/cs-admin.css' )
			: '';
		if ( $css_url !== '' ) {
			wp_enqueue_style( 'wpps-cs-admin', $css_url, [], $css_ver );
		}
		$module_settings_ui = defined( 'WP_POWERSUITE_SRC_DIR' )
			? WP_POWERSUITE_SRC_DIR . 'Admin' . DIRECTORY_SEPARATOR . 'ModuleSettingsUi.php'
			: '';
		if ( $module_settings_ui !== '' && is_readable( $module_settings_ui ) ) {
			require_once $module_settings_ui;
			wpps_enqueue_accordion_tooltip_script();
		}
		// Only load CodeMirror on add/edit pages, not list (faster list page)
		if ( $action === 'add' || ( $action === 'edit' && isset( $_GET['id'] ) && absint( $_GET['id'] ) > 0 ) ) {
			wp_enqueue_code_editor( [ 'type' => 'text/html' ] );
			wp_enqueue_code_editor( [ 'type' => 'text/css' ] );
			wp_enqueue_code_editor( [ 'type' => 'text/javascript' ] );
			wp_enqueue_code_editor( [ 'type' => 'application/x-httpd-php' ] );
		}
	}

	public function handleExport(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions.', 'wppowersuite-lite' ) );
		}
		if ( TemporarySessionGuard::isActive() ) {
			TemporarySessionGuard::denyAdminPage();
		}
		check_admin_referer( 'wpps_cs_export' );

		$ids = null;
		$label = 'all';
		if ( isset( $_REQUEST['id'] ) ) {
			$id = absint( wp_unslash( $_REQUEST['id'] ) );
			if ( $id > 0 ) {
				$ids   = [ $id ];
				$label = (string) $id;
			}
		} elseif ( isset( $_REQUEST['ids'] ) ) {
			$raw = wp_unslash( $_REQUEST['ids'] );
			if ( is_array( $raw ) ) {
				$ids = array_map( 'absint', $raw );
			} else {
				$ids = array_map( 'absint', explode( ',', (string) $raw ) );
			}
			$ids   = array_values( array_filter( $ids ) );
			$label = 'selected';
		}

		$this->sendSnippetExportDownload( $ids, $label );
	}

	public function handleImport(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions.', 'wppowersuite-lite' ) );
		}
		if ( TemporarySessionGuard::isActive() ) {
			TemporarySessionGuard::denyAdminPage();
		}
		check_admin_referer( 'wpps_cs_import' );

		$redirect = admin_url( 'admin.php?page=powersuite-code-snippet' );
		$json     = isset( $_POST['import_json'] ) ? trim( (string) wp_unslash( $_POST['import_json'] ) ) : '';

		if ( isset( $_FILES['import_file'] ) && is_array( $_FILES['import_file'] ) ) {
			$upload = ImportExport::readUploadedFile( $_FILES['import_file'] );
			if ( $upload['error'] !== '' ) {
				wp_safe_redirect( add_query_arg( 'cs_error', rawurlencode( $upload['error'] ), $redirect ) );
				exit;
			}
			if ( $upload['json'] !== '' ) {
				$json = $upload['json'];
			}
		}

		$as_inactive = isset( $_POST['import_inactive'] );
		$result      = ( new ImportExport() )->import( $json, $this, $as_inactive );

		if ( $result['imported'] > 0 ) {
			$redirect = add_query_arg( 'cs_imported', $result['imported'], $redirect );
			if ( $result['format'] !== '' ) {
				$redirect = add_query_arg( 'cs_import_format', sanitize_key( $result['format'] ), $redirect );
			}
		}
		$skipped = count( $result['skipped'] );
		if ( $skipped > 0 ) {
			$redirect = add_query_arg( 'cs_import_skipped', $skipped, $redirect );
		}

		$messages = array_merge( $result['errors'], $result['skipped'] );
		if ( $messages !== [] ) {
			$redirect = add_query_arg( 'cs_import_error', rawurlencode( implode( ' ', array_slice( $messages, 0, 5 ) ) ), $redirect );
		} elseif ( $result['imported'] === 0 ) {
			$redirect = add_query_arg(
				'cs_error',
				rawurlencode( __( 'No snippets were imported.', 'wppowersuite-lite' ) ),
				$redirect
			);
		}

		wp_safe_redirect( $redirect );
		exit;
	}

	/**
	 * Stream a JSON export download and exit.
	 *
	 * @param int[]|null $ids Specific snippet IDs, or null for all.
	 */
	private function sendSnippetExportDownload( ?array $ids, string $label ): void {
		$json = ( new ImportExport() )->exportJson( $ids );
		if ( $json === '' ) {
			wp_die( esc_html__( 'Could not build the export file.', 'wppowersuite-lite' ) );
		}

		$filename = 'wpps-code-snippets-' . $label . '-' . gmdate( 'Ymd' ) . '.json';
		nocache_headers();
		header( 'Content-Type: application/json; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename="' . sanitize_file_name( $filename ) . '"' );
		header( 'Content-Length: ' . strlen( $json ) );
		echo $json; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- JSON file download.
		exit;
	}

	public function renderAdminPage(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'wppowersuite-lite' ) );
		}
		if ( TemporarySessionGuard::isActive() ) {
			TemporarySessionGuard::denyAdminPage();
		}
		$view   = isset( $_GET['view'] ) ? sanitize_key( wp_unslash( $_GET['view'] ) ) : '';
		$action = isset( $_GET['action'] ) ? sanitize_key( wp_unslash( $_GET['action'] ) ) : '';
		$id     = isset( $_GET['id'] ) ? absint( $_GET['id'] ) : 0;

		if ( $view === 'settings' ) {
			$this->renderSettingsPage();
			return;
		}
		if ( $view === 'logs' ) {
			$this->renderLogsPage();
			return;
		}
		if ( $view === 'revisions' ) {
			$this->renderRevisionsPage();
			return;
		}

		if ( $id > 0 && in_array( $action, [ 'activate', 'deactivate', 'delete' ], true ) ) {
			$nonce = isset( $_GET['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ) : '';
			$nonce_action = $action . '-snippet_' . $id;
			if ( wp_verify_nonce( $nonce, $nonce_action ) ) {
				$post = get_post( $id );
				if ( $post && $post->post_type === self::POST_TYPE ) {
					if ( $action === 'delete' ) {
						$this->deleteSnippetCompletely( $id );
						$this->bustSnippetCaches();
					} else {
						$new_status = $action === 'activate' ? 'publish' : 'draft';
						if ( $new_status === 'publish' ) {
							$block = $this->getSnippetActivationBlockReason( $post );
							if ( $block !== null ) {
								wp_safe_redirect(
									add_query_arg(
										'cs_error',
										rawurlencode( $block ),
										remove_query_arg( [ 'action', 'id', '_wpnonce' ], wp_get_referer() ?: admin_url( 'admin.php?page=powersuite-code-snippet' ) )
									)
								);
								exit;
							}
							$this->clearSnippetErrorState( $id );
						}
						wp_update_post( [ 'ID' => $id, 'post_status' => $new_status ] );
						$this->bustSnippetCaches();
					}
				}
				$redirect = $action === 'delete'
					? admin_url( 'admin.php?page=powersuite-code-snippet' )
					: remove_query_arg( [ 'action', 'id', '_wpnonce' ], wp_get_referer() ?: admin_url( 'admin.php?page=powersuite-code-snippet' ) );
				wp_safe_redirect( $redirect );
				exit;
			}
		}

		$bulk_action = isset( $_REQUEST['action'] ) && $_REQUEST['action'] !== '-1' ? sanitize_key( wp_unslash( $_REQUEST['action'] ) ) : ( isset( $_REQUEST['action2'] ) && $_REQUEST['action2'] !== '-1' ? sanitize_key( wp_unslash( $_REQUEST['action2'] ) ) : '' );
		$bulk_ids = isset( $_REQUEST['snippet'] ) && is_array( $_REQUEST['snippet'] ) ? array_map( 'absint', wp_unslash( $_REQUEST['snippet'] ) ) : [];
		$bulk_ids = array_filter( $bulk_ids );
		if ( $bulk_action && ! empty( $bulk_ids ) && check_admin_referer( 'bulk-snippets' ) ) {
			if ( $bulk_action === 'export' ) {
				$export_ids = [];
				foreach ( $bulk_ids as $sid ) {
					$post = get_post( $sid );
					if ( $post && $post->post_type === self::POST_TYPE ) {
						$export_ids[] = $sid;
					}
				}
				if ( $export_ids === [] ) {
					wp_safe_redirect(
						add_query_arg(
							'cs_error',
							rawurlencode( __( 'No snippets were selected for export.', 'wppowersuite-lite' ) ),
							admin_url( 'admin.php?page=powersuite-code-snippet' )
						)
					);
					exit;
				}
				$this->sendSnippetExportDownload( $export_ids, 'selected' );
			}
			$done    = 0;
			$skipped = 0;
			foreach ( $bulk_ids as $sid ) {
				$post = get_post( $sid );
				if ( ! $post || $post->post_type !== self::POST_TYPE ) {
					continue;
				}
				if ( $bulk_action === 'delete' ) {
					$this->deleteSnippetCompletely( $sid );
					$done++;
				} elseif ( $bulk_action === 'activate' ) {
					if ( $this->getSnippetActivationBlockReason( $post ) !== null ) {
						$skipped++;
						continue;
					}
					$this->clearSnippetErrorState( $sid );
					wp_update_post( [ 'ID' => $sid, 'post_status' => 'publish' ] );
					$done++;
				} elseif ( $bulk_action === 'deactivate' ) {
					wp_update_post( [ 'ID' => $sid, 'post_status' => 'draft' ] );
					$done++;
				}
			}
			if ( $done > 0 || $skipped > 0 ) {
				$this->bustSnippetCaches();
			}
			$redirect = add_query_arg( 'page', 'powersuite-code-snippet', admin_url( 'admin.php' ) );
			$status_param = isset( $_POST['status'] ) ? sanitize_key( wp_unslash( $_POST['status'] ) ) : ( isset( $_GET['status'] ) ? sanitize_key( wp_unslash( $_GET['status'] ) ) : 'all' );
			$redirect = add_query_arg( 'status', $status_param, $redirect );
			if ( isset( $_POST['s'] ) && $_POST['s'] !== '' ) {
				$redirect = add_query_arg( 's', sanitize_text_field( wp_unslash( $_POST['s'] ) ), $redirect );
			} elseif ( isset( $_GET['s'] ) && $_GET['s'] !== '' ) {
				$redirect = add_query_arg( 's', sanitize_text_field( wp_unslash( $_GET['s'] ) ), $redirect );
			}
			$type_param = isset( $_REQUEST['snippet_type'] ) ? sanitize_key( wp_unslash( $_REQUEST['snippet_type'] ) ) : '';
			if ( in_array( $type_param, [ 'html', 'css', 'js', 'php' ], true ) ) {
				$redirect = add_query_arg( 'snippet_type', $type_param, $redirect );
			}
			$location_param = isset( $_REQUEST['snippet_location'] ) ? sanitize_key( wp_unslash( $_REQUEST['snippet_location'] ) ) : '';
			if ( $location_param !== '' && in_array( $location_param, self::getAllLocationSlugs(), true ) ) {
				$redirect = add_query_arg( 'snippet_location', $location_param, $redirect );
			}
			$device_param = isset( $_REQUEST['snippet_device'] ) ? sanitize_key( wp_unslash( $_REQUEST['snippet_device'] ) ) : '';
			if ( in_array( $device_param, [ 'all', 'desktop', 'mobile', 'tablet' ], true ) ) {
				$redirect = add_query_arg( 'snippet_device', $device_param, $redirect );
			}
			if ( $done > 0 ) {
				$redirect = add_query_arg( 'cs_done', $done . '_' . $bulk_action, $redirect );
			}
			if ( $skipped > 0 ) {
				$redirect = add_query_arg( 'cs_skipped', $skipped, $redirect );
			}
			wp_safe_redirect( $redirect );
			exit;
		}

		// Revisions page is handled by renderRevisionsPage() above.
		if ( $action === 'add' ) {
			$snippet_data = null;
			$is_edit      = false;
			include __DIR__ . '/edit.php';
		} elseif ( $action === 'edit' && $id > 0 ) {
			$snippet_data = $this->getSnippetData( $id );
			if ( $snippet_data === null ) {
				wp_safe_redirect( admin_url( 'admin.php?page=powersuite-code-snippet' ) );
				exit;
			}
			$is_edit = true;
			include __DIR__ . '/edit.php';
		} else {
			$module_id = self::MODULE_ID;
			include __DIR__ . '/admin.php';
		}
	}

	/**
	 * Get Code Snippet settings.
	 *
	 * @return array
	 */
	public static function getSettings(): array {
		$defaults = [
			'error_logging'            => false,
			'editor_height'            => 300,
			'editor_height_auto'       => false,
			'admin_bar_info'           => true,
			'load_snippets_as_files'   => false,
			'revisions_to_keep'        => 10,
			'merge_frontend_only_php'  => false,
			'merge_run_everywhere_php' => false,
			'global_safe_mode'         => false,
		];
		$opts = get_option( self::SETTINGS_OPTION, [] );
		$opts = is_array( $opts ) ? $opts : [];
		// Migrate from old separate options to single option.
		if ( ! isset( $opts['load_snippets_as_files'] ) && ( ! empty( $opts['load_php_as_files'] ) || ! empty( $opts['load_js_css_as_files'] ) ) ) {
			$opts['load_snippets_as_files'] = true;
		}
		return array_merge( $defaults, $opts );
	}

	/**
	 * Get a single setting.
	 *
	 * @param string $key Setting key.
	 * @param mixed  $default Default value.
	 * @return mixed
	 */
	public static function getSetting( string $key, $default = null ) {
		$opts = self::getSettings();
		return $opts[ $key ] ?? $default;
	}

	/**
	 * Render the settings page.
	 */
	public function renderSettingsPage(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions.', 'wppowersuite-lite' ) );
		}
		$settings = self::getSettings();
		if ( isset( $_POST['wpps_cs_settings'] ) && check_admin_referer( 'wpps_cs_settings' ) ) {
			$settings = [
				'error_logging'           => isset( $_POST['wpps_cs_error_logging'] ),
				'editor_height'           => ! empty( $_POST['wpps_cs_editor_height_auto'] )
					? ( (int) ( $settings['editor_height'] ?? 300 ) )
					: max( 100, min( 800, (int) ( $_POST['wpps_cs_editor_height'] ?? 300 ) ) ),
				'editor_height_auto'      => isset( $_POST['wpps_cs_editor_height_auto'] ),
				'admin_bar_info'          => isset( $_POST['wpps_cs_admin_bar_info'] ),
				'load_snippets_as_files'  => isset( $_POST['wpps_cs_load_snippets_as_files'] ),
				'revisions_to_keep'       => max( 1, min( 100, (int) ( $_POST['wpps_cs_revisions_to_keep'] ?? 10 ) ) ),
				'merge_frontend_only_php' => isset( $_POST['wpps_cs_merge_frontend_only_php'] ),
				'merge_run_everywhere_php' => isset( $_POST['wpps_cs_merge_run_everywhere_php'] ),
				'global_safe_mode'        => isset( $_POST['wpps_cs_global_safe_mode'] ),
			];
			update_option( self::SETTINGS_OPTION, $settings, false );
			update_option( 'wpps_cs_error_logging', $settings['error_logging'], false );
			update_option( 'wpps_cs_global_safe_mode', $settings['global_safe_mode'], false );
			if ( ! empty( $settings['load_snippets_as_files'] ) ) {
				$all = $this->getAllSnippets( [ 'post_status' => 'publish' ] );
				foreach ( $all as $post ) {
					$type = get_post_meta( $post->ID, '_wpps_code_type', true ) ?: 'html';
					$auto = get_post_meta( $post->ID, '_wpps_auto_insert', true ) === '1';
					if ( $auto && in_array( $type, [ 'php', 'html' ], true ) ) {
						$this->ensurePhpSnippetFile( $post );
					}
				}
				foreach ( [ 'header', 'body', 'footer' ] as $loc ) {
					$snippets = $this->getSnippetsForLocation( $loc );
					foreach ( $snippets as $post ) {
						$type = get_post_meta( $post->ID, '_wpps_code_type', true ) ?: 'html';
						if ( in_array( $type, [ 'js', 'css' ], true ) ) {
							$code = $post->post_content;
							$code = preg_replace( '/^\s*<' . 'script[^>]*>|<\/script>\s*$/i', '', $code );
							$code = preg_replace( '/^\s*<' . 'style[^>]*>|<\/style>\s*$/i', '', $code );
							$this->ensureSnippetFile( $post, $type, trim( $code ) );
						}
					}
				}
				$this->bustSnippetCaches();
			}
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings saved.', 'wppowersuite-lite' ) . '</p></div>';
		}
		$storage_dir      = SnippetPrivateStorage::getDir();
		$storage_available = SnippetPrivateStorage::isAvailable();
		$public_asset_dir = trailingslashit( WordPressPaths::uploadsDir() ) . 'wp-powersuite/snippets/';
		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Code Snippet Settings', 'wppowersuite-lite' ); ?></h1>
			<?php echo self::backToSnippetsButton(); ?>
			<form method="post">
				<?php wp_nonce_field( 'wpps_cs_settings' ); ?>
				<table class="form-table" role="presentation">
					<tr>
						<th scope="row"><?php esc_html_e( 'PHP Storage', 'wppowersuite-lite' ); ?></th>
						<td>
							<?php if ( $storage_available ) : ?>
								<p><?php esc_html_e( 'Private storage is active.', 'wppowersuite-lite' ); ?></p>
								<p class="description">
									<?php esc_html_e( 'Path:', 'wppowersuite-lite' ); ?>
									<code><?php echo esc_html( $storage_dir ); ?></code>
								</p>
								<p class="description"><?php esc_html_e( 'Override with WP_POWERSUITE_SNIPPET_PATH in wp-config.php if needed.', 'wppowersuite-lite' ); ?></p>
							<?php else : ?>
								<p><?php esc_html_e( 'Private storage is unavailable.', 'wppowersuite-lite' ); ?></p>
								<p class="description"><?php esc_html_e( 'PHP/HTML snippets run from the database. File-based PHP loading stays disabled until a private directory outside the public site is configured.', 'wppowersuite-lite' ); ?></p>
								<p class="description"><?php echo esc_html( SnippetPrivateStorage::configurationHelpMessage() ); ?></p>
							<?php endif; ?>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Error Logging', 'wppowersuite-lite' ); ?></th>
						<td>
							<label>
								<input type="checkbox" name="wpps_cs_error_logging" value="1" <?php checked( ! empty( $settings['error_logging'] ) ); ?>>
								<?php esc_html_e( 'Log PHP errors from snippets', 'wppowersuite-lite' ); ?>
							</label>
							<p class="description"><?php esc_html_e( 'Review logged errors under Error Logs.', 'wppowersuite-lite' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Global Safe Mode', 'wppowersuite-lite' ); ?></th>
						<td>
							<label>
								<input type="checkbox" name="wpps_cs_global_safe_mode" value="1" <?php checked( ! empty( $settings['global_safe_mode'] ) ); ?>>
								<?php esc_html_e( 'Disable all snippets site-wide', 'wppowersuite-lite' ); ?>
							</label>
							<p class="description"><?php esc_html_e( 'Emergency recovery only. Or define WPPS_CS_DISABLE in wp-config.php.', 'wppowersuite-lite' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Run Everywhere PHP', 'wppowersuite-lite' ); ?></th>
						<td>
							<label>
								<input type="checkbox" name="wpps_cs_merge_run_everywhere_php" value="1" <?php checked( ! empty( $settings['merge_run_everywhere_php'] ) ); ?>>
								<?php esc_html_e( 'Merge Run Everywhere and Admin Only snippets', 'wppowersuite-lite' ); ?>
							</label>
							<p class="description"><?php esc_html_e( 'Leave off to run each snippet separately. Recommended when migrating snippets.', 'wppowersuite-lite' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Frontend Only PHP', 'wppowersuite-lite' ); ?></th>
						<td>
							<label>
								<input type="checkbox" name="wpps_cs_merge_frontend_only_php" value="1" <?php checked( ! empty( $settings['merge_frontend_only_php'] ) ); ?>>
								<?php esc_html_e( 'Merge Frontend Only snippets', 'wppowersuite-lite' ); ?>
							</label>
							<p class="description"><?php esc_html_e( 'Leave off to run each snippet separately. Easier to isolate problems.', 'wppowersuite-lite' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Editor Height', 'wppowersuite-lite' ); ?></th>
						<td>
							<?php
							$eh      = max( 100, min( 800, (int) ( $settings['editor_height'] ?? 300 ) ) );
							$eh_auto = ! empty( $settings['editor_height_auto'] );
							?>
							<p>
								<label>
									<?php esc_html_e( 'Height (px)', 'wppowersuite-lite' ); ?>
									<?php if ( $eh_auto ) : ?>
										<input type="hidden" name="wpps_cs_editor_height" value="<?php echo esc_attr( (string) $eh ); ?>">
									<?php endif; ?>
									<input type="number" name="wpps_cs_editor_height" value="<?php echo esc_attr( (string) $eh ); ?>" data-wpps-min="100" data-wpps-max="800" data-wpps-step="1" style="width:80px" <?php disabled( $eh_auto ); ?>>
								</label>
								<label style="margin-left:16px;">
									<input type="checkbox" name="wpps_cs_editor_height_auto" value="1" <?php checked( $eh_auto ); ?>>
									<?php esc_html_e( 'Auto-grow', 'wppowersuite-lite' ); ?>
								</label>
							</p>
							<p class="description"><?php esc_html_e( 'Applies to the snippet code editor.', 'wppowersuite-lite' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Admin Bar', 'wppowersuite-lite' ); ?></th>
						<td>
							<label>
								<input type="checkbox" name="wpps_cs_admin_bar_info" value="1" <?php checked( ! empty( $settings['admin_bar_info'] ) ); ?>>
								<?php esc_html_e( 'Show loaded snippets in the admin bar', 'wppowersuite-lite' ); ?>
							</label>
							<p class="description"><?php esc_html_e( 'Requires the WordPress toolbar to be visible.', 'wppowersuite-lite' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Revisions', 'wppowersuite-lite' ); ?></th>
						<td>
							<?php
							$rev_keep = max( 1, min( 100, (int) ( $settings['revisions_to_keep'] ?? 10 ) ) );
							?>
							<input type="number" name="wpps_cs_revisions_to_keep" value="<?php echo esc_attr( (string) $rev_keep ); ?>" data-wpps-min="1" data-wpps-max="100" data-wpps-step="1" style="width:80px">
							<p class="description"><?php esc_html_e( 'Maximum revisions kept per snippet (1–100). Older ones are removed automatically.', 'wppowersuite-lite' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Load as Files', 'wppowersuite-lite' ); ?></th>
						<td>
							<label>
								<input type="checkbox" name="wpps_cs_load_snippets_as_files" value="1" <?php checked( ! empty( $settings['load_snippets_as_files'] ) ); ?>>
								<?php esc_html_e( 'Load active snippets from files', 'wppowersuite-lite' ); ?>
							</label>
							<p class="description"><?php esc_html_e( 'PHP and HTML require private storage (above). JS and CSS use:', 'wppowersuite-lite' ); ?> <code><?php echo esc_html( $public_asset_dir ); ?></code></p>
							<p class="description"><?php esc_html_e( 'Can also be set per snippet in the editor.', 'wppowersuite-lite' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"></th>
						<td>
							<button type="submit" name="wpps_cs_settings" class="button button-primary"><?php esc_html_e( 'Save Changes', 'wppowersuite-lite' ); ?></button>
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=powersuite-code-snippet&view=logs' ) ); ?>" class="button"><?php esc_html_e( 'Error Logs', 'wppowersuite-lite' ); ?></a>
						</td>
					</tr>
				</table>
			</form>
			<?php ob_start(); ?>
			document.querySelector('input[name="wpps_cs_editor_height_auto"]')?.addEventListener('change', function() {
				var num = document.querySelector('input[type="number"][name="wpps_cs_editor_height"]');
				var wrap = this.closest('form');
				if (num && wrap) {
					num.disabled = this.checked;
					var hidden = wrap.querySelector('input[type="hidden"][name="wpps_cs_editor_height"]');
					if (this.checked) {
						if (!hidden) {
							hidden = document.createElement('input');
							hidden.type = 'hidden';
							hidden.name = 'wpps_cs_editor_height';
							num.parentNode.insertBefore(hidden, num);
						}
						hidden.value = num.value;
					} else if (hidden) {
						hidden.remove();
					}
				}
			});
<?php \WP_PowerSuite\Core\InlineAssets::script( 'wpps-ia-modules-code-snippet-module-php-script-2', (string) ob_get_clean() ); ?>
		</div>
		<?php
	}

	/**
	 * Render the error logs page.
	 */
	/**
	 * Render the revisions compare page.
	 */
	public function renderRevisionsPage(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions.', 'wppowersuite-lite' ) );
		}
		if ( ! self::isProLicensed() || ! class_exists( Wpps_Revisions::class, false ) ) {
			echo '<div class="wrap wpps-cs-wrap"><h1>' . esc_html__( 'Code Revisions', 'wppowersuite-lite' ) . '</h1>';
			if ( function_exists( 'wpps_render_premium_upsell_notice' ) ) {
				wpps_render_premium_upsell_notice();
			}
			echo '</div>';
			return;
		}
		$revisions = new Wpps_Revisions();
		$snippet_id = isset( $_GET['snippet_id'] ) ? absint( $_GET['snippet_id'] ) : 0;
		$revision_id = isset( $_GET['revision'] ) ? absint( $_GET['revision'] ) : 0;
		$compare = isset( $_GET['compare'] ) && $_GET['compare'] === '1';

		if ( $revision_id > 0 && $snippet_id <= 0 ) {
			$snippet_id = $revisions->get_revision_parent_id( $revision_id );
		}
		if ( $snippet_id <= 0 ) {
			echo '<div class="wrap"><p>' . esc_html__( 'Invalid snippet.', 'wppowersuite-lite' ) . '</p>' . self::backToSnippetsButton() . '</div>';
			return;
		}
		$post = get_post( $snippet_id );
		if ( ! $post || $post->post_type !== self::POST_TYPE ) {
			echo '<div class="wrap"><p>' . esc_html__( 'Snippet not found.', 'wppowersuite-lite' ) . '</p>' . self::backToSnippetsButton() . '</div>';
			return;
		}

		// Restore returns to the edit screen, not the revisions list.
		$restore_id = isset( $_GET['restore'] ) ? absint( $_GET['restore'] ) : 0;
		if ( $restore_id > 0 && isset( $_GET['_wpnonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'wpps-restore-revision' ) ) {
			$rev_data = $revisions->get_revision_data( $restore_id );
			if ( ! empty( $rev_data ) ) {
				$rev_row = $revisions->get_revision( $restore_id );
				if ( $rev_row && (int) $rev_row->snippet_id === $snippet_id ) {
					$restore_err = $this->restoreSnippetFromRevisionData( $snippet_id, $rev_data, $revisions );
					if ( $restore_err !== null ) {
						wp_safe_redirect(
							add_query_arg(
								'cs_error',
								rawurlencode( $restore_err ),
								admin_url( 'admin.php?page=powersuite-code-snippet&action=edit&id=' . $snippet_id )
							)
						);
						exit;
					}
					$this->bustSnippetCaches();
					wp_cache_delete( 'wpps_revisions_' . $snippet_id, 'wpps' );
					wp_safe_redirect( add_query_arg( [ 'restored' => 1 ], admin_url( 'admin.php?page=powersuite-code-snippet&action=edit&id=' . $snippet_id ) ) );
					exit;
				}
			}
		}

		$compare_title      = $post->post_title ?: __( '(no title)', 'wppowersuite-lite' );
		$back_url           = admin_url( 'admin.php?page=powersuite-code-snippet&action=edit&id=' . $snippet_id );
		$revisions_instance = $revisions;
		include __DIR__ . '/revisions.php';
	}

	/**
	 * Restore snippet from revision data (post + meta).
	 * Creates a new revision so the restored state becomes the current version.
	 *
	 * @param int             $snippet_id Snippet ID.
	 * @param array           $data       Revision data.
	 * @param object|null $revisions Revisions instance (optional, for creating revision).
	 * @return string|null Error message, or null on success.
	 */
	private function restoreSnippetFromRevisionData( int $snippet_id, array $data, $revisions = null ): ?string {
		$post = get_post( $snippet_id );
		if ( ! $post || $post->post_type !== self::POST_TYPE ) {
			return __( 'Snippet not found.', 'wppowersuite-lite' );
		}

		$type = isset( $data['code_type'] ) ? sanitize_key( (string) $data['code_type'] ) : ( get_post_meta( $snippet_id, '_wpps_code_type', true ) ?: 'html' );
		$loc  = isset( $data['location'] ) ? sanitize_key( (string) $data['location'] ) : ( get_post_meta( $snippet_id, '_wpps_location', true ) ?: 'footer' );
		$code = isset( $data['code'] ) ? (string) $data['code'] : $post->post_content;

		// Same capability gate as ajaxSaveSnippet (multisite / custom-cap parity).
		if ( in_array( $type, [ 'html', 'js', 'php' ], true ) && ! current_user_can( 'unfiltered_html' ) ) {
			return __( 'Saving HTML, JavaScript, or PHP snippets requires the unfiltered_html capability.', 'wppowersuite-lite' );
		}

		$type_loc_err = $this->validateTypeLocationPair( $type, $loc );
		if ( $type_loc_err !== null ) {
			return $type_loc_err;
		}

		if ( $type === 'php' ) {
			$code = self::stripPhpTagsForStorage( $code );
			$syntax_err = self::checkPhpSyntax( $code );
			if ( $syntax_err !== null ) {
				return __( 'PHP syntax error:', 'wppowersuite-lite' ) . ' ' . $syntax_err;
			}
			$blocked = SnippetThreatScanner::getRuntimeBlockReason( $code );
			if ( $blocked !== null ) {
				return $blocked;
			}
		}

		if ( array_key_exists( 'custom_shortcode', $data ) ) {
			$custom_shortcode = $this->sanitizeCustomShortcode( (string) $data['custom_shortcode'] );
			$data['custom_shortcode'] = $custom_shortcode;
			$shortcode_err = $this->validateCustomShortcode( $custom_shortcode, $snippet_id );
			if ( $shortcode_err !== null ) {
				return $shortcode_err;
			}
		}

		$active = array_key_exists( 'active', $data ) ? (bool) $data['active'] : ( $post->post_status === 'publish' );
		if ( $active ) {
			if ( self::isProCodeType( $type ) ) {
				$pro_block = self::proCodeTypeBlockReason();
				if ( $pro_block !== null ) {
					return $pro_block;
				}
			}
			if ( ! self::isProLicensed() ) {
				$device = isset( $data['device_type'] ) ? (string) $data['device_type'] : ( get_post_meta( $snippet_id, '_wpps_device_type', true ) ?: 'all' );
				$cond   = array_key_exists( 'conditional_enabled', $data )
					? (bool) $data['conditional_enabled']
					: ( get_post_meta( $snippet_id, '_wpps_conditional_enabled', true ) === '1' );
				if ( $device !== 'all' || $cond ) {
					return __( 'Code Snippet requires WP PowerSuite Pro and an active license.', 'wppowersuite-lite' );
				}
			}
			if ( $type === 'php' ) {
				$runtime_err = $this->testPhpSnippetRuntime( $code );
				if ( $runtime_err !== null ) {
					return __( 'PHP error:', 'wppowersuite-lite' ) . ' ' . $runtime_err;
				}
			}
		}

		if ( isset( $data['conditional_rules'] ) && is_array( $data['conditional_rules'] ) ) {
			$data['conditional_rules'] = $this->sanitizeConditionalRules( $data['conditional_rules'] );
		}

		$saved_id = $this->persistSnippetPost(
			[
				'ID'           => $snippet_id,
				'post_title'   => $data['title'] ?? '',
				'post_content' => $code,
				'post_status'  => $active ? 'publish' : 'draft',
				'post_type'    => self::POST_TYPE,
			],
			$code
		);
		if ( is_wp_error( $saved_id ) ) {
			return $saved_id->get_error_message();
		}

		$this->applySnippetMetaFromRevisionData( $snippet_id, $data );

		if ( $revisions && get_post_meta( $snippet_id, '_wpps_revisions_enabled', true ) === '1' ) {
			$revisions->create_revision( $snippet_id, Wpps_Revisions::get_snippet_revision_data( $snippet_id ) );
		}

		$this->syncSnippetFilesAfterSave( get_post( $snippet_id ) );

		return null;
	}

	/**
	 * Persist a normalized import snapshot as a new snippet.
	 * Never honors foreign post IDs. Reuses the same save/restore gates.
	 *
	 * @param array<string, mixed> $data Allowlisted snapshot from ImportExport.
	 * @return int|\WP_Error New post ID or error.
	 */
	public function importNormalizedSnippet( array $data, bool $as_inactive = true ) {
		$type = isset( $data['code_type'] ) ? sanitize_key( (string) $data['code_type'] ) : 'html';
		$loc  = isset( $data['location'] ) ? sanitize_key( (string) $data['location'] ) : 'footer';
		$code = isset( $data['code'] ) ? (string) $data['code'] : '';
		$title = isset( $data['title'] ) ? sanitize_text_field( (string) $data['title'] ) : '';

		$allowed_types = [ 'html', 'css', 'js', 'php' ];
		if ( ! in_array( $type, $allowed_types, true ) ) {
			$type = 'html';
		}
		if ( ! in_array( $loc, self::getAllLocationSlugs(), true ) ) {
			$loc = $type === 'php' ? 'run_everywhere' : 'footer';
		}

		if ( in_array( $type, [ 'html', 'js', 'php' ], true ) && ! current_user_can( 'unfiltered_html' ) ) {
			return new \WP_Error(
				'wpps_cs_import_cap',
				__( 'Saving HTML, JavaScript, or PHP snippets requires the unfiltered_html capability.', 'wppowersuite-lite' )
			);
		}

		$type_loc_err = $this->validateTypeLocationPair( $type, $loc );
		if ( $type_loc_err !== null ) {
			return new \WP_Error( 'wpps_cs_import_location', $type_loc_err );
		}

		if ( $type === 'php' ) {
			$code       = self::stripPhpTagsForStorage( $code );
			$syntax_err = self::checkPhpSyntax( $code );
			if ( $syntax_err !== null ) {
				return new \WP_Error(
					'wpps_cs_import_php_syntax',
					__( 'PHP syntax error:', 'wppowersuite-lite' ) . ' ' . $syntax_err
				);
			}
			$blocked = SnippetThreatScanner::getRuntimeBlockReason( $code );
			if ( $blocked !== null ) {
				return new \WP_Error( 'wpps_cs_import_php_blocked', $blocked );
			}
		} elseif ( $type === 'js' ) {
			$code = self::stripJsTagsForStorage( $code );
		}

		$want_active = ! $as_inactive && ! empty( $data['active'] );
		if ( $want_active ) {
			if ( self::isProCodeType( $type ) ) {
				$pro_block = self::proCodeTypeBlockReason();
				if ( $pro_block !== null ) {
					return new \WP_Error( 'wpps_cs_import_pro', $pro_block );
				}
			}
			if ( $type === 'php' ) {
				$runtime_err = $this->testPhpSnippetRuntime( $code );
				if ( $runtime_err !== null ) {
					return new \WP_Error(
						'wpps_cs_import_php_runtime',
						__( 'PHP error:', 'wppowersuite-lite' ) . ' ' . $runtime_err
					);
				}
			}
		}

		$custom = $this->uniqueImportedShortcode( isset( $data['custom_shortcode'] ) ? (string) $data['custom_shortcode'] : '' );

		$is_pro = self::isProLicensed();
		$device = isset( $data['device_type'] ) ? sanitize_key( (string) $data['device_type'] ) : 'all';
		if ( ! in_array( $device, [ 'all', 'desktop', 'mobile', 'tablet' ], true ) ) {
			$device = 'all';
		}
		$cond_enabled = ! empty( $data['conditional_enabled'] );
		$cond_show    = ( isset( $data['conditional_show'] ) && (string) $data['conditional_show'] === '0' ) ? '0' : '1';
		$cond_rules   = ( isset( $data['conditional_rules'] ) && is_array( $data['conditional_rules'] ) )
			? $this->sanitizeConditionalRules( $data['conditional_rules'] )
			: $this->sanitizeConditionalRules( [] );
		$rev_enabled  = ! empty( $data['revisions_enabled'] );
		if ( ! $is_pro ) {
			$device       = 'all';
			$cond_enabled = false;
			$cond_show    = '1';
			$cond_rules   = $this->sanitizeConditionalRules( [] );
			$rev_enabled  = false;
		}

		$meta = [
			'title'                  => $title !== '' ? $title : __( 'Untitled Snippet', 'wppowersuite-lite' ),
			'code'                   => $code,
			'code_type'              => $type,
			'location'               => $loc,
			'location_param'         => isset( $data['location_param'] ) ? max( 1, absint( $data['location_param'] ) ) : 1,
			'location_selector'      => isset( $data['location_selector'] ) ? $this->sanitizeLocationSelector( (string) $data['location_selector'] ) : '',
			'location_element_index' => isset( $data['location_element_index'] ) && $data['location_element_index'] !== ''
				? (string) max( 0, (int) $data['location_element_index'] )
				: '',
			'custom_shortcode'       => $custom,
			'auto_insert'            => ! empty( $data['auto_insert'] ) && $loc !== 'shortcode',
			'priority'               => isset( $data['priority'] ) ? absint( $data['priority'] ) : 10,
			'notes'                  => isset( $data['notes'] ) ? sanitize_textarea_field( (string) $data['notes'] ) : '',
			'schedule_enabled'       => ! empty( $data['schedule_enabled'] ),
			'schedule_start'         => isset( $data['schedule_start'] ) ? sanitize_text_field( (string) $data['schedule_start'] ) : '',
			'schedule_end'           => isset( $data['schedule_end'] ) ? sanitize_text_field( (string) $data['schedule_end'] ) : '',
			'device_type'            => $device,
			'conditional_enabled'    => $cond_enabled,
			'conditional_show'       => $cond_show,
			'conditional_rules'      => $cond_rules,
			'revisions_enabled'      => $rev_enabled,
			'load_as_file'           => ! empty( $data['load_as_file'] ),
			'active'                 => $want_active,
		];

		$saved_id = $this->persistSnippetPost(
			[
				'post_title'   => $meta['title'],
				'post_content' => $code,
				'post_status'  => $want_active ? 'publish' : 'draft',
				'post_type'    => self::POST_TYPE,
			],
			$code
		);
		if ( is_wp_error( $saved_id ) ) {
			return $saved_id;
		}

		$snippet_id = (int) $saved_id;
		$this->applySnippetMetaFromRevisionData( $snippet_id, $meta );
		$this->syncSnippetFilesAfterSave( get_post( $snippet_id ) );

		return $snippet_id;
	}

	/**
	 * Resolve a unique custom shortcode for an imported snippet, suffixing on collision.
	 */
	private function uniqueImportedShortcode( string $custom ): string {
		$custom = $this->sanitizeCustomShortcode( $custom );
		if ( $custom === '' ) {
			return '';
		}

		$base = $custom;
		if ( strlen( $base ) > 40 ) {
			$base = substr( $base, 0, 40 );
			$base = $this->sanitizeCustomShortcode( $base );
		}

		for ( $i = 0; $i < 50; $i++ ) {
			$candidate = $i === 0 ? $base : $base . '_' . ( $i + 1 );
			$candidate = $this->sanitizeCustomShortcode( $candidate );
			if ( $candidate === '' ) {
				continue;
			}
			if ( $this->validateCustomShortcode( $candidate, 0 ) === null ) {
				return $candidate;
			}
		}

		return '';
	}

	/**
	 * Apply revision/snapshot meta fields onto a snippet post.
	 *
	 * @param array<string, mixed> $data Revision or snapshot data.
	 */
	private function applySnippetMetaFromRevisionData( int $snippet_id, array $data ): void {
		$meta_map = [
			'code_type'              => '_wpps_code_type',
			'location'               => '_wpps_location',
			'location_param'         => '_wpps_location_param',
			'location_selector'      => '_wpps_location_selector',
			'location_element_index' => '_wpps_location_element_index',
			'custom_shortcode'       => '_wpps_custom_shortcode',
			'auto_insert'            => '_wpps_auto_insert',
			'priority'               => '_wpps_priority',
			'notes'                  => '_wpps_notes',
			'schedule_enabled'       => '_wpps_schedule_enabled',
			'schedule_start'         => '_wpps_schedule_start',
			'schedule_end'           => '_wpps_schedule_end',
			'device_type'            => '_wpps_device_type',
			'conditional_enabled'    => '_wpps_conditional_enabled',
			'conditional_show'       => '_wpps_conditional_show',
			'revisions_enabled'      => '_wpps_revisions_enabled',
			'load_as_file'           => '_wpps_load_as_file',
		];
		foreach ( $meta_map as $key => $meta_key ) {
			if ( ! array_key_exists( $key, $data ) ) {
				continue;
			}
			$val = $data[ $key ];
			if ( in_array( $meta_key, [ '_wpps_auto_insert', '_wpps_schedule_enabled', '_wpps_conditional_enabled', '_wpps_revisions_enabled', '_wpps_load_as_file' ], true ) ) {
				$val = $val ? '1' : '0';
			}
			if ( $meta_key === '_wpps_location_element_index' ) {
				$val = ( $val === '' || $val === null ) ? '' : (string) max( 0, (int) $val );
			}
			update_post_meta( $snippet_id, $meta_key, $val );
		}
		if ( isset( $data['conditional_rules'] ) && is_array( $data['conditional_rules'] ) ) {
			update_post_meta( $snippet_id, '_wpps_conditional_rules', $data['conditional_rules'] );
		}
	}

	/**
	 * Write snippet asset files after save or restore when file loading is enabled / required.
	 */
	private function syncSnippetFilesAfterSave( ?\WP_Post $post ): void {
		if ( ! $post || $post->post_type !== self::POST_TYPE ) {
			return;
		}
		$type = get_post_meta( $post->ID, '_wpps_code_type', true ) ?: 'html';
		$auto = get_post_meta( $post->ID, '_wpps_auto_insert', true ) === '1';
		$load_file = get_post_meta( $post->ID, '_wpps_load_as_file', true ) === '1'
			|| ( $auto && self::getSetting( 'load_snippets_as_files', false ) );

		if ( $load_file && in_array( $type, [ 'js', 'css' ], true ) ) {
			$raw_code = $post->post_content;
			$raw_code = preg_replace( '/^\s*<' . 'script[^>]*>|<\/script>\s*$/i', '', $raw_code );
			$raw_code = preg_replace( '/^\s*<' . 'style[^>]*>|<\/style>\s*$/i', '', $raw_code );
			$this->ensureSnippetFile( $post, $type, trim( $raw_code ) );
			$this->cleanupOrphanSnippetFilesForPost( $post );
		}
		// Mixed PHP/HTML and explicit load-as-file must always rewrite private includes from DB.
		if ( in_array( $type, [ 'php', 'html' ], true ) && ( $load_file || $this->shouldLoadPhpFromFile( $post ) ) ) {
			$this->ensurePhpSnippetFile( $post );
		}
	}

	public function renderLogsPage(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions.', 'wppowersuite-lite' ) );
		}
		$settings = self::getSettings();
		if ( isset( $_POST['wpps_cs_clear_logs'] ) && check_admin_referer( 'wpps_cs_logs' ) ) {
			update_option( self::ERROR_LOG_OPTION, [], false );
			echo '<div class="notice notice-success"><p>' . esc_html__( 'Error logs cleared.', 'wppowersuite-lite' ) . '</p></div>';
		}
		$enabled = ! empty( $settings['error_logging'] );
		$logs = get_option( self::ERROR_LOG_OPTION, [] );
		$logs = is_array( $logs ) ? array_reverse( $logs ) : [];
		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Code Snippet Error Logs', 'wppowersuite-lite' ); ?></h1>
			<?php echo self::backToSnippetsButton(); ?>
			<p>
				<?php if ( $enabled ) : ?>
					<?php esc_html_e( 'Error logging is enabled.', 'wppowersuite-lite' ); ?>
				<?php else : ?>
					<?php esc_html_e( 'Error logging is disabled.', 'wppowersuite-lite' ); ?>
				<?php endif; ?>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=powersuite-code-snippet&view=settings' ) ); ?>"><?php esc_html_e( 'Change in Settings', 'wppowersuite-lite' ); ?></a>
			</p>
			<form method="post">
				<?php wp_nonce_field( 'wpps_cs_logs' ); ?>
				<p>
					<button type="submit" name="wpps_cs_clear_logs" value="1" class="button"><?php esc_html_e( 'Clear Logs', 'wppowersuite-lite' ); ?></button>
				</p>
			</form>
			<h2><?php esc_html_e( 'Recent Errors', 'wppowersuite-lite' ); ?></h2>
			<?php if ( empty( $logs ) ) : ?>
				<p><?php esc_html_e( 'No errors logged.', 'wppowersuite-lite' ); ?></p>
			<?php else : ?>
				<table class="widefat striped">
					<thead>
					<tr>
						<th><?php esc_html_e( 'Time', 'wppowersuite-lite' ); ?></th>
						<th><?php esc_html_e( 'Snippet', 'wppowersuite-lite' ); ?></th>
						<th><?php esc_html_e( 'Location', 'wppowersuite-lite' ); ?></th>
						<th><?php esc_html_e( 'Context', 'wppowersuite-lite' ); ?></th>
						<th><?php esc_html_e( 'Error', 'wppowersuite-lite' ); ?></th>
					</tr>
					</thead>
					<tbody>
					<?php foreach ( $logs as $log ) : ?>
						<tr>
							<td><?php echo esc_html( $log['time'] ?? '' ); ?></td>
							<td><a href="<?php echo esc_url( admin_url( 'admin.php?page=powersuite-code-snippet&action=edit&id=' . ( $log['snippet'] ?? 0 ) ) ); ?>"><?php echo esc_html( $log['title'] ?? $log['snippet'] ?? '' ); ?></a></td>
							<td><?php echo esc_html( (string) ( $log['location'] ?? '—' ) ); ?></td>
							<td><?php echo esc_html( (string) ( $log['merge_context'] ?? '—' ) ); ?><?php
							if ( isset( $log['snippet_line'] ) && $log['snippet_line'] !== null && $log['snippet_line'] !== '' ) :
								?>
								<br><span class="description"><?php
								printf(
									/* translators: %d: line number inside snippet source */
									esc_html__( 'Snippet line: %d', 'wppowersuite-lite' ),
									(int) $log['snippet_line']
								);
								?></span>
							<?php endif; ?></td>
							<td><?php echo esc_html( $log['message'] ?? '' ); ?><?php if ( ! empty( $log['line'] ) ) : ?> <span class="description">(eval <?php echo (int) $log['line']; ?>)</span><?php endif; ?></td>
						</tr>
					<?php endforeach; ?>
					</tbody>
				</table>
			<?php endif; ?>
		</div>
		<?php
	}

	// AJAX handlers
	public function ajaxSaveSnippet(): void {
		check_ajax_referer( 'wpps_cs_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wppowersuite-lite' ) ] );
		}
		if ( TemporarySessionGuard::isActive() ) {
			TemporarySessionGuard::denyJson();
		}

		$is_pro = self::isProLicensed();

		$id     = isset( $_POST['id'] ) ? absint( $_POST['id'] ) : 0;
		$title  = isset( $_POST['title'] ) ? sanitize_text_field( wp_unslash( $_POST['title'] ) ) : '';
		$code   = self::decodeSnippetCodeFromRequest();
		$type   = isset( $_POST['code_type'] ) ? sanitize_key( $_POST['code_type'] ) : 'html';
		$loc    = isset( $_POST['location'] ) ? sanitize_key( $_POST['location'] ) : 'footer';
		$loc_param    = isset( $_POST['location_param'] ) ? max( 1, absint( $_POST['location_param'] ) ) : 1;
		$loc_selector = isset( $_POST['location_selector'] ) ? $this->sanitizeLocationSelector( wp_unslash( $_POST['location_selector'] ) ) : '';
		$loc_element_index = '';
		if ( isset( $_POST['location_element_index'] ) && $_POST['location_element_index'] !== '' ) {
			$loc_element_index = max( 0, absint( $_POST['location_element_index'] ) );
		}
		$device_type  = isset( $_POST['device_type'] ) ? sanitize_key( $_POST['device_type'] ) : 'all';
		if ( ! in_array( $device_type, [ 'all', 'desktop', 'mobile', 'tablet' ], true ) ) {
			$device_type = 'all';
		}
		$auto   = isset( $_POST['auto_insert'] ) && $_POST['auto_insert'] === '1';
		$active = isset( $_POST['active'] ) && $_POST['active'] === '1';
		$prio   = isset( $_POST['priority'] ) ? absint( $_POST['priority'] ) : 10;
		$sched_enabled = isset( $_POST['schedule_enabled'] ) && $_POST['schedule_enabled'] === '1';
		$sched_start   = isset( $_POST['schedule_start'] ) ? sanitize_text_field( wp_unslash( $_POST['schedule_start'] ) ) : '';
		$sched_end     = isset( $_POST['schedule_end'] ) ? sanitize_text_field( wp_unslash( $_POST['schedule_end'] ) ) : '';

		$allowed_types = [ 'html', 'css', 'js', 'php' ];
		$allowed_locs  = self::getAllLocationSlugs();
		if ( ! in_array( $type, $allowed_types, true ) ) {
			$type = 'html';
		}
		if ( ! in_array( $loc, $allowed_locs, true ) ) {
			$loc = 'footer';
		}

		$type_loc_err = $this->validateTypeLocationPair( $type, $loc );
		if ( $type_loc_err !== null ) {
			wp_send_json_error( [ 'message' => $type_loc_err ] );
		}

		if ( in_array( $type, [ 'html', 'js', 'php' ], true ) && ! current_user_can( 'unfiltered_html' ) ) {
			wp_send_json_error( [ 'message' => __( 'Saving HTML, JavaScript, or PHP snippets requires the unfiltered_html capability.', 'wppowersuite-lite' ) ] );
		}

		if ( self::isProCodeType( $type ) ) {
			$pro_block = self::proCodeTypeBlockReason();
			if ( $pro_block !== null && ( ! $is_pro || $active ) ) {
				wp_send_json_error( [ 'message' => $pro_block ] );
			}
		}

		$rev_enabled  = isset( $_POST['revisions_enabled'] ) && $_POST['revisions_enabled'] === '1';
		$cond_enabled = isset( $_POST['conditional_enabled'] ) && $_POST['conditional_enabled'] === '1';
		$cond_show    = isset( $_POST['conditional_show'] ) && $_POST['conditional_show'] === '0' ? '0' : '1';
		$cond_rules   = isset( $_POST['conditional_rules'] ) && is_array( $_POST['conditional_rules'] ) ? $_POST['conditional_rules'] : [];
		$cond_rules   = $this->sanitizeConditionalRules( $cond_rules );

		if ( ! $is_pro ) {
			if ( $id > 0 ) {
				$device_type = get_post_meta( $id, '_wpps_device_type', true ) ?: 'all';
				if ( ! in_array( $device_type, [ 'all', 'desktop', 'mobile', 'tablet' ], true ) ) {
					$device_type = 'all';
				}
				$cond_enabled = get_post_meta( $id, '_wpps_conditional_enabled', true ) === '1';
				$cond_show    = get_post_meta( $id, '_wpps_conditional_show', true ) === '0' ? '0' : '1';
				$stored_rules = get_post_meta( $id, '_wpps_conditional_rules', true );
				$cond_rules   = is_array( $stored_rules ) ? $stored_rules : $cond_rules;
				$rev_enabled  = get_post_meta( $id, '_wpps_revisions_enabled', true ) === '1';
			} else {
				$device_type  = 'all';
				$cond_enabled = false;
				$cond_show    = '1';
				$cond_rules   = $this->sanitizeConditionalRules( [] );
				$rev_enabled  = false;
			}
		}

		// Strip wrappers before saving - we never store <?php or <' . 'script> in DB.
		if ( $type === 'php' ) {
			$code = self::stripPhpTagsForStorage( $code );
			$syntax_err = self::checkPhpSyntax( $code );
			if ( $syntax_err !== null ) {
				wp_send_json_error( [ 'message' => __( 'PHP syntax error:', 'wppowersuite-lite' ) . ' ' . $syntax_err ] );
			}
			$blocked = SnippetThreatScanner::getRuntimeBlockReason( $code );
			if ( $blocked !== null ) {
				wp_send_json_error( [ 'message' => $blocked ] );
			}
			if ( $active ) {
				$runtime_err = $this->testPhpSnippetRuntime( $code );
				if ( $runtime_err !== null ) {
					wp_send_json_error( [ 'message' => __( 'PHP error:', 'wppowersuite-lite' ) . ' ' . $runtime_err ] );
				}
			}
		} elseif ( $type === 'js' ) {
			$code = self::stripJsTagsForStorage( $code );
		}

		$custom_shortcode = isset( $_POST['custom_shortcode'] )
			? $this->sanitizeCustomShortcode( (string) wp_unslash( $_POST['custom_shortcode'] ) )
			: '';
		$shortcode_err    = $this->validateCustomShortcode( $custom_shortcode, $id );
		if ( $shortcode_err !== null ) {
			wp_send_json_error( [ 'message' => $shortcode_err ] );
		}

		$notes = isset( $_POST['notes'] ) ? sanitize_textarea_field( wp_unslash( $_POST['notes'] ) ) : '';

		$post_data = [
			'post_type'    => self::POST_TYPE,
			'post_title'   => $title ?: __( 'Untitled Snippet', 'wppowersuite-lite' ),
			'post_content' => $code,
			'post_status'  => $active ? 'publish' : 'draft',
		];
		if ( $id > 0 ) {
			$post_data['ID'] = $id;
		}

		// Prevent WordPress KSES and content filters from stripping/modifying PHP, script, style tags.
		$revisions = class_exists( Wpps_Revisions::class, false ) ? new Wpps_Revisions() : null;
		if ( $id > 0 ) {
			$existing = get_post( $id );
			if ( ! $existing || $existing->post_type !== self::POST_TYPE ) {
				wp_send_json_error( [ 'message' => __( 'Invalid snippet.', 'wppowersuite-lite' ) ] );
			}
			if ( $rev_enabled && $revisions ) {
				$revisions->capture_snippet_data( $id );
			}
		}

		$new_id = $this->persistSnippetPost( $post_data, $code );
		if ( is_wp_error( $new_id ) ) {
			wp_send_json_error( [ 'message' => $new_id->get_error_message() ] );
		}

		update_post_meta( $new_id, '_wpps_code_type', $type );
		update_post_meta( $new_id, '_wpps_location', $loc );
		update_post_meta( $new_id, '_wpps_location_param', $loc_param );
		update_post_meta( $new_id, '_wpps_location_selector', $loc_selector );
		update_post_meta( $new_id, '_wpps_location_element_index', $loc_element_index === '' ? '' : (string) $loc_element_index );
		update_post_meta( $new_id, '_wpps_device_type', $device_type );
		update_post_meta( $new_id, '_wpps_custom_shortcode', $custom_shortcode );
		update_post_meta( $new_id, '_wpps_notes', $notes );
		update_post_meta( $new_id, '_wpps_auto_insert', $auto ? '1' : '0' );
		update_post_meta( $new_id, '_wpps_conditional_enabled', $cond_enabled ? '1' : '0' );
		update_post_meta( $new_id, '_wpps_conditional_show', $cond_show );
		update_post_meta( $new_id, '_wpps_conditional_rules', $cond_rules );
		update_post_meta( $new_id, '_wpps_revisions_enabled', $rev_enabled ? '1' : '0' );
		update_post_meta( $new_id, '_wpps_priority', $prio );
		update_post_meta( $new_id, '_wpps_schedule_enabled', $sched_enabled ? '1' : '0' );
		update_post_meta( $new_id, '_wpps_schedule_start', $sched_start );
		update_post_meta( $new_id, '_wpps_schedule_end', $sched_end );
		$load_as_file = isset( $_POST['load_as_file'] ) && $_POST['load_as_file'] === '1';
		update_post_meta( $new_id, '_wpps_load_as_file', $load_as_file ? '1' : '0' );

		if ( $type === 'php' ) {
			$saved_post = get_post( $new_id );
			if ( $saved_post && is_string( $saved_post->post_content ) ) {
				$stored_code = self::stripPhpTagsForStorage( $saved_post->post_content );
				if ( $stored_code !== $code ) {
					$this->writeSnippetPostContentExact( (int) $new_id, $code );
					$saved_post  = get_post( $new_id );
					$stored_code = ( $saved_post instanceof \WP_Post && is_string( $saved_post->post_content ) )
						? self::stripPhpTagsForStorage( $saved_post->post_content )
						: $stored_code;
				}
				$stored_err  = self::checkPhpSyntax( $stored_code );
				if ( $stored_err !== null ) {
					wp_update_post( [ 'ID' => $new_id, 'post_status' => 'draft' ] );
					wp_send_json_error(
						[
							'message' => __( 'PHP syntax error in stored snippet (code was altered while saving):', 'wppowersuite-lite' ) . ' ' . $stored_err,
						]
					);
				}
			}
			if ( $load_as_file || ( $auto && strpos( $code, chr( 63 ) . chr( 62 ) ) !== false ) ) {
				$post_for_file = get_post( $new_id );
				if ( $post_for_file instanceof \WP_Post ) {
					$this->ensurePhpSnippetFile( $post_for_file );
				}
			}
		}

		// Saving as active clears any prior auto-deactivation notice for this snippet.
		if ( $active ) {
			$this->clearSnippetErrorState( (int) $new_id );
		}

		$this->bustSnippetCaches();

		if ( $id > 0 && $new_id > 0 && $rev_enabled && $revisions ) {
			$new_data = Wpps_Revisions::get_snippet_revision_data( $new_id );
			$revisions->maybe_create_revision( $new_id, $new_data );
		}

		delete_post_meta( $new_id, self::LAST_PHP_ERROR_META );

		$this->syncSnippetFilesAfterSave( get_post( $new_id ) );

		wp_send_json_success( [
			'id'      => $new_id,
			'message' => __( 'Snippet saved successfully.', 'wppowersuite-lite' ),
		] );
	}

	public function ajaxDeleteSnippet(): void {
		check_ajax_referer( 'wpps_cs_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wppowersuite-lite' ) ] );
		}
		if ( TemporarySessionGuard::isActive() ) {
			TemporarySessionGuard::denyJson();
		}
		$id = isset( $_POST['id'] ) ? absint( $_POST['id'] ) : 0;
		if ( $id === 0 ) {
			wp_send_json_error( [ 'message' => __( 'Invalid ID.', 'wppowersuite-lite' ) ] );
		}
		$post = get_post( $id );
		if ( ! $post || $post->post_type !== self::POST_TYPE ) {
			wp_send_json_error( [ 'message' => __( 'Snippet not found.', 'wppowersuite-lite' ) ] );
		}
		$this->deleteSnippetCompletely( $id );
		$this->bustSnippetCaches();
		wp_send_json_success( [ 'message' => __( 'Snippet deleted.', 'wppowersuite-lite' ) ] );
	}

	public function ajaxToggleSnippet(): void {
		check_ajax_referer( 'wpps_cs_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wppowersuite-lite' ) ] );
		}
		if ( TemporarySessionGuard::isActive() ) {
			TemporarySessionGuard::denyJson();
		}
		$id = isset( $_POST['id'] ) ? absint( $_POST['id'] ) : 0;
		if ( $id === 0 ) {
			wp_send_json_error( [ 'message' => __( 'Invalid ID.', 'wppowersuite-lite' ) ] );
		}
		$post = get_post( $id );
		if ( ! $post || $post->post_type !== self::POST_TYPE ) {
			wp_send_json_error( [ 'message' => __( 'Snippet not found.', 'wppowersuite-lite' ) ] );
		}
		$new_status = $post->post_status === 'publish' ? 'draft' : 'publish';

		if ( $new_status === 'publish' ) {
			$block = $this->getSnippetActivationBlockReason( $post );
			if ( $block !== null ) {
				wp_send_json_error( [ 'message' => $block ] );
			}
			$this->clearSnippetErrorState( $id );
		}

		wp_update_post( [ 'ID' => $id, 'post_status' => $new_status ] );
		$this->bustSnippetCaches();
		wp_send_json_success( [
			'active'  => $new_status === 'publish',
			'counts'  => $this->getSnippetCounts(),
			'message' => $new_status === 'publish' ? __( 'Snippet activated.', 'wppowersuite-lite' ) : __( 'Snippet deactivated.', 'wppowersuite-lite' ),
		] );
	}

	/**
	 * AJAX: refresh the snippets list without a full admin page load.
	 *
	 * Auth: manage_options + wpps_cs_nonce + TemporarySessionGuard.
	 * Input: allowlisted filter/sort scalars only. HTML is the same escaped
	 * list-table markup as the full page.
	 */
	public function ajaxListSnippets(): void {
		check_ajax_referer( 'wpps_cs_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wppowersuite-lite' ) ] );
		}
		if ( TemporarySessionGuard::isActive() ) {
			TemporarySessionGuard::denyJson();
		}

		$keys = [ 'status', 's', 'snippet_type', 'snippet_location', 'snippet_device', 'orderby', 'order', 'paged' ];
		foreach ( $keys as $key ) {
			if ( isset( $_POST[ $key ] ) && ! is_array( $_POST[ $key ] ) ) {
				$_REQUEST[ $key ] = wp_unslash( $_POST[ $key ] );
				$_GET[ $key ]     = $_REQUEST[ $key ];
			} else {
				unset( $_REQUEST[ $key ], $_GET[ $key ] );
			}
		}

		require_once __DIR__ . '/class-code-snippet-list-table.php';
		$filters = \Code_Snippet_List_Table::filtersFromRequest();
		wp_send_json_success(
			[
				'html' => \Code_Snippet_List_Table::renderAppInnerToString( $this, $filters ),
				'url'  => \Code_Snippet_List_Table::urlFromFilters( $filters ),
			]
		);
	}

	public function ajaxGetSnippet(): void {
		check_ajax_referer( 'wpps_cs_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wppowersuite-lite' ) ] );
		}
		$id = isset( $_GET['id'] ) ? absint( $_GET['id'] ) : 0;
		if ( $id === 0 ) {
			wp_send_json_error( [ 'message' => __( 'Invalid ID.', 'wppowersuite-lite' ) ] );
		}
		$snippet = $this->getSnippetData( $id );
		if ( $snippet === null ) {
			wp_send_json_error( [ 'message' => __( 'Snippet not found.', 'wppowersuite-lite' ) ] );
		}
		wp_send_json_success( $snippet );
	}

	/**
	 * AJAX: Load compare markup for two revisions (compare any two).
	 */
	public function ajaxLoadRevisionsCompare(): void {
		check_ajax_referer( 'wpps_cs_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wppowersuite-lite' ) ] );
		}
		if ( ! self::isProLicensed() || ! class_exists( Wpps_Revisions::class, false ) ) {
			wp_send_json_error( [ 'message' => __( 'Code Snippet requires WP PowerSuite Pro and an active license.', 'wppowersuite-lite' ) ], 403 );
		}
		$ids = isset( $_POST['ids'] ) && is_array( $_POST['ids'] ) ? array_map( 'absint', wp_unslash( $_POST['ids'] ) ) : [];
		$snippet_id = isset( $_POST['snippet_id'] ) ? absint( $_POST['snippet_id'] ) : 0;
		if ( count( $ids ) !== 2 || $snippet_id <= 0 ) {
			wp_send_json_error( [ 'message' => __( 'Invalid request.', 'wppowersuite-lite' ) ] );
		}
		$revisions = new Wpps_Revisions();
		$data1 = $revisions->get_revision_data( $ids[0] );
		$data2 = $revisions->get_revision_data( $ids[1] );
		if ( empty( $data1 ) || empty( $data2 ) ) {
			wp_send_json_error( [ 'message' => __( 'Revision not found.', 'wppowersuite-lite' ) ] );
		}
		$rev1 = $revisions->get_revision( $ids[0] );
		$rev2 = $revisions->get_revision( $ids[1] );
		if ( ! $rev1 || ! $rev2 || (int) $rev1->snippet_id !== $snippet_id || (int) $rev2->snippet_id !== $snippet_id ) {
			wp_send_json_error( [ 'message' => __( 'Invalid revision.', 'wppowersuite-lite' ) ] );
		}
		$created1 = strtotime( $rev1->created );
		$created2 = strtotime( $rev2->created );
		$left_data  = $created1 <= $created2 ? $data1 : $data2;
		$right_data = $created1 <= $created2 ? $data2 : $data1;
		$markup = Wpps_Revisions_Display::render_compare_any_two( $left_data, $right_data );
		wp_send_json_success( [ 'markup' => $markup ] );
	}

	/**
	 * AJAX: Get revisions list for edit page.
	 */
	public function ajaxGetRevisionsList(): void {
		check_ajax_referer( 'wpps_cs_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wppowersuite-lite' ) ] );
		}
		if ( ! self::isProLicensed() || ! class_exists( Wpps_Revisions::class, false ) ) {
			wp_send_json_error( [ 'message' => __( 'Code Snippet requires WP PowerSuite Pro and an active license.', 'wppowersuite-lite' ) ], 403 );
		}
		$snippet_id = isset( $_GET['snippet_id'] ) ? absint( $_GET['snippet_id'] ) : 0;
		if ( $snippet_id <= 0 ) {
			wp_send_json_error( [ 'message' => __( 'Invalid snippet.', 'wppowersuite-lite' ) ] );
		}
		$post = get_post( $snippet_id );
		if ( ! $post || $post->post_type !== self::POST_TYPE ) {
			wp_send_json_error( [ 'message' => __( 'Snippet not found.', 'wppowersuite-lite' ) ] );
		}
		$revisions_enabled = get_post_meta( $snippet_id, '_wpps_revisions_enabled', true ) === '1';
		if ( ! $revisions_enabled ) {
			wp_send_json_success( [
				'revisions' => [],
				'current_version' => null,
				'compare_url' => admin_url( 'admin.php?page=powersuite-code-snippet&view=revisions&snippet_id=' . $snippet_id ),
				'has_more' => false,
			] );
			return;
		}
		$limit  = isset( $_GET['limit'] ) ? max( 1, min( 50, (int) $_GET['limit'] ) ) : 5;
		$offset = isset( $_GET['offset'] ) ? max( 0, (int) $_GET['offset'] ) : 0;
		$revisions = new Wpps_Revisions();
		$total  = $revisions->count_snippet_revisions( $snippet_id );
		$rows   = $revisions->get_snippet_revisions_page( $snippet_id, $limit, $offset );
		$items = [];
		foreach ( $rows as $rev ) {
			$items[] = [
				'id'       => (int) $rev->revision_id,
				'date'     => $rev->created,
				'date_fmt' => wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $rev->created ) ),
				'author'   => get_the_author_meta( 'display_name', $rev->author_id ),
				'avatar'   => get_avatar_url( $rev->author_id, [ 'size' => 32 ] ),
			];
		}
		$has_more = ( $offset + count( $items ) ) < $total;
		$latest_row = $offset === 0 && ! empty( $rows ) ? $rows[0] : null;
		if ( $latest_row === null && $total > 0 ) {
			$latest_rows = $revisions->get_snippet_revisions_page( $snippet_id, 1, 0 );
			$latest_row  = ! empty( $latest_rows ) ? $latest_rows[0] : null;
		}
		$current = [
			'author'   => get_the_author_meta( 'display_name', (int) $post->post_author ),
			'avatar'   => get_avatar_url( (int) $post->post_author, [ 'size' => 32 ] ),
			'date_fmt' => wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $post->post_modified ) ),
			'is_current' => true,
		];
		$latest_revision_id = $latest_row ? (int) $latest_row->revision_id : 0;

		wp_send_json_success( [
			'revisions'        => $items,
			'current_version'  => $current,
			'compare_url'      => admin_url( 'admin.php?page=powersuite-code-snippet&view=revisions&snippet_id=' . $snippet_id ),
			'has_more'         => $has_more,
			'latest_revision_id' => $latest_revision_id,
		] );
	}

	/**
	 * AJAX: Restore revision (stays on edit page, no redirect to revisions page).
	 */
	public function ajaxRestoreRevision(): void {
		check_ajax_referer( 'wpps_cs_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wppowersuite-lite' ) ] );
		}
		if ( TemporarySessionGuard::isActive() ) {
			TemporarySessionGuard::denyJson();
		}
		if ( ! self::isProLicensed() || ! class_exists( Wpps_Revisions::class, false ) ) {
			wp_send_json_error( [ 'message' => __( 'Code Snippet requires WP PowerSuite Pro and an active license.', 'wppowersuite-lite' ) ], 403 );
		}
		$revision_id = isset( $_POST['revision_id'] ) ? absint( $_POST['revision_id'] ) : 0;
		$snippet_id  = isset( $_POST['snippet_id'] ) ? absint( $_POST['snippet_id'] ) : 0;
		if ( $revision_id <= 0 || $snippet_id <= 0 ) {
			wp_send_json_error( [ 'message' => __( 'Invalid request.', 'wppowersuite-lite' ) ] );
		}
		$revisions = new Wpps_Revisions();
		$rev_data  = $revisions->get_revision_data( $revision_id );
		if ( empty( $rev_data ) ) {
			wp_send_json_error( [ 'message' => __( 'Revision not found.', 'wppowersuite-lite' ) ] );
		}
		$rev_row = $revisions->get_revision( $revision_id );
		if ( ! $rev_row || (int) $rev_row->snippet_id !== $snippet_id ) {
			wp_send_json_error( [ 'message' => __( 'Invalid revision.', 'wppowersuite-lite' ) ] );
		}
		$restore_err = $this->restoreSnippetFromRevisionData( $snippet_id, $rev_data, $revisions );
		if ( $restore_err !== null ) {
			wp_send_json_error( [ 'message' => $restore_err ] );
		}
		$this->bustSnippetCaches();
		wp_cache_delete( 'wpps_revisions_' . $snippet_id, 'wpps' );
		$snippet = $this->getSnippetData( $snippet_id );
		wp_send_json_success( [
			'message' => __( 'Revision restored successfully.', 'wppowersuite-lite' ),
			'snippet' => $snippet,
		] );
	}

	/**
	 * Get snippet data by ID for edit page.
	 *
	 * @param int $id Snippet post ID.
	 * @return array|null Snippet data or null if not found.
	 */
	public function getSnippetData( int $id ): ?array {
		$post = get_post( $id );
		if ( ! $post || $post->post_type !== self::POST_TYPE ) {
			return null;
		}
		$cond_rules = get_post_meta( $post->ID, '_wpps_conditional_rules', true );
		return [
			'id'                    => $post->ID,
			'title'                 => $post->post_title,
			'code'                  => $post->post_content,
			'code_type'             => get_post_meta( $post->ID, '_wpps_code_type', true ) ?: 'html',
			'location'              => get_post_meta( $post->ID, '_wpps_location', true ) ?: 'footer',
			'location_param'        => (int) ( get_post_meta( $post->ID, '_wpps_location_param', true ) ?: 1 ),
			'location_selector'     => get_post_meta( $post->ID, '_wpps_location_selector', true ) ?: '',
			'location_element_index' => get_post_meta( $post->ID, '_wpps_location_element_index', true ) ?: '',
			'custom_shortcode'      => get_post_meta( $post->ID, '_wpps_custom_shortcode', true ) ?: '',
			'notes'                 => get_post_meta( $post->ID, '_wpps_notes', true ) ?: '',
			'auto_insert'           => ( get_post_meta( $post->ID, '_wpps_auto_insert', true ) ?: '0' ) === '1',
			'priority'              => (int) ( get_post_meta( $post->ID, '_wpps_priority', true ) ?: 10 ),
			'active'                => $post->post_status === 'publish',
			'schedule_enabled'      => ( get_post_meta( $post->ID, '_wpps_schedule_enabled', true ) ?: '0' ) === '1',
			'schedule_start'        => get_post_meta( $post->ID, '_wpps_schedule_start', true ) ?: '',
			'schedule_end'          => get_post_meta( $post->ID, '_wpps_schedule_end', true ) ?: '',
			'device_type'           => get_post_meta( $post->ID, '_wpps_device_type', true ) ?: 'all',
			'conditional_enabled'   => ( get_post_meta( $post->ID, '_wpps_conditional_enabled', true ) ?: '0' ) === '1',
			'conditional_show'      => get_post_meta( $post->ID, '_wpps_conditional_show', true ) ?: '1',
			'conditional_rules'     => is_array( $cond_rules ) ? $cond_rules : [],
			'revisions_enabled'     => ( get_post_meta( $post->ID, '_wpps_revisions_enabled', true ) ?: '0' ) === '1',
			'load_as_file'           => ( get_post_meta( $post->ID, '_wpps_load_as_file', true ) ?: '0' ) === '1',
		];
	}

	public function getDataLocations(): array {
		return [
			'post_type' => self::POST_TYPE,
			'transient' => self::CACHE_OPTION,
		];
	}

}
