<?php
/**
 * Mollie API SDK Autoloader for Bricksforge
 * 
 * This file initializes the Mollie SDK and its dependencies.
 * 
 * @since 3.1.8
 */

if (!defined('ABSPATH')) exit;

// Prevent double loading
if (class_exists('Mollie\Api\MollieApiClient')) {
    return;
}

/**
 * Simple PSR-4 Autoloader for Mollie SDK and its dependencies
 * 
 * Note: Psr\Http\Message namespace has classes in TWO directories:
 * - psr/http-message/src/ (PSR-7 Message interfaces)
 * - psr/http-factory/src/ (PSR-17 Factory interfaces, but same namespace!)
 */
spl_autoload_register(function ($class) {
    // Define namespace to directory mappings
    // Note: Order matters! For Psr\Http\Message, we check multiple directories
    $namespaces = [
        'Mollie\\Api\\' => [BRICKSFORGE_PATH . '/includes/vendor/mollie/mollie-api-php/src/'],
        'Nyholm\\Psr7\\' => [BRICKSFORGE_PATH . '/includes/vendor/nyholm/psr7/src/'],
        'Psr\\Http\\Client\\' => [BRICKSFORGE_PATH . '/includes/vendor/psr/http-client/src/'],
        // PSR-17 Factory interfaces use Psr\Http\Message namespace but are in http-factory!
        'Psr\\Http\\Message\\' => [
            BRICKSFORGE_PATH . '/includes/vendor/psr/http-message/src/',
            BRICKSFORGE_PATH . '/includes/vendor/psr/http-factory/src/',
        ],
        // Composer CA Bundle for SSL certificates
        'Composer\\CaBundle\\' => [BRICKSFORGE_PATH . '/includes/vendor/composer/ca-bundle/src/'],
    ];

    foreach ($namespaces as $prefix => $base_dirs) {
        // Check if the class uses this namespace
        $len = strlen($prefix);
        if (strncmp($prefix, $class, $len) !== 0) {
            continue;
        }

        // Get the relative class name
        $relative_class = substr($class, $len);

        // Check each base directory for this namespace
        foreach ($base_dirs as $base_dir) {
            // Replace namespace separators with directory separators
            $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

            // If the file exists, require it
            if (file_exists($file)) {
                require $file;
                return;
            }
        }
    }
});

