<?php
/**
 * Regenerate assets after plugin updated.
 *
 * This is the theme-side fallback for cache clearing. The primary handler
 * lives in jupiterx-core (includes/updater/functions.php). This file ensures
 * assets are still cleared when jupiterx-core is being updated (and therefore
 * its own upgrader hook may not be loaded yet during the update).
 *
 * @package JupiterX\Admin
 *
 * @since 1.25.0
 */

add_action( 'upgrader_process_complete', 'jupiterx_theme_upgrader_process_complete', 10, 2 );

/**
 * Run actions after WordPress upgrader process complete.
 *
 * @since 1.25.0
 *
 * @param object $upgrader_object WP_Upgrader instance.
 * @param array  $options         Update data.
 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
 */
function jupiterx_theme_upgrader_process_complete( $upgrader_object, $options ) {
	if ( 'update' !== ( $options['action'] ?? '' ) ) {
		return;
	}

	jupiterx_theme_log_updates( $upgrader_object, $options );

	if ( 'theme' === ( $options['type'] ?? '' ) ) {
		jupiterx_theme_flush_cache_all_sites();
		return;
	}

	if ( 'plugin' !== ( $options['type'] ?? '' ) ) {
		return;
	}

	$plugins_list = [];

	if ( ! empty( $options['plugins'] ) ) {
		$plugins_list = $options['plugins'];
	}

	if ( ! empty( $options['plugin'] ) ) {
		$plugins_list[] = $options['plugin'];
	}

	if ( empty( $plugins_list ) ) {
		return;
	}

	$watched_plugins = jupiterx_theme_get_watched_plugins();

	if ( empty( array_intersect( $watched_plugins, $plugins_list ) ) ) {
		return;
	}

	jupiterx_theme_flush_cache_all_sites();
}

/**
 * Get the list of plugins whose updates should trigger a cache flush.
 *
 * Mirrors the list in jupiterx-core but defined independently so the theme
 * can handle cache clearing even when the core plugin is mid-update.
 *
 * @since 1.25.0
 *
 * @return array
 */
function jupiterx_theme_get_watched_plugins() {
	return [
		'jupiterx-core/jupiterx-core.php',
		'elementor/elementor.php',
		'elementor-pro/elementor-pro.php',
		'raven/raven.php',
		'jet-engine/jet-engine.php',
		'jet-elements/jet-elements.php',
		'jet-menu/jet-menu.php',
		'jet-tabs/jet-tabs.php',
		'jet-tricks/jet-tricks.php',
		'jet-blocks/jet-blocks.php',
		'jet-blog/jet-blog.php',
		'jet-woo-builder/jet-woo-builder.php',
		'jet-popup/jet-popup.php',
		'jet-smart-filters/jet-smart-filters.php',
		'jet-theme-core/jet-theme-core.php',
	];
}

/**
 * Flush cache across all sites in a multisite network, or the current site.
 *
 * @since 1.25.0
 */
function jupiterx_theme_flush_cache_all_sites() {
	if ( ! is_multisite() ) {
		jupiterx_theme_flush_cache();
		return;
	}

	$sites = get_sites( [
		'fields' => 'ids',
		'number' => 0,
	] );

	foreach ( $sites as $blog_id ) {
		switch_to_blog( $blog_id );
		jupiterx_theme_flush_cache();
		restore_current_blog();
	}
}

/**
 * Wrapper function for flush cache functions.
 *
 * This is intentionally independent from jupiterx_core_flush_cache() so
 * it works even while jupiterx-core is being replaced during an update.
 *
 * @since 1.25.0
 */
function jupiterx_theme_flush_cache() {
	if ( function_exists( 'jupiterx_remove_dir' ) && function_exists( 'jupiterx_get_compiler_dir' ) ) {
		jupiterx_remove_dir( jupiterx_get_compiler_dir() );
		jupiterx_remove_dir( jupiterx_get_compiler_dir( true ) );
		jupiterx_remove_dir( jupiterx_get_images_dir() );
	}

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

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

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

/**
 * Log the update process of JupiterX and JupiterX-core
 *
 * @param object $upgrader_object WP_Upgrader instance.
 * @param array  $options         Update data.
 * @SuppressWarnings(PHPMD.NPathComplexity)
 * @since NEXT
 */
function jupiterx_theme_log_updates( $upgrader_object, $options ) {
	$item = [];
	$data = get_option( 'jupiterx_upgrade_products_log', [] );
	$last = [];

	if (
		'theme' === $options['type'] &&
		'jupiterx' === $upgrader_object->skin->theme_info->get( 'TextDomain' )
	) {
		$item = [
			'slug'    => 'jupiterx',
			'name'    => 'Jupiter X',
			'version' => $upgrader_object->skin->theme_info->get( 'Version' ),
			'action'  => current_action(),
			'time'    => time(),
		];
	}

	if (
		'plugin' === $options['type'] &&
		is_array( $upgrader_object->result ) &&
		in_array( 'jupiterx-core.php', $upgrader_object->result['source_files'], true ) ) {
		$item = [
			'slug'    => 'jupterx-core',
			'name'    => 'JupiterX Core',
			'version' => $upgrader_object->new_plugin_data['Version'],
			'action'  => current_action(),
			'time'    => time(),
		];
	}

	if ( empty( $item ) ) {
		return;
	}

	if ( 'jupiterx' === $item['slug'] && ! empty( $data['jupiterx'] ) ) {
		$last = end( $data['jupiterx'] );
	}

	if ( 'jupterx-core' === $item['slug'] && ! empty( $data['jupterx-core'] ) ) {
		$last = end( $data['jupterx-core'] );
	}

	if ( ! empty( $last ) && $last['version'] === $item['version'] ) {
		return;
	}

	$data[ $item['slug'] ][] = $item;

	update_option( 'jupiterx_upgrade_products_log', $data );
}

/**
 * Log the update process of JupiterX theme when theme is activated.
 *
 * @since NEXT
 */
function jupiterx_theme_switch_hook_log_plugins() {
	$active_theme = wp_get_theme();
	$theme_name   = $active_theme->get( 'Name' );

	if ( 'JupiterX' !== $theme_name ) {
		return;
	}

	$data = get_option( 'jupiterx_upgrade_products_log', [] );
	$item = [
		'slug'    => 'jupiterx',
		'name'    => 'Jupiter X',
		'version' => JUPITERX_VERSION,
		'action'  => current_action(),
		'time'    => time(),
	];

	// check if data last item is the same key and same version return.
	if ( ! empty( $data['jupiterx'] ) ) {
		$last_item = end( $data['jupiterx'] );

		if ( $last_item['version'] === $item['version'] ) {
			return;
		}
	}

	$data[ $item['slug'] ][] = $item;

	update_option( 'jupiterx_upgrade_products_log', $data );
}

add_action( 'after_switch_theme', 'jupiterx_theme_switch_hook_log_plugins', 10, 1 );
