<?php
/**
 * Cache module — Theme Compat: Divi (Elegant Themes)
 *
 * Divi serves a dynamic CSS endpoint by default (et_use_dynamic_css). When a
 * cache plugin captures the HTML, the dynamic CSS URL is included but its
 * generation runs at request-time — the cached HTML therefore references a
 * URL that may not exist any more after a layout change.
 *
 * Mirrors WP Rocket's strategy of forcing the dynamic CSS feature off when
 * we are caching.
 *
 * @package BlaminhorEssentials
 */

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

class Blaminhor_Essentials_Cache_Theme_Compat_Divi extends Blaminhor_Essentials_Cache_Theme_Compat_Base {

	public function id() {
		return 'divi';
	}

	public function label() {
		return 'Divi / Elegant Themes';
	}

	public function is_active() {
		if ( defined( 'ET_BUILDER_VERSION' ) || defined( 'ET_BUILDER_PRODUCT_VERSION' ) ) {
			return true;
		}
		if ( ! function_exists( 'wp_get_theme' ) ) {
			return false;
		}
		$theme    = wp_get_theme();
		$template = strtolower( (string) $theme->get_template() );
		return 'divi' === $template || 'extra' === $template;
	}

	public function register_hooks() {
		// Force-disable Divi's dynamic CSS endpoint so the cached HTML only
		// references static CSS files that survive any subsequent layout edit.
		add_filter( 'et_use_dynamic_css', '__return_false' );

		// Purge sync — Divi fires et_save_post on every Divi Builder save.
		add_action( 'et_save_post', array( $this, 'purge_all' ) );
		add_action( 'et_builder_loaded', array( $this, 'noop' ) ); // touchpoint for tests
	}

	public function noop() {
		// Reserved for future use (e.g. invalidate cache only on layout change).
	}

	public function purge_all() {
		if ( $this->parent->purge ) {
			$this->parent->purge->purge_all();
		}
	}

	public function defer_js_exclusions() {
		return array(
			'#/jquery-?[0-9.]*(.min|.slim|.slim.min)?\.js#',
			'/Divi/includes/builder/scripts/salvattore.min.js',
		);
	}

	public function delay_js_exclusions() {
		return array(
			'/Divi/js/custom.js',
			'/Divi/core/admin/js/common.js',
			'et_animation_data',
		);
	}

	public function rucss_safelist() {
		return array(
			'.et_pb_',
			'.et-pb-',
			'#et-main-area',
			'#main-content',
			'.et-fb-',
		);
	}

	public function async_css_excluded_handles() {
		// Divi compiles its CSS through et-builder-modules-style (parent rules)
		// and divi-style (child overrides). Async-loading either inverts the
		// cascade and strips column / row containers.
		return array(
			'divi-style',
			'divi-fonts',
			'et-builder-modules-style',
			'et-shortcodes-css',
			'et-frontend-builder',
			'et-',
		);
	}
}
