<?php

declare(strict_types=1);

/**
 * PSR-4 Autoloader for CloudXM NFe Plugin
 *
 * @package CloudXM\NFe
 */

namespace CloudXM\NFe;

/**
 * PSR-4 Autoloader
 */
class Autoloader
{
    /**
     * Base directory for the plugin
     *
     * @var string
     */
    private string $baseDir;

    /**
     * Namespace prefix
     *
     * @var string
     */
    private string $prefix = 'CloudXM\\NFe\\';

    /**
     * Constructor
     *
     * @param string $baseDir Base directory for the plugin
     */
    public function __construct(string $baseDir)
    {
        $this->baseDir = rtrim($baseDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
    }

    /**
     * Register the autoloader
     *
     * @return void
     */
    public function register(): void
    {
        spl_autoload_register([$this, 'autoload']);
    }

    /**
     * Autoload classes
     *
     * @param string $class Fully qualified class name
     * @return bool True if loaded, false otherwise
     */
    public function autoload(string $class): bool
    {
        // Check if the class uses the namespace prefix
        $len = strlen($this->prefix);
        if (strncmp($this->prefix, $class, $len) !== 0) {
            return false;
        }

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

        // Replace namespace separators with directory separators
        $file = $this->baseDir . str_replace('\\', DIRECTORY_SEPARATOR, $relativeClass) . '.php';

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

        return false;
    }
}

// Initialize the autoloader
$autoloader = new Autoloader(__DIR__);
$autoloader->register();
