<?php
/**
 * Helper Class
 *
 * @todo        Caching von "app.env" abhängig machen und einen Mechanismus für die automatische
 *              Aktualisierung des Cache entwickeln.
 *
 * @version     1.0.$Revision:$
 * @version     SVN: $Id:$
 * @package     bplan-base/globals
 * @subpackage  Helpers
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 * @copyright   Copyright (C) 2025, 2026 bplan-solutions GmbH & Co. KG <https://www.bplan-solutions.de/>
 * /Δ\
 */

 namespace BplanBase\Globals\Support;


use Illuminate\Support\Str;
use Illuminate\Support\Facades\File;
use Livewire\Livewire;


/**
 * Helper Class
 *
 * @version     2.0.0 / 2026-02-17
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 */
class LivewireComponentAutoDiscovery
{


/* +++ TRAITS +++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ CLASS CONSTANTS +++ ++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ OBJECT MEMBERS +++ +++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ CLASS MEMBERS +++ ++++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ OBJECT METHODS +++ +++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ CLASS METHODS +++ ++++++++++++++++++++++++++++++++++++++++++++++++++++ */


    /**
     * Write the cache file
     *
     * @param       string $cacheFile
     *
     * @param       array $data
     *
     * @version     1.0.0 / 2025-04-22
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    protected static function _writeCache(string $cacheFile, array $data): void
    {
        File::ensureDirectoryExists(dirname($cacheFile));

        $content = '<?php'
            ."\n\n"
            .'return '.var_export($data, true)
            .";\n";

        file_put_contents($cacheFile, $content);

    } // _writeCache()


    /**
     * Discovers all Livewire components under the given path
     *
     * @param       string $baseNamespace
     *
     * @param       string $basePath
     *
     * @param       null|string $prefix
     *
     * @return      void
     *
     * @version     1.0.0 / 2026-02-17
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public static function discover(string $baseNamespace, string $basePath, null|string $prefix = null): void
    {
        $cacheFile = base_path('bootstrap/cache/livewire-'.$prefix.'-components.php');
        $basePath = str_replace('\\', '/', realpath($basePath));
        $namespace = rtrim($baseNamespace, '\\');

        $useCache = false;

        if ($useCache && file_exists($cacheFile)) {
            $components = include $cacheFile;

        } else {
            $components = [];

            foreach (File::allFiles($basePath) as $File) {
                $fileName = $File->getFilename();
                /*
                **  Ignore files whose name begins with a dot or a diamond symbol. */
                if ($fileName[0] === '.' || $fileName[0] === '#') {
                    continue;
                }
                $fullPath = str_replace('\\', '/', $File->getPathname());
                $relativePath = Str::after($fullPath, $basePath . '/');
                $relativeClassPath = Str::replaceLast('.php', '', $relativePath);

                $class = $namespace.'\\'.str_replace('/', '\\', $relativeClassPath);

                $pathParts = explode('/', $relativeClassPath);

                $alias = '';

                if ($prefix !== null) {
                    $alias .= $prefix.'::';
                }
                $alias .= implode('.', array_map([Str::class, 'kebab'], $pathParts));

                $components[$alias] = $class;
            }
            /*
            **  Write the cache file. */
            if ($useCache) {
                self::_writeCache($cacheFile, $components);
            }
        }
        // dump($components);
        /*
        **  Register the components. */
        foreach ($components as $alias => $class) {
            Livewire::component($alias, $class);
        }
    } // discover()


} // class LivewireComponentAutoDiscovery {}
