<?php
// pages/components/email_editor_assign_maintemplate.php
// Assign a main template to a module or newsletter

use Components\Support\Htmx;

// Guard: only operate when BeezUI is active
if (!function_exists('mh_beezui') || !mh_beezui()) {
    return;
}

$module          = (string) mh_get('module', '');
$newsletterId    = (int) mh_get('newsletter_id', 0);
$maintemplateId  = (string) mh_post('maintemplate_id', '');

if ($maintemplateId === '') {
    return;
}

$obj = null;

if ($newsletterId > 0) {
    if (!class_exists('mb_newsletter')) {
        include_once(MH_DIR_MODULE . 'mb_newsletter' . MH_FILE_EXTENSION);
    }
    $obj = new mb_newsletter();
    $obj->iteration = $newsletterId;
} elseif ($module !== '') {
    $class = mh_get_class_name($module . MH_FILE_EXTENSION);
    if (!class_exists($class)) {
        include_once(MH_DIR_MODULE . $module . MH_FILE_EXTENSION);
    }
    if (class_exists($class)) {
        $obj = new $class();
        // For modules, iteration/workflow_step is usually handled in constructor or by the framework
        // but template_manager::set_maintemplate_id will use whatever is set on the object.
    }
}

if ($obj) {
    if (!class_exists('template_manager')) {
        include_once(MH_DIR_CONFIG . 'config_editor/classes/template_manager.php');
    }
    
    if (template_manager::set_maintemplate_id($obj, $maintemplateId)) {
        if (!function_exists('triggerEmailEditorRefresh')) {
            include_once(MH_PRO_DIR . 'includes/editor_ui/editor.inc.php');
        }

        // Trigger refresh of the editor for all languages
        if (function_exists('triggerEmailEditorRefresh')) {
            triggerEmailEditorRefresh(0);
        } else {
            Htmx::parentRefresh('email_editor:refresh', json_encode(['all' => true]));
        }
        
        // Return a success message
        echo Htmx::getSavedStatusMessage();
    }
}
