<?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\Dropdown;
use Components\Button;
use Components\Legacy\LegacyRouter;
use Components\Resources\TemplateCard;
use Components\Resources\TemplateCardSkeleton;
use Components\Ui\Tabs;

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

// 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 === 'module') {
    $mb_tmpl_manager = new template_manager('module');
    $maintemplate_id_short = null;

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

$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);
$activeTab = mh_get('templates_tab', $context == 'module' ?  'user' : 'user');

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

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

$template_path = $mb_tmpl_manager->template_path;

// Load templates
$templates_gallery = [];
if ($context === 'main' && ($activeTab === 'gallery' || mh_get('app_action') === 'gallery_content')) {
    $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 = $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) {
    $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
    ]);
    return '<div class="p-3 transition-all duration-500 flex " :class="itemWidthConfigs[columns]">' . $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 {
        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 = [];
$labelUser = ($context == 'main')
    ? mh_lng('TEXT_TAB_MAIN_TEMPLATES', 'Main Designs')
    : mh_lng('TEXT_TAB_USER', 'User');
$tabItems[] = [
    'value' => 'user',
    'label' => $labelUser . ' (' . count($templates_user) . ')',
];
if ($context == 'module') {
    $tabItems[] = [
        'value' => 'basic',
        'label' => mh_lng('TEXT_TAB_BASIC', 'Basic') . ' (' . count($templates_basic) . ')',
    ];
}
if ($context == 'main') {
    // Intentionally omit dynamic count here; gallery loads lazily
    $tabItems[] = [
        'value' => 'gallery',
        'label' => mh_lng('TEXT_TAB_MAIN_TEMPLATE_GALLERY', 'Gallery'),
    ];
}

ob_start();
?>
<?php if (!mh_get('partial')): ?>
    <div>
        <?php
        $headerTitle = ($context === 'module')
            ? mh_lng('MAILBEEZ_APP_LABEL_MODULE_TEMPLATES', 'Module Templates')
            : mh_lng('MAILBEEZ_APP_LABEL_TEMPLATES', 'Main Templates');
        $headerSubtitle = ($context === 'module')
            ? mh_lng('MAILBEEZ_APP_LABEL_MODULE_TEMPLATES_SUBTITLE', 'Module Templates define the content structure for your emails.')
            : mh_lng('MAILBEEZ_APP_LABEL_TEMPLATES_SUBTITLE', 'Main Templates define the overall layout and branding of your emails.');
        echo \Components\Ui\PageHeader::render($headerTitle, ['subtitle' => $headerSubtitle]);
        ?>
    </div>
<?php endif; ?>

    <div id="editor-templates-container" 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: 4,
            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);
            }
         }"
         @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-6 min-h-[70vh]">

            <?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'): ?>
            <div  x-show="templates_tab === 'gallery'"  x-cloak>
                <?php
                $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 foreach ($templates_gallery as $idx => $tpl) echo $renderCard($tpl, 'gallery', $idx); ?>
                        <?php endif; ?>
                    <?php else: ?>
                        <?= TemplateCardSkeleton::render(3); ?>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
            <div x-show="templates_tab === 'user'" x-cloak>
                <?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; ?>
                </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(); return false;"
                ]
            ]) ?>
        </div>
    </div>
<?php
$content = ob_get_clean();

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