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

$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;

// 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') {
    if (empty($templateName)) {
        $message = '<p class="text-red-600 font-semibold">' . \mh_lng('UI_ERROR_CREATE_TEMPLATE_EMPTY_NAME', 'Error: Template name cannot be empty.') . '</p>';
        $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');

        $uniqueTemplateName = $mb_tmpl_manager->get_unique_template_name($templateName, $module);
        if ($uniqueTemplateName !== $templateName) {
            $message = '<p class="text-orange-600 font-semibold mb-2">' . 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)) . '</p>';
            $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';
                $result = $mb_tmpl_manager->create_template($templateName, $module, $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();
                    Htmx::parentClose('confirm-modal');
                    return;
                }

                // Trigger refresh and close modal
                header('HX-Trigger: editor_templates:refresh');
                echo '<div class="p-4"><p class="text-green-600 font-semibold">' . \mh_lng('UI_TEXT_SUCCESS_CREATE_TEMPLATE', 'Template created successfully!') . '</p></div>';
                echo '<script>setTimeout(() => { command("close", {commandfor: "confirm-modal"}) }, 1000)</script>';
                return;
            } else {
                $error = is_array($result) ? $result['error'] : 'unknown_error';
                $message = '<p class="text-red-600 font-semibold">' . \mh_lng('UI_ERROR_CREATE_TEMPLATE_' . strtoupper($error), 'Error creating template: ' . $error) . '</p>';
                // 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?');
        $confirmUrl = (string)mh_get('select_url');
        $confirmLabel = \mh_lng('UI_BUTTON_TEMPLATE_SELECT', 'Select');
        $confirmTarget = '#editor-inline-modal-body';
        $confirmSwap = 'innerHTML';
        $confirmIndicator = '#editor-templates-loader';
        $confirmModalClose = true;
        break;

    case 'create_from_gallery':
    case 'save_template_as':
        if ($action === 'create_from_gallery') {
            $title = \mh_lng('UI_LABEL_CREATE_DESIGN', 'Create Design');
            $confirmAction = 'do_create_from_gallery';
            $helpText = \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,
            'maintemplate_id' => $maintemplate_id,
            'content_module_id' => $content_module_id,
            'partial' => 1
        ]);
        $confirmLabel = \mh_lng('UI_CREATE', 'Create');
        $confirmMethod = 'POST';
        $hxInclude = '#confirm-modal-body';

        ob_start();
        ?>
        <div class="space-y-3">
            <?php if ($helpText): ?>
                <p class="text-sm text-gray-500"><?= $helpText ?></p>
            <?php endif; ?>
            <?= 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 _)')
            ]) ?>
        </div>
        <?php
        $formHtml = ob_get_clean();
        $message .= $formHtml;
        break;
}

$formId = 'confirm-form-' . uniqid();
ob_start();
?>
<div class="space-y-3">
    <?php if ($title): ?>
        <span hx-swap-oob="innerHTML:#confirm-modal-title"><?= 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 ?>
        <div class="text-sm text-gray-500">
            <?= $message ?>
        </div>
        <button type="submit" class="hidden"></button>
    </form>

    <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>
</div>
<?php
echo ob_get_clean();
