<?php
/**
 * Docy Core Compatibility Layer
 *
 * Fixes compatibility issues between Forumax and older versions of Docy Core plugin.
 * 
 * The issue: 
 * - Old Docy Core (v4.3.1 and below) had Forums widget that conflicted with Forumax
 * - New Docy Core (v4.3.2+) removed Forums widget (now handled by Forumax)
 * - During update transition, class conflicts can occur
 *
 * Solution: 
 * - Detect docy-core version
 * - Only load Forums_widget.php if it exists in old version
 * - Prevent duplicate class declarations
 * - Unregister old widgets and register new Forumax widgets
 *
 * @package Forumax
 * @since 2.1.1
 */

defined( 'ABSPATH' ) || exit;

/**
 * Handle Docy Core Forums Widget Compatibility
 * 
 * This function ensures smooth transition from old docy-core to new version
 * and prevents "class already declared" errors.
 */
function forumax_handle_docy_core_compatibility() {
	// Only proceed if bbPress is active
	if ( ! class_exists( 'bbPress' ) ) {
		return;
	}

	// Check if docy-core plugin is active
	if ( ! defined( 'DOCY_CORE_VERSION' ) && ! class_exists( 'Docy_core' ) ) {
		return;
	}

	// Path to the Forums_widget.php file in docy-core
	$forums_widget_file = WP_PLUGIN_DIR . '/docy-core/wp-widgets/Forums_widget.php';
	
	// Get docy-core version
	$docy_version = defined( 'DOCY_CORE_VERSION' ) ? DOCY_CORE_VERSION : '0.0.0';
	if ( class_exists( 'Docy_core' ) && defined( 'Docy_core::VERSION' ) ) {
		$docy_version = Docy_core::VERSION;
	}

	// Check if this is old docy-core version (has Forums widget)
	$is_old_docy = file_exists( $forums_widget_file );

	// If old docy-core and class doesn't exist yet, load it
	if ( $is_old_docy && ! class_exists( 'DocyCore\WpWidgets\Forums' ) ) {
		require_once $forums_widget_file;
	}

	// Unregister old docy-core Forums widget
	// Priority 15: Standard priority for widget cleanup
	add_action( 'widgets_init', 'forumax_unregister_old_docy_widgets', 15 );
}

/**
 * Unregister old Docy Core widgets that are now handled by Forumax/bbPress
 * 
 * Note: We only unregister docy-core Forums widget.
 * bbPress widgets (BBP_Forums_Widget, BBP_Topics_Widget, BBP_Replies_Widget) 
 * are kept active as they are the primary widgets for forums functionality.
 */
function forumax_unregister_old_docy_widgets() {
	// Unregister old docy-core Forums widget if it was registered
	if ( class_exists( 'DocyCore\WpWidgets\Forums' ) ) {
		unregister_widget( 'DocyCore\WpWidgets\Forums' );
	}
	
	// Note: bbPress widgets are NOT unregistered
	// They are the primary widgets for:
	// - Forums List (BBP_Forums_Widget)
	// - Recent Topics (BBP_Topics_Widget)
	// - Recent Replies (BBP_Replies_Widget)
}

// Run compatibility handler
forumax_handle_docy_core_compatibility();
