<?php
/**
 * Simple PSR-4 style autoloader.
 *
 * @package PrimeLink
 */

namespace PrimeLink;

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

final class Autoloader {

    /**
     * Register autoloader.
     *
     * @return void
     */
    public static function run() {
        // Load Composer autoloader only on PHP 8.1.2+ (vendor libraries require PHP 8.0+)
        // On PHP 7.4, skip vendor autoload and use native functions only
        if ( version_compare( PHP_VERSION, '8.1.2', '>=' ) ) {
            $composer_autoload_lib = MT_PRIMELINK_PATH . 'lib/vendor/autoload.php';
            $composer_autoload_root = MT_PRIMELINK_PATH . 'vendor/autoload.php';
            
            if ( file_exists( $composer_autoload_lib ) ) {
                require_once $composer_autoload_lib;
            } elseif ( file_exists( $composer_autoload_root ) ) {
                require_once $composer_autoload_root;
            }
        }
        
        // Register our custom autoloader
        spl_autoload_register( array( __CLASS__, 'autoload' ) );
    }

    /**
     * Autoload callback.
     *
     * @param string $class Fully qualified class name.
     * @return void
     */
    private static function autoload( $class ) {
        if ( 0 !== strpos( $class, __NAMESPACE__ . '\\' ) ) {
            return;
        }

        $relative = str_replace( __NAMESPACE__ . '\\', '', $class );
        $relative = str_replace( '\\', DIRECTORY_SEPARATOR, $relative );

        // Try includes/ first
        $file = MT_PRIMELINK_PATH . 'includes/' . $relative . '.php';
        if ( file_exists( $file ) ) {
            require_once $file;
            return;
        }

        // Try lib/vendor/ for library helpers
        $file = MT_PRIMELINK_PATH . 'lib/vendor/' . $relative . '.php';
        if ( file_exists( $file ) ) {
            require_once $file;
        }
    }
}