<?php
// pages/components/newsletter_template_selection_modal.php
require_once BEEZUI_ROOT . '/components/index.php';

use Components\Base;
use Components\Router;
use Components\Button;
use Components\Support\Htmx;

// Inputs
$campaignId = (int)\mh_get('newsletter_campaign_id', 0, 'int');
if ($campaignId <= 0) { $campaignId = (int)\mh_post('newsletter_campaign_id', 0); }

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

$skipAudience = (int)\mh_get('skip_audience', 0, 'int');
if (!$skipAudience) { $skipAudience = (int)\mh_post('skip_audience', 0); }

$pageMode = \mh_get('page_mode', 'automation', 'string');

$templateId = (string)\mh_get('template_id', '');
if ($templateId === '') { $templateId = (string)\mh_post('template_id', ''); }

$templatesTab = \mh_get('templates_tab', 'gallery', 'string');
if ($templatesTab === '') { $templatesTab = (string)\mh_post('templates_tab', 'gallery'); }

$date = \mh_get('date', '', 'string');
if ($date === '') { $date = (string)\mh_post('date', ''); }

ob_start();
?>
<div>
    <script>
        (function() {
            var m = document.getElementById('<?= Htmx::resolvePanelId(); ?>');
            if (m) {
                m.setAttribute('data-title', <?= json_encode(\mh_lng('UI_NEWSLETTER_TEMPLATE_SELECTION_TITLE', 'Select Template')); ?>);
                m.setAttribute('data-size', '5xl');
            }

            var state = {
                selectUrl: '',
                templateId: ''
            };
            var continueButtonId = 'newsletter-template-continue-btn';

            function getContinueButton() {
                return document.getElementById(continueButtonId);
            }

            function setContinueState(selectUrl, templateId) {
                state.selectUrl = selectUrl || '';
                state.templateId = templateId || '';

                var button = getContinueButton();
                if (!button) {
                    return;
                }

                var enabled = !!state.selectUrl;
                button.disabled = !enabled;
                button.setAttribute('aria-disabled', enabled ? 'false' : 'true');
                button.classList.toggle('opacity-50', !enabled);
                button.classList.toggle('pointer-events-none', !enabled);
            }

            window.__mhNewsletterTemplateSelectionContinue = function() {
                if (!state.selectUrl || typeof htmx === 'undefined') {
                    return;
                }
                htmx.ajax('GET', state.selectUrl, {
                    target: '#config-modal-body',
                    swap: 'innerHTML'
                });
            };

            window.addEventListener('newsletter-template-selected', function(ev) {
                var detail = (ev && ev.detail) ? ev.detail : {};
                setContinueState(detail.select_url || '', detail.template_id || '');
            });

            setTimeout(function() {
                var selectedCard = document.querySelector('#editor-templates-container [data-newsletter-template-card="1"].is-selected');
                if (selectedCard) {
                    setContinueState(
                        selectedCard.getAttribute('data-select-url') || '',
                        selectedCard.getAttribute('data-template-id') || ''
                    );
                } else {
                    setContinueState('', '');
                }
            }, 0);
        })();
    </script>

    <?= \Components\Newsletter\WizardSteps::renderStepper(\Components\Newsletter\WizardSteps::STEP_TEMPLATE); ?>

    <?php
    // Use the editor_templates page in partial mode
    $_GET['context'] = 'newsletter';
    $_GET['partial'] = 1;
    $_GET['is_modal'] = 1;
    $_GET['newsletter_campaign_id'] = $campaignId;
    $_GET['newsletter_list_id'] = $listId;
    $_GET['page_mode'] = $pageMode;
    $_GET['skip_audience'] = $skipAudience;
    $_GET['template_id'] = $templateId;
    $_GET['templates_tab'] = $templatesTab;
    $_GET['date'] = $date;
    
    // We don't want the layout and page header inside the modal
    require BEEZUI_ROOT . '/pages/editor_templates.php';
    ?>

    <template x-teleport="#config-modal-footer">
        <div class="flex">
        <?= Button::render(\mh_lng('UI_PREVIOUS', 'Back'), [
                'variant' => 'ghost',
                'attrs' => [
                        'hx-get' => Router::url('newsletter_audience_selection_modal', [
                                'partial' => 1,
                                'page_mode' => $pageMode,
                                'newsletter_campaign_id' => $campaignId,
                                'date' => $date
                        ]),
                        'hx-target' => '#config-modal-body',
                        'hx-push-url' => 'false',
                ]
        ]); ?>

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

            <?= Button::render(\mh_lng('UI_NEXT', 'Continue'), [
            'variant' => 'primary',
            'class' => 'opacity-50 pointer-events-none',
            'attrs' => [
                'id' => 'newsletter-template-continue-btn',
                'disabled' => 'disabled',
                'aria-disabled' => 'true',
                'onclick' => 'if (typeof window.__mhNewsletterTemplateSelectionContinue === "function") { window.__mhNewsletterTemplateSelectionContinue(); } return false;'
            ]
        ]); ?>

        </div>
    </template>
</div>
<?php
echo ob_get_clean();
