<?php
/**
 * Plugin Name: Solid Performance Advanced Cache Drop-In
 * Plugin URI: https://go.solidwp.com/performance-author
 * Description: A Solid Performance drop-in that enhances site performance by caching responses, reducing server load, and minimizing response times.
 * Version: {{swpsp-advanced-cache-version}}
 * Author: SolidWP
 * Author URI: https://go.solidwp.com/performance-author
 * License: GPLv2 or later
 *
 * This file is automatically generated. Do Not Modify.
 *
 * @package SolidWP\Performance
 */

use SolidWP\Performance\Page_Cache\Buffer;
use SolidWP\Performance\Page_Cache\Cache;

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

define( 'SWPSP_ADVANCED_CACHE', (bool) realpath( WP_CONTENT_DIR . '/{{swpsp-plugin-dir}}/solid-performance.php' ) );
define( 'SWPSP_ADVANCED_CACHE_VERSION', '{{swpsp-advanced-cache-version}}' );

if ( SWPSP_ADVANCED_CACHE ) {
	// 1. Initialize Required Dependencies.
	require_once WP_CONTENT_DIR . '/{{swpsp-plugin-dir}}/vendor/vendor-prefixed/autoload.php';
	require_once WP_CONTENT_DIR . '/{{swpsp-plugin-dir}}/src/functions/app.php';
	require_once WP_CONTENT_DIR . '/{{swpsp-plugin-dir}}/src/functions/filesystem.php';
	require_once WP_CONTENT_DIR . '/{{swpsp-plugin-dir}}/src/functions/config.php';

	spl_autoload_register(
		static function ( $path ): void {
			// Return if not loading a Solid Performance class.
			if ( strpos( $path, '\\SolidWP\\Performance' ) !== false ) {
				return;
			}

			$path = str_replace( 'SolidWP\\Performance\\', 'src/Performance/', $path );
			$path = str_replace( '\\', DIRECTORY_SEPARATOR, $path );
			$file = WP_CONTENT_DIR . "/{{swpsp-plugin-dir}}/{$path}.php";

			if ( file_exists( $file ) ) {
				include_once $file;
			}
		}
	);

	// If the plugin is not activated, but this file remains, delete it.
	add_action(
		'init',
		static function (): void {
			if ( did_action( 'solidwp/performance/bootstrap_file_loaded' ) ) {
				return;
			}

			if ( __DIR__ !== WP_CONTENT_DIR ) {
				return;
			}

			// Skip this check if WordPress is installing/updating, as the actions won't fire.
			if ( wp_installing() ) {
				return;
			}

			unlink( __FILE__ );
		}
	);

	// Boot our plugin instance early.
	$container = swpsp_plugin()->container();

	// Don't do anything if page caching is disabled.
	// NOTE: You should not put any other code above this section, as the updater stops here.
	if ( ! swpsp_config_get( 'page_cache.enabled' ) ) {
		return;
	}

	try {
		// 1. If cached file exists, serve it.
		$cache = $container->get( Cache::class );
		$cache->serve_cached_file();

		// 2. If no cached file exists, try to save a cached version.
		$buffer = $container->get( Buffer::class );
		$buffer->register();
	} catch ( Throwable $e ) {
		swpsp_log( 'Solid Performance - A critical error occurred: ' . $e->getMessage() );
	}
} elseif ( __DIR__ === WP_CONTENT_DIR ) {
	// If the plugin was deleted without deactivation, clean up after ourselves.
	@unlink( __FILE__ );
}
