<?php
// pages/editor_templates.php — BeezUI Email Template Gallery
require_once BEEZUI_ROOT . '/components/index.php';
require_once BEEZUI_ROOT . '/pages/layout.php';

use Components\Base;
use Components\Router;
use Components\Button;
use Components\Legacy\LegacyRouter;
use Components\Resources\TemplateCard;
use Components\Resources\TemplateCardSkeleton;
use Components\Ui\CardUI;
use Components\Ui\Tabs;
use Components\Ui\FilterPills;
use Components\Ui\FilterPillsSkeleton;

// 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;
}

if (!class_exists('template_manager')) {
    require_once(MH_DIR_CONFIG . 'config_editor/classes/template_manager.php');
}

// Inputs
$context = mh_get('context', 'main');
$module = mh_get('module');
$content_module_id = mh_get('content_module_id');
$isModal = (int)mh_get('is_modal', 0);

$newsletterCampaignId = (int)mh_get('newsletter_campaign_id', 0, 'int');
if ($newsletterCampaignId <= 0) {
    $newsletterCampaignId = (int)mh_post('newsletter_campaign_id', 0);
}

$newsletterListId = mh_get('newsletter_list_id', '');
if ($newsletterListId === '') {
    $newsletterListId = mh_post('newsletter_list_id', '');
}

$newsletterPageMode = mh_get('page_mode', 'automation', 'string');

// Define app_module_id for main context
$app_module_id = '';
if (mh_cfg('MAILBEEZ_CONFIG_TMPLMNGR_LNG_STATUS') == 'True') {
    $app_module_id = 'config_tmplmngr_lng';
} elseif (mh_cfg('MAILBEEZ_CONFIG_TMPLMNGR_STATUS') == 'True') {
    $app_module_id = 'config_tmplmngr';
}

$maintemplate_id_short = null;
if ($context === 'newsletter') {
    require_once BEEZUI_ROOT . '/components/Models/NewsletterItem.php';
    $newsletter_obj = \Components\Models\NewsletterItem::mbNewsletter();
    $campaign_data = $newsletter_obj->get_campaign_data($newsletterCampaignId);
    $campaign_type = $campaign_data['newsletter_campaign_type'] ?? '';
    $language = $_SESSION['language'];

    $mb_tmpl_manager = new template_manager();
    $template_path = $newsletter_obj->template_path;
    $mb_tmpl_manager->set_template_location($newsletter_obj->template_dir);
} elseif ($context === 'module') {
    $mb_tmpl_manager = new template_manager('module');
    $maintemplate_id_short = null;
    $template_path = $mb_tmpl_manager->template_path;
} else {
    // main template
    $mb_tmpl_manager = new template_manager();
    if ($app_module_id !== '') {
        $mb_main_file = MH_DIR_CONFIG . $app_module_id . '/mb_main.php';
        if (file_exists($mb_main_file)) {
            require_once($mb_main_file);
            if (class_exists('mb_main')) {
                $mb_main = new mb_main();
                $maintemplate_id_short = $mb_main->get_maintemplate_id(true);
            }
        }
    }
    $template_path = $mb_tmpl_manager->template_path;
}

$lngId = (int)mh_get('lng_id', mh_session('languages_id', 1));
$newsletterId = (int)mh_get('newsletter_id', 0);
$flowId = (int)mh_get('flow_id', 0);
$selectionMode = (string)mh_get('selection_mode', '');
$activeTab = mh_get('templates_tab', $context === 'newsletter' ? 'gallery' : 'user');
if ($selectionMode === 'create_main_from_gallery' && $context === 'main') {
    $activeTab = 'gallery';
}

$url_params = [
        'module' => $module,
        'lng_id' => $lngId,
        'newsletter_id' => $newsletterId,
        'flow_id' => $flowId,
        'context' => $context,
        'maintemplate_id' => $maintemplate_id_short,
        'is_modal' => $isModal,
        'content_module_id' => $content_module_id,
        'selection_mode' => $selectionMode
];

if ($context === 'newsletter') {
    $url_params['newsletter_campaign_id'] = $newsletterCampaignId;
    $url_params['newsletter_list_id'] = $newsletterListId;
    $url_params['page_mode'] = $newsletterPageMode;
}

$select_url = LegacyRouter::url('templateSelect', $url_params);
$export_url = LegacyRouter::url('templateExport', $url_params);
$delete_url = LegacyRouter::url('templateDelete', $url_params);

$mb_tmpl_manager->select_url = $select_url;
$mb_tmpl_manager->export_url = $export_url;
$mb_tmpl_manager->delete_url = $delete_url;

// Load templates
$templates_gallery = [];
if (($context === 'main' || $context === 'newsletter') && ($activeTab === 'gallery' || mh_get('app_action') === 'gallery_content')) {
    if ($context === 'newsletter') {
        $templates_gallery = \mb_newsletter_items::getTemplates($template_path, 'gallery', $campaign_type, $language, $lngId);
        // Add url_select to each template
        foreach ($templates_gallery as $key => $tpl) {
            $selectParams = [
                'partial' => 1,
                'mode' => 'new',
                'page_mode' => $newsletterPageMode,
                'newsletter_campaign_id' => $newsletterCampaignId,
                'newsletter_list_id' => $newsletterListId,
                'template_id' => $tpl['filepath']
            ];
            if (mh_get('skip_audience')) { $selectParams['skip_audience'] = 1; }
            if (mh_get('skip_template')) { $selectParams['skip_template'] = 1; }

            $date = mh_get('date', '', 'string');
            if ($date !== '') { $selectParams['date'] = $date; }

            $templates_gallery[$key]['url_select'] = Router::url('newsletter_item_modal', $selectParams);
        }
    } else {
        $templates_gallery = $mb_tmpl_manager->get_static_templates_list($template_path, 'gallery');
    }
}



$templates_basic = [];
if ($context === 'module') {
    $templates_basic = $mb_tmpl_manager->get_static_templates_list($template_path, 'basic');
}

$templates_user = ($context === 'newsletter') ? [] : $mb_tmpl_manager->get_user_templates_list();

$markTemplates = function (&$list) use ($context, $maintemplate_id_short, $module) {
    foreach ($list as &$tpl) {
        $tpl['is_main'] = false;
        $tpl['is_current'] = false;
        if ($context === 'main') {
            if ($tpl['maintemplate_id'] === 'MAIN') {
                $tpl['is_main'] = true;
            } else {


                if ($maintemplate_id_short !== null) {
                    if ($tpl['maintemplate_id'] === $maintemplate_id_short) {
                        $tpl['is_current'] = true;
                    } elseif ($tpl['maintemplate_id'] === 'user_template_' . $maintemplate_id_short) {
                        $tpl['is_current'] = true;
                    }
                }
            }
        } elseif ($context === 'module') {
            if ($module !== null && isset($tpl['content_module_id']) && $tpl['content_module_id'] === $module) {
                $tpl['is_current'] = true;
            }
        }
    }
};

//$markTemplates($templates_gallery);
$markTemplates($templates_basic);
$markTemplates($templates_user);

$app_action = mh_get('app_action', '');

/**
 * Render a single template card
 */
$renderCard = function ($tpl, $type, $idx) use ($context, $module, $lngId, $newsletterId, $flowId, $isModal, $maintemplate_id_short, $content_module_id, $selectionMode) {
    $cardHtml = TemplateCard::render([
            'tpl' => $tpl,
            'type' => $type,
            'idx' => $idx,
            'context' => $context,
            'module' => $module,
            'lng_id' => $lngId,
            'newsletter_id' => $newsletterId,
            'flow_id' => $flowId,
            'is_modal' => $isModal,
            'maintemplate_id' => $maintemplate_id_short,
            'content_module_id' => $content_module_id,
            'selection_mode' => $selectionMode
    ]);
    $tagsJson = json_encode($tpl['tags'] ?? []);
    $xShow = 'filter === \'ALL\' || ' . $tagsJson . '.includes(filter)';
    return '<div class="p-3 transition-all duration-500 flex " :class="itemWidthConfigs[columns]" x-show="' . Base::h($xShow, false) . '">' . $cardHtml . '</div>';
};

// Action: Gallery Content Partial
if ($app_action === 'gallery_content') {
    if (empty($templates_gallery)) {
        echo '<div class="col-span-full py-12 text-center text-secondary text-sm italic">' . mh_lng('TEXT_NO_GALLERY_TEMPLATES', 'No gallery templates available.') . '</div>';
    } else {
        $gallery_tags = [];
        foreach ($templates_gallery as $tpl) {
            if (!empty($tpl['tags'])) {
                foreach ($tpl['tags'] as $tag) {
                    $gallery_tags[$tag] = $tag;
                }
            }
        }
        if (!empty($gallery_tags)) {
            echo '<div class="w-full px-3 pb-1 pt-1 flex gap-2 flex-wrap">';
            echo FilterPills::render(array_values($gallery_tags), ['labels_map' => \beez::tagLabels()]);
            echo '</div>';
        }

        foreach ($templates_gallery as $idx => $tpl) {
            echo $renderCard($tpl, 'gallery', $idx);
        }
    }
    return;
}


$pageKey = 'editor_templates';

$listUrl = Router::url('editor_templates', array_merge($url_params, ['partial' => 1]));
$trigs = [
        'refresh',
];

// Tabs items for Templates UI (uses Components\Ui\Tabs)
$tabItems = [];
$mainGallerySelectionMode = ($selectionMode === 'create_main_from_gallery' && $context === 'main');
$galleryTabLabel = mh_lng('TEXT_TAB_MAIN_TEMPLATE_GALLERY', 'Gallery');
$labelUser = ($context == 'main')
        ? mh_lng('TEXT_TAB_MAIN_TEMPLATES', 'Main Designs')
        : mh_lng('TEXT_TAB_USER', 'User');
if ($mainGallerySelectionMode) {
    $tabItems[] = [
            'value' => 'gallery',
            'label' => $galleryTabLabel,
    ];
} else {
    if ($context !== 'newsletter') {
        $tabItems[] = [
                'value' => 'user',
                'label' => $labelUser . ' (' . count($templates_user) . ')',
        ];
    }
}
if (!$mainGallerySelectionMode && $context == 'module') {
    $tabItems[] = [
            'value' => 'basic',
            'label' => mh_lng('TEXT_TAB_BASIC', 'Basic') . ' (' . count($templates_basic) . ')',
    ];
}
if (($context == 'main' || $context == 'newsletter') && !$mainGallerySelectionMode) {
    // Intentionally omit dynamic count here; gallery loads lazily
    $tabItems[] = [
            'value' => 'gallery',
            'label' => $galleryTabLabel,
    ];
}

ob_start();
?>
<?php if (!mh_get('partial')): ?>
    <div>
        <?php
        if ($context === 'newsletter') {
            $headerTitle = mh_lng('MAILBEEZ_APP_LABEL_NEWSLETTER_TEMPLATES', 'Newsletter Templates');
            $headerSubtitle = mh_lng('MAILBEEZ_APP_LABEL_NEWSLETTER_TEMPLATES_SUBTITLE', 'Select a template for your newsletter campaign.');
        } elseif ($context === 'module') {
            $headerTitle = mh_lng('MAILBEEZ_APP_LABEL_MODULE_TEMPLATES', 'Module Templates');
            $headerSubtitle = mh_lng('MAILBEEZ_APP_LABEL_MODULE_TEMPLATES_SUBTITLE', 'Module Templates define the content structure for your emails.');
        } else {
            $headerTitle = mh_lng('MAILBEEZ_APP_LABEL_TEMPLATES', 'Main Templates');
            $headerSubtitle = mh_lng('MAILBEEZ_APP_LABEL_TEMPLATES_SUBTITLE', 'Main Templates define the overall layout and branding of your emails.');
        }

        $headerOptions = ['subtitle' => $headerSubtitle];
        if ($context === 'main' && $selectionMode !== 'create_main_from_gallery') {
            $createTitle = mh_lng('UI_TITLE_CREATE_MAIN_TEMPLATE', 'Create New Main Template');
            $headerOptions['right'] = Button::render(mh_lng('UI_BUTTON_NEW_TEMPLATE', 'New Template'), [
                'variant' => 'secondary',
                'size' => 'md',
                'icon' => Base::SVG_PLUS,
                'iconPosition' => 'front',
                'attrs' => [
                    'command' => 'show-modal',
                    'commandfor' => 'config-modal',
                    'data-title' => $createTitle,
                    'data-size' => '6xl',
                    'hx-get' => Router::url('main_template_gallery_selection_modal', [
                        'partial' => 1,
                        'lng_id' => $lngId,
                        'context' => 'main',
                        'module' => $module,
                        'content_module_id' => $content_module_id,
                    ]),
                    'hx-target' => '#config-modal-body',
                    'hx-swap' => 'innerHTML',
                ],
            ]);
        }
        echo \Components\Ui\PageHeader::render($headerTitle, $headerOptions);
        ?>
    </div>
<?php endif; ?>

<div id="editor-templates-container" x-cloak class="space-y-6"
     hx-get="<?= Base::h($listUrl) ?>"
     hx-trigger="<?= Base::h(implode(', ', $trigs)) ?>"
     hx-swap="outerHTML"
     :hx-vals="JSON.stringify({templates_tab: templates_tab})"
     x-data="{
            templates_tab: '<?= $activeTab ?>',
            columns: 3,
            itemWidthConfigs: <?= htmlspecialchars(json_encode([
             2 => 'w-full xl:w-1/2',
             3 => 'w-full sm:w-1/2 lg:w-1/2 xl:w-1/3',
             4 => 'w-1/2 sm:w-1/3 lg:w-1/3 xl:w-1/4',
             5 => 'w-1/3 sm:w-1/4 lg:w-1/4 xl:w-1/5',
             6 => 'w-1/4 sm:w-1/5 lg:w-1/5 xl:w-1/6',
     ]), ENT_QUOTES, 'UTF-8') ?>,
            init() {
                const stored = localStorage.getItem('editor_templates_columns');
                if (stored && this.itemWidthConfigs[stored]) this.columns = parseInt(stored);
            },
            updateColumns(val) {
                this.columns = val;
                localStorage.setItem('editor_templates_columns', val);
            },
            filter: 'ALL',
            setFilter(v) { this.filter = v },
            isFilter(v) { return this.filter === v }
         }"
     @hashchange.window="if(location.hash) templates_tab = location.hash.substring(1)"
     @editor_templates:refresh.window="if($event.detail.templates_tab) templates_tab = $event.detail.templates_tab; $nextTick(() => htmx.trigger($el, 'refresh'))">
    <!-- Tabs and Header -->
    <!--        context: --><?php //= $context ?><!--<br>-->
    <!--        module: --><?php //= $module ?>
    <?= Tabs::mobile('templates_tab', $tabItems, ['ariaLabel' => 'Select templates tab']) ?>

    <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-divider">
        <div class="hidden sm:block">
            <?= Tabs::desktopNavOnly('templates_tab', $tabItems) ?>
        </div>

        <div class="pb-3 sm:pb-0 flex items-center gap-4">
            <div class="flex items-center rounded-full p-0 overflow-hidden border border-divider">
                <?= Button::render('', [
                        'variant' => 'ghost',
                        'size' => 'sm',
                        'icon' => Base::SVG_MINUS,
                        'rounded' => 'full',
                        'attrs' => [
                                '@click' => 'updateColumns(columns === 6 ? 6 : columns + 1)',
                                'title' => 'Smaller cards',
                                ':disabled' => 'columns === 6',
                                ':class' => "{ 'opacity-50 pointer-events-none': columns === 6 }"
                        ]
                ]) ?>
                <div class="w-px h-4 bg-divider mx-1"></div>
                <?= Button::render('', [
                        'variant' => 'ghost',
                        'size' => 'sm',
                        'icon' => Base::SVG_PLUS,
                        'rounded' => 'full',
                        'attrs' => [
                                '@click' => 'updateColumns(columns === 2 ? 2 : columns - 1)',
                                'title' => 'Larger cards',
                                ':disabled' => 'columns === 2',
                                ':class' => "{ 'opacity-50 pointer-events-none': columns === 2 }"
                        ]
                ]) ?>
            </div>

        </div>
    </div>

    <!-- Grid Content -->
    <div class="mt-4 min-h-[30vh]">

        <?php if ($context == 'module'): ?>
            <div x-show="templates_tab === 'basic'"
                 x-cloak>
                <?php
                $message = mh_lng('TEXT_EDITOR_TEMPLATES_BASIC_INFO', 'This is the gallery for module templates, you can not edit these but you can create a new module template based on these templates.<br>Preview is shown based on Standard Main Template, you can open the preview and select a different main template');
                echo \Components\Notification::render($message, [
                        'id' => 'editor_templates_basic_info',
                        'dismissible' => true,
                ]);
                ?>

                <div class="flex flex-wrap -m-3">
                    <?php foreach ($templates_basic as $idx => $tpl) {
                        echo $renderCard($tpl, 'basic', $idx);
                    } ?>
                </div>
            </div>
        <?php endif; ?>
        <?php if ($context == 'main' || $context == 'newsletter'): ?>
            <div x-show="templates_tab === 'gallery'" x-cloak>
                <?php
                if ($context === 'newsletter') {
                    $message = mh_lng('TEXT_EDITOR_TEMPLATES_NEWSLETTER_GALLERY_INFO', 'This is the gallery for newsletter templates. Select a template to use for your campaign.');
                } else {
                    $message = mh_lng('TEXT_EDITOR_TEMPLATES_GALLERY_INFO', 'This is the gallery for main templates, you can not edit these but create a new main template based on these templates.');
                }
                echo \Components\Notification::render($message, [
                        'id' => 'editor_templates_gallery_info',
                        'dismissible' => true,
                ]);
                ?>
                <div class="flex flex-wrap h-full -m-3"
                        <?php if ($activeTab !== 'gallery'): ?>
                            hx-get="<?= Router::url('editor_templates', array_merge($url_params, ['partial' => 1, 'app_action' => 'gallery_content'])) ?>"
                            hx-trigger="intersect once"
                            hx-swap="innerHTML"
                        <?php endif; ?>
                >
                    <?php if ($activeTab === 'gallery'): ?>
                        <?php if (empty($templates_gallery)): ?>
                            <div class="col-span-full py-12 text-center text-secondary text-sm italic"><?= mh_lng('TEXT_NO_GALLERY_TEMPLATES', 'No gallery templates available.') ?></div>
                        <?php else: ?>
                            <?php
                            $gallery_tags = [];
                            foreach ($templates_gallery as $tpl) {
                                if (!empty($tpl['tags'])) {
                                    foreach ($tpl['tags'] as $tag) {
                                        $gallery_tags[$tag] = $tag;
                                    }
                                }
                            }
                            if (!empty($gallery_tags)) {
                                echo '<div class="w-full px-3 pt-1 pb-1 flex gap-2 flex-wrap">';
                                echo FilterPills::render(array_values($gallery_tags), ['labels_map' => \beez::tagLabels()]);
                                echo '</div>';
                            }
                            ?>
                            <?php foreach ($templates_gallery as $idx => $tpl) {
                                echo $renderCard($tpl, 'gallery', $idx);
                            } ?>
                        <?php endif; ?>
                    <?php else: ?>
                        <div class="w-full px-3 pb-1 pt-1 flex gap-2 flex-wrap">
                            <?= FilterPillsSkeleton::render(4); ?>
                        </div>
                        <?= TemplateCardSkeleton::render(3); ?>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
        <div x-show="templates_tab === 'user'" x-cloak>
            <?php if ($context === 'newsletter'): ?>
                <?php
                $message = mh_lng('TEXT_EDITOR_TEMPLATES_NEWSLETTER_USER_INFO', 'Own templates for newsletters are not supported yet.');
                echo \Components\Notification::render($message, [
                        'id' => 'editor_templates_newsletter_user_info',
                        'dismissible' => false,
                ]);
                ?>
            <?php endif; ?>
            <?php if ($context == 'module'): ?>
                <?php
                $message = mh_lng('TEXT_EDITOR_TEMPLATES_USER_BODY_INFO', 'These are the user body templates. The preview is shown based on the Standard Main Template. You can open the preview and select a different main template. You can import these templates into the module step template.');
                echo \Components\Notification::render($message, [
                        'id' => 'editor_templates_user_info',
                        'dismissible' => true,
                ]);
                ?>
            <?php endif; ?>
            <?php if ($context == 'main'): ?>
            <?php
            $message = mh_lng('TEXT_EDITOR_TEMPLATES_USER_MAIN_INFO', 'These are the user main templates.');
            echo \Components\Notification::render($message, [
                    'id' => 'editor_templates_main_info',
                    'dismissible' => true,
            ]);
            ?>
            <div>

                <?php endif; ?>

                <div class="flex flex-wrap -m-3">
                    <?php if (empty($templates_user)): ?>
                        <div class="col-span-full py-12 text-center text-secondary text-sm italic">
                            You haven't created any
                            custom templates yet.
                        </div>
                    <?php else: ?>
                        <?php foreach ($templates_user as $idx => $tpl) echo $renderCard($tpl, 'user', $idx); ?>
                    <?php endif; ?>

                    <?php if ($context === 'main' && $selectionMode !== 'create_main_from_gallery'): ?>
                        <div class="p-3 transition-all duration-500 flex" :class="itemWidthConfigs[columns]">
                            <?php
                            $createTitle = mh_lng('UI_TITLE_CREATE_MAIN_TEMPLATE', 'Create New Main Template');
                            $createCardAttrs = Base::attrs([
                                    'command' => 'show-modal',
                                    'commandfor' => 'config-modal',
                                    'data-title' => $createTitle,
                                    'data-size' => '6xl',
                                    'hx-get' => Router::url('main_template_gallery_selection_modal', [
                                            'partial' => 1,
                                            'lng_id' => $lngId,
                                            'context' => 'main',
                                            'module' => $module,
                                            'content_module_id' => $content_module_id,
                                    ]),
                                    'hx-target' => '#config-modal-body',
                                    'hx-swap' => 'innerHTML',
                            ]);

                            echo CardUI::render([
                                    'interactive' => true,
                                    'card_classes' => 'border-dashed border-1 h-full',
                                    'card_attrs' => $createCardAttrs,
                                    'body_header_html' => '
                                        <div class="flex flex-col items-center justify-center gap-4">
                                            <div class="text-brand-500 scale-200">' . Base::SVG_PLUS . '</div>
                                            <h4 class="text-sm font-semibold text-secondary/70 group-hover:text-primary text-center">' . $createTitle . '</h4>
                                        </div>',
                                    'no_preview' => true,
                                    'body_classes' => 'flex-1 flex items-center justify-center',
                            ]);
                            ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="mt-6 pb-6">
            <?= Button::render(\mh_lng('UI_BUTTON_REFRESH_ALL_THUMBNAILS', 'Refresh all thumbnails'), [
                    'variant' => 'ghost',
                    'size' => 'sm',
                    'class' => 'text-secondary/50 hover:text-primary',
                    'attrs' => [
                            'onclick' => "if(typeof refreshAllThumbnails === 'function') refreshAllThumbnails(this.closest('container')); return false;"
                    ]
            ]) ?>
        </div>
    </div>
<?php
$content = ob_get_clean();

if (mh_get('partial')) {
    echo $content;
} else {
    echo layout($pageKey, $content);
}
