<?php

/**
 * Stripe Force Loader
 *
 * This file provides a robust solution to force load the correct Stripe library
 * and prevent conflicts with other plugins that load different versions.
 */

if (!defined('ABSPATH')) exit;  // Exit if accessed directly

// Global flag to track if we've successfully loaded our Stripe library
global $wpgv_stripe_force_loaded;
$wpgv_stripe_force_loaded = false;

/**
 * Force load our Stripe library and prevent any interference
 */
function wpgv_force_load_stripe_library()
{
    global $wpgv_stripe_force_loaded;

    // If already loaded successfully, return true
    if ($wpgv_stripe_force_loaded) {
        return true;
    }
    // If any Stripe classes are already declared by another plugin, prefer the existing
    // implementation to avoid redeclaring classes and causing a fatal error.
    $declared = get_declared_classes();
    $has_stripe = false;
    foreach ($declared as $c) {
        if (strpos($c, 'Stripe\\') === 0) {
            $has_stripe = true;
            break;
        }
    }

    if ($has_stripe) {
        // If the required Checkout Session class exists on the already-loaded Stripe,
        // reuse it. This avoids require_once and redeclaration errors.
        if (class_exists('\\Stripe\\Checkout\\Session')) {
            $wpgv_stripe_force_loaded = true;
            return true;
        }

        // Existing Stripe is present but missing Checkout\Session. We must NOT require
        // our bundled library because that would attempt to redeclare classes and
        // cause a fatal error. Return false and let the caller handle the missing
        // functionality gracefully.
        error_log('WPGV: Existing Stripe classes detected but Checkout\\Session is missing; skipping bundled load to avoid fatal error.');
        return false;
    }

    // No Stripe classes declared yet — it's safe to require our bundled library.
    wpgv_clear_autoloaders();

    // Force load our specific Stripe library
    $stripe_path = WPGIFT__PLUGIN_DIR . '/vendor/stripe/stripe-php/init.php';

    if (file_exists($stripe_path)) {
        try {
            // Load the library
            require_once($stripe_path);

            // Verify that the Checkout Session class is available
            if (class_exists('\\Stripe\\Checkout\\Session')) {
                $wpgv_stripe_force_loaded = true;
                return true;
            }

            return false;
        } catch (Exception $e) {
            error_log('WPGV: Failed to require bundled Stripe library: ' . $e->getMessage());
            return false;
        }
    }

    return false;
}

/**
 * Clear existing autoloaders that might interfere
 */
function wpgv_clear_autoloaders()
{
    // Get all registered autoloaders
    $autoloaders = spl_autoload_functions();

    if ($autoloaders) {
        foreach ($autoloaders as $autoloader) {
            // Remove autoloaders that might load conflicting Stripe versions
            if (is_array($autoloader) && isset($autoloader[0])) {
                $class = $autoloader[0];
                if (is_string($class) && strpos($class, 'ComposerAutoloader') !== false) {
                    // This is a Composer autoloader, we'll keep it but be careful
                    continue;
                }
            }
        }
    }
}

/**
 * Clear existing Stripe classes to prevent conflicts
 */
function wpgv_clear_stripe_classes()
{
    // Get all declared classes and report whether any Stripe classes exist.
    $classes = get_declared_classes();
    $found = false;
    foreach ($classes as $class) {
        if (strpos($class, 'Stripe\\') === 0) {
            $found = true;
            // Keep logging commented out to avoid activation-time noise; only use
            // error_log for important cases.
            // error_log('WPGV: Found existing Stripe class: ' . $class);
        }
    }

    return $found;
}

/**
 * Initialize Stripe with API key using force-loaded library
 */
function wpgv_init_force_stripe($secret_key)
{
    // Force load our Stripe library
    if (!wpgv_force_load_stripe_library()) {
        // Debug logging disabled to prevent activation output
        // error_log('WPGV: Failed to force load Stripe library');
        return false;
    }

    try {
        // Set the API key
        \Stripe\Stripe::setApiKey($secret_key);

        // Set app info to identify our plugin
        \Stripe\Stripe::setAppInfo('GiftVoucherPro', '1.0.0', 'https://giftvoucherpro.com');

        // Debug logging disabled to prevent activation output
        // error_log('WPGV: Force-loaded Stripe initialized successfully');
        return true;
    } catch (Exception $e) {
        // Debug logging disabled to prevent activation output
        // error_log('WPGV: Force-loaded Stripe initialization error: ' . $e->getMessage());
        return false;
    }
}

/**
 * Create Stripe Checkout Session using force-loaded library
 */
function wpgv_create_force_stripe_session($session_data)
{
    try {
        // Ensure our Stripe library is force-loaded
        if (!wpgv_force_load_stripe_library()) {
            return array(
                'success' => false,
                'data' => 'Stripe library not found'
            );
        }

        // Log the session data for debugging
        // Debug logging disabled to prevent activation output
        // error_log('WPGV: Creating force-loaded Stripe session with data: ' . json_encode($session_data));

        // Create the session using our force-loaded library
        $session = \Stripe\Checkout\Session::create($session_data);

        // Debug logging disabled to prevent activation output
        // error_log('WPGV: Force-loaded Stripe session created successfully: ' . $session->id);

        return array(
            'success' => true,
            'data' => $session
        );
    } catch (\Stripe\Exception\ApiErrorException $e) {
        // Debug logging disabled to prevent activation output
        // error_log('WPGV: Force-loaded Stripe API Error: ' . $e->getMessage());
        return array(
            'success' => false,
            'data' => 'Stripe API error: ' . $e->getMessage()
        );
    } catch (Exception $e) {
        error_log('WPGV: Force-loaded Stripe General Error: ' . $e->getMessage());
        return array(
            'success' => false,
            'data' => 'Payment processing error: ' . $e->getMessage()
        );
    }
}

/**
 * Test function to verify our force-loaded Stripe library works
 */
function wpgv_test_force_stripe()
{
    error_log('WPGV: Testing force-loaded Stripe library...');

    // Test 1: Force load the library
    if (!wpgv_force_load_stripe_library()) {
        error_log('WPGV: FAILED - Could not force load Stripe library');
        return false;
    }

    // Test 2: Check if Checkout Session class exists
    if (!class_exists('\Stripe\Checkout\Session')) {
        error_log('WPGV: FAILED - Checkout Session class not found after force load');
        return false;
    }

    // Test 3: Try to create a test session object
    try {
        $test_session = new \Stripe\Checkout\Session();
        // Debug logging disabled to prevent activation output
        // error_log('WPGV: PASSED - Successfully created Checkout Session object');
    } catch (Exception $e) {
        // Debug logging disabled to prevent activation output
        // error_log('WPGV: FAILED - Could not create Checkout Session object: ' . $e->getMessage());
        return false;
    }

    // Debug logging disabled to prevent activation output
    // error_log('WPGV: All force-loaded Stripe tests passed!');
    return true;
}

// Force load the Stripe library immediately when this file is included
// NOTE: We intentionally do NOT force-load the Stripe library at include time to
// avoid fatal errors during plugin activation when another plugin has already
// declared Stripe classes. Call `wpgv_force_load_stripe_library()` explicitly
// where needed (e.g., when creating a session) instead.
