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

$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');
$batchId = (int)mh_get('batch_id', 0, 'int');
$statusFilter = (string)mh_get('status', '', 'string');
$perPage = ConfigStore::getListPerPage('coupons', 25);

// Build template options using Coupon::listOptions for rich identity rendering in the filter
$templateOptions = ['0' => ['label_html' => (string)mh_lng('UI_TEXT_ALL_TEMPLATES', '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
}


$batchOptions = ['0' => ['label_html' => (string)mh_lng('UI_TEXT_ALL_SERIES', 'All Series')]];
try {
    $opt = \Components\Models\CouponBatch::listOptions(false);
    foreach ($opt as $k => $def) {
        $batchOptions[(string)$k] = $def;
    }
} catch (\Throwable $e) {}

// 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;
    }
    if ($batchId > 0) {
        $filters['batch_id'] = $batchId;
    }
    if ($statusFilter !== '') {
        $filters['status'] = $statusFilter;
    }
    $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 ?? (\mh_lng('UI_TEXT_COUPON', '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[] = array_merge($c->toArray(), [
            'id' => $id,
            'label' => $code,
            'status_label' => $status,
            'icon' => $c->icon ?? [],
            'value' => $valueLabel,
            '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,
    'template_coupon_id' => $templateId,
    'batch_id' => $batchId,
    'status' => $statusFilter,
]);
$outerAttrs = 'id="coupons-list" hx-trigger="refresh consume, list-per-page-updated:coupons from:body, 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' => \mh_lng('UI_TEXT_COUPONS', 'Coupons'),
    'table_id' => 'coupons',
    'layout' => 'clean',
    'items' => $items,
    'id_key' => 'id',
    'label_key' => 'label',
    'status_key' => 'status',
    'hide_name_column' => true,
    'refresh_action' => [
        'url' => $refreshUrl,
    ],
    'columns' => [
        [
            'type' => 'identity',
            'label' => \mh_lng('UI_TEXT_COUPON', 'Coupon'),
        ],
        [
            'key' => 'value',
            'label' => \mh_lng('UI_TEXT_VALUE', 'Value'),
            'align' => 'right',
        ],
        [
            'key' => 'text',
            'label' => \mh_lng('UI_TEXT_TEXT', 'Text'),
            'optional' => true,
            'default' => false,
            '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',
                    'trigger_attrs' => [
                        'onclick' => 'event.stopPropagation();',
                        'onmousedown' => 'event.stopPropagation();',
                        'data-no-modal' => 'true',
                    ],
                ]);
            }
        ],

        [
            'key' => 'validity',
            'label' => \mh_lng('UI_TEXT_VALIDITY', 'Validity'),
            'optional' => true,
            'render' => function ($val, $item) {
                $start = $item['coupon_start_date'] ?? '';
                $expire = $item['coupon_expire_date'] ?? '';
                $isStartValid = ($start && substr($start, 0, 4) !== '0000' && substr($start, 0, 4) !== '0001' && substr($start, 0, 4) !== '1000');
                $isExpireValid = ($expire && substr($expire, 0, 4) !== '0000' && substr($expire, 0, 4) !== '0001' && substr($expire, 0, 4) !== '1000');

                if (!$isStartValid && !$isExpireValid) {
                    return '<span class="text-gray-400">' . \mh_lng('UI_TEXT_UNLIMITED', 'Unlimited') . '</span>';
                }

                $startFmt = $isStartValid ? date('Y-m-d', strtotime($start)) : '...';
                $expireFmt = $isExpireValid ? date('Y-m-d', strtotime($expire)) : \mh_lng('UI_TEXT_UNLIMITED', 'Unlimited');

                $html = '<div class="flex flex-col leading-tight">';
                $html .= '<span>' . $startFmt . ' <span class="opacity-50 mx-1"></span> ' . $expireFmt . '</span>';

                if ($isStartValid && $isExpireValid) {
                    $diff = strtotime($expire) - strtotime($start);
                    $days = floor($diff / (60 * 60 * 24));
                    if ($days >= 0) {
                        $html .= '<span class="text-[10px] opacity-70">' . $days . ' ' . \mh_lng('UI_TEXT_DAYS', 'days') . ' </span>';
                    }
                }
                $html .= '</div>';
                return $html;
            }
        ],
        [
            'key' => 'status_badge',
            'label' => \mh_lng('UI_TEXT_STATUS', 'Status'),
            'optional' => false,
            'render' => function ($val, $item) {
                return Coupon::renderStatusBadge($item);
            }
        ],
        [
            'key' => 'date_created',
            'label' => \mh_lng('UI_TEXT_CREATED', 'Created'),
            'optional' => true,
            'default' => false,
            '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' => \mh_lng('UI_TEXT_USES_PER_COUPON', 'Uses/C'),
        ],
        [
            'key' => 'uses_per_user',
            'label' => \mh_lng('UI_TEXT_USES_PER_USER', 'Uses/U'),
        ],
        [
            'key' => 'has_restrictions',
            'label' => '',
            'render' => function ($val) {
                return $val ? '<div title="' . \mh_lng('UI_TEXT_RESTRICTIONS_APPLY', 'Restrictions apply') . '" class="text-orange-500">' . \Components\Base::SVG_OUTLINE_FILTER . '</div>' : '';
            }
        ]
        */
    ],
    'outer_attrs' => $outerAttrs,
    'empty_text' => \mh_lng('UI_TEXT_NO_COUPONS_FOUND', 'No coupons found'),
    'panel_type' => 'drawer',
    'search' => [
        'value' => $search,
        'placeholder' => mh_lng('UI_TEXT_COUPON_SEARCH', 'Search coupon code...'),
        'target' => '#coupons-list',
        'url' => Router::url('coupons_list', ['template_coupon_id' => $templateId, 'batch_id' => $batchId, 'status' => $statusFilter]),
    ],
    'filters' => [
        'template_coupon_id' => [
            'value' => $templateId,
            'options' => $templateOptions,
            'component' => 'rich_select',
            'target' => '#coupons-list',
            'url' => Router::url('coupons_list', ['search' => $search, 'batch_id' => $batchId, 'status' => $statusFilter]),
            'attrs' => [
                'x-model' => 'template_coupon_id',
            ]
        ],
        'batch_id' => [
            'value' => $batchId,
            'options' => $batchOptions,
            'component' => 'rich_select',
            'target' => '#coupons-list',
            'url' => Router::url('coupons_list', ['search' => $search, 'template_coupon_id' => $templateId, 'status' => $statusFilter]),
            'attrs' => [
                'x-model' => 'batch_id',
            ]
        ],
        'status' => [
            'value' => $statusFilter,
            'options' => array_merge([
                '' => [
                    'label_html' => (string)mh_lng('UI_TEXT_ALL_STATUSES', 'All Statuses'),
                ]
            ], Coupon::getStatusOptions()),
            'component' => 'rich_select',
            'target' => '#coupons-list',
            'url' => Router::url('coupons_list', ['search' => $search, 'template_coupon_id' => $templateId, 'batch_id' => $batchId]),
            'attrs' => [
                'x-model' => 'status',
            ]
        ]
    ],
    'pagination' => [
        'total' => $total,
        'per_page' => $perPage,
        'current_page' => $page,
        'url' => Router::url('coupons_list', ['search' => $search, 'template_coupon_id' => $templateId, 'batch_id' => $batchId, 'status' => $statusFilter]),
        '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',
    'primary_action' => 'view',
    'row_actions' => array_filter([
        [
            'key' => 'view',
            'label' => \mh_lng('UI_BUTTON_VIEW', 'View'),
            'icon' => \Components\Base::SVG_EYE,
            'url' => $viewBase . '&id={id}',
            'attrs' => [ 'data-title' => \mh_lng('UI_BUTTON_VIEW_COUPON', 'View Coupon'), 'data-size' => 'xl' ],
            'variant' => 'secondary',
        ],
        [
            'key' => 'edit',
            'label' => \mh_lng('UI_BUTTON_EDIT', 'Edit'),
            'icon' => \Components\Base::SVG_EDIT,
            'url' => $editBase . '&id={id}',
            'attrs' => [ 'data-title' => \mh_lng('UI_BUTTON_EDIT_COUPON', 'Edit Coupon'), 'data-size' => 'xl' ],
        ],
        !mh_saas() ? [
            'key' => 'edit_legacy',
            'label' => sprintf(\mh_lng('UI_BUTTON_EDIT_IN_PLATFORM', 'Edit in %s'), \Components\Base::platformLabel()),
            'icon' => \Components\Base::SVG_EDIT,
            'end_icon' => \Components\Base::platformIcon(),
            'attrs' => [
                'command' => 'show-modal',
                'commandfor' => 'config-modal',
                'data-title' => \mh_lng('UI_BUTTON_EDIT'),
                'data-size' => 'full-margin',
                'data-url' => \Components\Legacy\LegacyRouter::url('couponEdit', ['cid' => '{id}']),
                'hx-target' => '#config-modal-body',
                'hx-swap' => 'innerHTML',
            ],
            'variant' => 'primary',
        ] : null,
    ]),
]);

$__html = ob_get_clean();
echo $__html;
