<?php
// pages/components/coupons_list.php
// Lists all coupons with actions opening the global modal
use Components\Router;
use Components\Models\Coupon;
use Components\Resources\ResourceList;

$oob = (int) (mh_get('oob', 0, 'int'));
$outerAttrs = 'id="coupons-list"';
if ($oob) { $outerAttrs .= ' hx-swap-oob="outerHTML"'; }

// Build items from model
$items = [];
if (function_exists('mh_db_query')) {
    foreach (Coupon::all() as $c) {
        $id = (int)($c->coupon_id ?? 0);
        if ($id <= 0) { continue; }
        $code = (string)($c->coupon_code ?? ('Coupon ' . $id));
        $activeRaw = (string)($c->coupon_active ?? '');
        $status = ($activeRaw === 'Y' || $activeRaw === '1') ? 'Y' : '';
        $items[] = ['id' => $id, 'name' => $code, 'status' => $status, 'icon' => $c->icon ?? []];
    }
}
ob_start();

$viewBase = Router::url('coupon_modal', ['partial' => 1, 'mode' => 'view']);
$editBase = Router::url('coupon_modal', ['partial' => 1, 'mode' => 'edit']);

echo ResourceList::render([
    'title' => 'Coupons',
    'items' => $items,
    'id_key' => 'id',
    'name_key' => 'name',
    'status_key' => 'status',
    'outer_attrs' => $outerAttrs,
    'empty_text' => 'No coupons found or database not available.',
    'panel_type' => 'drawer',
    'new_action' => [
        'label' => 'New',
        'url' => Router::url('coupon_modal', ['partial' => 1, 'mode' => 'new']),
        'attrs' => [
            'data-title' => 'New Coupon',
            'data-size' => 'xl',
        ],
        'variant' => 'primary',
    ],
    'row_actions' => [
        [
            'label' => 'View',
            'url' => $viewBase . '&id={id}',
            'attrs' => [ 'data-title' => 'View Coupon', 'data-size' => 'xl' ],
            'variant' => 'secondary',
        ],
        [
            'label' => 'Edit',
            'url' => $editBase . '&id={id}',
            'attrs' => [ 'data-title' => 'Edit Coupon', 'data-size' => 'xl' ],
            'variant' => 'primary',
        ],
    ],
]);

$__html = ob_get_clean();
echo $__html;
