<?php
/**
 * @var $lots array
 * @var $loadMoreBtn boolean
 * @var string $hiddenPrice
 * @var string $showEstimatedPriceInItemsList
 * @var string $displayStartPriceInCatalog
 */

use auctionforge\inc\abs\ImageModel;
use auctionforge\inc\controllers\BidspiritLots;
use auctionforge\inc\helpers\LotHelper;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\helpers\View;
use auctionforge\inc\model\LotImage;
use auctionforge\inc\BidSpiritRequest;

$auctionBg = "#ffffff";
$cdnUse = SettingsHelper::getOption('cdn_images', 'on');
$limitWords = apply_filters('auctionforge_lot_title_words', 8);

if (!empty($lots) && is_array($lots)) {

    // --- Pre-fetch live bid data from BidSpirit API (same pattern as search.php) ---
    $liveBidData = array();
    $postAuctionMap = array();
    $auctionBsIds = array();

    foreach ($lots as $lot) {
        $terms = get_the_terms($lot->ID, BidspiritLots::TAX_AUCTION_TYPE);
        if ($terms && !is_wp_error($terms)) {
            $term = reset($terms);
            $term = apply_filters('auctionforge_prepare_auction_object', $term);
            $bsId = SettingsHelper::getTermOption($term->term_id, 'auction_id');
            if ($bsId) {
                $lotHelper_tmp = new LotHelper($lot->ID);
                $itemIdx = $lotHelper_tmp->getOptionValue('lot_itemIndex', 0);
                if ($itemIdx !== false && $itemIdx !== 0) {
                    $postAuctionMap[$lot->ID] = array('bsId' => $bsId, 'itemIndex' => $itemIdx);
                    $auctionBsIds[$bsId] = true;
                }
            }
        }
    }

    $auctionBidCache = array();
    foreach (array_keys($auctionBsIds) as $bsId) {
        $cacheKey = 'af_widget_bids_' . $bsId;
        $cached = get_transient($cacheKey);
        if ($cached !== false) {
            $auctionBidCache[$bsId] = $cached;
            continue;
        }
        $data = array('auctionId' => $bsId, 'language' => 'en');
        $response = BidSpiritRequest::send('items/getAllItemsInfoForAuction.api', $data);
        $auctionItems = array();
        if (!empty($response['response'])) {
            $decoded = json_decode($response['response']);
            if (isset($decoded->response->itemsInfo)) {
                foreach ($decoded->response->itemsInfo as $idx => $info) {
                    $bidPrice = 0;
                    $soldPrice = 0;
                    if (!empty($info->leadingBid) && isset($info->leadingBid->price)) {
                        $bidPrice = $info->leadingBid->price;
                    }
                    if (!empty($info->soldBid) && isset($info->soldBid->price)) {
                        $soldPrice = $info->soldBid->price;
                    }
                    if ($bidPrice > 0 || $soldPrice > 0) {
                        $auctionItems[$idx] = array('leadingBid' => $bidPrice, 'soldBid' => $soldPrice);
                    }
                }
            }
        }
        set_transient($cacheKey, $auctionItems, 120);
        $auctionBidCache[$bsId] = $auctionItems;
    }

    foreach ($postAuctionMap as $postId => $info) {
        $bsId = $info['bsId'];
        $itemIdx = (string)$info['itemIndex'];
        if (isset($auctionBidCache[$bsId][$itemIdx])) {
            $liveBidData[$postId] = $auctionBidCache[$bsId][$itemIdx];
        }
    }
    // --- End pre-fetch ---

    ?>
    <div class="bt-wi-lots_wrp" data-bg-color="<?= $auctionBg ?>">
        <div class="bp-lots bp-d-flex bp-f-wrap bp-f-center bp-md-f-around bt-wi-lots">
            <?php
            // Read once per page rather than once per lot.
            $bpCardGalleryOn = (SettingsHelper::getOption('lot_card_gallery', 'off') === 'on');
            /** @var WP_Post $lot */
            foreach ($lots as $lot) { ?>
                <?php
                $lotHelper = new LotHelper($lot->ID);
                $featureImage = $lotHelper->getFeatureImage();

                // Catalog card gallery (opt-in). Collect the lot's other photos so
                // buyers can page through them without opening the lot. Only kicks
                // in when there is genuinely more than one image — a single-image
                // card renders exactly as it always has.
                $bpCardImages = array();
                if (!empty($bpCardGalleryOn)) {
                    $bpImageList = (new LotImage($lot->ID))->getImageList();
                    if (is_array($bpImageList) && count($bpImageList) > 1) {
                        foreach ($bpImageList as $bpImg) {
                            $bpImg = (array) $bpImg;
                            if (!empty($bpImg[ImageModel::LABEL_MEDIUM])) {
                                $bpCardImages[] = $bpImg[ImageModel::LABEL_MEDIUM];
                            }
                        }
                        if (count($bpCardImages) < 2) {
                            $bpCardImages = array();
                        }
                    }
                }

                $auctions = get_the_terms($lot->ID, BidspiritLots::TAX_AUCTION_TYPE);
                $auction = 0;
                if (!empty($auctions)) {
                    $auctions[0] = apply_filters('auctionforge_prepare_auction_object', $auctions[0]);
                    $auction = $auctions[0];
                    $auctionId = SettingsHelper::getTermOption($auction->term_id, 'auction_id');
                } else {
                    $auctionId = 0;
                }

                $title = $lotHelper->getOptionValue('lot_name', '');
                $content = $lot->post_content;
                $title = LotHelper::getLotTitle($title, $content);
                $lotIndex = $lotHelper->getOptionValue('lot_itemIndex', 0);

                $isRemovedItem = $lotHelper->getOptionValue('removedFromAuction', 0);

                $estimatedPrice = $lotHelper->getOptionValue('lot_estimatedPrice', 0);
                $hasEstimate = !empty($estimatedPrice) && $estimatedPrice != '' && $estimatedPrice != '0';

                $startPrice = $lotHelper->getOptionValue('lot_start_price', 0);
                $leadingBid = $lotHelper->getOptionValue('lot_leadingBid', 0);
                $soldBid = $lotHelper->getOptionValue('lot_soldBid', 0);

                // Override with live bid data from API if available
                if (isset($liveBidData[$lot->ID])) {
                    if ($liveBidData[$lot->ID]['leadingBid'] > 0) {
                        $leadingBid = $liveBidData[$lot->ID]['leadingBid'];
                    }
                    if ($liveBidData[$lot->ID]['soldBid'] > 0) {
                        $soldBid = $liveBidData[$lot->ID]['soldBid'];
                    }
                }

                // Get auction state
                $auctionState = '';
                if (!empty($auctions) && !is_wp_error($auctions)) {
                    $auctionState = get_term_meta($auctions[0]->term_id, 'auction_state', true);
                }

                // Determine price display
                $priceClass = '';
                if ($soldBid != 0 && $soldBid > 0) {
                    $priceDesc = __('Sold for', 'auctionforge');
                    $price = LotHelper::formattedPrice($soldBid);
                    $priceClass = 'bp-lead bp-bg-blue';
                } elseif ($leadingBid != 0 && $leadingBid > 0) {
                    $priceDesc = __('Highest bid', 'auctionforge');
                    $price = LotHelper::formattedPrice($leadingBid);
                    $priceClass = 'bp-lead';
                } elseif ($auctionState === 'ENDED') {
                    $priceDesc = '';
                    $price = __('Unsold', 'auctionforge');
                    $priceClass = '';
                } else {
                    $priceDesc = __('Start price', 'auctionforge');
                    $price = LotHelper::formattedPrice($startPrice);
                }

                $itemData = new stdClass();
                $itemData->title = $title;
                $itemData->content = $content;
                ?>
                <div id="single-lot-<?= $auctionId ?>-<?= $lotIndex ?>"
                     class="bp-lot"
                     data-lot-index="<?= $lotIndex ?>"
                     data-auction-id="<?= $auctionId ?>"
                     data-estimated-price="<?= $estimatedPrice ?>"
                     data-content="<?= urlencode(json_encode($itemData)) ?>"
                >
                    <?php if (!empty($bpCardImages)) { ?>
                        <div class="bp-lot-gallery" data-bp-gallery data-bp-index="0">
                            <a href="<?= get_the_permalink($lot->ID) ?>" class="bp-lot__wrp-image">
                                <?php foreach ($bpCardImages as $bpI => $bpSrc) { ?>
                                    <div class="bp-lot__image bp-lot-gallery__slide<?= $bpI === 0 ? ' is-active' : '' ?>"
                                         <?php if ($bpI === 0) { ?>style="background-image:url(<?= esc_url($bpSrc) ?>);"<?php } else { ?>data-bp-src="<?= esc_url($bpSrc) ?>"<?php } ?>></div>
                                <?php } ?>
                            </a>
                            <?= View::render('templates.parts.lot-card-gallery-controls', array('bpCount' => count($bpCardImages))) ?>
                        </div>
                    <?php } else { ?>
                        <a href="<?= get_the_permalink($lot->ID) ?>" class="bp-lot__wrp-image">
                            <div class="bp-lot__image" style="background-image:url(<?= $featureImage ?>);"></div>
                        </a>
                    <?php } ?>
                    <div id="single-lot-<?= $auctionId ?>-<?= $lotIndex ?>-content"
                         class="bp-lot__content lot-<?= ($isRemovedItem === "1") ? "removed" : "isset" ?>">
                        <div class="bp-lot__title">
                            <a href="<?= get_the_permalink($lot->ID) ?>"><span class="bp-title">
                                    <?= LotHelper::printTranslateLot($lotIndex) ?>:</span><?= $title ?>
                            </a>
                        </div>
                        <div class="bp-lot__message">
                            <?php if ($hasEstimate) { ?>
                                <p class="bp-lot__message-inner bp-text-grey"><?= __('Estimated price', 'auctionforge') ?>: <strong><?= $estimatedPrice ?></strong></p>
                            <?php } ?>
                        </div>
                        <div class="bp-lot__tool <?= $priceClass ?>" data-entry="0.1">
                            <?php if ($priceDesc) { ?>
                                <p class="bp-subtitle"><?= $priceDesc ?>:</p>
                            <?php } ?>
                            <p class="bp-price"><?= $price ?></p>
                        </div>
                    </div>
                </div>
            <?php } ?>
        </div>
        <?php if ($loadMoreBtn) { ?>
            <div class="bt-wi-lots_more">
                <button class="btn"><?= __('Load more', 'auctionforge') ?></button>
            </div>
        <?php } ?>
    </div>
    <?php
    echo View::render('templates.parts.shortcodes-templates', array());
}
