<?php
// pages/module_configuration.php
// Dynamic configuration: default view mode shows values; edit mode renders form; includes module extensions

use Components\Form\Engine;
use Components\ModuleLoader;
use Components\Button;
use Components\ConfigStore;
use Components\Form\Presentation\ValuePresenter;

$module = mh_get('module', 'overview', 'key');
$mode = mh_get('mode', 'view', 'key');
$drawer = mh_get('drawer', 0, 'int');
$returnParam = mh_get('return', '', 'key');
$targetParam = mh_get('target', '', 'key');
$autoCloseRaw = mh_get('autoclose', null) !== null ? mh_get('autoclose', '', 'string') : ($drawer ? '1' : '');
// Optional: limit view/edit to a subset of configuration keys (comma-separated or repeated keys[])
$keysParam = '';
if (mh_get('keys', null) !== null) {
    $kp = mh_get('keys', '', 'string');
    if ($kp === '' && is_array($_GET['keys'] ?? null)) {
        $keysParam = implode(',', array_map('strval', (array)$_GET['keys']));
    } else {
        $keysParam = (string)$kp;
    }
} else {
    // tolerate aliases
    foreach (['fields', 'field', 'only', 'names'] as $alias) {
        if (mh_get($alias, null) !== null) {
            $kp = mh_get($alias, '', 'string');
            if ($kp === '' && is_array($_GET[$alias] ?? null)) {
                $keysParam = implode(',', array_map('strval', (array)$_GET[$alias]));
            } else {
                $keysParam = (string)$kp;
            }
            break;
        }
    }
}



$persistParams = [];
if ($drawer) {
    $persistParams['drawer'] = 1;
}
if ($returnParam !== '') {
    $persistParams['return'] = $returnParam;
}
if ($keysParam !== '') {
    $persistParams['keys'] = $keysParam;
}
if ($targetParam !== '') {
    $persistParams['target'] = $targetParam;
}
if ($autoCloseRaw !== '') {
    $persistParams['autoclose'] = $autoCloseRaw;
}

// ensure inlineTarget is available from param if not already set by including page
if (!isset($inlineTarget) || $inlineTarget === '') {
    $inlineTarget = $targetParam;
}

// Special: list views for service and filter modules via configuration submenu
if ($module === 'service_modules' || $module === 'filter_modules') {
    $listTitle = $module === 'service_modules' ? 'Service Modules' : 'Filter Modules';
    $modulesByTouchpoint = $module === 'service_modules'
            ? ModuleLoader::serviceModulesByGroup()
            : ModuleLoader::filterModulesByGroup();
    ob_start();
    ?>
    <div>
        <h3 class="text-lg font-semibold mb-3"><?php echo \Components\Base::h($listTitle); ?></h3>
        <?php include BEEZUI_ROOT . '/pages/components/trigger_layout_list.php'; ?>
    </div>
    <?php
    echo ob_get_clean();
    return;
}




$title = $module && ModuleLoader::exists($module) ? ModuleLoader::title($module) : 'Unknown Module';

// Resolve merged blueprints for the selected module (supports alias config modules)
$blueprintPaths = ModuleLoader::mergedBlueprintPaths($module);
// Load current saved config first so dynamic sources can receive current values
$savedValues = ConfigStore::getModuleConfig($module);
$engine = Engine::fromBlueprints($blueprintPaths, is_array($savedValues) ? $savedValues : null);
$fields = $engine->getFields();
$groups = $engine->getGroups();
$ungrouped = $engine->getUngroupedFieldNames();

// If a subset of keys is requested, filter groups/fields accordingly
$allowedSet = null;
if ($keysParam !== '') {
    $req = array_filter(array_map(function ($s) {
        return strtoupper(trim((string)$s));
    }, preg_split('/[,\s]+/', $keysParam)));
    if (!empty($req)) {
        $allowedSet = [];
        foreach ($req as $name) {
            if (isset($fields[$name])) {
                $allowedSet[$name] = true;
            }
        }
        if (!empty($allowedSet)) {
            // Filter groups
            $filteredGroups = [];
            foreach ($groups as $g) {
                $gf = [];
                foreach ((array)($g['fields'] ?? []) as $fn) {
                    if (is_array($fn)) {
                        $rowOptions = $fn['_row_options'] ?? null;
                        $row = array_values(array_filter($fn, function ($k) use ($fn, $allowedSet) {
                            if (!is_int($k)) return false;
                            $subFn = $fn[$k];
                            return isset($allowedSet[$subFn]);
                        }, ARRAY_FILTER_USE_KEY));
                        if (!empty($row)) {
                            if ($rowOptions) {
                                $row['_row_options'] = $rowOptions;
                            }
                            $gf[] = $row;
                        }
                    } else {
                        if (isset($allowedSet[$fn])) {
                            $gf[] = $fn;
                        }
                    }
                }
                if (!empty($gf)) {
                    $g['fields'] = $gf;
                    $filteredGroups[] = $g;
                }
            }
            $groups = $filteredGroups;
            // Filter ungrouped
            $ungrouped = array_values(array_filter($ungrouped, function ($fn) use ($allowedSet) {
                return isset($allowedSet[$fn]);
            }));
        }
    }
}

$isPost = (mh_server('REQUEST_METHOD', 'GET') === 'POST');
$savedValues = ConfigStore::getModuleConfig($module);
$submittedValues = $isPost ? $engine->normalizeSubmittedValues(\Components\Common\Request::all('post')) : $savedValues;
// Inject mode into submitted/validation contexts for mode-based field visibility
if (is_array($submittedValues)) {
    $submittedValues['__mode'] = $mode;
}
$validatePayload = $isPost ? array_merge($savedValues, \Components\Common\Request::all('post')) : [];
if ($isPost) {
    $validatePayload['__mode'] = $mode;
}
$errors = $isPost ? $engine->validate($validatePayload) : [];
if ($isPost && is_array($allowedSet) && !empty($allowedSet)) {
    // Limit to the requested subset and only to fields that were actually posted
    $errors = array_intersect_key($errors, $allowedSet);
    $posted = array_fill_keys(array_keys(array_diff_key($_POST, ['module' => 1, 'mode' => 1, 'drawer' => 1, 'return' => 1, 'keys' => 1])), true);
    $errors = array_intersect_key($errors, $posted);
}

$isSaved = ($isPost && empty($errors)) || (isset($saveSucceeded) && $saveSucceeded);

if ($drawer && \Components\Support\Htmx::isRequest()) {
    $panelId = \Components\Support\Htmx::resolvePanelId(null, true);
    $titleId = $panelId . '-title'; // Defaults to 'config-drawer-title'
    ?>
    <span hx-swap-oob="innerHTML:#<?= $titleId ?>">
        <?= \Components\Base::h($title) ?>
    </span>
    <?php
}

// Use different content ids depending on drawer mode so clients can target correctly
$bodyId = $drawer ? 'module-config-drawer-content' : 'module-config-content-' . $module;

?>
<div id="<?php echo $bodyId; ?>"
        <?php if (false && !$drawer): ?>
            class="border border-divider rounded p-6 bg-white dark:border-white/10 dark:bg-slate-900"
        <?php endif ?>
>
    <div class="hidden mb-3 flex items-center gap-2">
        <span class="inline-flex items-center rounded bg-blue-50 px-2 py-1 text-xs font-medium text-blue-700 border border-blue-200"><?php echo \mh_lng('UI_MODULE_PREFIX', 'Module: '); ?><?php echo \Components\Base::h($module ?: \mh_lng('UI_NA', 'n/a')); ?></span>
    </div>

    <!--  <h6 class="text-base font-semibold text-gray-900 mb-3">--><?php //echo \Components\Base::h($title); ?><!-- -->
    <?php //echo \mh_lng('UI_SETTINGS','Settings'); ?><!--</h6>-->


    <?php if ($module == 'overview' || $module==''): ?>
        <?php include BEEZUI_ROOT . '/pages/components/configuration_overview.php';?>
    <?php elseif (!ModuleLoader::exists($module)): ?>
        <p class="text-sm text-gray-600"><?php echo \mh_lng('UI_NO_MODULE_SELECTED', 'No module selected or unknown module id ' . $module . ' . Please close the drawer and try again.'); ?></p>
    <?php else: ?>

        <!-- Extensions section -->
        <?php if ($mode !== 'edit'): ?>
            <?php $extensions = ModuleLoader::extensions($module); ?>
            <?php if (!empty($extensions)): ?>
                <div class="mb-4 rounded-lg border border-gray-200 bg-white p-3 dark:border-white/10 dark:bg-slate-900">
                    <div class="mb-2 flex items-center justify-between">
                        <div>
                            <div class="text-sm font-semibold text-gray-900 dark:text-gray-100"><?php echo \mh_lng('UI_EXTENSIONS', 'Extensions'); ?></div>
                            <div class="text-xs text-gray-500"><?php echo \mh_lng('UI_ENHANCE_PREFIX', 'Enhance '); ?><?php echo \Components\Base::h($title); ?><?php echo \mh_lng('UI_ENHANCE_SUFFIX', ' with optional features'); ?></div>
                        </div>
                    </div>
                    <div class="grid grid-cols-1 gap-2">
                        <?php foreach ($extensions as $ext): ?>
                            <div class="flex items-start justify-between rounded-md border border-gray-200 p-2 dark:border-white/10">
                                <div>
                                    <div class="text-sm font-medium text-gray-900 dark:text-gray-100"><?php echo \Components\Base::h($ext['title'] ?? ''); ?></div>
                                    <div class="text-xs text-gray-600 dark:text-gray-400"><?php echo \Components\Base::h($ext['desc'] ?? ''); ?></div>
                                </div>
                                <div class="ml-3 shrink-0">
                                    <?php if (!empty($ext['installed'])): ?>
                                        <span class="inline-flex items-center rounded bg-green-50 px-2 py-1 text-xs font-medium text-green-700 border border-green-200"><?php echo \mh_lng('UI_INSTALLED', 'Installed'); ?></span>
                                    <?php else: ?>
                                        <?php echo Button::render(\mh_lng('UI_INSTALL', 'Install'), [
                                                'as' => 'a',
                                                'href' => $ext['url'] ?? '#',
                                                'variant' => 'primary',
                                                'size' => 'sm',
                                        ]); ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>
        <?php endif; ?>

        <?php if ($mode === 'edit'): ?>
            <?php
            // Build reusable edit form for the module resource
            $showUninstall = ModuleLoader::canUninstall($module);

            echo \Components\Resources\ResourceEditForm::render([
                    'engine' => $engine,
                    'fields' => $fields,
                    'groups' => $groups,
                    'ungrouped' => $ungrouped,
                    'submitted' => $submittedValues,
                    'errors' => $errors,
                    'hx_post' => route('save_module_config', ['module' => $module, 'return' => ($returnParam !== '' ? $returnParam : 'config_view'), 'partial' => 1] + ($keysParam !== '' ? ['keys' => $keysParam] : []) + ($autoCloseRaw !== '' ? ['autoclose' => $autoCloseRaw] : [])),
                    'hx_get' => route('module_config', array_merge(['module' => $module, 'mode' => 'edit'], $persistParams)),
                    'panel_target_id' => $inlineTarget ?? $bodyId,
                    'persist_params' => $persistParams,
                    'allowed_set' => $allowedSet,
                    'module' => $module,
                    'drawer' => $drawer,
                    'autoclose' => $autoCloseRaw,
                    'saved' => $isSaved,
                    'show_uninstall' => $showUninstall,
            ]);
            ?>
        <?php else: ?>
            <div class="flex shrink-0 justify-end px-4 py-4">
                <?php echo Button::render(\mh_lng('UI_EDIT_CONFIGURATION', 'Edit Configuration'), [
                        'variant' => 'primary',
                        'size' => 'md',
                        'attrs' => [
                                'hx-get' => route('module_config', array_merge(['module' => $module, 'mode' => 'edit'], $persistParams)),
                                'hx-target' => '#' . $bodyId,
                                'hx-swap' => 'outerHTML',
                        ],
                ]); ?>
            </div>
            <?php
            echo \Components\Resources\ResourcePresentation::render([
                    'engine' => $engine,
                    'fields' => $fields,
                    'groups' => $groups,
                    'ungrouped' => $ungrouped,
                    'values' => $submittedValues,
                    'container' => true,
            ]);
            ?>

        <?php endif; ?>
    <?php endif; ?>
</div>
