<?php
// pages/components/email_editor_undo_redo.php
// Undo / Redo support for BeezUI EmailEditor

use Components\Support\Htmx;

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

$module       = (string) mh_get('module', '');
$content_module_id = (string) mh_get('content_module_id', '');
$newsletterId = (int) mh_get('newsletter_id', 0);
$lngId        = (int) mh_post('lng_id', 0, 'int');
$history_action = (string) mh_get('history_action', 'undo');

// Normalise action
$history_action = strtolower($history_action) === 'redo' ? 'redo' : 'undo';

$ok = false;

$editorItemId  = $content_module_id ?: $module;
$newsletterObj = null;

if ($newsletterId > 0) {
    if (!class_exists('mb_newsletter')) {
        include_once(MH_DIR_MODULE . 'mb_newsletter' . MH_FILE_EXTENSION);
    }
    $newsletterObj = \Components\Models\NewsletterItem::mbNewsletter();
    $editorItemId  = mb_newsletter::get_newsletter_module_id($newsletterId);
}

// Robust module detection for user templates if $module is missing
if ($module === '' && strpos($editorItemId, 'user_module_template_') === 0) {
    $parts = explode('--*--', str_replace('user_module_template_', '', $editorItemId));
    $module = (isset($parts[0]) && $parts[0] !== '') ? $parts[0] : (isset($parts[1]) ? $parts[1] : '');
}

if ($editorItemId !== '' && $lngId > 0) {

    // Ensure history helpers are available
    if (!function_exists('mh_language_object_undo') || !function_exists('mh_language_object_redo')) {
        include_once(MH_PRO_DIR . 'includes/editor_ui/editor.inc.php');
    }

    if (function_exists('mh_db_emoji_support')) {
        mh_db_emoji_support();
    }

    $fn = $history_action === 'redo' ? 'mh_language_object_redo' : 'mh_language_object_undo';

    if (function_exists($fn)) {
        // Apply the operation to all relevant language object types.
        $types = [
            'htmlBodyTemplate',
            'txtBodyTemplate',
            'subjectTemplate',
            'preheaderTemplate',
        ];


        $targetType = null;
        $q = mh_db_query(
            "SELECT language_objects_type
                   FROM " . TABLE_MAILBEEZ_LANGUAGE_OBJECTS_HISTORY . "
                  WHERE language_module='" . mh_db_input($editorItemId) . "'
                    AND language_id='" . (int)$lngId . "'
                    AND stack_type='" . mh_db_input($history_action) . "'
                    AND language_objects_type IN ('" . implode("','", array_map('mh_db_input', $types)) . "')
                  ORDER BY id DESC
                  LIMIT 1"
        );
        if ($row = mh_db_fetch_array($q)) {
            $targetType = $row['language_objects_type'];
        }

        if ($targetType) {
            try {
                if ($fn($editorItemId, $lngId, $targetType)) {
                    $ok = true;
                }
            } catch (Throwable $e) {
                // print_r($e);
                // Swallow individual failures; best-effort per type.
            }
        }

        // When at least one field was changed, ask the EmailEditor shell
        // to refresh the visual editor iframe for this language and
        // propagate the latest subject + preheader values so the inputs
        // can be updated via Alpine/HTMX.
        if ($ok) {
            try {
                $subject = '';
                $preheader = '';

                // Load current subject/preheader content for this
                // item + language after the undo/redo operation.
                $mb_tmpl_restore = false;
                try {
                    if ($newsletterObj !== null) {
                        list($subjectVal)   = mb_newsletter::load_newsletter_object($editorItemId, $lngId, 'subjectTemplate', $newsletterObj, $mb_tmpl_restore);
                        list($preheaderVal) = mb_newsletter::load_newsletter_object($editorItemId, $lngId, 'preheaderTemplate', $newsletterObj, $mb_tmpl_restore);
                    } elseif (function_exists('mh_load_language_object')) {
                        list($subjectVal)   = mh_load_language_object($editorItemId, $lngId, 'subjectTemplate', null, $mb_tmpl_restore);
                        list($preheaderVal) = mh_load_language_object($editorItemId, $lngId, 'preheaderTemplate', null, $mb_tmpl_restore);
                    }
                    $subject = (string)$subjectVal;
                    $preheader = (string)$preheaderVal;
                } catch (Throwable $e) {
                    // Best-effort only; fall back to iframe refresh
                    // without updating header inputs when this fails.
                }

                if (function_exists('triggerEmailEditorRefresh')) {
                    // Newer helper signature supports passing subject /
                    // preheader so the EmailEditor can update its inputs.
                    triggerEmailEditorRefresh($lngId, $subject, $preheader);
                } else {
                    // Fallback: emit event directly via Htmx helper.
                    $detail = [
                        'lng_id' => (string)$lngId,
                    ];
                    if ($subject !== '') {
                        $detail['subject'] = $subject;
                    }
                    if ($preheader !== '') {
                        $detail['preheader'] = $preheader;
                    }
                    Htmx::parentRefresh('email_editor:refresh', json_encode($detail));
                }
            } catch (Throwable $e) {
                // best-effort only
            }
        }
    }
}

// Minimal status response suitable for swapping into the autosave indicator.
$ts = date('H:i:s');
if ($ok) {
    echo '<span class=" text-green-600">' .
        mh_lng('MAILBEEZ_UNDO_REDO_OK', 'History updated at') . ' ' . $ts . '</span>';
} else {
    echo '<span class="text-brand">' .
        mh_lng('MAILBEEZ_UNDO_REDO_EMPTY', 'Nothing to undo/redo') . '</span>';
}
