<?php
defined('BASEPATH') or exit('No direct script access allowed');

class App_modules_fallback
{
    public static function enrich(&$modules)
    {
        if (!is_array($modules)) return;
        $root = defined('FCPATH') ? FCPATH : rtrim(str_replace('\\','/', realpath(__DIR__.'/../../..')),'/').'/';

        foreach ($modules as $k => &$m) {
            $sys = $m['system_name'] ?? (is_string($k) ? $k : null);
            if (!$sys) continue;
            if (!empty($m['module_name'])) continue;

            $dir = $root.'modules/'.$sys;

            // 1) config.php
            $module = null;
            if (is_file($dir.'/config.php')) {
                if (!defined('BASEPATH')) define('BASEPATH', __FILE__);
                include $dir.'/config.php';
                if (isset($module) && is_array($module)) $m = array_merge($m, $module);
            }

            // 2) docblock
            if (empty($m['module_name'])) {
                $file = $dir.'/'.$sys.'.php';
                if (is_file($file)) {
                    $txt = file_get_contents($file, false, null, 0, 8192);
                    $map = [
                        'module_name' => '/^\s*(?:Module\s+Name|Name)\s*:\s*(.+)\s*$/mi',
                        'version'     => '/^\s*Version\s*:\s*(.+)\s*$/mi',
                        'author'      => '/^\s*Author\s*:\s*(.+)\s*$/mi',
                        'description' => '/^\s*Description\s*:\s*(.+)\s*$/mi',
                    ];
                    foreach ($map as $kk=>$re) {
                        if (preg_match($re, $txt, $mm)) $m[$kk] = trim($mm[1]);
                    }
                }
            }

            // 3) config.xml
            if (empty($m['module_name']) && is_file($dir.'/config.xml')) {
                $xml = @simplexml_load_file($dir.'/config.xml');
                if ($xml) {
                    $m['module_name'] = (string)$xml->name ?: ($m['module_name'] ?? null);
                    $m['version']     = (string)$xml->version ?: ($m['version'] ?? null);
                    $m['author']      = (string)$xml->author  ?: ($m['author'] ?? null);
                    $m['description'] = (string)$xml->description ?: ($m['description'] ?? null);
                }
            }

            if (empty($m['module_name'])) {
                $m['module_name'] = ucwords(str_replace(['_','-'],' ', $sys));
            }
        }
    }
}
