<?php

// EN: If this file is called directly, abort.
// IT: Se questo file viene chiamato direttamente, interrompi.
 if ( ! defined( 'ABSPATH' ) ) exit; // Exit
/**
 * FILE: class-pkinex-autoloader.php
 * DESCRIPTION:
 * EN: Dynamic recursive autoloader for PK_Inexpress classes.
 * IT: Autoloader dinamico e ricorsivo per le classi di PK_Inexpress.
 */

class PKINEX_Autoloader
{
    /**
     * Register the autoloader with SPL.
     * EN: Registers the class loader so PHP knows how to include files quick ally.
     * IT: Registra il caricatore in modo che PHP sappia includere i file automaticamente.
     */
    public static function pkinex_register()
    {
        spl_autoload_register([__CLASS__, 'pkinex_load']);
    }

    /**
     * Load a class file based on class name.
     *
     * @param string $class Nome della classe / Class name
     */
    public static function pkinex_load($class)
    {
        // Only classes starting with PKINEX_
        if (strpos($class, 'PKINEX_') !== 0) {
            return;
        }

        // Remove prefix
        $relative = substr($class, strlen('PKINEX_'));

        // Convert CamelCase → kebab-case
        $relative = preg_replace('/([a-z])([A-Z])/', '$1-$2', $relative);

        // Lowercase
        $relative = strtolower($relative);

        // Build file name
        $filename = 'class-pkinex-' . $relative . '.php';

        // Start searching in /includes
       $base_dir = PKINEX_INEXPRESS_DIR;

        $file = self::pkinex_recursiveSearch($filename, $base_dir);

        if ($file) {
            require_once $file;
        }
    }

    /**
     * Recursive search for a file inside a directory.
     *
     * @param string $filename Nome file da cercare
     * @param string $directory Directory di partenza
     * @return string|false Path trovato o false se non esiste
     */
    protected static function pkinex_recursiveSearch($filename, $directory)
    {
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::SELF_FIRST
        );

        foreach ($iterator as $file) {
            if ($file->isFile() && $file->getFilename() === $filename) {
                return $file->getPathname();
            }
        }

        return false;
    }
}
