<?php
/**
 * Smart bbPress nVerify Compatibility Layer
 * 
 * Fixes compatibility issues between Forumax and Smart bbPress nVerify plugin.
 * The issue: sbv_render_account_link() function doesn't check for WP_Error
 * before calling methods on the API response, causing fatal errors.
 * 
 * Solution: Remove the problematic action when API is not configured.
 * 
 * @package Forumax
 * @since 2.1.0
 */

defined('ABSPATH') || exit;

/**
 * Fix Smart bbPress nVerify compatibility with Forumax
 * Runs on plugins_loaded with high priority to catch issues early
 */
add_action('plugins_loaded', 'forumax_init_sbv_compatibility', 999);

function forumax_init_sbv_compatibility()
{
    // Only proceed if smart-bbpress-nverify is active
    if (!class_exists('sbv_bbpress')) {
        return;
    }

    // Add our safety check before the profile template loads
    add_action('bbp_template_after_user_profile', 'forumax_sbv_safety_check', 0);
}

/**
 * Safety check that runs before sbv_bbpress tries to render
 * Removes the problematic action if API is not configured
 */
function forumax_sbv_safety_check()
{
    // Check if required functions exist
    if (!function_exists('smart_sbv_core') || !function_exists('sbv_api')) {
        forumax_remove_sbv_profile_action();
        return;
    }

    // Check if API settings are properly configured
    $api_token = smart_sbv_core()->get('global_api_token');
    $user_name = smart_sbv_core()->get('global_user_name');

    // If API is not configured, remove the problematic action
    if (empty($api_token) || empty($user_name)) {
        forumax_remove_sbv_profile_action();
        return;
    }

    // Test if API actually works
    $user = sbv_api()->user($user_name);
    if (is_wp_error($user)) {
        forumax_remove_sbv_profile_action();
    }
}

/**
 * Remove the sbv_bbpress profile action that causes fatal errors
 */
function forumax_remove_sbv_profile_action()
{
    global $sbv_bbpress;

    if (isset($sbv_bbpress) && is_object($sbv_bbpress)) {
        remove_action('bbp_template_after_user_profile', array($sbv_bbpress, 'bbp_template_after_user_profile'));
    }

    // Also try to find and remove by class name
    global $wp_filter;
    if (isset($wp_filter['bbp_template_after_user_profile'])) {
        foreach ($wp_filter['bbp_template_after_user_profile']->callbacks as $priority => $callbacks) {
            foreach ($callbacks as $key => $callback) {
                if (is_array($callback['function']) && is_object($callback['function'][0])) {
                    if (get_class($callback['function'][0]) === 'sbv_bbpress') {
                        unset($wp_filter['bbp_template_after_user_profile']->callbacks[$priority][$key]);
                    }
                }
            }
        }
    }
}
