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

$oob = (int) (mh_get('oob', 0, 'int'));
$page = (int)mh_get('page', 1, 'int');
$search = (string)mh_get('search', '', 'string');
$templateId = (int)mh_get('template_coupon_id', 0, 'int');
$perPage = 10;

// Build template options using Coupon::listOptions for rich identity rendering in the filter
$templateOptions = ['0' => ['label' => 'All Templates']];
try {
    $opt = Coupon::listOptions(false);
    // Ensure keys are strings for stable comparison in controls
    foreach ($opt as $k => $def) {
        $templateOptions[(string)$k] = $def;
    }
} catch (\Throwable $e) {
    // Fallback to a plain option when provider fails
}

// Build items from model
$items = [];
$total = 0;

// Instantiate coupon engine
if (!class_exists('couponbeez')) {
    $configDir = function_exists('mh_cfg') ? mh_cfg('MH_DIR_CONFIG') : null;
    if ($configDir && file_exists($configDir . 'config_coupon_engine/classes/couponbeez.php')) {
        require_once($configDir . 'config_coupon_engine/classes/couponbeez.php');
    }
}
$cbEngine = class_exists('couponbeez') ? new \couponbeez() : null;

$currentLanguageId = (int)($_SESSION['languages_id'] ?? 1);
$allLanguages = function_exists('mh_get_languages') ? mh_get_languages() : [];

if (function_exists('mh_db_query')) {
    $filters = [];
    if ($templateId > 0) {
        $filters['template_coupon_id'] = $templateId;
    }
    $paginationResult = Coupon::paginate($perPage, $page, $search, ['coupon_code'], $filters);
    $total = $paginationResult['total'];
    foreach ($paginationResult['items'] 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' : '';

        $valueLabel = $cbEngine ? $cbEngine->get_coupon_type_label($id) : '';

        // Fetch descriptions
        $descriptions = CouponDescription::forCoupon($id);

        // Find current language description
        $currentDesc = $descriptions[$currentLanguageId] ?? reset($descriptions) ?? [];
        $couponName = (string)($currentDesc['coupon_name'] ?? '');
        $couponDesc = (string)($currentDesc['coupon_description'] ?? '');

        // Tooltip content
        $tooltipContent = '<div class="space-y-3 p-1">';
        foreach ($allLanguages as $lang) {
            $lid = (int)$lang['id'];
            $d = $descriptions[$lid] ?? [];
            if (empty($d['coupon_name']) && empty($d['coupon_description'])) continue;

            $tooltipContent .= '<div>';
            $tooltipContent .= '<div class="font-bold border-b border-white/20 pb-0.5 mb-1 flex items-center gap-1.5 text-blue-300">';
            $tooltipContent .= BaseField::flagIconHtml($lang['code'] ?? null);
            $tooltipContent .= \Components\Base::h($lang['name']) . '</div>';
            $tooltipContent .= '<div class="font-semibold">' . \Components\Base::h($d['coupon_name']) . '</div>';
            $tooltipContent .= '<div class="italic opacity-80 text-[10px] leading-tight">' . \Components\Base::h($d['coupon_description']) . '</div>';
            $tooltipContent .= '</div>';
        }
        $tooltipContent .= '</div>';

        // Check for restrictions
        $hasRestrictions = false;
        if (!empty($c->restrict_to_products) || !empty($c->restrict_to_categories) || !empty($c->restrict_to_customers) || !empty($c->rules)) {
            $hasRestrictions = true;
        }
        if (isset($c->coupon_minimum_order) && (float)$c->coupon_minimum_order > 0) {
            $hasRestrictions = true;
        }

        $items[] = [
            'id' => $id,
            'label' => $code,
            'status' => $status,
            'icon' => $c->icon ?? [],
            'value' => $valueLabel,
            'start_date' => $c->coupon_start_date ?? '',
            'expire_date' => $c->coupon_expire_date ?? '',
            'date_created' => $c->date_created ?? '',
            'uses_per_coupon' => $c->uses_per_coupon ?? 0,
            'uses_per_user' => $c->uses_per_user ?? 0,
            'has_restrictions' => $hasRestrictions,
            'coupon_name' => $couponName,
            'coupon_description' => $couponDesc,
            'tooltip_content' => $tooltipContent,
        ];
    }
}

// Update outer attrs
$refreshUrl = Router::url('coupons_list', [
    'partial' => 1,
    'search' => $search,
    'page' => $page,
]);
$outerAttrs = 'id="coupons-list" hx-trigger="refresh consume, coupon:created from:body, coupon:updated from:body, coupon:deleted from:body" hx-get="' . \Components\Base::h($refreshUrl) . '" hx-target="this" hx-swap="outerHTML"';
if ($oob) { $outerAttrs .= ' hx-swap-oob="outerHTML"'; }

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',
    'label_key' => 'label',
    'status_key' => 'status',
    'hide_name_column' => true,
    'columns' => [
        [
            'type' => 'identity',
            'label' => 'Coupon',
        ],
        [
            'key' => 'text',
            'label' => 'Text',
            'render' => function ($val, $item) {
                $name = $item['coupon_name'] ?? '';
                $desc = $item['coupon_description'] ?? '';
                $truncatedDesc = mb_strimwidth($desc, 0, 60, '...');

                $triggerHtml = '<div class="text-sm flex flex-col max-w-50">';
                $triggerHtml .= '<span class="font-semibold text-gray-900 dark:text-gray-100 truncate">' . \Components\Base::h($name) . '</span>';
                if ($truncatedDesc) {
                    $triggerHtml .= '<span class="opacity-70 truncate">' . \Components\Base::h($truncatedDesc) . '</span>';
                }
                $triggerHtml .= '</div>';

                return Tooltip::render($triggerHtml, $item['tooltip_content'], [
                    'anchor' => 'top end',
                    'popover_class' => ' min-w-50 max-w-100',
                    'trigger_tag' => 'div',
                ]);
            }
        ],
        [
            'key' => 'value',
            'label' => 'Value',
        ],
        [
            'key' => 'start_date',
            'label' => 'Starts',
            'render' => function ($val) {
                $y = substr((string)$val, 0, 4);
                return ($val && $y !== '0000' && $y !== '0001' && $y !== '1000') ? date('Y-m-d', strtotime($val)) : '-';
            }
        ],
        [
            'key' => 'expire_date',
            'label' => 'Expires',
            'render' => function ($val) {
                $y = substr((string)$val, 0, 4);
                return ($val && $y !== '0000' && $y !== '0001' && $y !== '1000') ? date('Y-m-d', strtotime($val)) : '-';
            }
        ],
        [
            'key' => 'date_created',
            'label' => 'Created',
            'render' => function ($val) {
                $y = substr((string)$val, 0, 4);
                return ($val && $y !== '0000' && $y !== '0001' && $y !== '1000') ? date('Y-m-d', strtotime($val)) : '-';
            }
        ],
        [
            'key' => 'uses_per_coupon',
            'label' => 'Uses/C',
        ],
        [
            'key' => 'uses_per_user',
            'label' => 'Uses/U',
        ],
        [
            'key' => 'has_restrictions',
            'label' => '',
            'render' => function ($val) {
                return $val ? '<div title="Restrictions apply" class="text-orange-500">' . \Components\Base::SVG_OUTLINE_FILTER . '</div>' : '';
            }
        ]
    ],
    'outer_attrs' => $outerAttrs,
    'empty_text' => 'No coupons found',
    'panel_type' => 'drawer',
    'search' => [
        'value' => $search,
        'target' => '#coupons-list',
        'url' => Router::url('coupons_list', ['partial' => 1]),
    ],
    'filters' => [
        'template_coupon_id' => [
            'value' => $templateId,
            'options' => $templateOptions,
            'component' => 'rich_select',
            'target' => '#coupons-list',
            'url' => Router::url('coupons_list', ['partial' => 1, 'search' => $search]),
            'attrs' => [
                'x-model' => 'template_coupon_id',
            ]
        ]
    ],
    'pagination' => [
        'total' => $total,
        'per_page' => $perPage,
        'current_page' => $page,
        'url' => Router::url('coupons_list', ['partial' => 1, 'search' => $search]),
        'target' => '#coupons-list',
    ],
//    '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_as_menu' => true,
    'menu_trigger' => 'ellipsis',
    'row_actions' => [
        [
            'label' => 'View',
            'icon' => \Components\Base::SVG_EYE,
            'url' => $viewBase . '&id={id}',
            'attrs' => [ 'data-title' => 'View Coupon', 'data-size' => 'xl' ],
            'variant' => 'secondary',
        ],
        [
            'label' => 'Edit',
            'icon' => \Components\Base::SVG_EDIT,
            'url' => $editBase . '&id={id}',
            'attrs' => [ 'data-title' => 'Edit Coupon', 'data-size' => 'xl' ],
            'variant' => 'primary',
        ],
    ],
]);

$__html = ob_get_clean();
echo $__html;
