<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! function_exists( 'misticease_fs_boot' ) ) {
	function misticease_fs_boot(): bool {
		require_once ABSPATH . 'wp-admin/includes/file.php';
		if ( function_exists( 'WP_Filesystem' ) ) {
			WP_Filesystem();
		}
		global $wp_filesystem;
		return (bool) ( $wp_filesystem && is_object( $wp_filesystem ) );
	}
}

if ( ! function_exists( 'misticease_recursive_rmdir' ) ) {
	function misticease_recursive_rmdir( string $dir ): void {
		$dir = rtrim( wp_normalize_path( $dir ), "/ \t\n\r\0\x0B" );

		if ( '' === $dir || is_link( $dir ) || ! is_dir( $dir ) || ! misticease_path_is_under_uploads( $dir ) ) {
			return;
		}

		$uploads_root = misticease_uploads_root_normalized();
		$real_dir     = realpath( $dir );
		$real_uploads = realpath( untrailingslashit( $uploads_root ) );

		if ( false === $real_dir || false === $real_uploads ) {
			return;
		}

		$real_dir     = trailingslashit( wp_normalize_path( $real_dir ) );
		$real_uploads = trailingslashit( wp_normalize_path( $real_uploads ) );

		if ( 0 !== strpos( $real_dir, $real_uploads ) || 'misticease' !== basename( untrailingslashit( $real_dir ) ) ) {
			return;
		}

		if ( ! misticease_fs_boot() ) {
			return;
		}

		misticease_recursive_rmdir_safe( untrailingslashit( $real_dir ), $real_uploads );
	}
}

if ( ! function_exists( 'misticease_recursive_rmdir_safe' ) ) {
	function misticease_recursive_rmdir_safe( string $dir, string $real_uploads ): void {
		$dir = untrailingslashit( wp_normalize_path( $dir ) );

		if ( '' === $dir || is_link( $dir ) || ! is_dir( $dir ) ) {
			return;
		}

		$real_dir = realpath( $dir );
		if ( false === $real_dir ) {
			return;
		}

		$real_dir = trailingslashit( wp_normalize_path( $real_dir ) );
		if ( 0 !== strpos( $real_dir, $real_uploads ) ) {
			return;
		}

		$items = array_merge(
			glob( trailingslashit( $dir ) . '*', GLOB_NOSORT ) ?: [],
			glob( trailingslashit( $dir ) . '.[!.]*', GLOB_NOSORT ) ?: [],
			glob( trailingslashit( $dir ) . '.??*', GLOB_NOSORT ) ?: []
		);

		global $wp_filesystem;
		foreach ( $items as $item ) {
			$item = wp_normalize_path( (string) $item );
			if ( is_link( $item ) || is_file( $item ) ) {
				if ( $wp_filesystem && is_object( $wp_filesystem ) && method_exists( $wp_filesystem, 'delete' ) ) {
					$wp_filesystem->delete( $item, false, 'f' );
				}
				continue;
			}
			if ( is_dir( $item ) ) {
				misticease_recursive_rmdir_safe( $item, $real_uploads );
			}
		}

		if ( $wp_filesystem && is_object( $wp_filesystem ) && method_exists( $wp_filesystem, 'delete' ) ) {
			$wp_filesystem->delete( untrailingslashit( $real_dir ), false, 'd' );
		}
	}
}

function misticease_cache_dir_abs_for_current_site(): string {
	$u       = wp_upload_dir( null, false );
	$basedir = isset( $u['basedir'] ) ? (string) $u['basedir'] : '';
	$abs     = rtrim( $basedir, "/ \t\n\r\0\x0B" ) . '/misticease';
	return rtrim( $abs, '/' );
}

if ( ! function_exists( 'misticease_uploads_root_normalized' ) ) {
	function misticease_uploads_root_normalized(): string {
		$u       = wp_upload_dir( null, false );
		$uploads = wp_normalize_path( (string) ( $u['basedir'] ?? '' ) );
		if ( '' === $uploads ) {
			return '';
		}
		return trailingslashit( $uploads );
	}
}

if ( ! function_exists( 'misticease_path_is_under_uploads' ) ) {
	function misticease_path_is_under_uploads( string $path ): bool {
		$uploads_root = misticease_uploads_root_normalized();
		if ( '' === $uploads_root ) {
			return false;
		}
		$target = wp_normalize_path( $path );
		return 0 === strpos( $target, $uploads_root );
	}
}

if ( ! function_exists( 'misticease_maybe_write_file_under_uploads' ) ) {
	function misticease_maybe_write_file_under_uploads( string $path, string $contents ): void {
		$path = wp_normalize_path( $path );
		if ( '' === $path || file_exists( $path ) || ! misticease_path_is_under_uploads( $path ) ) {
			return;
		}

		$dir = dirname( $path );
		if ( ! is_dir( $dir ) ) {
			wp_mkdir_p( $dir );
		}

		if ( ! misticease_fs_boot() ) {
			return;
		}

		global $wp_filesystem;
		if ( $wp_filesystem && is_object( $wp_filesystem ) && method_exists( $wp_filesystem, 'put_contents' ) ) {
			$wp_filesystem->put_contents( $path, $contents, FS_CHMOD_FILE );
		}
	}
}

function misticease_ensure_dir_with_index( string $dir ): void {
	$dir = rtrim( $dir, "/ \t\n\r\0\x0B" );
	if ( '' === $dir || ! misticease_path_is_under_uploads( $dir ) ) {
		return;
	}

	wp_mkdir_p( $dir );

	misticease_maybe_write_file_under_uploads( trailingslashit( $dir ) . 'index.php', "<?php\n// Silence is golden.\n" );
	misticease_maybe_write_file_under_uploads( trailingslashit( $dir ) . 'index.html', '' );
	misticease_maybe_write_file_under_uploads(
		trailingslashit( $dir ) . '.htaccess',
		"Options -Indexes\n<IfModule mod_headers.c>\nHeader set X-Content-Type-Options \"nosniff\"\n</IfModule>\n"
	);
}

function misticease_clear_schedule(): void {
	if ( function_exists( 'wp_clear_scheduled_hook' ) ) {
		wp_clear_scheduled_hook( 'misticease_cleanup_thumbs' );
	}
}


/* -------------------------------------------------------------------------
 * FS helpers + activation/uninstall
 * ---------------------------------------------------------------------- */
function misticease_activation_handler( $network_wide ): void {
	if ( is_multisite() && $network_wide ) {
		$ids = get_sites( [ 'number' => 0, 'fields' => 'ids', 'deleted' => false ] );
		foreach ( (array) $ids as $blog_id ) {
			$blog_id = (int) $blog_id;
			if ( $blog_id <= 0 ) {
				continue;
			}

			switch_to_blog( $blog_id );
			misticease_ensure_dir_with_index( misticease_cache_dir() );
			restore_current_blog();
		}
		set_site_transient( 'misticease_activated_network', true, 30 );
		return;
	}

	misticease_ensure_dir_with_index( misticease_cache_dir() );
	set_transient( 'misticease_activated', true, 30 );
}

function misticease_delete_blogmeta( int $blog_id ): void {
	if ( $blog_id <= 0 || ! function_exists( 'delete_metadata' ) ) {
		return;
	}

	delete_metadata( 'blog', $blog_id, 'misticease_used_cache_bytes' );
	delete_metadata( 'blog', $blog_id, 'misticease_blogname' );
}

function misticease_delete_all_blogmeta(): void {
	if ( ! function_exists( 'delete_metadata' ) ) {
		return;
	}

	delete_metadata( 'blog', 0, 'misticease_used_cache_bytes', '', true );
	delete_metadata( 'blog', 0, 'misticease_blogname', '', true );
}

function misticease_on_site_deleted( $site_or_blog_id ): void {
	if ( ! is_multisite() ) {
		return;
	}

	$blog_id = 0;

	if ( is_object( $site_or_blog_id ) && isset( $site_or_blog_id->blog_id ) ) {
		$blog_id = (int) $site_or_blog_id->blog_id;
	} else {
		$blog_id = (int) $site_or_blog_id;
	}

	if ( $blog_id <= 0 ) {
		return;
	}

	switch_to_blog( $blog_id );
	$site_dir = function_exists( 'misticease_cache_dir' ) ? misticease_cache_dir() : misticease_cache_dir_abs_for_current_site();
	misticease_recursive_rmdir( $site_dir );
	restore_current_blog();

	misticease_delete_blogmeta( $blog_id );
}

add_action( 'wp_delete_site', 'misticease_on_site_deleted', 10, 1 );
add_action( 'wp_uninitialize_site', 'misticease_on_site_deleted', 10, 1 );
add_action( 'wpmu_delete_blog', 'misticease_on_site_deleted', 10, 1 );

function misticease_deactivate(): void {
	misticease_clear_schedule();
}

function misticease_uninstall(): void {
	$cleanup_site = static function (): void {
		misticease_clear_schedule();

		delete_option( 'misticease_options' );

		delete_transient( 'misticease_activated' );
		delete_transient( 'misticease_used_cache_bytes_t' );
		delete_transient( 'misticease_notice' );

		$dir = misticease_cache_dir_abs_for_current_site();
		misticease_recursive_rmdir( $dir );
	};

	if ( is_multisite() ) {
		$ids = get_sites( array( 'number' => 0, 'fields' => 'ids', 'deleted' => false ) );

		foreach ( (array) $ids as $blog_id ) {
			$blog_id = (int) $blog_id;

			if ( $blog_id <= 0 ) {
				continue;
			}

			switch_to_blog( $blog_id );
			$cleanup_site();
			restore_current_blog();

			misticease_delete_blogmeta( $blog_id );
		}

		misticease_delete_all_blogmeta();

		delete_site_option( 'misticease_network_enforce_quota' );
		delete_site_option( 'misticease_network_default_quota_mb' );
		delete_site_option( 'misticease_network_enforce_cdn' );
		delete_site_option( 'misticease_network_cdn_hosts' );

		delete_site_transient( 'misticease_activated_network' );
		delete_site_transient( 'misticease_redirect_router_needed' );
	} else {
		$cleanup_site();
	}
}
