<?php
// pages/components/coupon_batches_list.php
use Components\Models\CouponBatch;
use Components\Resources\ResourceList;
use Components\Base;
use Components\Router;
use Components\Ui\Badge;
use Components\ConfigStore;

$oob = (int) (mh_get('oob', 0, 'int'));
$page = (int)mh_get('page', 1, 'int');
$search = (string)mh_get('search', '', 'string');
$typeFilter = (string)mh_get('batch_type', '', 'string');
$perPage = ConfigStore::getListPerPage('coupon_batches', 25);

$filters = [];
if ($typeFilter !== '') {
    $filters['batch_type'] = $typeFilter;
}

$paginationResult = CouponBatch::paginate($perPage, $page, $search, ['batch_name'], $filters);
$batches = $paginationResult['items'];
$total = $paginationResult['total'];

$items = [];
foreach ($batches as $batch) {
    $stats = $batch->getStats();
    $items[] = array_merge($batch->toArray(), [
        'id' => $batch->batch_id,
        'label' => $batch->batch_name,
        'stats_data' => $stats,
        'icon' => CouponBatch::getIdentityDataByType((string)$batch->batch_type)
    ]);
}

$refreshUrl = Router::url('coupon_batches_list', [
    'partial' => 1,
    'search' => $search,
    'page' => $page,
    'batch_type' => $typeFilter,
]);
$outerAttrs = 'id="coupon-batches-list" hx-trigger="refresh consume, list-per-page-updated:coupon_batches from:body, batch:created from:body, batch:updated from:body, batch:deleted from:body" hx-get="' . \Components\Base::h($refreshUrl) . '" hx-target="this" hx-swap="outerHTML"';
if ($oob) { $outerAttrs .= ' hx-swap-oob="outerHTML"'; }

echo ResourceList::render([
    'items' => $items,
    'layout' => 'clean',
    'new_action' => [
        'label' => (string)mh_lng('TEXT_GENERATE', 'Generate'),
        'url' => Router::url('coupon_generate_modal', ['partial' => 1, 'selectable_coupon' => 1]),
        'attrs' => [
            'data-title' => (string)mh_lng('TEXT_GENERATE_COUPONS', 'Generate Coupons'),
            'data-size' => '4xl-sm',
            'data-dismissible' => 'false',
            'command' => 'show-modal',
            'commandfor' => 'config-modal',
            'hx-target' => '#config-modal-body',
            'hx-swap' => 'innerHTML',
        ],
        'variant' => 'primary',
    ],
    'refresh_action' => [
        'url' => $refreshUrl,
    ],

//    'id_key' => 'batch_id',
    'table_id' => 'coupon_batches',
    'outer_attrs' => $outerAttrs,
    'label_key' => 'label',
    'batch_type_key' => 'batch_type',

    'name_label' => \mh_lng('UI_TEXT_NAME', 'Name'),
    'columns' => [
        [
            'key' => 'batch_id',
            'label' => \mh_lng('UI_TEXT_BATCH', 'Series'),
            'optional' => true,
            'default' => true,
        ],
        [
            'key' => 'batch_type',
            'label' => (string)mh_lng('UI_TEXT_BATCH_TYPE', 'Type'),
            'render' => function($val) {
                return CouponBatch::getTypeBadge((string)$val);
            }
        ],
        [
            'key' => 'stats_data',
            'label' => (string)mh_lng('UI_REDEMPTION_RATE', 'Redemption'),
            'render' => function($stats) {
                $total = (int)($stats['total'] ?? 0);
                $redeemed = (int)($stats['redeemed'] ?? 0);
                $percent = $stats['percent'] ?? 0;
                
                $html = '<div class="flex flex-col gap-1 w-48">';
                $html .= '<div class="flex justify-between text-[10px] font-medium">';
                $html .= '<span class="text-gray-500 dark:text-gray-400">' . $redeemed . ' / ' . $total . '</span>';
                $html .= '<span class="text-brand-600 dark:text-brand-400">' . $percent . '%</span>';
                $html .= '</div>';
                $html .= '<div class="w-full bg-gray-100 dark:bg-gray-800 rounded-full h-1.5 overflow-hidden">';
                $html .= '<div class="bg-brand-500 h-full rounded-full" style="width: ' . $percent . '%"></div>';
                $html .= '</div>';
                $html .= '</div>';
                return $html;
            }
        ],
        [
            'key' => 'date_created',
            'label' => (string)mh_lng('UI_CREATED_AT', 'Created'),
            'optional' => true,
            'default' => true,
            'render' => function($val) {
                $y = substr((string)$val, 0, 4);
                return ($val && $y !== '0000' && $y !== '0001' && $y !== '1000') ? date('Y-m-d', strtotime($val)) : '-';
            }
        ]
    ],
    'search' => [
        'value' => $search,
        'placeholder' => mh_lng('UI_TEXT_COUPON_SERIES_SEARCH', 'Search series name...'),
        'target' => '#coupon-batches-list',
        'url' => Router::url('coupon_batches_list', ['batch_type' => $typeFilter]),
    ],
    'filters' => [
        'batch_type' => [
            'value' => $typeFilter,
            'options' => CouponBatch::getTypeOptions(true),
            'component' => 'rich_select',
            'target' => '#coupon-batches-list',
            'url' => Router::url('coupon_batches_list', ['search' => $search]),
            'attrs' => [
                'x-model' => 'batch_type',
            ]
        ]
    ],
    'pagination' => [
        'total' => $total,
        'per_page' => $perPage,
        'current_page' => $page,
        'url' => Router::url('coupon_batches_list', ['search' => $search, 'batch_type' => $typeFilter]),
        'target' => '#coupon-batches-list',
    ],
    'row_actions_as_menu' => true,
    'menu_trigger' => 'ellipsis',
    'primary_action' => 'filter',
    'row_actions' => [
        [
            'key' => 'filter',
            'label' => \mh_lng('UI_TEXT_X_GENERATED_COUPONS', 'Filter'),
            'variant' => 'primary',
            'icon' => Base::SVG_OUTLINE_FILTER,
            'attrs' => [
                '@click.stop' => "template_coupon_id = 0;coupons_tab = 'coupons'; batch_id = {id}; \$nextTick(() => htmx.trigger('#coupons-list', 'refresh'))",
            ]
        ],
        [
            'key' => 'export',
            'label' => (string)mh_lng('UI_EXPORT', 'Export...'),
            'icon' => Base::SVG_ARROW_DOWN_SQUARE   ,

            'attrs' => [
                'command' => 'show-modal',
                'commandfor' => 'config-modal',
                'data-title' => (string)mh_lng('UI_TEXT_EXPORT_COUPON_BATCH', 'Export coupon batch'),
                'hx-get' => Router::url('coupon_export_modal', ['batch_id' => '{id}', 'partial' => 1]),
                'hx-target' => '#config-modal-body',
                'hx-swap' => 'innerHTML',
                'hx-params' => 'not coupons_tab, template_coupon_id, batch_id, status',
                '@click.stop' => '',
            ]
        ],
        [
            'label' => \mh_lng('UI_BUTTON_DELETE_COUPON_SERIES', 'Delete Series'),
            'variant' => 'danger',
            'icon' => Base::SVG_TRASH,
            'attrs' => [
                'hx-post' => Router::url('coupon_batch_delete', ['id' => '{id}']),
                'hx-confirm' => \mh_lng('UI_TEXT_BATCH_DELETE_CONFIRM', 'Are you sure you want to delete this series? The coupons will remain, but the series grouping will be removed.'),
                'hx-target' => '#coupon-batches-list',
                'hx-swap' => 'outerHTML',
            ]
        ]
    ],
    'empty_text' => \mh_lng('UI_TEXT_NO_BATCHES_FOUND', 'No series found'),
]);
