<?php
// pages/email_editor.php — BeezUI Email Editor shell
require_once BEEZUI_ROOT . '/components/index.php';
require_once BEEZUI_ROOT . '/pages/layout.php';

use Components\Base;
use Components\Router;
use Components\Ui\EmailEditor;

// Guard: only render inside BeezUI context
if (!mh_beezui()) {
    echo '<div class="p-6 text-sm text-red-600">BeezUI is not enabled.</div>';
    return;
}
mh_load_modules_language_files(MH_DIR_MODULE, 'mb_newsletter');

// Inputs
$context = mh_get('context', 'module');
$module = mh_get('module');
$lngId = mh_get('lng_id', 0);
$newsletterId = (int)mh_get('newsletter_id', 0);
$campaignId = (int)mh_get('campaign_id', 0);
$flowId = (int)mh_get('flow_id', 0);
$maintemplate_id = mh_get('maintemplate_id');
$content_module_id = mh_get('content_module_id');

/** @var \Components\Models\NewsletterItem $newsletterItem */
$newsletterItem = ($newsletterId > 0 && class_exists('\Components\Models\NewsletterItem'))
    ? \Components\Models\NewsletterItem::find($newsletterId)
    : null;

// Schedule summary logic moved to Components\Models\NewsletterItem::buildScheduleSummary()

if (mh_get('partial') === 'date_range' && $newsletterItem) {
    echo Base::h($newsletterItem->buildScheduleSummary());
    return;
}

if (mh_get('partial') === 'to_placeholder' && $newsletterItem) {
    $audListId = (int)($newsletterItem->newsletter_list_id ?? 0);
    if ($audListId <= 0) {
        try {
            $c = $newsletterItem->campaign();
            $audListId = (int)($c->newsletter_list_id ?? 0);
        } catch (\Throwable $e) { /* ignore */ }
    }
    $audName = '';
    if ($audListId > 0 && class_exists('\Components\Models\Audience')) {
        try {
            $aud = \Components\Models\Audience::find($audListId);
            $audName = $aud->getLabel($newsletterItem);
        } catch (\Throwable $e) { /* ignore */ }
    }
    $moduleTitle = 'Newsletter Profi'; // Fallback
    if ($newsletterItem->newsletter_item_name) {
        $moduleTitle .= ' - ' . $newsletterItem->newsletter_item_name;
    }
    if ($audName !== '') {
        echo Base::h($moduleTitle . ' - ' . $audName);
    } else {
        echo Base::h($moduleTitle);
    }
    return;
}

if (mh_get('partial') === 'modal_title' && $newsletterItem) {
    $moduleTitle = 'Newsletter Profi'; // Fallback
    if ($newsletterItem->newsletter_item_name) {
        $moduleTitle .= ' - ' . $newsletterItem->newsletter_item_name;
    }
    echo Base::h($moduleTitle);
    return;
}

$moduleTitle = mh_get('title', '');
if ($context === 'newsletter' && $newsletterItem) {
    $moduleTitle = 'Newsletter Profi'; // Fallback
    if ($newsletterItem->newsletter_item_name) {
        $moduleTitle .= ' - ' . $newsletterItem->newsletter_item_name;
    }
}

$newsletterStatusLocked = false;
$newsletterIsFollowUp = false;
if ($context === 'newsletter' && $newsletterItem) {
    $newsletterStatusLocked = $newsletterItem->isLocked();
    $newsletterIsFollowUp = $newsletterItem->isFollowup();
}

mh_define('MH_EDITOR_CONTEXT', $context);

// Language list (fallback to default)
$languages = [];
$defaultLanguageId = (int)(mh_session('languages_id', 1));
if ($lngId <= 0) {
    $lngId = $defaultLanguageId;
}
try {
    $languages = (array)mh_get_language_list();
} catch (Throwable $e) {
//    print_r($e);
    $languages = [];
}
if (!$languages) {
    $languages = [['id' => $defaultLanguageId, 'code' => 'EN', 'text' => 'EN']];
}

// Resolve visual editor and autosave endpoints (per language)
$templateManager = (mh_cfg('MAILBEEZ_CONFIG_TMPLMNGR_LNG_STATUS') == 'True') ? 'config_tmplmngr_lng' : 'config_tmplmngr';
if ($context === 'main' && empty($module)) {
    $module = $templateManager;
}
$appPathModule = 'configbeez/' . $templateManager;

// Collect per-language data so we can switch with Alpine.js without reloading
$langInfos = [];

try {
    $obj = null;
    $editorItemId = $content_module_id ?: $module;

    if ($context === 'newsletter' && $newsletterId > 0) {
        $module = 'mb_newsletter';
        include_once(MH_DIR_MODULE . $module . MH_FILE_EXTENSION);
        mh_load_modules_language_files(MH_DIR_MODULE, $module);
        mh_load_modules_language_files(MH_DIR_CONFIG, 'config_editor');
        $obj = new mb_newsletter();
        $obj->iteration = $newsletterId;
        $editorItemId = mb_newsletter::get_newsletter_module_id($newsletterId);

//        if (method_exists($obj, 'loadAllTemplates')) {
//            $obj->loadAllTemplates();
//        }
    } elseif ($context === 'main') {
        include_once(MH_DIR_CONFIG . $templateManager . '/mb_main.php');
        $obj = new mb_main();
        $editorItemId = $maintemplate_id ?: 'MAIN';

        mh_load_modules_language_files(MH_DIR_CONFIG, $templateManager);
        mh_load_modules_language_files(MH_DIR_CONFIG, 'config_editor');
    } elseif ($module !== '') {
        include_once(MH_DIR_MODULE . $module . MH_FILE_EXTENSION);
        $class = mh_get_class_name($module);
//        $baseModule = mh_get_module_name($module);
        mh_load_modules_language_files(MH_DIR_MODULE, mh_get_module_name($module));
        mh_load_modules_language_files(MH_DIR_CONFIG, 'config_editor');
        $obj = new $class();
        $module_path = mh_get_class_path($class);
        if (empty($editorItemId)) {
            $editorItemId = $module;
        }

//        if (method_exists($obj, 'loadAllTemplates')) {
//            $obj->loadAllTemplates();
//        }
    }
    foreach ($languages as $li) {
        if (!is_array($li)) continue;
        $id = isset($li['id']) ? (int)$li['id'] : (int)($li['languages_id'] ?? 0);
        if ($id <= 0) continue;
        $text = isset($li['text']) ? (string)$li['text'] : (isset($li['code']) ? strtoupper((string)$li['code']) : ('#' . $id));
        $code = isset($li['code']) ? (string)$li['code'] : (string)($li['languages_code'] ?? '');

        if ($context === 'newsletter') {
            $visualUrl = mh_href_link(
                    FILENAME_MAILBEEZ,
                    'app=load_app&app_path=mailbeez/mb_newsletter/admin_application_plugins/visual_editor.php'
                    . '&newsletter_id=' . $newsletterId
                    . '&flow_id=' . $flowId
                    . '&lng_id=' . (int)$id
                    . '&popup=true'
                    . (mh_cfg('MAILBEEZ_FILTER_ADD_GENDER_STATUS') === 'True' ? '&gnd=unknown' : '')
            );
            $autoUrl = mh_href_link(
                    FILENAME_MAILBEEZ,
                    'app=load_app&app_path=mailbeez/mb_newsletter/admin_application_plugins/newsletter_edit.php'
                    . '&app_action=save_meta_htmx'
                    . '&newsletter_id=' . $newsletterId
                    . '&flow_id=' . $flowId
                    . '&lng_id=' . (int)$id
            );
        } else {
            $appPathAuto = ($context === 'main') ? 'cfg_language_common.php' : 'cfg_language_module.php';
            $visualUrl = mh_href_link(
                    FILENAME_MAILBEEZ,
                    'app=load_app&app_path=' . $appPathModule . '/admin_application_plugins/visual_editor.php'
                    . ($context !== 'main' ? '&module=' . rawurlencode($module) : '')
                    . ($maintemplate_id ? '&maintemplate_id=' . rawurlencode($maintemplate_id) : ($context === 'main' ? '&maintemplate_id=MAIN' : ''))
                    . ($content_module_id ? '&content_module_id=' . rawurlencode($content_module_id) : ($context === 'main' ? '&content_module_id=MAIN' : ''))
                    . '&popup=true'
                    . '&lng_id=' . (int)$id
                    . (mh_cfg('MAILBEEZ_FILTER_ADD_GENDER_STATUS') === 'True' ? '&gnd=unknown' : '')
            );
            $autoUrl = mh_href_link(
                    FILENAME_MAILBEEZ,
                    'app=load_app&app_path=' . $appPathModule . '/admin_application_plugins/' . $appPathAuto
                    . '&app_action=save_meta_htmx'
                    . ($context !== 'main' ? '&module=' . rawurlencode($module) : '')
                    . ($maintemplate_id ? '&maintemplate_id=' . rawurlencode($maintemplate_id) : ($context === 'main' ? '&maintemplate_id=MAIN' : ''))
                    . ($content_module_id ? '&content_module_id=' . rawurlencode($content_module_id) : ($context === 'main' ? '&content_module_id=MAIN' : ''))
                    . '&lng_id=' . (int)$id
            );
        }

        $subject = '';
        $preheader = '';
        if ($obj) {
            $mb_tmpl_restore = false;
            try {
                if ($context === 'newsletter') {
                    list($subjectVal) = mb_newsletter::load_newsletter_object($editorItemId, $id, 'subjectTemplate', $obj, $mb_tmpl_restore);
                    list($preheaderVal) = mb_newsletter::load_newsletter_object($editorItemId, $id, 'preheaderTemplate', $obj, $mb_tmpl_restore);
                } else {
                    list($subjectVal) = mh_load_language_object($editorItemId, $id, 'subjectTemplate', $obj, $mb_tmpl_restore);
                    list($preheaderVal) = mh_load_language_object($editorItemId, $id, 'preheaderTemplate', $obj, $mb_tmpl_restore);
                }
                $subject = (string)$subjectVal;
                $preheader = (string)$preheaderVal;
            } catch (Throwable $e) {
//                print_r($e);
                // keep defaults if a single language fails
            }
        }

        $langInfos[] = [
                'id' => $id,
                'text' => $text,
                'code' => $code,
                'visualEditorUrl' => $visualUrl,
                'autosaveUrl' => $autoUrl,
                'subject' => $subject,
                'preheader' => $preheader,
        ];
    }
} catch (Throwable $e) {
//    print_r($e);
    // Fall back handled by initial $languages setup
}

// Placeholder resolution logic
$toPlaceholder = mh_lng('MAILBEEZ_EDITOR_TO_PLACEHOLDER', 'contact list');
$fromPlaceholder = mh_lng('MAILBEEZ_EDITOR_FROM_PLACEHOLDER', 'sender');
$dateRangeText = '';
$scheduleEditUrl = '';

if ($obj) {
    // 1. Resolve from_placeholder: Name <email>
    $sender = property_exists($obj, 'sender') ? $obj->sender : null;
    $senderName = property_exists($obj, 'sender_name') ? $obj->sender_name : null;
    if ($sender !== null && $sender !== '') {
        $fromPlaceholder = ($senderName !== null && $senderName !== '') ? $senderName . ' - ' . $sender . '' : $sender;
    }

// 2. Resolve iteration name for modules (to_placeholder)
$toPlaceholderOptions = [];
if ($context === 'module' && method_exists($obj, 'flow')) {
    $className = function_exists('mh_get_class_name') ? \mh_get_class_name($module) : $module;
    $flowData = $obj->flow();
    $targetStepId = '';
    if (strpos($className, '_step') !== false) {
        $targetStepId = substr($className, strpos($className, '_step') + 1);
    } elseif ($flowId > 0) {
        $targetStepId = 'step' . $flowId;
    }

    foreach ($flowData as $fitem) {
        if (isset($fitem['type']) && $fitem['type'] === 'step' && !($fitem['disabled'] ?? false)) {
            $stepId = $fitem['id'] ?? '';
            $stepSubtitle = $fitem['subtitle'] ?? '';
            if ($stepId !== '' && $stepSubtitle !== '') {
                $stepEditorUrl = '';
                if (isset($fitem['dropdown']['items'])) {
                    foreach ($fitem['dropdown']['items'] as $ditem) {
                        if (isset($ditem['label']) && $ditem['label'] === mh_lng('MAILBEEZ_BUTTON_EDITOR_LABEL', 'Editor')) {
                            $stepEditorUrl = $ditem['attrs']['hx-get'] ?? '';
                            break;
                        }
                    }
                }

                if ($stepEditorUrl !== '') {
                    $toPlaceholderOptions[] = [
                        'label' => $stepSubtitle,
                        'url' => $stepEditorUrl,
                        'active' => ($stepId === $targetStepId)
                    ];
                }
            }

            if ($targetStepId !== '' && $stepId === $targetStepId) {
                if ($stepSubtitle !== '') {
                    $toPlaceholder = $stepSubtitle;
                }
            }
        }
    }
}
}

if ($newsletterItem) {
    // Human-friendly schedule summary for the Email Details header
    $dateRangeText = $newsletterItem->buildScheduleSummary();

    $params = [
            'partial' => 1,
            'mode' => 'edit',
            'id' => $newsletterId,
            'fields' => 'schedule_config',
            'autoclose' => 'true',
            'event_suffix' => 'expandable:refresh',
    ];
    if (($flowId ?? 0) > 0) { $params['ui_event_id'] = $flowId; }
    $scheduleEditUrl = \Components\Router::url('newsletter_item_modal', $params);

    // Resolve audience name for to_placeholder
    $audListId = (int)($newsletterItem->newsletter_list_id ?? 0);
    if ($audListId <= 0) {
        try {
            $c = $newsletterItem->campaign();
            $audListId = (int)($c->newsletter_list_id ?? 0);
        } catch (\Throwable $e) { /* ignore */ }
    }

    $audName = '';
    if ($audListId > 0 && class_exists('\Components\Models\Audience')) {
        try {
            $aud = \Components\Models\Audience::find($audListId);
            $audName = $aud->getLabel($newsletterItem);
        } catch (\Throwable $e) { /* ignore */ }
    }

    if ($audName !== '') {
        $toPlaceholder = ($moduleTitle !== '' ? $moduleTitle . ' - ' : '') . $audName;
    }
}

// Helper to render language tabs as Alpine.js buttons (no reload)
$renderLanguageTabs = function (array $langInfos, int $activeId) {
    $out = '';
    foreach ($langInfos as $li) {
        if (!is_array($li)) continue;
        $id = (int)($li['id'] ?? 0);
        if ($id <= 0) continue;
        $text = (string)($li['text'] ?? ('#' . $id));
        $selected = ($id === $activeId);
        $attrs = Base::attrs([
                'type' => 'button',
                'class' => 'px-3 py-1 rounded-md text-sm',
                ':class' => 'activeLngId === ' . $id . ' ? "bg-gray-100" : ""',
                '@click' => 'activeLngId = ' . $id,
                'aria-pressed' => $selected ? 'true' : 'false',
        ]);
        $out .= '<button ' . $attrs . '>' . Base::h($text) . '</button>';
    }
    return $out;
};

// When this page is rendered as an HTMX partial inside a BeezUI modal
// (see mailbeez_pro::getEditorDialog which uses the global #config-modal),
// move the EmailEditor toolbar into the modal header via Alpine's
// x-teleport. The EmailEditor component accepts an optional modal_id
// matching the dialog id; we default to "config-modal" for partial loads.
$modalIdForToolbar = '';
if ((int)mh_get('partial', 0) === 1) {
    $modalIdForToolbar = 'config-modal';
}

ob_start();
?>
    <div>
        <?php

        if ($context === 'newsletter') {
            $previewUrl = mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=mailbeez/mb_newsletter/admin_application_plugins/preview.php&popup=true&module=mb_newsletter&format=html&preview_item_id=' . $newsletterId);
            $sendTestUrl = mh_cfg('MAILBEEZ_MAILHIVE_URL') . 'test&module=mb_newsletter&send_test_item_id=' . $newsletterId;
        } else {
            $previewUrl = Components\Legacy\LegacyRouter::url('preview', [
                    'module' => ($context === 'main') ? 'MAIN' : (string)$module,
                    'maintemplate_id' => ($context === 'main') ? ($maintemplate_id ?: 'MAIN') : (string)$maintemplate_id,
                    'content_module_id' => ($context === 'main') ? 'MAIN' : (string)$content_module_id,
            ]);
            $sendTestUrl = Components\Legacy\LegacyRouter::url('sendTest', [
                    'module' => ($context === 'main') ? '' : (string)$module,
                    'maintemplate_id' => ($context === 'main') ? ($maintemplate_id ?: 'MAIN') : (string)$maintemplate_id,
                    'content_module_id' => ($context === 'main') ? '' : (string)$content_module_id,
            ]);
        }

        // Base URLs for Alpine bindings: append lng_id dynamically based on activeLngId
        $previewUrlLngBase = $previewUrl . (strpos($previewUrl, '?') !== false ? '&lng_id=' : '?lng_id=');
        $sendTestUrlLngBase = $sendTestUrl . (strpos($sendTestUrl, '?') !== false ? '&lng_id=' : '?lng_id=');

        $dropdownItems = [
                [
                        'label' => mh_lng('MAILBEEZ_BUTTON_PREVIEW_LABEL', 'Preview'),
                        'attrs' => [
                                'command' => 'show-modal',
                                'commandfor' => 'email-preview',
                                'data-title' => mh_lng('MAILBEEZ_BUTTON_PREVIEW_LABEL', 'Preview'),
                                'data-url' => $previewUrl,
                                ':data-url' => "'" . $previewUrlLngBase . "' + activeLngId + '&gnd=' + activeGnd",
                                'data-size' => '5xl',
                                'data-width' => 'var(--container-5xl)',
                                'data-height' => '95vh',
                                'hx-target' => '#email-preview-body',
                                'hx-swap' => 'innerHTML',
                        ],
                        'icon' => \Components\Base::SVG_DEVICE_MOBILE,
                ],
                [
                        'label' => mh_lng('MAILBEEZ_BUTTON_SEND_TESTMAIL_LABEL', 'Send Test'),
                        'attrs' => [
                                'command' => 'show-modal',
                                'commandfor' => 'editor-inline-modal',
                                'data-title' => mh_lng('MAILBEEZ_BUTTON_SEND_TESTMAIL_LABEL', 'Send Test'),
                                'data-size' => '2xl',
                                'data-url' => $sendTestUrl,
                                ':data-url' => "'" . $sendTestUrlLngBase . "' + activeLngId + '&gnd=' + activeGnd",
                                'hx-target' => '#editor-inline-modal-body',
                                'hx-swap' => 'innerHTML',
                        ],
                        'icon' => \Components\Base::SVG_OUTLINE_PAPER_PLANE,
                ],
        ];

        $nerdModeUrl = \Components\Legacy\LegacyRouter::url('nerdmode', [
            'context' => $context,
            'module' => (string)$module,
            'lng_id' => $lngId,
            'newsletter_id' => $newsletterId,
            'flow_id' => $flowId,
            'maintemplate_id' => (string)$maintemplate_id,
            'content_module_id' => (string)$content_module_id,
        ]);
        $textModeUrl = \Components\Legacy\LegacyRouter::url('textmode', [
            'context' => $context,
            'module' => (string)$module,
            'lng_id' => $lngId,
            'newsletter_id' => $newsletterId,
            'flow_id' => $flowId,
            'maintemplate_id' => (string)$maintemplate_id,
            'content_module_id' => (string)$content_module_id,
        ]);

        $nerdModeUrlLngBase = $nerdModeUrl . (strpos($nerdModeUrl, '?') !== false ? '&lng_id=' : '?lng_id=');
        $textModeUrlLngBase = $textModeUrl . (strpos($textModeUrl, '?') !== false ? '&lng_id=' : '?lng_id=');

        $dropdownItems[] = ['divider' => true];
        $dropdownItems[] = [
                'label' => mh_lng('BUTTON_NERDMODE', 'nerdmode: edit sourcecode'),
                'attrs' => [
                        'command' => 'show-modal',
                        'commandfor' => 'editor-inline-modal',
                        'data-title' => mh_lng('BUTTON_NERDMODE', 'nerdmode: edit sourcecode'),
                        'data-size' => 'full-margin',
                        'data-url' => $nerdModeUrl,
                        ':data-url' => "'" . $nerdModeUrlLngBase . "' + activeLngId + '&gnd=' + activeGnd",
                        'hx-target' => '#editor-inline-modal-body',
                        'hx-swap' => 'innerHTML',
                ],
                'icon' => \Components\Base::SVG_OUTLINE_CODE,
        ];
        $dropdownItems[] = [
                'label' => mh_lng('BUTTON_TXTMODE', 'txt: edit text version'),
                'attrs' => [
                        'command' => 'show-modal',
                        'commandfor' => 'editor-inline-modal',
                        'data-title' => mh_lng('BUTTON_TXTMODE', 'txt: edit text version'),
                        'data-size' => 'full-margin',
                        'data-url' => $textModeUrl,
                        ':data-url' => "'" . $textModeUrlLngBase . "' + activeLngId + '&gnd=' + activeGnd",
                        'hx-target' => '#editor-inline-modal-body',
                        'hx-swap' => 'innerHTML',
                ],
                'icon' => \Components\Base::SVG_OUTLINE_DOCUMENT_TEXT,
        ];

        if ($context === 'newsletter' && $newsletterId > 0) {
            $dropdownItems[] = ['divider' => true];
            $dropdownItems[] = [
                    'label' => mh_lng('MAILBEEZ_BUTTON_EDIT_NAME_DESCRIPTION_LABEL', 'Edit Name & Description'),
                    'attrs' => [
                            'command' => 'show-modal',
                            'commandfor' => 'editor-inline-modal',
                            'data-title' => mh_lng('MAILBEEZ_BUTTON_EDIT_NAME_DESCRIPTION_LABEL', 'Edit Name & Description'),
                            'data-size' => 'xl',
                            'hx-get' => Router::url('newsletter_item_modal', [
                                    'partial' => 1,
                                    'mode' => 'edit',
                                    'id' => (int)$newsletterId,
                                    'fields' => 'edit_name_description_hint,newsletter_item_name,newsletter_item_description',
                                    'autoclose' => 'true',
                                    'event_suffix' => 'updated',
                            ]),
                            'hx-target' => '#editor-inline-modal-body',
                            'hx-swap' => 'innerHTML',
                    ],
                    'icon' => \Components\Base::SVG_EDIT,
            ];
        }

        if ($context !== 'newsletter') {
            $templateSelectUrl = Router::url('editor_templates', [
                    'partial' => 1,
                    'is_modal' => 1,
                    'module' => (string)$module,
                    'newsletter_id' => $newsletterId,
                    'flow_id' => $flowId,
                    'context' => $context,
                    'maintemplate_id' => $maintemplate_id,
                    'content_module_id' => $content_module_id
            ]);
            $saveAsLabel = $context === 'main' ? mh_lng('BUTTON_MAINTEMPLATE_CREATE', 'Save as Layout-Template') : mh_lng('BUTTON_CREATE', 'Save as Content-Template');
            $templateSaveAsUrl = Router::url('template_action_confirm', [
                    'partial' => 1,
                    'confirm_action' => 'save_template_as',
                    'module' => (string)$module,
                    'newsletter_id' => $newsletterId,
                    'flow_id' => $flowId,
                    'context' => $context,
                    'maintemplate_id' => $maintemplate_id,
                    'lng_id' => $lngId,
            ]);

            $dropdownItems[] = ['divider' => true];
            $dropdownItems[] = [
                    'label' => mh_lng('BUTTON_SELECT', 'Select Content-Template'),
                    'attrs' => [
                            'command' => 'show-modal',
                            'commandfor' => 'editor-inline-modal',
                            'data-title' => mh_lng('BUTTON_SELECT', 'Select Content-Template'),
                            'data-size' => '5xl',
                            'hx-get' => $templateSelectUrl,
                            'hx-target' => '#editor-inline-modal-body',
                            'hx-swap' => 'innerHTML',
                    ],
                    'icon' => \Components\Base::SVG_OUTLINE_FOLDER_OPEN,
            ];
            $dropdownItems[] = [
                    'label' => $saveAsLabel,
                    'attrs' => [
                            'command' => 'show-modal',
                            'commandfor' => 'confirm-modal',
                            'data-title' => $saveAsLabel,
                            'hx-get' => $templateSaveAsUrl,
                            'hx-target' => '#confirm-modal-body',
                            'hx-swap' => 'innerHTML',
                    ],
                    'icon' => \Components\Base::SVG_OUTLINE_DOCUMENT_ADD,
            ];
        }


        // Main Template Selection
        if ($obj && ($context === 'module' || $context === 'newsletter')) {
            if (!class_exists('template_manager')) {
                include_once(MH_DIR_CONFIG . 'config_editor/classes/template_manager.php');
            }
            $currentMainTemplate = template_manager::get_maintemplate_id($obj);
            $mainTemplateOptions = template_manager::get_maintemplates_options($obj, null, true);

            $assignUrl = Router::url('email_editor_assign_maintemplate', [
                    'module' => $module,
                    'newsletter_id' => $newsletterId
            ]);

            $selectHtml = \Components\Form\Select::render('maintemplate_id', mh_lng('TEXT_HELP_MAINTEMPLATE_HEADLINE', 'Main Template'), $mainTemplateOptions, $currentMainTemplate, [
                    'include_empty' => false,
                    'input_attrs' => 'onchange="htmx.ajax(\'POST\', \'' . $assignUrl . '\', { target:\'#autosave-status\', swap:\'innerHTML\', values:{ maintemplate_id: this.value } }); var m = this.closest(\'el-menu\'); if(m) setTimeout(() => m.hidePopover(), 150);" :disabled="locked" tabindex="-1"',
            ]);

            $dropdownItems[] = ['divider' => true];
            $dropdownItems[] = [
                    'content' => '<div class="px-3 py-2" :class="locked ? \'opacity-50 pointer-events-none\' : \'\'"><form>' . MH_POST_TOKEN . $selectHtml . '</form></div>'
            ];
        }


        $stylingUrl = '';
        if ($context === 'main') {
            $stylingUrl = \Components\Legacy\LegacyRouter::url('stylingEditor', [
                'lng_id' => $lngId,
                'maintemplate_id' => $maintemplate_id ?: 'MAIN',
            ]);
        }

        echo EmailEditor::render([
                'module' => $module,
                'newsletter_id' => $newsletterId,
                'campaign_id' => $campaignId,
                'context' => $context,
                'lng_id' => $lngId,
                'flow_id' => $flowId,
                'maintemplate_id' => $maintemplate_id,
                'content_module_id' => $content_module_id,
                'styling_url' => $stylingUrl,
                'newsletter_status_locked' => $newsletterStatusLocked,
                'newsletter_is_follow_up' => $newsletterIsFollowUp ?? false,
                'modal_id' => $modalIdForToolbar,
                'to_placeholder' => $toPlaceholder,
                'to_placeholder_options' => $toPlaceholderOptions,
                'from_placeholder' => $fromPlaceholder,
                'date_range_text' => $dateRangeText,
                'schedule_edit_url' => $scheduleEditUrl ?? '',
                'actions_dropdown' => [
                        'items' => $dropdownItems
                ]
        ], $langInfos);
        ?>
    </div>
<?php
$content = ob_get_clean();
$pageKey = 'email_editor';
echo $content;
//echo layout($pageKey, $content);
