<?php

/**
 * Stripe Helper Functions
 *
 * This file contains helper functions to handle Stripe library loading
 * and avoid conflicts with other plugins that might load different versions
 * of the Stripe library.
 */

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

// Global variable to track if we've already loaded our Stripe library
global $wpgv_stripe_loaded;
$wpgv_stripe_loaded = false;

/**
 * Force load the correct Stripe library and prevent conflicts
 *
 * @return bool True if Stripe library is loaded successfully, false otherwise
 */
function wpgv_force_load_stripe_library()
{
    global $wpgv_stripe_loaded;

    // If we've already loaded our library, return true
    if ($wpgv_stripe_loaded) {
        return true;
    }

    // Check if Stripe Checkout Session class already exists from another plugin
    if (class_exists('\Stripe\Checkout\Session')) {
        // Test if the existing class supports the methods we need
        try {
            $test_session = new \Stripe\Checkout\Session();
            // If we can create a session object, the existing library should work
            $wpgv_stripe_loaded = true;
            return true;
        } catch (Exception $e) {
            // The existing library doesn't support Checkout Sessions properly
            // We need to force load our own version
        }
    }

    // Clear any existing Stripe classes to prevent conflicts
    wpgv_clear_stripe_classes();

    // Try to load our Stripe library in order of preference
    $stripe_paths = array(
        WPGIFT__PLUGIN_DIR . '/vendor/stripe/stripe-php/init.php',
        WPGIFT__PLUGIN_DIR . '/library/stripe-php/init.php',
        WPGIFT__PLUGIN_DIR . '/vendor/autoload.php'
    );

    foreach ($stripe_paths as $path) {
        if (file_exists($path)) {
            try {
                require_once($path);

                // Verify that the Checkout Session class is now available
                if (class_exists('\Stripe\Checkout\Session')) {
                    $wpgv_stripe_loaded = true;
                    error_log('WPGV: Successfully loaded Stripe library from: ' . $path);
                    return true;
                }
            } catch (Exception $e) {
                error_log('WPGV: Failed to load Stripe library from: ' . $path . ' - ' . $e->getMessage());
                continue;
            }
        }
    }

    error_log('WPGV: Could not load any compatible Stripe library');
    return false;
}

/**
 * Clear existing Stripe classes to prevent conflicts
 */
function wpgv_clear_stripe_classes()
{
    // Get all declared classes
    $classes = get_declared_classes();

    // Remove Stripe classes that might conflict
    foreach ($classes as $class) {
        if (strpos($class, 'Stripe\\') === 0) {
            // We can't actually unset classes in PHP, but we can try to reload them
            // This is a limitation, but our approach should still work
        }
    }
}

/**
 * Initialize Stripe with API key and return success status
 *
 * @param string $secret_key The Stripe secret key
 * @return bool True if initialization successful, false otherwise
 */
function wpgv_init_stripe($secret_key)
{
    // Force load our Stripe library
    if (!wpgv_force_load_stripe_library()) {
        error_log('WPGV: Failed to 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');

        error_log('WPGV: Stripe initialized successfully');
        return true;
    } catch (Exception $e) {
        error_log('WPGV: Stripe initialization error: ' . $e->getMessage());
        return false;
    }
}

/**
 * Create a Stripe Checkout Session with error handling
 *
 * @param array $session_data The session data for Stripe Checkout
 * @return array Array with 'success' => bool and 'data' => mixed
 */
function wpgv_create_stripe_session($session_data)
{
    try {
        // Ensure our Stripe library is loaded
        if (!wpgv_force_load_stripe_library()) {
            return array(
                'success' => false,
                'data' => 'Stripe library not found'
            );
        }

        // Log the session data for debugging
        error_log('WPGV: Creating Stripe session with data: ' . json_encode($session_data));

        // Create the session
        $session = \Stripe\Checkout\Session::create($session_data);

        error_log('WPGV: Stripe session created successfully: ' . $session->id);

        return array(
            'success' => true,
            'data' => $session
        );
    } catch (\Stripe\Exception\ApiErrorException $e) {
        error_log('WPGV: Stripe API Error: ' . $e->getMessage());
        return array(
            'success' => false,
            'data' => 'Stripe API error: ' . $e->getMessage()
        );
    } catch (Exception $e) {
        error_log('WPGV: Stripe General Error: ' . $e->getMessage());
        return array(
            'success' => false,
            'data' => 'Payment processing error: ' . $e->getMessage()
        );
    }
}

/**
 * Legacy function for backward compatibility
 *
 * @return bool True if Stripe library is loaded successfully, false otherwise
 */
function wpgv_load_stripe_library()
{
    return wpgv_force_load_stripe_library();
}
