<?php
// pages/components/reviews_list.php

use Components\ConfigStore;
use Components\Models\Review;
use Components\Resources\ResourceList;
use Components\Router;
use Components\Ui\Badge;
use Components\Ui\Stars;

$oob = (int) (mh_get('oob', 0, 'int'));
$page = (int)mh_get('page', 1, 'int');
$search = (string)mh_get('search', '', 'string');
$statusFilter = (string)\mh_get('status', '', 'string');
$starsFilter = (int)\mh_get('stars', 0, 'int');
$starsFilter = ($starsFilter >= 1 && $starsFilter <= 5) ? (string)$starsFilter : '';
$perPage = ConfigStore::getListPerPage('reviews', 25);

$filters = [];
if ($statusFilter !== '') {
    $filters['review_status'] = $statusFilter;
}
if ($starsFilter !== '') {
    $filters['reviews_rating'] = $starsFilter;
}

$items = [];
$total = 0;

if (function_exists('mh_db_query')) {
    $paginationResult = Review::paginate(
        $perPage,
        $page,
        $search,
        ['customers_name', 'reviews_text', 'products_name', 'products_id'],
        $filters
    );
    $total = (int)($paginationResult['total'] ?? 0);

    foreach ($paginationResult['items'] as $review) {
        /** @var Review $review */
        $row = $review->toArray();
        $id = (int)($row['reviews_id'] ?? 0);
        if ($id <= 0) {
            continue;
        }

        $customerName = trim((string)($row['customers_name'] ?? ''));
        if ($customerName === '') {
            $customerName = \mh_lng('MAILBEEZ_APP_LABEL_REVIEW', 'Review') . ' #' . $id;
        }

        $productId = (int)($row['products_id'] ?? 0);
        $productName = trim((string)($row['products_name'] ?? ''));
        if ($productName === '') {
            $productName = '#' . $productId;
        }
        $statusValue = (int)($row['reviews_status'] ?? ($row['status'] ?? 1));
        $isActive = $statusValue > 0;

        $rating = max(0, min(5, (int)($row['reviews_rating'] ?? 0)));
        $ratingHtml = Stars::render($rating, 5, [
            'size' => 'lg',
            'show_label' => false,
            'wrapper_class' => 'w-full justify-end',
        ]);

        $reviewText = trim((string)($row['reviews_text'] ?? ''));
        $preview = $reviewText;
        if (function_exists('mb_strimwidth')) {
            $preview = mb_strimwidth($preview, 0, 140, '…');
        } elseif (strlen($preview) > 140) {
            $preview = substr($preview, 0, 137) . '...';
        }

        $addedAt = (string)($row['date_added'] ?? '');
        $y = substr($addedAt, 0, 4);
        $addedAtLabel = ($addedAt && $y !== '0000' && $y !== '0001' && $y !== '1000') ? date('Y-m-d', strtotime($addedAt)) : '-';

        $items[] = [
            'id' => $id,
            'label' => $customerName,
            'sublabel' => \mh_lng('UI_LABEL_PRODUCT', 'Product') . ': ' . $productName,
            'status' => $isActive ? 'Y' : '',
            'icon' => [
                'svg' => ($rating >= 4) ? \Components\Base::SVG_STAR : \Components\Base::SVG_STAR_OUTLINE,
                'color' => $isActive ? 'brand' : 'gray',
                'size' => 'sm',
            ],
            'product_name' => $productName,
            'reviews_rating' => $ratingHtml,
            'reviews_text_preview' => $preview,
            'date_added_fmt' => $addedAtLabel,
            'reviews_status' => $statusValue, // ensures Review::renderStatusBadge works if using the array
        ];
    }
}

$refreshUrl = Router::url('reviews_list', [
    'partial' => 1,
    'search' => $search,
    'page' => $page,
    'status' => $statusFilter,
    'stars' => $starsFilter,
]);

$outerAttrs = 'id="reviews-list" hx-trigger="refresh consume, reviews:refresh from:body, review:created from:body, review:updated from:body, review:deleted from:body, list-per-page-updated:reviews 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('review_modal', ['partial' => 1, 'mode' => 'view']);
$editBase = Router::url('review_modal', ['partial' => 1, 'mode' => 'edit']);

$starsFilterOptions = [
    '' => [
        'label_html' => (string)\mh_lng('UI_TEXT_ALL_RATINGS', 'All Ratings'),
    ],
];
for ($stars = 5; $stars >= 1; $stars--) {
    $starsFilterOptions[(string)$stars] = [
        'label_html' => Stars::render($stars, 5, [
            'size' => 'md',
            'show_label' => false,
            'wrapper_class' => 'justify-start',
        ]),
    ];
}

echo ResourceList::render([
    'title' => \mh_lng('MAILBEEZ_APP_LABEL_REVIEWS', 'Reviews'),
    'table_id' => 'reviews',
    'layout' => 'clean',

    'items' => $items,
    'id_key' => 'id',
    'label_key' => 'label',
    'sublabel_key' => 'sublabel',
    'status_key' => 'status',
    'hide_name_column' => true,
    'refresh_action' => [
        'url' => $refreshUrl,
    ],
    'columns' => [
        [
            'type' => 'identity',
            'label' => \mh_lng('UI_LABEL_CUSTOMER', 'Customer'),
        ],
        [
            'key' => 'product_name',
            'label' => \mh_lng('UI_LABEL_PRODUCT', 'Product'),
            'align' => 'right',
        ],
        [
            'key' => 'reviews_rating',
            'label' => \mh_lng('UI_LABEL_RATING', 'Rating'),
            'align' => 'right',
            'render' => function ($val) {
                return (string)$val;
            }
        ],
        [
            'key' => 'reviews_text_preview',
            'label' => \mh_lng('UI_LABEL_REVIEW_TEXT', 'Review'),
        ],
        [
            'key' => 'status_badge',
            'label' => \mh_lng('UI_TEXT_STATUS', 'Status'),
            'render' => function ($val, $item) {
                return Review::renderStatusBadge($item);
            }
        ],
        [
            'key' => 'date_added_fmt',
            'label' => \mh_lng('UI_TEXT_CREATED', 'Created'),
            'optional' => true,
            'default' => false,
        ],
    ],
    'outer_attrs' => $outerAttrs,
    'empty_text' => \mh_lng('UI_REVIEWS_EMPTY', 'No reviews found'),
    'panel_type' => 'drawer',
    'search' => [
        'value' => $search,
        'placeholder' => \mh_lng('UI_REVIEWS_SEARCH', 'Search by customer, product or text'),
        'target' => '#reviews-list',
        'url' => Router::url('reviews_list', ['partial' => 1]),
        'attrs' => [
            'x-model.debounce.500ms' => 'search',
        ]
    ],
    'filters' => [
        'status' => [
            'value' => $statusFilter,
            'options' => array_merge([
                '' => [
                    'label_html' => (string)\mh_lng('UI_TEXT_ALL_STATUSES', 'All Statuses'),
                ]
            ], Review::getStatusOptions()),
            'component' => 'rich_select',
            'target' => '#reviews-list',
            'url' => Router::url('reviews_list', ['partial' => 1]),
            'attrs' => [
                'x-model' => 'status',
            ]
        ],
        'stars' => [
            'value' => $starsFilter,
            'options' => $starsFilterOptions,
            'component' => 'rich_select',
            'target' => '#reviews-list',
            'url' => Router::url('reviews_list', ['partial' => 1]),
            'attrs' => [
                'x-model' => 'stars',
            ]
        ],
    ],
    'pagination' => [
        'total' => $total,
        'per_page' => $perPage,
        'current_page' => $page,
        'url' => Router::url('reviews_list', ['partial' => 1]),
        'target' => '#reviews-list',
    ],
    '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('MAILBEEZ_VIEW_REVIEW', 'View Review'), 'data-size' => '3xl'],
            '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('MAILBEEZ_EDIT_REVIEW', 'Edit Review'), 'data-size' => '3xl'],
        ],
        !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('reviewEdit', ['rID' => '{id}']),
                'hx-target' => '#config-modal-body',
                'hx-swap' => 'innerHTML',
            ],
            'variant' => 'primary',
        ] : null,
    ]),
]);

$__html = ob_get_clean();
echo $__html;
