<?php

/**
 * Abstract Loader Class  ArraySubs
 *
 * This class provides base functionality for loading and initializing
 * classes dynamically based on directory scanning.
 *
 * @package ArraySubs
 * @subpackage Supports\Abstracts
 * @since 1.0.0
 */

namespace ArraySubs\Supports\Abstracts;

use ArraySubs\Supports\Config;

if (! defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

class AbstractLoader
{
    /**
     * Load feature/service classes from the provided directories.
     *
     * @param array $dirs Absolute directory paths to scan.
     * @return void
     */
    public function classLoader($dirs): void
    {
        $extended_class_name = static::class;

        // check if the extended classname has ArraySubsPro in it, if so, use proplugin.src_path, otherwise use plugin.src_path
        if (strpos($extended_class_name, 'ArraySubsPro') !== false) {
            $src_path =  Config::get('proplugin.src_path');
            $base_namespace = 'ArraySubsPro';
        } else {
            $src_path = Config::get('plugin.src_path');
            $base_namespace = 'ArraySubs';
        }

        foreach ($dirs as $dir) {
            foreach (glob($dir . '/*.php') as $filename) {
                if (empty($filename) || empty($src_path) || empty($base_namespace)) {
                    continue;
                }

                $parts = explode($src_path, $filename);
                $relative_path = array_pop($parts);

                $classname = str_replace(
                    '.php',
                    '',
                    str_replace(
                        '/',
                        '\\',
                        $relative_path
                    )
                );

                $classname = '\\' . $base_namespace . '\\' . ltrim($classname, '\\');

                /**
                 * Fully qualified class name.
                 *
                 * @var class-string $classname
                 */
                if (class_exists($classname) && isset($classname::$loadable) && $classname::$loadable === true) {
                    new $classname();
                }
            }
        }
    }
}
