<?php
namespace Components\Resources\Controllers;

use Components\ConfigStore;

class ModuleConfigController extends BaseController
{
    /**
     * Handle save/read for module configuration.
     * Returns HTML string and sets appropriate HTTP status codes when needed.
     */
    public static function handle(): string
    {
        $module = (string) self::getParam('module', '', 'key');

        if ($module === '') {
            http_response_code(400);
            return '<div class="text-sm text-red-600">Missing module key</div>';
        }

        // Return mode & UI flags
        $returnMode = self::determineReturnMode();
        [$drawerFlag, $autoCloseRaw, $autoCloseEnabled] = self::resolveDrawerAndAutoClose();

        // Custom logic: status toggle and UI open state
        self::handleStatusToggleForModule($module);
        $uiOpen = self::handleUiOpenForModule($module, $returnMode);
        if ($uiOpen !== null) { return $uiOpen; }

        // Engine + keys
        $engine = self::getEngineForModule($module);
        [$keysParam, $allowedSet] = self::getKeysAndAllowedSet($engine);

        // Posted fields
        $postAll = \Components\Common\Request::all('post');
        $hasPostedFields = self::hasPostedFields($postAll);
        $returnMode = self::finalizeReturnModeForStatus($returnMode, $hasPostedFields);

        $saveSucceeded = false;
        if ($hasPostedFields) {
            $existing = ConfigStore::getModuleConfig($module);
            $normalized = $engine->normalizeSubmittedValues($postAll);
            $validatePayload = array_merge($existing, $postAll);
            $validatePayload['__mode'] = 'edit';
            $errors = $engine->validate($validatePayload);
            if (is_array($allowedSet) && !empty($allowedSet)) {
                $normalized = array_intersect_key($normalized, $allowedSet);
                $errors = array_intersect_key($errors, $allowedSet);
            }
            if (!empty($errors)) {
                // Render edit form with errors
                return self::renderConfigEditPage($module, $keysParam);
            }

            // Checkbox/toggle semantics and persistence
            $isFullForm = !is_array($allowedSet) || empty($allowedSet);
            if ($keysParam !== '') { $isFullForm = false; }
            $normalized = self::applyCheckboxSemantics($engine, $normalized, $isFullForm, $allowedSet);

            $toPersist = $isFullForm ? array_merge($existing, $normalized) : $normalized;
            ConfigStore::setModuleConfig($module, $toPersist, !$isFullForm);
            \Components\Data\DataRegistry::reset();
            $saveSucceeded = true;
        }

        // Response rendering
        if ($returnMode === 'module_card') {
            return self::renderModuleCard($module, $saveSucceeded, $autoCloseEnabled);
        }

        // Default: configuration view
        return self::renderConfigurationView($module, $keysParam, $saveSucceeded, $autoCloseEnabled);
    }


    /** Handle status toggle if requested. Returns true when status was toggled. */
    protected static function handleStatusToggleForModule(string $module): bool
    {
        if (\mh_request('status_toggle', null) !== null) {
            \Components\ConfigStore::setModuleStatus($module, \mh_post('status', null) !== null);
            \Components\Data\DataRegistry::reset();
            return true;
        }
        return false;
    }

    /** Persist UI open state; returns '' (empty string) when 204 open_state response should be returned, otherwise null. */
    protected static function handleUiOpenForModule(string $module, string $returnMode): ?string
    {
        if (\mh_post('ui_open', null) !== null) {
            $isOpen = \mh_post('ui_open', '', 'string') !== '';
            \Components\ConfigStore::setUiOpenState($module, $isOpen);
            if ($returnMode === 'open_state') {
                http_response_code(204);
                return '';
            }
        }
        return null;
    }

    /** Render edit page for module with optional keys param. */
    protected static function renderConfigEditPage(string $module, string $keysParam): string
    {
        $_GET['module'] = $module;
        $_GET['mode'] = 'edit';
        self::persistCommonParamsToGet();
        if ($keysParam !== '') { $_GET['keys'] = $keysParam; }
        ob_start();
        include BEEZUI_ROOT . '/pages/module_configuration.php';
        return ob_get_clean();
    }

    /** Render configuration view page and optional auto-close + OOB module_card. */
    protected static function renderConfigurationView(string $module, string $keysParam, bool $saveSucceeded, bool $autoCloseEnabled): string
    {
        $_SERVER['REQUEST_METHOD'] = 'GET';
        $_GET['module'] = $module;
        $_GET['mode'] = 'view';
        self::persistCommonParamsToGet();
        if ($keysParam !== '') { $_GET['keys'] = $keysParam; }
        ob_start();
        include BEEZUI_ROOT . '/pages/module_configuration.php';
        if ($saveSucceeded && $autoCloseEnabled) {
            ?>
            <div style="min-height: 240px"></div>
            <script>(function(){try{var d=document.getElementById('config-drawer');if(d&&typeof d.close==='function'){d.close();}var m=document.getElementById('config-modal');if(m&&typeof m.close==='function'){m.close();}}catch(e){}})();</script>
            <?php
        }
        if ($saveSucceeded && \mh_post('return', null, 'string') === 'module_card') {
            $all = \Components\ModuleLoader::all();
            $m = $all[$module] ?? null;
            if ($m) {
                $oobSwap = 'outerHTML';
                include BEEZUI_ROOT . '/pages/components/trigger_module.php';
            }
        }
        return ob_get_clean();
    }

    /** Render module card for trigger list and optionally auto-close script. */
    protected static function renderModuleCard(string $module, bool $saveSucceeded, bool $autoCloseEnabled): string
    {
        $all = \Components\ModuleLoader::all();
        $m = $all[$module] ?? null;
        if (!$m) {
            http_response_code(404);
            return '<div class="text-sm text-red-600">Unknown module: ' . \Components\Base::h($module) . '</div>';
        }
        $oobSwap = 'outerHTML';
        ob_start();
        include BEEZUI_ROOT . '/pages/components/trigger_module.php';
        if ($saveSucceeded && $autoCloseEnabled) {
            ?>
            <div style="min-height: 240px"></div>
            <script>(function(){try{var d=document.getElementById('config-drawer');if(d&&typeof d.close==='function'){d.close();}var m=document.getElementById('config-modal');if(m&&typeof m.close==='function'){m.close();}}catch(e){}})();</script>
            <?php
        }
        return ob_get_clean();
    }
}
