<?php
// pages/components/switch_to_legacy.php
// HTMX endpoint to switch back to the legacy frontend by setting MAILBEEZ_CONFIG_BEEZ_UI = 'False'


require_once BEEZUI_ROOT . '/components/bootstrap.php';

// Best effort: persist via legacy configuration API when available
try {
    if (function_exists('mh_update_config_value')) {
        mh_update_config_value([
            'configuration_key'   => 'MAILBEEZ_CONFIG_BEEZ_UI',
            'configuration_value' => 'False',
        ]);
        if (function_exists('mh_cfg_override_set')) {
            // Ensure immediate consistency for current request if cache is used
            mh_cfg_override_set('MAILBEEZ_CONFIG_BEEZ_UI', 'False');
        }
    }
} catch (\Throwable $e) {
    // ignore, we still attempt to redirect
}

// Compute legacy entrypoint (strip query from BEEZUI_ENTRYPOINT if present)
$legacy = 'mailbeez.php';
if (defined('BEEZUI_ENTRYPOINT')) {
    $entry = (string)constant('BEEZUI_ENTRYPOINT');
    if ($entry !== '') {
        $legacy = strtok($entry, '?') ?: 'mailbeez.php';
    }
}

$s = print_r($_SERVER, true);

$legacy = $_SERVER['REQUEST_URI'];

// Non-HTMX fallback: return minimal HTML that navigates the top window to legacy URL
$html = <<<HTML
<script>

window.top.location.href = '{$legacy}';
</script>
HTML;
echo $html;
return;
