<?php
// pages/components/template_action_confirm.php
use Components\Base;
use Components\Button;
use Components\Legacy\LegacyRouter;
use Components\Resources\TemplateCard;
use Components\Router;
use Components\Form\Input;
use Components\Support\Htmx;
use Components\MainTemplate\WizardSteps;

$action = (string)mh_get('confirm_action');
$templateId = (string)mh_get('template_id');
$lngId = (int)mh_get('lng_id', 0, 'int');
$newsletterId = (int)mh_get('newsletter_id', 0, 'int');
$flowId = (int)mh_get('flow_id', 0, 'int');
$module = (string)mh_get('module');
$context = (string)mh_get('context', 'module');
$maintemplate_id = (string)mh_get('maintemplate_id');
$content_module_id = (string)mh_get('content_module_id');
$templateName = (string)mh_post('template_name');

$title = '';
$message = '';
$confirmLabel = \mh_lng('UI_BUTTON_OK', 'OK');
$confirmUrl = '';
$confirmMethod = 'GET';
$confirmTarget = '#confirm-modal-body';
$confirmSwap = 'innerHTML';
$confirmVariant = 'primary';
$hxInclude = '';
$confirmIndicator = '#confirm-modal-loading';
$confirmModalClose = false;
$isMainCreateFromGallery = false;
$mainCreateBackUrl = '';
$messageWrapperClass = 'text-sm text-gray-500';
$selectedMainGalleryTemplate = null;
$feedbackMessage = '';

if (($action === 'create_from_gallery' || $action === 'do_create_from_gallery') && $context === 'main' && $templateId !== '') {
    if (!class_exists('template_manager')) {
        require_once(MH_DIR_CONFIG . 'config_editor/classes/template_manager.php');
    }
    if (class_exists('template_manager')) {
        $mainTemplateManager = new template_manager();
        $mainGalleryTemplates = $mainTemplateManager->get_static_templates_list($mainTemplateManager->template_path, 'gallery');
        foreach ($mainGalleryTemplates as &$galleryTemplate) {
            if (!empty($galleryTemplate['hasThumbnail']) && is_string($galleryTemplate['hasThumbnail'])) {
                $galleryTemplate['hasThumbnail'] = Router::normalizeUrl($galleryTemplate['hasThumbnail']);
            }
        }
        unset($galleryTemplate);
        foreach ($mainGalleryTemplates as $galleryTemplate) {
            if (($galleryTemplate['filepath'] ?? '') === $templateId) {
                $selectedMainGalleryTemplate = $galleryTemplate;
                break;
            }
        }
    }
}

// Handle execution of actions if it's a POST or a specific do_* action
if ($action === 'do_create_from_gallery' || $action === 'do_save_template_as' || $action === 'do_select_template') {
    if ($action === 'do_select_template') {
        if ($context === 'newsletter' && $newsletterId > 0 && !empty($templateId)) {
            require_once BEEZUI_ROOT . '/components/Models/NewsletterItem.php';
            $newsletterItem = \Components\Models\NewsletterItem::find($newsletterId);
            if ($newsletterItem) {
                $newsletterItem->initializeFromTemplate($templateId);
                Htmx::parentRefresh('email_editor:refresh', json_encode(['all' => true]));
                Htmx::flushTriggers();
                Htmx::parentClose('confirm-modal');
                return;
            }
        }
    }

    if ($action === 'do_create_from_gallery' || $action === 'do_save_template_as') {
        if (empty($templateName)) {
            $message = '<div class="text-danger font-semibold text-sm">' . \mh_lng('UI_ERROR_CREATE_TEMPLATE_EMPTY_NAME', 'Error: Template name cannot be empty.') . '</div>';
            $action = ($action === 'do_create_from_gallery') ? 'create_from_gallery' : 'save_template_as';
        } else {
            if (!class_exists('template_manager')) {
                require_once(MH_DIR_CONFIG . 'config_editor/classes/template_manager.php');
            }
            $mb_tmpl_manager = new template_manager($context === 'main' ? 'MAIN' : 'module');

            $sourceModuleForUniqueness = $module;
            if ($context === 'newsletter' && $newsletterId > 0) {
                if (!class_exists('mb_newsletter')) {
                    require_once(MH_DIR_MAILBEEZ . 'mb_newsletter.php');
                }
                $sourceModuleForUniqueness = \mb_newsletter::get_newsletter_module_id($newsletterId);
            }

            $uniqueTemplateName = $mb_tmpl_manager->get_unique_template_name($templateName, $sourceModuleForUniqueness);
            if ($uniqueTemplateName !== $templateName) {
                $message = '<div class="text-danger font-semibold text-sm">' . sprintf(\mh_lng('UI_TEXT_TEMPLATE_NAME_TAKEN', 'The name "%s" was already taken. We suggest using "%s".'), \Components\Base::h($templateName), \Components\Base::h($uniqueTemplateName)) . '</div>';
                $templateName = $uniqueTemplateName;
                $action = ($action === 'do_create_from_gallery') ? 'create_from_gallery' : 'save_template_as';
            } else {
                if ($action === 'do_create_from_gallery') {
                    if ($context === 'main') {
                        $result = $mb_tmpl_manager->create_template($templateName, 'MAIN', 'MAIN');
                    } else {
                        $result = $mb_tmpl_manager->create_template($templateName, $module, 'MAIN');
                    }
                } else {
                    // For save_template_as, we use the provided module and maintemplate_id
                    $maintemplate_id_short = $maintemplate_id ?: 'MAIN';

                    $sourceModule = $module;
                    if ($context === 'newsletter' && $newsletterId > 0) {
                        if (!class_exists('mb_newsletter')) {
                            require_once(MH_DIR_MAILBEEZ . 'mb_newsletter.php');
                        }
                        $sourceModule = \mb_newsletter::get_newsletter_module_id($newsletterId);
                    }

                    $result = $mb_tmpl_manager->create_template($templateName, $sourceModule, $maintemplate_id_short);
                }
            }

            if ($result === true) {
                if ($action === 'do_create_from_gallery') {
                    if ($context === 'main') {
                        $new_module_template = 'user_template_' . $templateName;
                        $mb_tmpl_manager->import_file_template($templateId, $new_module_template, 'htmlTemplate');
                        $mb_tmpl_manager->import_file_template($templateId, $new_module_template, 'txtTemplate');
                    } else {
                        $new_module_template = 'user_module_template_' . $module . '--*--' . $templateName;
                        $mb_tmpl_manager->import_file_template($templateId, $new_module_template, 'htmlBodyTemplate');
                        $mb_tmpl_manager->import_file_template($templateId, $new_module_template, 'txtBodyTemplate');
                        $mb_tmpl_manager->import_file_template($templateId, $new_module_template, 'subjectTemplate');
                        $mb_tmpl_manager->import_file_template($templateId, $new_module_template, 'preheaderTemplate');
                    }

                    Htmx::trigger('editor_templates:refresh', ['templates_tab' => 'user']);
                    Htmx::flushTriggers();
                    if ($context === 'main') {
                        $_GET['maintemplate_id'] = $new_module_template;
                        $_GET['template_name'] = $templateName;
                        $_GET['template_id'] = $templateId;
                        $_GET['lng_id'] = $lngId;
                        include BEEZUI_ROOT . '/pages/components/main_template_created_success.php';
                        return;
                    }

                    Htmx::parentClose('confirm-modal');
                    return;
                }

                // Trigger refresh and show success with an explicit close button.
                header('HX-Trigger: editor_templates:refresh');
                echo '<div class="p-4 space-y-4">';
                echo '<p class="text-success font-semibold">' . \mh_lng('UI_TEXT_SUCCESS_CREATE_TEMPLATE', 'Template created successfully!') . '</p>';
                echo '<div class="flex justify-end">';
                echo Button::render(\mh_lng('UI_BUTTON_CLOSE', 'Close'), [
                    'variant' => 'primary',
                    'attrs' => [
                        'command' => 'close',
                        'commandfor' => 'confirm-modal',
                    ],
                ]);
                echo '</div></div>';
                echo '<script>setTimeout(() => { command("close", {commandfor: "confirm-modal"}) }, 2500)</script>';
                return;
            } else {
                $error = is_array($result) ? $result['error'] : 'unknown_error';
                $message = '<div class="text-danger font-semibold text-sm">' . \mh_lng('UI_ERROR_CREATE_TEMPLATE_' . strtoupper($error), 'Error creating template: ' . $error) . '</div>';
                // Fallback to showing the form again with error
                $action = ($action === 'do_create_from_gallery') ? 'create_from_gallery' : 'save_template_as';
            }
        }
    }
}

switch ($action) {
    case 'import':
        if ($maintemplate_id !== '' && $maintemplate_id !== 'MAIN') {
            $title = \mh_lng('UI_BUTTON_IMPORT_INTO_CURRENT', 'Import into Current');
            $message = \mh_lng('UI_CONFIRM_IMPORT_INTO_CURRENT', 'This will overwrite the current template. Are you sure?');
            $confirmLabel = \mh_lng('UI_BUTTON_IMPORT_INTO_CURRENT', 'Import into Current');
        } else {
            $title = \mh_lng('UI_BUTTON_IMPORT_INTO_MAIN', 'Import into Main');
            $message = \mh_lng('UI_CONFIRM_IMPORT_INTO_MAIN', 'This will overwrite the main template. Are you sure?');
            $confirmLabel = \mh_lng('UI_BUTTON_IMPORT_INTO_MAIN', 'Import into Main');
        }
        $confirmUrl = LegacyRouter::url('templateImportToMain', ['template_id' => $templateId, 'maintemplate_id' => $maintemplate_id, 'lng_id' => $lngId, 'content_module_id' => $content_module_id]);
        $confirmVariant = 'danger';
        break;
    case 'delete':
        $title = \mh_lng('UI_BUTTON_DELETE', 'Delete');
        $message = \mh_lng('UI_CONFIRM_DELETE_TEMPLATE', 'Are you sure you want to delete this template?');
        $confirmUrl = LegacyRouter::url('templateDeleteConfirm', [
            'template_id' => $templateId,
            'lng_id' => $lngId,
            'newsletter_id' => $newsletterId,
            'flow_id' => $flowId,
            'context' => $context,
            'module' => $module,
            'content_module_id' => $content_module_id,
            'app_action' => 'delete_user_template_confirm'
        ]);
        $confirmLabel = \mh_lng('UI_BUTTON_DELETE', 'Delete');
        $confirmVariant = 'danger';
        break;
    case 'select_template':
//        $title = \mh_lng('UI_BUTTON_TEMPLATE_SELECT', 'Select Template');
        $message = \mh_lng('UI_CONFIRM_OVERWRITE_TEMPLATE', 'The current template will be overwritten for all languages. This can not be undone. Are you sure?');

        if ($context === 'newsletter') {
            $confirmUrl = \Components\Router::url('template_action_confirm', [
                'confirm_action' => 'do_select_template',
                'template_id' => $templateId,
                'newsletter_id' => $newsletterId,
                'context' => $context,
                'partial' => 1
            ]);
            $confirmTarget = '#confirm-modal-body';
            $confirmSwap = 'innerHTML';
        } else {
            $confirmUrl = (string)mh_get('select_url');
            $confirmTarget = '#editor-inline-modal-body';
            $confirmSwap = 'innerHTML';
        }

        $confirmLabel = \mh_lng('UI_BUTTON_TEMPLATE_SELECT', 'Select');
        $confirmIndicator = '#editor-templates-loader';
        $confirmModalClose = true;
        break;

    case 'create_from_gallery':
    case 'save_template_as':
        $feedbackMessage = $message;
        $message = '';
        if ($action === 'create_from_gallery') {
            $title = $context === 'main'
                ? \mh_lng('UI_TITLE_CREATE_MAIN_TEMPLATE', 'Create New Main Template')
                : \mh_lng('UI_LABEL_CREATE_DESIGN', 'Create Design');
            $confirmAction = 'do_create_from_gallery';
            $helpText = $context === 'main'
                ? \mh_lng('UI_TEXT_MAIN_TEMPLATE_NAME_HELP', 'Give your template a clear internal name. You can refine all design details in the editor next.')
                : \mh_lng('UI_TEXT_CREATE_DESIGN_FROM_GALLERY', 'Please provide a name for your new design based on this gallery template.');
        } else {
            $title = $context === 'main' ? mh_lng('UI_LABEL_MAINTEMPLATE_CREATE', 'Save as Layout-Template') : mh_lng('UI_LABEL_CONTENTTEMPLATE_CREATE', 'Save as Content-Template');
            $confirmAction = 'do_save_template_as';
            $helpText = '';
        }

        $confirmUrl = \Components\Router::url('template_action_confirm', [
            'confirm_action' => $confirmAction,
            'template_id' => $templateId,
            'lng_id' => $lngId,
            'module' => $module,
            'context' => $context,
            'newsletter_id' => $newsletterId,
            'flow_id' => $flowId,
            'maintemplate_id' => $maintemplate_id,
            'content_module_id' => $content_module_id,
            'partial' => 1
        ]);
        $confirmLabel = ($action === 'create_from_gallery' && $context === 'main')
            ? \mh_lng('UI_BUTTON_CREATE_MAIN_TEMPLATE', 'Create Main Template')
            : \mh_lng('UI_CREATE', 'Create');
        $confirmMethod = 'POST';
        $isMainCreateFromGallery = ($action === 'create_from_gallery' && $context === 'main');
        if ($isMainCreateFromGallery) {
            $mainCreateBackUrl = Router::url('main_template_gallery_selection_modal', [
                'partial' => 1,
                'lng_id' => $lngId,
                'context' => 'main',
                'module' => $module,
                'content_module_id' => $content_module_id,
            ]);
            $confirmTarget = '#config-modal-body';
            $confirmIndicator = '#config-modal-loading';
            $hxInclude = '#config-modal-body';
        } else {
            $hxInclude = '#confirm-modal-body';
        }
        $messageWrapperClass = '';

        ob_start();
        $templateSlug = trim($templateId);
        $templateToken = $templateSlug !== '' ? basename(str_replace('\\', '/', $templateSlug)) : '';
        $templateLabel = $templateToken !== ''
            ? ucwords(str_replace(['_', '-'], ' ', $templateToken))
            : \mh_lng('UI_TEXT_GALLERY_TEMPLATE', 'Gallery Template');
        $selectedTemplateCard = is_array($selectedMainGalleryTemplate) ? $selectedMainGalleryTemplate : [];
        if (!isset($selectedTemplateCard['maintemplate_id']) || (string)$selectedTemplateCard['maintemplate_id'] === '') {
            $selectedTemplateCard['maintemplate_id'] = $templateId;
        }
        if (!isset($selectedTemplateCard['filepath']) || (string)$selectedTemplateCard['filepath'] === '') {
            $selectedTemplateCard['filepath'] = $templateId;
        }
        if (!isset($selectedTemplateCard['title']) || trim((string)$selectedTemplateCard['title']) === '') {
            $selectedTemplateCard['title'] = $templateLabel;
        }
        $selectedTemplateCardHtml = TemplateCard::render([
            'tpl' => $selectedTemplateCard,
            'type' => 'gallery',
            'idx' => 0,
            'context' => 'main',
            'module' => $module,
            'lng_id' => $lngId,
            'newsletter_id' => $newsletterId,
            'flow_id' => $flowId,
            'is_modal' => true,
            'maintemplate_id' => $maintemplate_id,
            'content_module_id' => $content_module_id,
            'only_actions' => ['preview'],
        ]);
        ?>
        <?php if ($isMainCreateFromGallery): ?>
            <script>
                (function() {
                    var m = document.getElementById('<?= Htmx::resolvePanelId(); ?>');
                    if (m) {
                        m.setAttribute('data-size', '4xl');
                        m.setAttribute('data-height', 'auto');
                    }
                })();
            </script>

            <?= WizardSteps::renderStepper(WizardSteps::STEP_NAMING); ?>

            <div class="mt-4 grid grid-cols-1 lg:grid-cols-5 gap-4 lg:gap-6">
                <div class="lg:col-span-2">
                    <div class="">
                        <?= $selectedTemplateCardHtml ?>
                    </div>
                </div>

                <div class="lg:col-span-3 rounded-2xl border border-divider bg-white p-5 lg:p-6 space-y-4">
                    <?php if ($helpText): ?>
                        <p class="text-sm text-secondary"><?= $helpText ?></p>
                    <?php endif; ?>

                    <div>
                        <?= Input::render('template_name', \mh_lng('UI_TEXT_TEMPLATE_NAME', 'Template Name'), $templateName, [
                            'input_attrs' => 'autofocus placeholder="' . \mh_lng('UI_TEXT_TEMPLATE_NAME_PLACEHOLDER', 'e.g. My Summer Sale') . '" oninput="this.value = this.value.replace(/ /g, \'_\').replace(/[^a-zA-Z0-9_\\-.]/g, \'\')"',
                            'validate' => ['required' => true],
                            'help' => \mh_lng('UI_TEXT_ALLOWED_CHARACTERS_HINT', 'Allowed characters: a-z, A-Z, 0-9, _, -, . (Spaces are converted to _)')
                        ]) ?>
                        <?php if ($feedbackMessage): ?>
                            <div class="mt-2 text-sm">
                                <?= $feedbackMessage ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <div class="space-y-4">
                <?php if ($helpText): ?>
                    <p class="text-sm text-gray-500"><?= $helpText ?></p>
                <?php endif; ?>
                <div>
                    <?= Input::render('template_name', \mh_lng('UI_TEXT_TEMPLATE_NAME', 'Template Name'), $templateName, [
                        'input_attrs' => 'autofocus placeholder="' . \mh_lng('UI_TEXT_TEMPLATE_NAME_PLACEHOLDER', 'e.g. My Summer Sale') . '" oninput="this.value = this.value.replace(/ /g, \'_\').replace(/[^a-zA-Z0-9_\\-.]/g, \'\')"',
                        'validate' => ['required' => true],
                        'help' => \mh_lng('UI_TEXT_ALLOWED_CHARACTERS_HINT', 'Allowed characters: a-z, A-Z, 0-9, _, -, . (Spaces are converted to _)')
                    ]) ?>
                    <?php if ($feedbackMessage): ?>
                        <div class="mt-2 text-sm">
                            <?= $feedbackMessage ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
        <?php
        $formHtml = ob_get_clean();
        $message .= $formHtml;
        break;
}

$formId = 'confirm-form-' . uniqid();
$titleTargetSelector = $isMainCreateFromGallery ? '#config-modal-title' : '#confirm-modal-title';
ob_start();
?>
<div class="space-y-4">
    <?php if ($title): ?>
        <span hx-swap-oob="innerHTML:<?= Base::h($titleTargetSelector, false) ?>"><?= Base::h($title) ?></span>
    <?php endif; ?>

    <?php
    $formAttrs = [
        'id' => $formId,
        'hx-' . strtolower($confirmMethod) => $confirmUrl,
        'hx-target' => $confirmTarget,
        'hx-swap' => $confirmSwap,
        'hx-indicator' => $confirmIndicator,
    ];
    if ($hxInclude) {
        $formAttrs['hx-include'] = $hxInclude;
    }
    ?>
    <form <?= Base::attrs($formAttrs) ?>>
        <?= MH_POST_TOKEN ?>
        <?php if ($messageWrapperClass !== ''): ?>
            <div class="<?= $messageWrapperClass ?>">
                <?= $message ?>
            </div>
        <?php else: ?>
            <?= $message ?>
        <?php endif; ?>
        <button type="submit" class="hidden"></button>
    </form>

    <?php if ($isMainCreateFromGallery): ?>
        <template x-teleport="#config-modal-footer">
            <div class="flex items-center gap-3 w-full">
                <?= Button::render(\mh_lng('UI_PREVIOUS', 'Back'), [
                    'variant' => 'ghost',
                    'attrs' => [
                        'hx-get' => $mainCreateBackUrl,
                        'hx-target' => '#config-modal-body',
                        'hx-swap' => 'innerHTML',
                        'hx-push-url' => 'false',
                    ],
                ]) ?>

                <div class="flex-1"></div>

                <?= Button::render($confirmLabel, [
                    'variant' => $confirmVariant,
                    'type' => 'submit',
                    'attrs' => array_merge([
                        'form' => $formId,
                        'hx-' . strtolower($confirmMethod) => $confirmUrl,
                        'hx-target' => $confirmTarget,
                        'hx-swap' => $confirmSwap,
                        'hx-indicator' => $confirmIndicator,
                    ], $hxInclude ? ['hx-include' => $hxInclude] : []),
                ]) ?>
            </div>
        </template>
    <?php else: ?>
        <template x-teleport="#confirm-modal-footer">
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 w-full">

                <?= Button::render(\mh_lng('UI_BUTTON_CANCEL', 'Cancel'), [
                        'variant' => 'outline',
                        'fullWidth' => true,
                        'attrs' => [
                                'command' => 'close',
                                'commandfor' => 'confirm-modal',
                        ],
                ]) ?>

                <?= Button::render($confirmLabel, [
                    'variant' => $confirmVariant,
                    'type' => 'submit',
                    'fullWidth' => true,
                    'modal_close' => $confirmModalClose ? 'confirm-modal' : null,
                    'attrs' => array_merge([
                        'form' => $formId,
                        'hx-' . strtolower($confirmMethod) => $confirmUrl,
                        'hx-target' => $confirmTarget,
                        'hx-swap' => $confirmSwap,
                        'hx-indicator' => $confirmIndicator,
                    ], $hxInclude ? ['hx-include' => $hxInclude] : []),
                ]) ?>
            </div>
        </template>
    <?php endif; ?>
</div>
<?php
echo ob_get_clean();
