<?php

/**
 * Autoloader for Kubelio namespace
 * 
 * Supports PSR-4 with class-classname.php naming convention.
 */

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

spl_autoload_register(function ($class) {
    // Check if the class belongs to our namespace (Compatible with PHP 7.4+)
    if (0 !== strpos($class, 'Kubelio\\')) {
        return;
    }

    // Cache the base directory and prefix length to avoid redundant calculations
    static $base_dir;
    if (null === $base_dir) {
        $base_dir = __DIR__ . DIRECTORY_SEPARATOR;
    }

    // Remove the prefix from the class name
    $relative_class = substr($class, 8); // 8 is the length of 'Kubelio\'

    // Split into namespace parts and class name
    $parts      = explode('\\', $relative_class);
    $class_name = array_pop($parts);

    // Build the path. Directory names are expected to be lowercase.
    $directory = '';
    if (!empty($parts)) {
        $directory = strtolower(implode(DIRECTORY_SEPARATOR, $parts)) . DIRECTORY_SEPARATOR;
    }

    // WordPress naming convention: class-{classname}.php (lowercase, underscores to hyphens)
    $file_name = 'class-' . strtolower(str_replace('_', '-', $class_name)) . '.php';

    $file_path = $base_dir . $directory . $file_name;

    // Include the file if it exists.
    // require is slightly faster than require_once and safe here since the 
    // autoloader only triggers if the class hasn't been loaded yet.
    if (file_exists($file_path)) {
        require $file_path;
    }
});
