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

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

$pageKey = 'coupons';
$targetContainer = '#app-container-' . $pageKey;

$activeTab = mh_get('coupons_tab', 'template_coupons');
$templateCouponId = mh_get('template_coupon_id', 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
}

$tabItems = [
    [
        'value' => 'template_coupons',
        'label' => \mh_lng('UI_TAB_COUPON_TEMPLATES', 'Templates'),
    ],
    [
        'value' => 'coupons',
        'label' => \mh_lng('UI_TAB_COUPONS_GENERATED', 'Generated'),
    ],
];

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

ob_start();
?>

<?php if (!mh_get('partial')): ?>
    <div>
        <?php echo \Components\Ui\PageHeader::render(\mh_lng('MAILBEEZ_APP_LABEL_COUPONS', 'Coupons')); ?>
    </div>
<?php endif; ?>

<div id="coupons-page-container" class="space-y-6"
     hx-get="<?= Base::h($listUrl) ?>"
     hx-trigger="<?= Base::h(implode(', ', $trigs)) ?>"
     hx-swap="outerHTML"
     :hx-vals="JSON.stringify({coupons_tab: coupons_tab, template_coupon_id: template_coupon_id})"
     x-data="{ coupons_tab: '<?= $activeTab ?>', template_coupon_id: <?= $templateCouponId ?> }"
     @hashchange.window="if(location.hash) coupons_tab = location.hash.substring(1)"
     @coupons:refresh.window="$nextTick(() => htmx.trigger($el, 'refresh'))">

    <?= Tabs::mobile('coupons_tab', $tabItems, ['ariaLabel' => 'Select coupons 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('coupons_tab', $tabItems) ?>
        </div>
    </div>

    <div class="mt-6">
        <!-- Tab: Coupons -->
        <div x-show="coupons_tab === 'coupons'" x-cloak class="space-y-4">
            <?php
            $message = \mh_lng('MAILBEEZ_COUPON_EXPLAINER_GENERATED', 'coupons: generated coupons, can be applied by customers');
            echo \Components\Notification::render($message, [
                    'id' => 'coupons_info',
                    'dismissible' => true,
            ]);
            ?>
            <div id="coupons-list"
                 hx-get="<?= \Components\Router::url('coupons_list', ['partial' => 1]) ?>"
                 hx-trigger="load, refresh consume"
                 hx-swap="outerHTML">
                <div class="text-sm text-muted">Loading coupons…</div>
            </div>
        </div>

        <!-- Tab: Template Coupons -->
        <div x-show="coupons_tab === 'template_coupons'" x-cloak>
            <?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,
            ]);
            ?>

            <div class="grid grid-cols-[repeat(auto-fill,minmax(240px,1fr))] gap-6">
                <?php foreach ($templates as $tpl): ?>
                    <div class="max-w-[400px]">
                        <?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, \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="<?= $genCount ?> generated coupons"
                                      @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 = [];
                        $actions[] = [
                            'label' => \mh_lng('UI_BUTTON_EDIT', 'Edit'),
                            'attrs' => [
                                'command' => 'show-modal',
                                'commandfor' => 'config-modal',
                                'data-title' => \mh_lng('UI_BUTTON_EDIT', 'Edit'),
                                'data-url' => LegacyRouter::url('couponAdmin', ['action' => 'edit', 'cID' => $tpl['id']]),
                                'hx-target' => '#config-modal-body',
                                'hx-swap' => 'innerHTML',
                            ],
                            'icon' => Base::SVG_EDIT,
                        ];

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

                        echo CardUI::render([
                            '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',
                        ]);
                        ?>
                    </div>
                <?php endforeach; ?>
                <div class="max-w-[400px]">
                    <?php
                    echo CardUI::render([
                        'interactive' => true,
                        'card_classes' => 'border-dashed border-2 h-full',
                        'preview_content' => '<div class="w-full h-full flex items-center justify-center text-brand-500 scale-200">' . Base::SVG_PLUS . '</div>',
                        'preview_container_classes' => 'border-0',
                        'preview_base_classes' => 'bg-transparent',
                        'aspect_ratio' => 'aspect-[316/190]',
                        'body_header_html' => '<h4 class="text-sm font-semibold text-primary">' . \mh_lng('UI_TITLE_CREATE_TEMPLATE_COUPON', 'Create New') . '</h4>',
                        'no_preview' => false,
                        'card_attrs' => Base::attrs([
                            'command' => 'show-modal',
                            'commandfor' => 'config-modal',
                            'data-title' => \mh_lng('UI_TITLE_CREATE_TEMPLATE_COUPON', 'Create New Template Coupon'),
                            'data-url' => LegacyRouter::url('couponAdmin', ['action' => 'new']),
                            'hx-target' => '#config-modal-body',
                            'hx-swap' => 'innerHTML',
                        ])
                    ]);
                    ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
$content = ob_get_clean();

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