<?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 appropriately depending on context
// - If running inside wrapper.php (iframe id="app-iframe"), reload the top window
// - Else if inside any iframe, reload the parent
// - Else reload the current window
$legacyJs = json_encode($legacy, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$html = <<<HTML
<script>
(function(){
  var legacy = {$legacyJs};
  try {
    var inIframe = (window.parent && window.parent !== window);
    var inWrapper = !!(window.frameElement && window.frameElement.id === 'app-iframe');
    if (inWrapper) {
      window.parent.location.href = legacy;
      return;
    }
  } catch (e) { /* ignore and fall back to self */ }
  window.location.href = legacy;
})();
</script>
HTML;
echo $html;
return;
