<?php
// pages/components/trigger_install.php
require_once BEEZUI_ROOT . '/components/index.php';

$key = \Components\Common\Request::get('module', '', 'key');
if ($key === '') {
    echo "Missing module key";
    exit;
}

// Ensure the module class is loaded
if (!class_exists($key)) {
    if (defined('MH_DIR_MODULE')) {
        $file = MH_DIR_MODULE . $key . (defined('MH_FILE_EXTENSION') ? MH_FILE_EXTENSION : '.php');
        if (file_exists($file)) {
            mh_load_modules_language_files(MH_DIR_MODULE, $key);
            require_once $file;
        }
    }
}

if (class_exists($key)) {
    $module = new $key();
    if (method_exists($module, 'install')) {
        $module->install();

        // Keep ModuleLoader/module provider caches in sync after install.
        try {
            \Components\ModuleLoader::forceRefresh();
        } catch (\Throwable $e) {
            // Best-effort fallback for current request.
            \Components\Data\DataRegistry::reset();
        }

        // Success!
        // Instead of triggering refresh via HTMX events, we return the refreshed prebuild section directly
        // to avoid an additional request.
        $_GET['partial'] = 1;
        $_GET['section'] = 'prebuild';
        $_GET['installed_module'] = $key;
        // Note: 'layout' and 'group' are already in the request if passed via the URL
        include BEEZUI_ROOT . '/pages/trigger.php';
        exit;
    }
}

echo "Module not found or could not be installed.";
