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

use Components\Base;
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');
$batchId = mh_get('batch_id', 0, 'int');
$statusFilter = mh_get('status', '', 'string');
$batchType = mh_get('batch_type', '', 'string');


$tabItems = [
        [
                'value' => 'template_coupons',
                'label' => \mh_lng('UI_TAB_COUPON_TEMPLATES', 'templates'),
        ],
        [
                'value' => 'coupons',
                'label' => \mh_lng('UI_TAB_COUPONS_GENERATED', 'generated'),
        ],
        [
                'value' => 'coupon_batches',
                'label' => \mh_lng('UI_TAB_COUPON_BATCHES', 'Series'),
        ],
];

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

$headerRight = '
<div class="flex gap-2 items-center" x-data="{ tab: ' . Base::h(json_encode($activeTab), false) . ' }" @coupons-tab-changed.window="tab = $event.detail">
    ' . \Components\Button::render(\mh_lng('UI_NEW_TEMPLATE_COUPON', 'New Template Coupon'), [
                'icon' => \Components\Base::SVG_PLUS,
                'iconPosition' => 'front',
                'size' => 'md',
                'variant' => 'secondary',
                'attrs' => [
                        'command' => 'show-modal',
                        'commandfor' => 'config-modal',
                        'data-title' => \mh_lng('UI_TITLE_CREATE_TEMPLATE_COUPON', 'Create New Template Coupon'),
                        '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',
                        'x-show' => "tab === 'template_coupons'",
                        'x-cloak' => true,
                ],
        ]) . '
    ' . \Components\Button::render(\mh_lng('UI_NEW_COUPON_BATCH', 'New Batch'), [
                'icon' => \Components\Base::SVG_PLUS,
                'iconPosition' => 'front',
                'size' => 'md',
                'variant' => 'secondary',
                'attrs' => [
                        'command' => 'show-modal',
                        'commandfor' => 'config-modal',
                        'data-title' => (string)mh_lng('TEXT_GENERATE_COUPONS', 'Generate Coupons'),
                        'data-size' => '4xl-sm',
                        'hx-get' => Router::url('coupon_generate_modal', ['partial' => 1, 'selectable_coupon' => 1]),
                        'hx-target' => '#config-modal-body',
                        'hx-swap' => 'innerHTML',
                        'x-show' => "tab === 'coupon_batches'",
                        'x-cloak' => true,
                ],
        ]) . '
</div>';

ob_start();
?>

<?php if (!mh_get('partial')): ?>
    <div>
        <?php echo \Components\Ui\PageHeader::render(\mh_lng('MAILBEEZ_APP_LABEL_COUPONS'), [
            'subtitle' => \mh_lng('MAILBEEZ_APP_LABEL_COUPONS_SUBTITLE', 'Create and manage coupon templates and generated series.'),
            'right' => $headerRight,
        ]); ?>
    </div>
<?php endif; ?>

    <div id="coupons-page-container" class="space-y-4" x-cloak
         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, batch_id: batch_id, status: status, batch_type: batch_type, coupon_type_filter: coupon_type_filter})"
         x-data="{ coupons_tab: <?= Base::h(json_encode($activeTab), false) ?>, template_coupon_id: <?= (int)$templateCouponId ?>, batch_id: <?= (int)$batchId ?>, status: <?= Base::h(json_encode($statusFilter), false) ?>, batch_type: <?= Base::h(json_encode($batchType), false) ?>, coupon_type_filter: 'ALL', setCouponFilter(v) { this.coupon_type_filter = v }, isCouponFilter(v) { return this.coupon_type_filter === v } }"
         x-init="$watch('coupons_tab', v => $dispatch('coupons-tab-changed', v)); $dispatch('coupons-tab-changed', coupons_tab)"
         @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' => \mh_lng('UI_COUPONS_SELECT_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-4">
            <!-- Tab: Coupons -->
            <div x-show="coupons_tab === 'coupons'" x-cloak class="space-y-4 mt-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,
                ]);
                ?>
                <?php if ($activeTab === 'coupons'): ?>
                    <?php include BEEZUI_ROOT . '/pages/components/coupons_list.php'; ?>
                <?php else: ?>
                    <div id="coupons-list"
                         hx-get="<?= Base::h(\Components\Router::url('coupons_list', ['partial' => 1, 'template_coupon_id' => $templateCouponId, 'batch_id' => $batchId, 'status' => $statusFilter])) ?>"
                         hx-trigger="load, refresh consume"
                         hx-swap="outerHTML">
                        <div class="text-sm text-muted"><?= \mh_lng('UI_TEXT_LOADING_COUPONS') ?></div>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Tab: Coupon Batches -->
            <div x-show="coupons_tab === 'coupon_batches'" x-cloak class="space-y-4 mt-4">
                <?php
                $message = \mh_lng('MAILBEEZ_COUPON_EXPLAINER_BATCHED', 'Coupon series are generated from a template coupon. They are ideal for offline use or other systems/platforms and can be exported anytime.');
                echo \Components\Notification::render($message, [
                        'id' => 'coupons_info',
                        'dismissible' => true,
                ]);
                ?>
                <?php if ($activeTab === 'coupon_batches'): ?>
                    <?php include BEEZUI_ROOT . '/pages/components/coupon_batches_list.php'; ?>
                <?php else: ?>
                    <div id="coupon-batches-list"
                         hx-get="<?= Base::h(\Components\Router::url('coupon_batches_list', ['partial' => 1, 'batch_type' => $batchType])) ?>"
                         hx-trigger="load, refresh consume"
                         hx-swap="outerHTML">
                        <div class="text-sm text-muted"><?= \mh_lng('UI_TEXT_LOADING_BATCHES') ?></div>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Tab: Template Coupons -->
            <?php if ($activeTab === 'template_coupons'): ?>
                <?php include BEEZUI_ROOT . '/pages/components/template_coupons_grid.php'; ?>
            <?php else: ?>
                <div id="template-coupons-grid"
                     x-show="coupons_tab === 'template_coupons'" x-cloak
                     hx-get="<?= Base::h(Router::url('template_coupons_grid', ['partial' => 1])) ?>"
                     hx-trigger="load, refresh consume, coupon_template:created from:body, coupon_template:updated from:body, coupon_template:deleted from:body"
                     hx-swap="outerHTML">
                    <div class="text-sm text-muted"><?= \mh_lng('UI_TEXT_LOADING_TEMPLATES', 'Loading Templates') ?></div>
                </div>
            <?php endif; ?>
        </div>
    </div>

<?php
$content = ob_get_clean();

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