<?php
// pages/components/template_coupons_grid.php

use Components\Button;
use Components\Base;
use Components\Ui\CardUI;
use Components\Dropdown;
use Components\Ui\VoucherMockup;
use Components\Legacy\LegacyRouter;
use Components\Router;
use Components\Ui\FilterPills;
use Components\Ui\SelectableCard;

$oob = (int) (mh_get('oob', 0, 'int'));

// Load templates via data provider when available; fallback to static list
$templates = [];
try {
    $prov = \Components\Data\DataRegistry::templateCoupons();
    if ($prov) {
        $data = $prov->templates(false);
        if (is_array($data) && $data) {
            $templates = $data;
        }
    }
} catch (\Throwable $e) {
    // ignore and fallback to static
}

// Collect used types to show in FilterPills
$usedTypes = [];
foreach ($templates as $tpl) {
    if (!empty($tpl['type'])) {
        $usedTypes[$tpl['type']] = $tpl['type'];
    }
}
$usedTypes = array_values($usedTypes);
sort($usedTypes);

$labelsMap = [
    'F' => \mh_lng('UI_TEXT_COUPON_TYPE_FIXED', 'Fixed'),
    'P' => \mh_lng('UI_TEXT_COUPON_TYPE_PERCENTAGE', 'Percentage'),
    'S' => \mh_lng('UI_TEXT_COUPON_TYPE_FREE_SHIPPING', 'Free Shipping'),
];

$refreshUrl = Router::url('template_coupons_grid', ['partial' => 1]);
$outerAttrs = 'id="template-coupons-grid" hx-get="' . Base::h($refreshUrl) . '" hx-trigger="refresh consume, coupon_template:created from:body, coupon_template:updated from:body, coupon_template:deleted from:body" hx-target="this" hx-swap="outerHTML"';
if ($oob) { $outerAttrs .= ' hx-swap-oob="outerHTML"'; }

ob_start();
?>
<div <?= $outerAttrs ?> x-show="coupons_tab === 'template_coupons'" x-cloak>
    <?= SelectableCard::renderScripts() ?>
    <?php
    $message = \mh_lng('MAILBEEZ_COUPON_EXPLAINER_TEMPLATES', 'Template coupons: used to generated personalized coupons when sending emails');
    echo \Components\Notification::render($message, [
        'id' => 'template_coupons_info',
        'dismissible' => true,
    ]);
    ?>

    <?php if (count($usedTypes) > 0): ?>
        <div class="flex gap-2 flex-wrap mb-4">
            <?php
            echo FilterPills::render($usedTypes, [
                'labels_map' => $labelsMap,
                'isFilterFn' => 'isCouponFilter',
                'setFilterFn' => 'setCouponFilter',
            ]);
            ?>
        </div>
    <?php endif; ?>

    <div class="grid grid-cols-[repeat(auto-fill,minmax(240px,1fr))] gap-6">
        <?php foreach ($templates as $tpl): ?>
            <div class="max-w-[400px]" x-show="isCouponFilter('ALL') || isCouponFilter(<?= Base::h(json_encode($tpl['type']), false) ?>)" >
                <?php
                $typeLabel = Base::h($tpl['typeLabel']);
                $code = Base::h($tpl['code']);
                $name = Base::h($tpl['name']);
                $codeMain = Base::h($tpl['codeMain'] ?? str_replace('template_', '', $tpl['code']));

                // Preview content: Voucher mockup
                $previewContent = VoucherMockup::render($typeLabel, $codeMain, $code, (string)\mh_lng('UI_TEXT_COUPON_NO_RESTRICTIONS', 'no restrictions'), $tpl['type'] ?? '');

                // Body Header
                ob_start();
                ?>
                <div class="flex items-center gap-2 min-w-0">
                    <h4 class="text-sm font-semibold text-primary truncate" title="<?= $code ?>">
                        <?= $codeMain ?>
                    </h4>
                </div>
                <?php
                $bodyHeaderHtml = ob_get_clean();

                // Body Footer
                ob_start();
                $genCount = (int)($tpl['generated_count'] ?? 0);
                ?>
                <div class="flex items-center justify-between mt-0.5">
                    <p class="text-[10px] text-secondary uppercase tracking-wider font-medium flex flex-wrap items-center min-w-0">
                        <span class="flex-shrink-0 truncate"><?= $name ?></span>
                        <span class="mx-1 opacity-50">&middot;</span>
                        <span class="normal-case tracking-normal font-normal truncate"><?= $typeLabel ?></span>
                    </p>
                    <?php if ($genCount > 0): ?>
                        <span class="flex-shrink-0 ml-2 bg-brand-100 text-brand-700 px-1.5 py-0.5 rounded-full text-[10px] font-bold cursor-pointer hover:bg-brand-200 transition-colors"
                              title="<?= Base::h(sprintf(\mh_lng('UI_TEXT_X_GENERATED_COUPONS'), $genCount)) ?>"
                              @click.stop="template_coupon_id = <?= $tpl['id'] ?>; coupons_tab = 'coupons'; $nextTick(() => htmx.trigger('#coupons-list', 'refresh'))">
                        <?= $genCount ?>
                    </span>
                    <?php endif; ?>
                </div>
                <?php
                $bodyFooterHtml = ob_get_clean();

                // Actions
                $actions = [];
                $editActionAttrs = [
                    'command' => 'show-modal',
                    'commandfor' => 'config-modal',
                    'data-title' => \mh_lng('TEXT_GENERATE_EDIT_COUPON', 'Edit Coupon'),
                    'data-size' => '4xl-sm',
                    'hx-get' => Router::url('coupon_modal', ['partial' => 1, 'mode' => 'edit', 'id' => $tpl['id'], 'is_template' => 1, 'drawer' => 0]),
                    'hx-target' => '#config-modal-body',
                    'hx-swap' => 'innerHTML',
                ];
                $actions[] = [
                        'label' => \mh_lng('UI_BUTTON_EDIT', 'Edit'),
                        'attrs' => $editActionAttrs,

                        'icon' => Base::SVG_EDIT,
                ];
                $actions[] = [
                    'label' => \mh_lng('UI_TEXT_X_GENERATED_COUPONS', 'Show generated coupons'),
                    'attrs' => [
                        '@click' => "template_coupon_id = " . (int)$tpl['id'] . "; coupons_tab = 'coupons'; \$nextTick(() => htmx.trigger('#coupons-list', 'refresh'))"
                    ],
                    'icon' => Base::SVG_OUTLINE_FILTER,
                ];

                $actions[] = [
                    'divider' => true,
                ];

                $actions[] = [
                    'label' => \mh_lng('UI_BUTTON_GENERATE_COUPON_SERIES'),
                    'attrs' => [
                        'command' => 'show-modal',
                        'commandfor' => 'config-modal',
                        'data-title' => \mh_lng('UI_BUTTON_GENERATE_COUPON_SERIES', 'Generate Coupons'),
                        'data-size' => '4xl-sm',
                        'hx-get' => Router::url('coupon_generate_modal', ['partial' => 1, 'id' => $tpl['id']]),
                        'hx-target' => '#config-modal-body',
                        'hx-swap' => 'innerHTML',
                    ],
                    'icon' => Base::SVG_VOUCHER_1,
                ];


                if (!mh_saas()) {
                    $actions[] = [
                        'label' => sprintf(\mh_lng('UI_BUTTON_EDIT_IN_PLATFORM', 'Edit in %s'), Base::platformLabel()),
                        'attrs' => [
                            'command' => 'show-modal',
                            'commandfor' => 'config-modal',
                            'data-title' => \mh_lng('UI_BUTTON_EDIT'),
                            'data-size' => 'full-margin',
                            'data-url' => LegacyRouter::url('couponEdit', ['cid' => $tpl['id']]),
                            'hx-target' => '#config-modal-body',
                            'hx-swap' => 'innerHTML',
                        ],
                        'icon' => Base::SVG_EDIT,
                        'end_icon' => Base::platformIcon(),
                    ];
                }

                $actionsHtml = Dropdown::render([
                    'trigger_tag' => 'div',
                    'trigger_attrs' => ['@click.stop' => ''],
                    'trigger_html' => Button::render('', [
                        'variant' => 'ghost',
                        'size' => 'md',
                        'icon' => Base::SVG_ELLIPSIS_HORIZONTAL,
                        'attrs' => ['@click.stop' => '', 'aria-label' => \mh_lng('UI_MORE', 'More')],
                    ]),
                    'items' => $actions,
                    'anchor' => 'bottom end'
                ]);

                $cardClasses = SelectableCard::cardClasses();
                $cardAttrs = Base::attrs([
                    'data-template-coupon-card' => '1',
                    'aria-selected' => 'false',
                    '@click' => "if (window.__mhSelectableCard) { window.__mhSelectableCard.handleClick(\$event, \$el, { containerSelector: '#template-coupons-grid', cardSelector: '[data-template-coupon-card=\"1\"]', skipSelector: '[data-skip-template-card-click]' }); }",
                    '@dblclick' => "if (window.__mhSelectableCard) { window.__mhSelectableCard.handleDoubleClick(\$event, \$el, { containerSelector: '#template-coupons-grid', cardSelector: '[data-template-coupon-card=\"1\"]', skipSelector: '[data-skip-template-card-click]' }); }",
                ]);

                $primaryActionHtml = '<button ' . Base::attrs(array_merge($editActionAttrs, [
                    'type' => 'button',
                    'class' => 'hidden',
                    'tabindex' => '-1',
                    'aria-hidden' => 'true',
                    'data-card-primary-action' => '1',
                    'data-skip-template-card-click' => '1',
                ])) . '></button>';

                echo CardUI::render([
                    'card_classes' => $cardClasses,
                    'card_attrs' => $cardAttrs,
                    'preview_content' => $previewContent,
                    'body_header_html' => $bodyHeaderHtml,
                    'body_footer_html' => $bodyFooterHtml,
                    'actions_html' => $actionsHtml,
                    'aspect_ratio' => 'aspect-[316/190]',
                    'preview_base_classes' => '',
                    'preview_container_classes' => 'border-0',
                    'preview_classes' => 'overflow-visible',
                    'scripts' => $primaryActionHtml,
                ]);
                ?>
            </div>
        <?php endforeach; ?>
        <div class="max-w-[400px]">
            <?php
            $createTitle = \mh_lng('UI_TITLE_CREATE_TEMPLATE_COUPON', 'Create New');
            $createCardAttrs = Base::attrs([
                'command' => 'show-modal',
                'commandfor' => 'config-modal',
                'data-title' => $createTitle,
                'data-size' => '4xl-sm',
                'hx-get' => Router::url('coupon_template_selection_modal', ['partial' => 1, 'is_template' => 1]),
                '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>
    </div>
    <div class="flex justify-start mt-8">
        <?php
        echo Button::render(\mh_lng('UI_REFRESH', 'Refresh'), [
            'variant' => 'ghost',
            'size' => 'md',
            'icon' => Base::SVG_REFRESH,
            'attrs' => [
                '@click' => 'htmx.trigger("#template-coupons-grid", "refresh")',
            ],
        ]);
        ?>
    </div>
</div>
<?php
echo ob_get_clean();
