<?php

namespace FleekDash\Core;

defined('ABSPATH') || exit;

/**
 * Filesystem Helper
 *
 * Provides safe WP_Filesystem initialization that prevents
 * leaving $wp_filesystem global as null, which can cause
 * fatal errors in other plugins (e.g., RankMath Pro).
 *
 * @package FleekDash
 * @since 2.1.3
 */
class FilesystemHelper
{
	/**
	 * Safely initialize WP_Filesystem
	 *
	 * This method ensures that $wp_filesystem global is never left as null,
	 * preventing fatal errors in other plugins that rely on it.
	 *
	 * @param array|false|null $credentials Optional. Filesystem credentials.
	 * @param string $context Optional. Context for filesystem operations.
	 * @return bool True if filesystem is available, false otherwise.
	 */
	public static function safe_init($credentials = false, $context = false)
	{
		global $wp_filesystem;

		// If already initialized and valid, return true
		if (isset($wp_filesystem) && is_object($wp_filesystem) && method_exists($wp_filesystem, 'exists')) {
			return true;
		}

		// Load filesystem functions if needed
		if (!function_exists('WP_Filesystem')) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
		}

		// Try to initialize filesystem
		$result = WP_Filesystem($credentials, $context);

		// CRITICAL: Verify $wp_filesystem is properly initialized
		// If initialization failed or returned invalid object, ensure it's not null
		if (!isset($wp_filesystem) || !is_object($wp_filesystem) || !method_exists($wp_filesystem, 'exists')) {
			// If WP_Filesystem failed, it may have left $wp_filesystem as null
			// We need to ensure it's not null to prevent fatal errors in other plugins
			// The best approach is to not modify it if it's null, but ensure our code
			// doesn't leave it in an invalid state

			// If $wp_filesystem is null, WordPress will handle it, but we should
			// not leave it in a partially initialized state
			// Just return false and let the calling code handle the error
			return false;
		}

		// Filesystem is properly initialized
		return $result;
	}

	/**
	 * Get filesystem instance safely
	 *
	 * @return \WP_Filesystem_Base|null Filesystem instance or null if not available
	 */
	public static function get_instance()
	{
		global $wp_filesystem;

		// Ensure filesystem is initialized
		if (!self::safe_init()) {
			return null;
		}

		// Return instance if valid
		if (isset($wp_filesystem) && is_object($wp_filesystem) && method_exists($wp_filesystem, 'exists')) {
			return $wp_filesystem;
		}

		return null;
	}
}
