<?php
/**
 * Clear Divi's static CSS/JS cache via the official PageResource API.
 *
 * @package DiviSupreme
 */

declare(strict_types=1);

namespace DiviSupreme\Includes;

if ( ! defined( 'ABSPATH' ) ) {
	die( 'Direct access forbidden.' );
}

/**
 * Shared Divi static cache clear for manual triggers and post-update auto-clear.
 */
final class DiviCacheClear {

	public const INSTALLED_VERSION_OPTION = 'dsm_pro_installed_version';

	public const AJAX_ACTION = 'dsm_clear_divi_cache';

	public const AJAX_NONCE_ACTION = 'dsm_clear_divi_cache';

	public const SCOPE_ALL = 'all';

	public const SCOPE_POST = 'post';

	public const SCOPE_HOME = 'home';

	/**
	 * @return void
	 */
	public static function register(): void {
		add_action( 'admin_init', array( self::class, 'maybe_clear_after_version_upgrade' ), 5 );
		add_action( 'upgrader_process_complete', array( self::class, 'maybe_clear_after_version_upgrade_on_upgrader' ), 10, 2 );
		add_action( 'activated_plugin', array( self::class, 'maybe_clear_after_version_upgrade_on_activation' ), 10, 2 );
		add_action( 'wp_ajax_' . self::AJAX_ACTION, array( self::class, 'ajax_clear' ) );
		add_action( 'admin_bar_menu', array( self::class, 'register_admin_bar_node' ), 100 );
		add_action( 'wp_before_admin_bar_render', array( self::class, 'position_admin_bar_node_before_divi' ) );
		add_action( 'wp_enqueue_scripts', array( self::class, 'enqueue_admin_bar_script' ) );
		add_action( 'admin_enqueue_scripts', array( self::class, 'enqueue_admin_bar_script' ) );
	}

	/**
	 * Detect a DSM version upgrade and optionally clear Divi static cache once.
	 *
	 * @return void
	 */
	public static function maybe_clear_after_version_upgrade(): void {
		if ( ! defined( 'DSM_PRO_VERSION' ) ) {
			return;
		}

		$current = (string) DSM_PRO_VERSION;
		$stored  = get_option( self::INSTALLED_VERSION_OPTION, '' );

		if ( ! is_string( $stored ) ) {
			$stored = '';
		}

		if ( '' === $stored ) {
			update_option( self::INSTALLED_VERSION_OPTION, $current, false );

			return;
		}

		if ( version_compare( $stored, $current, '>=' ) ) {
			return;
		}

		if ( function_exists( 'dsm_auto_clear_divi_cache_on_update_enabled' ) && dsm_auto_clear_divi_cache_on_update_enabled() ) {
			self::clear_static_cache( self::SCOPE_ALL );
		}

		update_option( self::INSTALLED_VERSION_OPTION, $current, false );
	}

	/**
	 * Run the version-upgrade cache clear when this plugin is updated via the WP upgrader (admin).
	 *
	 * @param \WP_Upgrader $upgrader   Upgrader instance.
	 * @param array        $hook_extra Extra arguments passed to hooked filters.
	 * @return void
	 */
	public static function maybe_clear_after_version_upgrade_on_upgrader( $upgrader, array $hook_extra ): void {
		unset( $upgrader );

		if (
			! isset( $hook_extra['action'], $hook_extra['type'] )
			|| 'update' !== $hook_extra['action']
			|| 'plugin' !== $hook_extra['type']
		) {
			return;
		}

		$plugin_basenames = array();

		if ( isset( $hook_extra['plugins'] ) && is_array( $hook_extra['plugins'] ) ) {
			$plugin_basenames = array_merge( $plugin_basenames, $hook_extra['plugins'] );
		}

		if ( isset( $hook_extra['plugin'] ) && is_string( $hook_extra['plugin'] ) ) {
			$plugin_basenames[] = $hook_extra['plugin'];
		}

		if ( array() === $plugin_basenames || ! defined( 'DSM_DIR_PATH' ) ) {
			return;
		}

		$our_plugin = plugin_basename( DSM_DIR_PATH . 'supreme-modules-pro-for-divi.php' );

		foreach ( $plugin_basenames as $plugin_basename ) {
			if ( is_string( $plugin_basename ) && $plugin_basename === $our_plugin ) {
				self::maybe_clear_after_version_upgrade();
				break;
			}
		}
	}

	/**
	 * Stamp version / clear cache when this plugin is activated from wp-admin (fresh install or re-enable).
	 *
	 * @param string $plugin Basename of the activated plugin.
	 * @param bool   $network_wide Whether the plugin was network-activated.
	 * @return void
	 */
	public static function maybe_clear_after_version_upgrade_on_activation( string $plugin, bool $network_wide ): void {
		unset( $network_wide );

		if ( ! defined( 'DSM_DIR_PATH' ) ) {
			return;
		}

		$our_plugin = plugin_basename( DSM_DIR_PATH . 'supreme-modules-pro-for-divi.php' );

		if ( $plugin === $our_plugin ) {
			self::maybe_clear_after_version_upgrade();
		}
	}

	/**
	 * AJAX handler for manual cache clear (settings dashboard + admin bar).
	 *
	 * @return void
	 */
	public static function ajax_clear(): void {
		check_ajax_referer( self::AJAX_NONCE_ACTION, 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error(
				array(
					'message' => esc_html__( 'You do not have permission to clear the Divi cache.', 'dsm-supreme-modules-pro-for-divi' ),
				),
				403
			);
		}

		$scope   = sanitize_key( (string) ( $_POST['scope'] ?? self::SCOPE_ALL ) );
		$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;

		$result = self::clear_static_cache( $scope, $post_id > 0 ? $post_id : null );

		if ( ! $result['success'] ) {
			wp_send_json_error(
				array(
					'message'  => $result['message'],
					'deferred' => $result['deferred'],
				)
			);
		}

		wp_send_json_success(
			array(
				'message'  => $result['message'],
				'deferred' => $result['deferred'],
			)
		);
	}

	/**
	 * Clear Divi static page resources using Divi's official API.
	 *
	 * @param string   $scope   Clear scope: all, post, or home.
	 * @param int|null $post_id Target post ID for post scope (optional override).
	 * @return array{success: bool, message: string, deferred: bool}
	 */
	public static function clear_static_cache( string $scope = self::SCOPE_ALL, ?int $post_id = null ): array {
		if ( ! self::is_divi_cache_api_available() ) {
			return array(
				'success'  => false,
				'message'  => esc_html__( 'Divi cache API is not available. Ensure the Divi theme is active.', 'dsm-supreme-modules-pro-for-divi' ),
				'deferred' => false,
			);
		}

		if ( ! self::can_invoke_clear_now() ) {
			self::schedule_deferred_clear();

			return array(
				'success'  => true,
				'message'  => esc_html__( 'Divi static cache clear has been scheduled and will complete on the next admin visit.', 'dsm-supreme-modules-pro-for-divi' ),
				'deferred' => true,
			);
		}

		switch ( $scope ) {
			case self::SCOPE_HOME:
				$home_post_id = null !== $post_id && $post_id > 0 ? $post_id : self::resolve_home_post_id();

				if ( null !== $home_post_id && $home_post_id > 0 ) {
					return self::clear_static_cache_for_post( $home_post_id, self::get_home_clear_success_message( $home_post_id ) );
				}

				return self::clear_blog_home_static_cache();

			case self::SCOPE_POST:
				$target_post_id = null !== $post_id && $post_id > 0 ? $post_id : self::resolve_context_post_id();

				if ( null === $target_post_id || $target_post_id <= 0 ) {
					return array(
						'success'  => false,
						'message'  => esc_html__( 'No page context is available to clear.', 'dsm-supreme-modules-pro-for-divi' ),
						'deferred' => false,
					);
				}

				return self::clear_static_cache_for_post( $target_post_id, self::get_post_clear_success_message( $target_post_id ) );

			case self::SCOPE_ALL:
			default:
				return self::clear_all_static_cache();
		}
	}

	/**
	 * @return bool
	 */
	public static function is_divi_cache_api_available(): bool {
		return class_exists( '\ET_Core_PageResource' )
			&& method_exists( '\ET_Core_PageResource', 'remove_static_resources' );
	}

	/**
	 * @param \WP_Admin_Bar $admin_bar Admin bar instance.
	 * @return void
	 */
	public static function register_admin_bar_node( \WP_Admin_Bar $admin_bar ): void {
		if ( ! is_admin_bar_showing() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		if ( ! function_exists( 'dsm_show_clear_divi_cache_admin_bar_enabled' ) || ! dsm_show_clear_divi_cache_admin_bar_enabled() ) {
			return;
		}

		if ( ! self::is_divi_cache_api_available() ) {
			return;
		}

		$admin_bar->add_node(
			array(
				'id'    => 'dsm-clear-divi-cache',
				'title' => esc_html__( 'Clear Divi Cache', 'dsm-supreme-modules-pro-for-divi' ),
				'href'  => '#dsm-clear-divi-cache',
				'meta'  => array(
					'class' => 'menupop dsm-clear-divi-cache-root',
					'title' => esc_attr__( 'Clear Divi static CSS cache (rebuilds automatically on next page visit)', 'dsm-supreme-modules-pro-for-divi' ),
				),
			)
		);

		foreach ( self::get_admin_bar_scope_items() as $item ) {
			$admin_bar->add_node(
				array(
					'id'     => 'dsm-clear-divi-cache-' . $item['scope'],
					'parent' => 'dsm-clear-divi-cache',
					'title'  => esc_html( $item['label'] ),
					'href'   => '#dsm-clear-divi-cache-' . $item['scope'],
					'meta'   => array(
						'class' => 'dsm-clear-divi-cache-scope',
						'title' => esc_attr( $item['description'] ),
					),
				)
			);
		}
	}

	/**
	 * Move Clear Divi Cache immediately before Divi's Edit With Divi toolbar item.
	 *
	 * @return void
	 */
	public static function position_admin_bar_node_before_divi(): void {
		global $wp_admin_bar;

		if ( ! is_admin_bar_showing() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		if ( ! function_exists( 'dsm_show_clear_divi_cache_admin_bar_enabled' ) || ! dsm_show_clear_divi_cache_admin_bar_enabled() ) {
			return;
		}

		if ( ! $wp_admin_bar instanceof \WP_Admin_Bar ) {
			return;
		}

		$root_node_id = 'dsm-clear-divi-cache';

		if ( ! $wp_admin_bar->get_node( $root_node_id ) ) {
			return;
		}

		$divi_node_id = self::get_divi_admin_bar_node_id( $wp_admin_bar );

		if ( null === $divi_node_id ) {
			return;
		}

		$divi_node = $wp_admin_bar->get_node( $divi_node_id );

		if ( ! $divi_node ) {
			return;
		}

		$nodes_to_move = self::collect_admin_bar_subtree_nodes( $wp_admin_bar, $root_node_id );

		foreach ( array_keys( $nodes_to_move ) as $node_id ) {
			$wp_admin_bar->remove_node( $node_id );
		}

		$wp_admin_bar->remove_node( $divi_node_id );

		foreach ( $nodes_to_move as $node ) {
			self::restore_admin_bar_node( $wp_admin_bar, $node );
		}

		self::restore_admin_bar_node( $wp_admin_bar, $divi_node );
	}

	/**
	 * @param \WP_Admin_Bar $admin_bar Admin bar instance.
	 * @return string|null
	 */
	private static function get_divi_admin_bar_node_id( \WP_Admin_Bar $admin_bar ): ?string {
		foreach ( array( 'et-use-visual-builder', 'et-disable-visual-builder' ) as $node_id ) {
			if ( $admin_bar->get_node( $node_id ) ) {
				return $node_id;
			}
		}

		return null;
	}

	/**
	 * @param \WP_Admin_Bar $admin_bar Admin bar instance.
	 * @param string        $root_id   Root node ID.
	 * @return array<string, object>
	 */
	private static function collect_admin_bar_subtree_nodes( \WP_Admin_Bar $admin_bar, string $root_id ): array {
		$all_nodes = $admin_bar->get_nodes();

		if ( empty( $all_nodes ) || ! isset( $all_nodes[ $root_id ] ) ) {
			return array();
		}

		$ordered_nodes = array(
			$root_id => $all_nodes[ $root_id ],
		);

		foreach ( $all_nodes as $node_id => $node ) {
			if ( $root_id === $node_id ) {
				continue;
			}

			if ( $root_id === ( $node->parent ?? '' ) ) {
				$ordered_nodes[ $node_id ] = $node;
			}
		}

		return $ordered_nodes;
	}

	/**
	 * @param \WP_Admin_Bar $admin_bar Admin bar instance.
	 * @param object        $node      Admin bar node object.
	 * @return void
	 */
	private static function restore_admin_bar_node( \WP_Admin_Bar $admin_bar, object $node ): void {
		$args = array(
			'id'     => $node->id,
			'title'  => $node->title,
			'parent' => $node->parent,
			'href'   => $node->href,
			'meta'   => isset( $node->meta ) && is_array( $node->meta ) ? $node->meta : array(),
		);

		if ( ! empty( $node->group ) ) {
			$args['group'] = true;
		}

		$admin_bar->add_node( $args );
	}

	/**
	 * @return void
	 */
	public static function enqueue_admin_bar_script(): void {
		if ( ! is_admin_bar_showing() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		if ( ! function_exists( 'dsm_show_clear_divi_cache_admin_bar_enabled' ) || ! dsm_show_clear_divi_cache_admin_bar_enabled() ) {
			return;
		}

		if ( ! self::is_divi_cache_api_available() ) {
			return;
		}

		wp_register_script(
			'dsm-divi-cache-clear-admin-bar',
			DSM_DIR_URL . 'assets/js/divi-cache-clear-admin-bar.js',
			array(),
			defined( 'DSM_PRO_VERSION' ) ? DSM_PRO_VERSION : '1.0.0',
			true
		);

		wp_localize_script(
			'dsm-divi-cache-clear-admin-bar',
			'dsmDiviCacheClear',
			self::get_script_payload()
		);

		wp_enqueue_script( 'dsm-divi-cache-clear-admin-bar' );
	}

	/**
	 * @return array<string, mixed>
	 */
	public static function get_script_payload(): array {
		return array(
			'ajaxUrl' => admin_url( 'admin-ajax.php' ),
			'action'  => self::AJAX_ACTION,
			'nonce'   => wp_create_nonce( self::AJAX_NONCE_ACTION ),
			'scopes'  => self::get_admin_bar_scope_items(),
			'strings' => array(
				'clearing'     => esc_html__( 'Clearing…', 'dsm-supreme-modules-pro-for-divi' ),
				'success'      => esc_html__( 'Divi static cache cleared successfully.', 'dsm-supreme-modules-pro-for-divi' ),
				'successAll'   => esc_html__( 'All Divi static cache cleared.', 'dsm-supreme-modules-pro-for-divi' ),
				'successPost'  => esc_html__( 'Divi static cache cleared for this page.', 'dsm-supreme-modules-pro-for-divi' ),
				'successHome'  => esc_html__( 'Divi static cache cleared for the homepage.', 'dsm-supreme-modules-pro-for-divi' ),
				'deferred'     => esc_html__( 'Divi static cache clear scheduled for the next admin visit.', 'dsm-supreme-modules-pro-for-divi' ),
				'error'        => esc_html__( 'Could not clear Divi static cache.', 'dsm-supreme-modules-pro-for-divi' ),
				'parentLabel'  => esc_html__( 'Clear Divi Cache', 'dsm-supreme-modules-pro-for-divi' ),
			),
		);
	}

	/**
	 * @return array<int, array{scope: string, label: string, description: string, post_id: int}>
	 */
	public static function get_admin_bar_scope_items(): array {
		$items = array(
			array(
				'scope'       => self::SCOPE_ALL,
				'label'       => __( 'Clear all static cache', 'dsm-supreme-modules-pro-for-divi' ),
				'description' => __( 'Clear Divi static CSS/JS for the entire site.', 'dsm-supreme-modules-pro-for-divi' ),
				'post_id'     => 0,
			),
		);

		$page_context = self::resolve_page_context();

		if ( null !== $page_context ) {
			if ( $page_context['is_front_page'] ) {
				$items[] = array(
					'scope'       => self::SCOPE_HOME,
					'label'       => sprintf(
						/* translators: %s: homepage label */
						__( 'Clear homepage (%s)', 'dsm-supreme-modules-pro-for-divi' ),
						$page_context['label']
					),
					'description' => __( 'Clear Divi static CSS/JS for the site homepage.', 'dsm-supreme-modules-pro-for-divi' ),
					'post_id'     => $page_context['post_id'],
				);
			} else {
				$items[] = array(
					'scope'       => self::SCOPE_POST,
					'label'       => sprintf(
						/* translators: %s: page or post title */
						__( 'Clear this page (%s)', 'dsm-supreme-modules-pro-for-divi' ),
						$page_context['label']
					),
					'description' => __( 'Clear Divi static CSS/JS for the page you are viewing or editing.', 'dsm-supreme-modules-pro-for-divi' ),
					'post_id'     => $page_context['post_id'],
				);
			}
		}

		$home_post_id = self::resolve_home_post_id();

		if ( null !== $home_post_id && $home_post_id > 0 && ( null === $page_context || $home_post_id !== $page_context['post_id'] ) ) {
			$items[] = array(
				'scope'       => self::SCOPE_HOME,
				'label'       => sprintf(
					/* translators: %s: homepage title */
					__( 'Clear homepage (%s)', 'dsm-supreme-modules-pro-for-divi' ),
					self::get_post_label( $home_post_id )
				),
				'description' => __( 'Clear Divi static CSS/JS for the site homepage.', 'dsm-supreme-modules-pro-for-divi' ),
				'post_id'     => $home_post_id,
			);
		}

		return $items;
	}

	/**
	 * Resolve the current page context for scoped cache clearing.
	 *
	 * @return array{scope: string, post_id: int, label: string, is_front_page: bool}|null
	 */
	public static function resolve_page_context(): ?array {
		if ( is_admin() ) {
			global $post;

			if ( $post instanceof \WP_Post && $post->ID > 0 ) {
				return array(
					'scope'         => self::SCOPE_POST,
					'post_id'       => (int) $post->ID,
					'label'         => self::get_post_label( (int) $post->ID ),
					'is_front_page' => self::is_static_front_page_id( (int) $post->ID ),
				);
			}

			$post_id = filter_input( INPUT_GET, 'post', FILTER_VALIDATE_INT );

			if ( is_int( $post_id ) && $post_id > 0 && get_post( $post_id ) instanceof \WP_Post ) {
				return array(
					'scope'         => self::SCOPE_POST,
					'post_id'       => $post_id,
					'label'         => self::get_post_label( $post_id ),
					'is_front_page' => self::is_static_front_page_id( $post_id ),
				);
			}

			return null;
		}

		if ( is_front_page() ) {
			$home_post_id = self::resolve_home_post_id();

			if ( null !== $home_post_id && $home_post_id > 0 ) {
				return array(
					'scope'         => self::SCOPE_HOME,
					'post_id'       => $home_post_id,
					'label'         => self::get_post_label( $home_post_id ),
					'is_front_page' => true,
				);
			}

			return array(
				'scope'         => self::SCOPE_HOME,
				'post_id'       => 0,
				'label'         => __( 'Homepage', 'dsm-supreme-modules-pro-for-divi' ),
				'is_front_page' => true,
			);
		}

		if ( is_singular() ) {
			$post_id = (int) get_queried_object_id();

			if ( $post_id > 0 ) {
				return array(
					'scope'         => self::SCOPE_POST,
					'post_id'       => $post_id,
					'label'         => self::get_post_label( $post_id ),
					'is_front_page' => false,
				);
			}
		}

		return null;
	}

	/**
	 * @return int|null
	 */
	public static function resolve_context_post_id(): ?int {
		$page_context = self::resolve_page_context();

		if ( null === $page_context || self::SCOPE_POST !== $page_context['scope'] || $page_context['post_id'] <= 0 ) {
			return null;
		}

		return $page_context['post_id'];
	}

	/**
	 * @param int $post_id Post ID.
	 * @return bool
	 */
	private static function is_static_front_page_id( int $post_id ): bool {
		if ( 'page' !== get_option( 'show_on_front' ) ) {
			return false;
		}

		return $post_id === (int) get_option( 'page_on_front' );
	}

	/**
	 * @return int|null
	 */
	public static function resolve_home_post_id(): ?int {
		if ( 'page' !== get_option( 'show_on_front' ) ) {
			return null;
		}

		$page_on_front = (int) get_option( 'page_on_front' );

		return $page_on_front > 0 ? $page_on_front : null;
	}

	/**
	 * @param int $post_id Post ID.
	 * @return string
	 */
	private static function get_post_label( int $post_id ): string {
		$title = get_the_title( $post_id );

		if ( ! is_string( $title ) || '' === trim( $title ) ) {
			/* translators: %d: post ID */
			return sprintf( __( 'ID %d', 'dsm-supreme-modules-pro-for-divi' ), $post_id );
		}

		$title = wp_strip_all_tags( $title );

		if ( strlen( $title ) > 36 ) {
			return substr( $title, 0, 33 ) . '…';
		}

		return $title;
	}

	/**
	 * @param int $post_id Post ID.
	 * @return string
	 */
	private static function get_post_clear_success_message( int $post_id ): string {
		return sprintf(
			/* translators: %s: page or post title */
			esc_html__( 'Divi static cache cleared for “%s”.', 'dsm-supreme-modules-pro-for-divi' ),
			self::get_post_label( $post_id )
		);
	}

	/**
	 * @param int $post_id Homepage post ID.
	 * @return string
	 */
	private static function get_home_clear_success_message( int $post_id ): string {
		return sprintf(
			/* translators: %s: homepage title */
			esc_html__( 'Divi static cache cleared for homepage “%s”.', 'dsm-supreme-modules-pro-for-divi' ),
			self::get_post_label( $post_id )
		);
	}

	/**
	 * @return array{success: bool, message: string, deferred: bool}
	 */
	private static function clear_all_static_cache(): array {
		self::boot_divi_page_resources();

		\ET_Core_PageResource::remove_static_resources( 'all', 'all', true, 'all', true );

		if ( method_exists( '\ET_Core_PageResource', 'remove_all_taxonomy_archive_resources' ) ) {
			\ET_Core_PageResource::remove_all_taxonomy_archive_resources();
		}

		if ( function_exists( 'et_core_clear_wp_cache' ) ) {
			et_core_clear_wp_cache( '' );
		}

		return array(
			'success'  => true,
			'message'  => esc_html__( 'Divi static cache cleared successfully.', 'dsm-supreme-modules-pro-for-divi' ),
			'deferred' => false,
		);
	}

	/**
	 * @param int    $post_id Post ID.
	 * @param string $message Success message.
	 * @return array{success: bool, message: string, deferred: bool}
	 */
	private static function clear_static_cache_for_post( int $post_id, string $message ): array {
		if ( ! get_post( $post_id ) instanceof \WP_Post ) {
			return array(
				'success'  => false,
				'message'  => esc_html__( 'The selected page could not be found.', 'dsm-supreme-modules-pro-for-divi' ),
				'deferred' => false,
			);
		}

		self::boot_divi_page_resources();

		\ET_Core_PageResource::remove_static_resources( (string) $post_id, 'all', true, 'all', true );

		if ( function_exists( 'et_core_clear_wp_cache' ) ) {
			et_core_clear_wp_cache( (string) $post_id );
		}

		return array(
			'success'  => true,
			'message'  => $message,
			'deferred' => false,
		);
	}

	/**
	 * Clear Divi static cache for the blog posts homepage (Reading → latest posts).
	 *
	 * @return array{success: bool, message: string, deferred: bool}
	 */
	private static function clear_blog_home_static_cache(): array {
		if ( ! function_exists( 'et_core_cache_dir' ) ) {
			return array(
				'success'  => false,
				'message'  => esc_html__( 'Divi cache directory is not available.', 'dsm-supreme-modules-pro-for-divi' ),
				'deferred' => false,
			);
		}

		self::boot_divi_page_resources();

		$cache_dir = et_core_cache_dir()->path;

		if ( ! is_string( $cache_dir ) || '' === $cache_dir ) {
			return array(
				'success'  => false,
				'message'  => esc_html__( 'Divi cache directory is not available.', 'dsm-supreme-modules-pro-for-divi' ),
				'deferred' => false,
			);
		}

		$files = array_filter(
			(array) glob( $cache_dir . '/home/et-*' ),
			static function ( $file ): bool {
				return is_string( $file ) && is_file( $file ) && ! str_ends_with( $file, '.stale' );
			}
		);

		$wp_filesystem = et_core_cache_dir()->wpfs;

		foreach ( $files as $file ) {
			if ( function_exists( 'et_' ) && ! et_()->starts_with( $file, $cache_dir ) ) {
				continue;
			}

			$stale_marker = $file . '.stale';

			if ( ! file_exists( $stale_marker ) && is_object( $wp_filesystem ) && method_exists( $wp_filesystem, 'put_contents' ) ) {
				$wp_filesystem->put_contents( $stale_marker, '' );
			}
		}

		if ( function_exists( 'et_core_clear_wp_cache' ) ) {
			et_core_clear_wp_cache( '' );
		}

		return array(
			'success'  => true,
			'message'  => esc_html__( 'Divi static cache cleared for the homepage.', 'dsm-supreme-modules-pro-for-divi' ),
			'deferred' => false,
		);
	}

	/**
	 * Whether Divi's security gate allows an immediate clear.
	 *
	 * @return bool
	 */
	private static function can_invoke_clear_now(): bool {
		if ( wp_doing_cron() ) {
			return true;
		}

		if ( function_exists( 'et_core_security_check_passed' ) && et_core_security_check_passed( 'edit_posts' ) ) {
			return true;
		}

		return false;
	}

	/**
	 * Defer clear using Divi's own admin-init flag (used after core/theme updates).
	 *
	 * @return void
	 */
	private static function schedule_deferred_clear(): void {
		update_option( 'et_core_page_resource_remove_all', true );
	}

	/**
	 * @return void
	 */
	private static function boot_divi_page_resources(): void {
		if ( class_exists( '\ET_Core_PageResource' ) && method_exists( '\ET_Core_PageResource', 'startup' ) ) {
			\ET_Core_PageResource::startup();
		}
	}
}
